Files
cloud-mcp/scripts/init-db.ts

82 lines
2.6 KiB
TypeScript

/**
* Database initialization script
* Creates all required tables in PostgreSQL
*/
import postgres from "postgres";
import { readFileSync } from "fs";
import { join } from "path";
async function initDatabase() {
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
console.error("Error: DATABASE_URL environment variable is required");
console.error("Please set it in your .env file or export it:");
console.error(" export DATABASE_URL=postgresql://user:password@host:port/database");
process.exit(1);
}
console.log("Connecting to PostgreSQL...");
const sql = postgres(dbUrl);
try {
// Test connection
await sql`SELECT 1`;
console.log("✓ Connected to PostgreSQL");
// Read schema file
const schemaPath = join(process.cwd(), "src", "storage", "schema.sql");
console.log(`Reading schema from ${schemaPath}...`);
const schema = readFileSync(schemaPath, "utf-8");
// Split by semicolons and execute each statement
const statements = schema
.split(";")
.map((s) => s.trim())
.filter((s) => s.length > 0 && !s.startsWith("--"));
console.log(`Executing ${statements.length} SQL statements...`);
for (const statement of statements) {
if (statement) {
try {
// Use postgres.unsafe() to execute raw SQL
await (sql as any).unsafe(statement);
console.log(`✓ Executed: ${statement.substring(0, 50)}...`);
} catch (error) {
// Check if it's a "already exists" error (which is OK)
const errorMessage = (error as Error).message;
if (errorMessage.includes("already exists") || errorMessage.includes("duplicate")) {
console.log(`⚠ Skipped (already exists): ${statement.substring(0, 50)}...`);
} else {
console.error(`✗ Error executing statement: ${errorMessage}`);
console.error(` Statement: ${statement.substring(0, 100)}...`);
throw error;
}
}
}
}
console.log("\n✓ Database initialization completed successfully!");
console.log("\nTables created:");
console.log(" - code_snippets");
console.log(" - notes");
console.log(" - tasks");
console.log(" - baby_milestones");
console.log(" - math_resources");
console.log(" - game_wishlist");
} catch (error) {
console.error("\n✗ Database initialization failed:", error);
process.exit(1);
} finally {
await sql.end();
}
}
// Run initialization
initDatabase().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});