Vercel Postgres数据库初始化时出现prepared statement不存在错误
解决Vercel Postgres执行seed.js时的
prepared statement does not exist错误 可行修复方案
禁用Prepared Statement缓存
如果你用的是@vercel/postgres库,默认的Prepared Statement复用机制在pgbouncer事务模式下容易触发这个错误。可以在创建客户端时直接禁用:import { sql } from '@vercel/postgres'; // 全局禁用Prepared Statement sql.prepare = false; // 或者在单个查询前手动清理 await sql`DEALLOCATE ALL;`;用事务包裹所有插入操作
部分数据插入成功说明错误发生在批量过程中,用事务包裹可以保证要么全插入成功,要么全回滚,同时避免跨事务的Prepared Statement问题:try { await sql`BEGIN;`; // 逐个插入发票数据 for (const invoice of invoices) { await sql` INSERT INTO invoices (customer_id, amount, status, date) VALUES (${invoice.customer_id}, ${invoice.amount}, ${invoice.status}, ${invoice.date}) `; } await sql`COMMIT;`; } catch (error) { await sql`ROLLBACK;`; throw error; }明确指定pgbouncer连接模式
把连接字符串中的参数改成?pgbouncer=transaction,而不是简单的pgbouncer=true,确保pgbouncer使用事务模式处理连接:POSTGRES_URL="postgres://your-user:your-pass@your-host:your-port/your-db?pgbouncer=transaction"改用原生pg库编写seed脚本
如果@vercel/postgres的封装限制了灵活性,直接用pg库控制连接生命周期:import { Pool } from 'pg'; import dotenv from 'dotenv'; import { invoices } from './placeholder-data.js'; dotenv.config(); const pool = new Pool({ connectionString: process.env.POSTGRES_URL }); async function seed() { const client = await pool.connect(); try { await client.query('BEGIN'); for (const inv of invoices) { await client.query( 'INSERT INTO invoices (customer_id, amount, status, date) VALUES ($1, $2, $3, $4)', [inv.customer_id, inv.amount, inv.status, inv.date] ); } await client.query('COMMIT'); console.log('数据初始化完成'); } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); await pool.end(); } } seed().catch(err => console.error('初始化失败:', err));
内容的提问来源于stack exchange,提问作者Ecki
相关产品推荐
相关产品推荐

