MCPcopy Create free account
hub / github.com/alexankitty/Myrient-Search-Engine / initDB

Function initDB

lib/database/database.js:71–137  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

69}
70
71export async function initDB() {
72 try {
73 // First try to connect to postgres directly to create database if needed
74 const rootSequelize = new Sequelize(
75 "postgres",
76 process.env.POSTGRES_USER,
77 process.env.POSTGRES_PASSWORD,
78 {
79 host: process.env.POSTGRES_HOST || "localhost",
80 port: process.env.POSTGRES_PORT || 5432,
81 dialect: "postgres",
82 logging: false,
83 }
84 );
85
86 try {
87 // Try to create database if it doesn't exist
88 await rootSequelize.query(`CREATE DATABASE ${process.env.POSTGRES_DB};`);
89 console.log("Database did not exist, created.");
90 } catch (err) {
91 // Ignore error if database already exists
92 if (!err.message.includes("already exists")) {
93 throw err;
94 }
95 } finally {
96 await rootSequelize.close();
97 }
98
99 // Now connect to the actual database
100 await sequelize.authenticate();
101 console.log("DB connected.");
102
103 // Get current database schema
104 const queryInterface = sequelize.getQueryInterface();
105 const tables = await queryInterface.showAllTables();
106
107 if (!tables.includes("Files") || !tables.includes("QueryCounts")) {
108 // If tables don't exist, create them
109 console.log("DB doesn't exist, creating initial database schema...");
110 await sequelize.sync();
111 await enableTrigram();
112 console.log("Database schema created.");
113
114 // Initialize QueryCount if it's a new installation
115 await QueryCount.create({ count: 0 });
116 } else {
117 // Auto-migrate existing schema
118 console.log("Checking for DB migrations...");
119 await sequelize.sync({ alter: true });
120 await enableTrigram();
121 console.log("DB migrations completed.");
122 }
123
124 // Only force sync if explicitly requested
125 if (process.env.FORCE_FILE_REBUILD === "1") {
126 let queryCount = (await QueryCount.findOne())?.count || 0;
127 await sequelize.sync({ force: true });
128 await enableTrigram();

Callers 1

server.jsFile · 0.90

Calls 1

enableTrigramFunction · 0.85

Tested by

no test coverage detected