|
@@ -1,6 +1,5 @@
|
|
|
import { Pool } from 'pg';
|
|
|
import { config } from '../config';
|
|
|
-import { createUsersTable, getAllUsers, createUser } from './users.repository'; // 添加这行导入
|
|
|
|
|
|
// 创建连接池
|
|
|
const pool = new Pool({
|
|
@@ -37,5 +36,45 @@ pool.on('error', (err: Error) => {
|
|
|
console.error('Unexpected database error', err);
|
|
|
});
|
|
|
|
|
|
-// 导出所有需要的函数
|
|
|
-export { createUsersTable, getAllUsers, createUser }; // 添加这行导出
|
|
|
+// 初始化数据库 - 检查并创建 cloth 表
|
|
|
+export const initializeDatabase = async () => {
|
|
|
+ try {
|
|
|
+ // 检查 cloth 表是否存在
|
|
|
+ const tableExists = await query(
|
|
|
+ `SELECT EXISTS (
|
|
|
+ SELECT FROM information_schema.tables
|
|
|
+ WHERE table_schema = 'public'
|
|
|
+ AND table_name = 'cloth'
|
|
|
+ )`
|
|
|
+ );
|
|
|
+
|
|
|
+ if (!tableExists.rows[0].exists) {
|
|
|
+ console.log('Creating cloth table...');
|
|
|
+ await query(`
|
|
|
+ CREATE TABLE cloth (
|
|
|
+ id SERIAL PRIMARY KEY,
|
|
|
+ name VARCHAR(100) NOT NULL,
|
|
|
+ description TEXT,
|
|
|
+ price DECIMAL(10,2) NOT NULL,
|
|
|
+ size VARCHAR(10)[],
|
|
|
+ colors VARCHAR(20)[],
|
|
|
+ material VARCHAR(50),
|
|
|
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
|
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
|
+ )
|
|
|
+ `);
|
|
|
+ console.log('Cloth table created successfully');
|
|
|
+ } else {
|
|
|
+ console.log('Cloth table already exists');
|
|
|
+ }
|
|
|
+
|
|
|
+ // 测试数据库连接
|
|
|
+ const dbStatus = await testDbConnection();
|
|
|
+ console.log('Database connection successful:', dbStatus);
|
|
|
+
|
|
|
+ } catch (error) {
|
|
|
+ const err = error as Error;
|
|
|
+ console.error('Database initialization failed:', err.message);
|
|
|
+ throw err;
|
|
|
+ }
|
|
|
+};
|