来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
71 lines
2.2 KiB
TypeScript
71 lines
2.2 KiB
TypeScript
import { Pool } from 'pg';
|
|
|
|
function resolveAdminDatabaseUrl(): string {
|
|
if (process.env.ADMIN_DATABASE_URL) return process.env.ADMIN_DATABASE_URL;
|
|
const appUrl = process.env.DATABASE_URL || '';
|
|
try {
|
|
if (appUrl) {
|
|
const u = new URL(appUrl);
|
|
const host = u.hostname || '127.0.0.1';
|
|
const port = u.port || '5432';
|
|
// 与应用库同主机端口;用户名默认 postgres(可用 ADMIN_DATABASE_URL 覆盖)
|
|
return `postgresql://postgres@${host}:${port}/postgres`;
|
|
}
|
|
} catch {
|
|
/* fall through */
|
|
}
|
|
return 'postgresql://postgres@127.0.0.1:5432/postgres';
|
|
}
|
|
|
|
const ADMIN_URL = resolveAdminDatabaseUrl();
|
|
const APP_URL = process.env.DATABASE_URL || 'postgresql://canteen:canteen123@127.0.0.1:5432/canteen_delivery';
|
|
|
|
async function setupDatabase() {
|
|
const admin = new Pool({ connectionString: ADMIN_URL });
|
|
try {
|
|
console.log('Setting up local PostgreSQL database...');
|
|
|
|
const userExists = await admin.query(`SELECT 1 FROM pg_roles WHERE rolname = 'canteen'`);
|
|
if (!userExists.rowCount) {
|
|
await admin.query(`CREATE USER canteen WITH PASSWORD 'canteen123'`);
|
|
console.log('Created user: canteen');
|
|
} else {
|
|
await admin.query(`ALTER USER canteen WITH PASSWORD 'canteen123'`);
|
|
console.log('Updated password for user: canteen');
|
|
}
|
|
|
|
const dbExists = await admin.query(`SELECT 1 FROM pg_database WHERE datname = 'canteen_delivery'`);
|
|
if (!dbExists.rowCount) {
|
|
await admin.query(`CREATE DATABASE canteen_delivery OWNER canteen`);
|
|
console.log('Created database: canteen_delivery');
|
|
} else {
|
|
console.log('Database already exists: canteen_delivery');
|
|
}
|
|
|
|
await admin.query(`GRANT ALL PRIVILEGES ON DATABASE canteen_delivery TO canteen`);
|
|
} finally {
|
|
await admin.end();
|
|
}
|
|
|
|
const app = new Pool({ connectionString: APP_URL });
|
|
try {
|
|
await app.query('SELECT 1');
|
|
console.log('Application database connection OK');
|
|
} finally {
|
|
await app.end();
|
|
}
|
|
}
|
|
|
|
if (require.main === module) {
|
|
setupDatabase()
|
|
.then(() => {
|
|
console.log('Database setup complete.');
|
|
})
|
|
.catch((error) => {
|
|
console.error('Database setup failed:', error);
|
|
process.exit(1);
|
|
});
|
|
}
|
|
|
|
export { setupDatabase };
|