Skip to content

Instantly share code, notes, and snippets.

@vagra
Last active July 26, 2024 12:04
Show Gist options
  • Save vagra/c146f99ec6b062a4227fdc6145b87a5c to your computer and use it in GitHub Desktop.
Save vagra/c146f99ec6b062a4227fdc6145b87a5c to your computer and use it in GitHub Desktop.
To replace vercel/postgres from the official Next.js tutorial with a local PostgreSQL setup, you simply need to add this /lib/db.ts file, and then change the imports in /lib/data.ts and /seed/router.ts from vercel/postgres to ./db or ../lib/db. Also, don’t forget to run npm install pg.
// db.ts
import { Pool, PoolClient } from 'pg';
import dotenv from 'dotenv';
dotenv.config();
const pool = new Pool({
connectionString: process.env.POSTGRES_URL,
});
async function executeQuery<T = any>(client: PoolClient, query: string, values: any[]): Promise<{ rows: T[] }> {
const isSimpleCommand = /^BEGIN|COMMIT|ROLLBACK/.test(query.trim().toUpperCase());
if (isSimpleCommand) {
// 处理简单的 SQL 命令,如 BEGIN、COMMIT、ROLLBACK
await client.query(query);
return { rows: [] };
} else {
// 处理带参数的 SQL 查询
const result = await client.query(query, values);
return { rows: result.rows };
}
}
class Client {
private client: PoolClient | null = null;
async connect(): Promise<Client> {
this.client = await pool.connect();
return this;
}
async sql<T = any>(strings: TemplateStringsArray, ...values: any[]): Promise<{ rows: T[] }> {
if (!this.client) {
throw new Error('Client is not connected. Call connect() first.');
}
const query = strings.reduce((prev, curr, i) => prev + curr + (i < values.length ? '$' + (i + 1) : ''), '');
return executeQuery(this.client, query, values);
}
async release(): Promise<void> {
if (this.client) {
await this.client.release();
this.client = null;
}
}
}
export async function sql<T = any>(strings: TemplateStringsArray, ...values: any[]): Promise<{ rows: T[] }> {
const client = await pool.connect();
try {
const query = strings.reduce((prev, curr, i) => prev + curr + (i < values.length ? '$' + (i + 1) : ''), '');
return executeQuery(client, query, values);
} finally {
client.release();
}
}
export const db = {
connect: async () => new Client().connect(),
};
@vagra
Copy link
Author

vagra commented Jul 26, 2024

使用本地 postgresql 替代 next.js 官方教程 中的 vercel/postgres ,只需要简单添加这个 /lib/db.ts ,然后把 /lib/data.ts 和 /seed/router.ts 中的 import from vercel/postges 修改为 import from './db' 或 '../lib/db' 即可。对了记得 npm install pg

@vagra
Copy link
Author

vagra commented Jul 26, 2024

What's the use of this? In some cases, connecting to Vercel might not be possible, so I prefer to use a local PostgreSQL setup.

这个有什么用?有的地方可能连接不上 vercel ,你懂的,所以更希望使用本地 postgresql 。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment