-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate.js
More file actions
177 lines (148 loc) · 5.62 KB
/
migrate.js
File metadata and controls
177 lines (148 loc) · 5.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
const fs = require('node:fs');
const path = require('node:path');
const Database = require('better-sqlite3');
const DB_PATH = './storage/application.db';
const MIGRATIONS_DIR = 'migrations';
const SEEDER_FILE = 'seeder.sql';
if(!fs.existsSync(path.dirname(DB_PATH))) {
fs.mkdirSync(path.dirname(DB_PATH), { recursive: true });
console.log(`Created database directory: '${path.dirname(DB_PATH)}'`);
}
/**
* Applies data from the seeder file.
* @param {Database.Database} db The database instance.
*/
function applySeeder(db) {
if (!fs.existsSync(SEEDER_FILE)) {
console.log(`Seeder file '${SEEDER_FILE}' not found, skipping.`);
return;
}
console.log(`Applying data from seeder file: ${SEEDER_FILE}...`);
try {
const sql = fs.readFileSync(SEEDER_FILE, 'utf8');
db.exec(sql);
console.log(`✅ Successfully applied seeder data.`);
} catch (err) {
console.error(`❌ FAILED to apply seeder file '${SEEDER_FILE}'.`);
throw err;
}
}
function applyMigrations() {
console.log('Starting database migration process...');
const db = new Database(DB_PATH, {
// verbose: console.log
});
try {
db.exec(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY NOT NULL,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`);
console.log(`Make sure 'schema_migrations' table exists.`);
} catch (err) {
console.error(`Failed to create migrations table: ${err.message}`);
db.close();
process.exit(1);
}
const getAppliedStmt = db.prepare(`SELECT version FROM schema_migrations`);
const appliedRows = getAppliedStmt.all();
const appliedVersions = new Set(appliedRows.map(row => row.version));
console.log(`Found ${appliedVersions.size} applied migrations.`);
if (!fs.existsSync(MIGRATIONS_DIR)) {
console.log(`Migrations directory '${MIGRATIONS_DIR}' not found. Nothing to do.`);
}
const allMigrationFiles = fs.existsSync(MIGRATIONS_DIR)
? fs.readdirSync(MIGRATIONS_DIR)
.filter(file => file.endsWith('.sql'))
.sort()
: [];
const pendingMigrations = allMigrationFiles.filter(file => {
const version = file.split('-')[0];
return !appliedVersions.has(version);
});
if (pendingMigrations.length === 0) {
console.log('Database schema is up to date. No new migrations to apply.');
} else {
console.log(`Found ${pendingMigrations.length} pending migrations to apply.`);
for (const migrationFile of pendingMigrations) {
const applyMigrationTx = db.transaction(() => {
try {
const migrationPath = path.join(MIGRATIONS_DIR, migrationFile);
const sql = fs.readFileSync(migrationPath, 'utf8');
db.exec(sql);
const version = migrationFile.split('-')[0];
const recordMigrationStmt = db.prepare(`INSERT INTO schema_migrations (version) VALUES (?)`);
recordMigrationStmt.run(version);
console.log(`✅ Successfully applied migration: ${migrationFile}`);
} catch (err) {
console.error(`❌ FAILED to apply migration ${migrationFile}. Rolling back.`);
throw err;
}
});
try {
applyMigrationTx();
} catch (err) {
console.error(`Migration failed: ${err.message}`);
db.close();
process.exit(1);
}
}
}
try {
applySeeder(db);
} catch (err) {
console.error(`Seeding failed: ${err.message}`);
db.close();
process.exit(1);
}
console.log('Migration and seeding process finished successfully.');
db.close();
}
/**
* Creates a new, empty .sql file in the
* @param {string} name
*/
function createMigration(name) {
if (!name) {
console.error('❌ Migration name is required. Usage: node migrate.js create <MigrationName>');
process.exit(1);
}
const sanitizedName = name.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
const timestamp = Math.floor(Date.now() / 1000);
const filename = `${timestamp}-${sanitizedName}.sql`;
const filepath = path.join(MIGRATIONS_DIR, filename);
if (!fs.existsSync(MIGRATIONS_DIR)) {
fs.mkdirSync(MIGRATIONS_DIR);
console.log(`Created migrations directory: '${MIGRATIONS_DIR}'`);
}
fs.writeFileSync(filepath, `-- Add your SQL migration statements here for ${filename}\n`);
console.log(`✅ Created new migration file: ${filepath}`);
}
function main() {
const command = process.argv[2];
const argument = process.argv[3];
switch (command) {
case 'apply':
applyMigrations();
break;
case 'create':
createMigration(argument);
break;
case 'seed':
applySeeder(new Database(DB_PATH));
break;
case 'setup':
applyMigrations();
applySeeder(new Database(DB_PATH));
break;
default:
console.log('Usage:');
console.log(' node migrate.js <command> [args]');
console.log(' node migrate.js seed - Applies data from the seeder file.');
console.log(' node migrate.js apply - Applies pending migrations and seeds data.');
console.log(' node migrate.js create <Name> - Creates a new, empty migration file.');
process.exit(1);
}
}
main();