Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 | 5x 30x 30x 20x 20x 1x 19x 12x 1x 1x 10x 45x 23x 23x 23x 3x 5x 21x 20x 18x 2x 1x 1x 3x 5x 21x 21x 21x 2x 2x 2x 19x 19x 2x 2x 3x 1x 1x 1x 1x 1x 23x 22x 38x 15x 1x 14x 1x 13x 23x 23x 38x 38x 38x 2x 36x 1x 38x 15x 38x 2x 2x 2x 2x 2x 15x 38x 15x 4x 2x 2x 30x 4x 4x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 29x 33x 33x 33x 33x 33x 15x 13x 13x 13x 13x 5x 9x 9x 8x 10x 14x 9x 2x 7x 7x 7x 7x 10x 10x 10x 10x 8x 8x 8x 8x 2x 2x 1x 6x 4x 4x 4x 4x 4x 4x 7x 7x 3x 3x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 4x 3x 5x 3x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 1x 7x 7x 7x 1x 1x 1x 1x 12x 12x 3x 12x 12x 12x 12x 8x 10x 9x 9x 1x 1x 1x 8x 8x 12x 1x 11x 1x 1x 10x 10x 8x 6x 17x 17x 6x 6x 6x 6x 6x 1x 1x 1x 1x 2x 1x 2x 2x 3x 22x 22x 22x 22x 9x 9x 9x 8x 8x 8x 2x 2x 2x 3x 3x 3x 1x 1x 1x 7x 7x 7x 3x 3x 3x 3x 3x 3x 3x 8x 8x 2x 4x 9x 9x 9x 9x 13x 13x 13x 9x 13x 13x 13x 13x 5x 13x 13x 13x 4x 4x 9x 13x 9x 13x 13x 12x 5x 5x 5x 1x 1x 1x 2x 9x 13x 13x 13x 11x 10x 10x 5x 5x 5x 5x 5x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 1x 1x 1x 1x 1x 1x 1x 1x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 8x 5x 5x 5x 5x 2x 2x 7x 7x 7x 9x 9x 7x 7x 7x 6x 3x 1x 1x 1x 7x | /**
* Database Migration System for Coherent.js
*
* @fileoverview Provides database schema migration functionality with version control,
* rollback support, and automatic migration tracking.
*/
import { readdir, writeFile, mkdir } from 'fs/promises';
import { join, resolve } from 'path';
import { pathToFileURL } from 'url';
import { assertIdentifier } from './query-builder.js';
// ============================================================================
// Shared helpers
// ============================================================================
const DIALECT_ALIASES = {
postgresql: 'postgresql',
postgres: 'postgresql',
pg: 'postgresql',
mysql: 'mysql',
mariadb: 'mysql',
sqlite: 'sqlite',
sqlite3: 'sqlite'
};
/**
* SQL dialect for generated DDL: `config.dialect`, else the DatabaseManager's `type`,
* else SQLite syntax (the historical default).
*
* @private
*/
function resolveDialect(db, config = {}) {
const requested = config.dialect ?? db?.config?.type;
if (requested === undefined || requested === null) return 'sqlite';
const dialect = DIALECT_ALIASES[String(requested).toLowerCase()];
if (!dialect) {
throw new Error(`SQL migrations are not supported for the '${requested}' database type. Use postgresql, mysql or sqlite.`);
}
return dialect;
}
/**
* CREATE TABLE statement for the migrations tracking table.
*
* @private
*/
function migrationsTableSQL(tableName, dialect) {
switch (dialect) {
case 'postgresql':
return `CREATE TABLE ${tableName} (
id SERIAL PRIMARY KEY,
migration VARCHAR(255) NOT NULL UNIQUE,
batch INTEGER NOT NULL,
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;
case 'mysql':
return `CREATE TABLE ${tableName} (
id INT AUTO_INCREMENT PRIMARY KEY,
migration VARCHAR(255) NOT NULL UNIQUE,
batch INT NOT NULL,
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;
default:
return `CREATE TABLE ${tableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
migration VARCHAR(255) NOT NULL UNIQUE,
batch INTEGER NOT NULL,
executed_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`;
}
}
/**
* Absolute path of a migrations directory; relative paths resolve against the
* process working directory (not this module's location).
*
* @private
*/
function resolveDirectory(directory) {
return resolve(process.cwd(), directory);
}
/**
* Import a migration module by file URL (a bare path such as `migrations/x.js` would be
* resolved as a package name).
*
* @private
*/
async function importMigration(directory, file) {
const url = pathToFileURL(join(resolveDirectory(directory), file)).href;
try {
return await import(url);
} catch (error) {
throw new Error(`Failed to load migration ${file}: ${error.message}`, { cause: error });
}
}
const warnedWithoutTransaction = new WeakSet();
/**
* Start the transaction a migration runs in.
*
* `transactional: false` runs migrations directly on the connection (for statements
* that cannot run inside a transaction). A database object without `transaction()`
* also runs directly, with a one-time warning.
*
* @private
*/
async function beginMigrationTransaction(db, config) {
if (config.transactional !== false) {
if (typeof db.transaction === 'function') {
return await db.transaction();
}
if (!warnedWithoutTransaction.has(db)) {
warnedWithoutTransaction.add(db);
console.warn(
'Running migrations without a transaction: the database object has no transaction() method, ' +
'so a failed migration can be left half-applied. Pass { transactional: false } to run without ' +
'transactions on purpose and silence this warning.'
);
}
}
return {
query: (sql, params) => db.query(sql, params),
commit: async () => {},
rollback: async () => {}
};
}
/**
* Run `work(tx)` in a migration transaction, committing on success and rolling back on failure.
*
* @private
*/
async function inMigrationTransaction(db, config, work) {
const tx = await beginMigrationTransaction(db, config);
try {
await work(tx);
} catch (error) {
Eif (typeof tx.rollback === 'function') {
await tx.rollback();
}
throw error;
}
Eif (typeof tx.commit === 'function') {
await tx.commit();
}
}
function assertBatchCount(count) {
Iif (!Number.isSafeInteger(count) || count < 1) {
throw new Error(`Number of batches to roll back must be a positive integer, got ${count}`);
}
return count;
}
function migrationTimestamp() {
return new Date().toISOString().replace(/[-:T]/g, '').split('.')[0];
}
/**
* SQL literal for a column default. Strings are quoted with embedded quotes doubled;
* use `defaultRaw()` for expressions such as CURRENT_TIMESTAMP.
*
* @private
*/
function formatDefault(value) {
Iif (value === null) return 'NULL';
Iif (typeof value === 'number') {
if (!Number.isFinite(value)) throw new Error(`Invalid column default: ${value}`);
return String(value);
}
Iif (typeof value === 'bigint' || typeof value === 'boolean') return String(value);
Iif (value instanceof Date) return `'${value.toISOString()}'`;
Eif (typeof value === 'string') return `'${value.replace(/'/g, "''")}'`;
throw new Error(`Unsupported column default: ${String(value)}. Use defaultRaw() for SQL expressions.`);
}
function renderColumnType(column, dialect) {
if (column.type === 'DATETIME' && dialect === 'postgresql') return 'TIMESTAMP';
return column.type;
}
function renderColumn(column, dialect) {
let def;
if (column.primaryKey && column.autoIncrement) {
if (dialect === 'postgresql') {
def = `${column.name} SERIAL PRIMARY KEY`;
} else if (dialect === 'mysql') {
def = `${column.name} ${column.type} PRIMARY KEY AUTO_INCREMENT`;
} else {
def = `${column.name} ${column.type} PRIMARY KEY AUTOINCREMENT`;
}
} else {
def = `${column.name} ${renderColumnType(column, dialect)}`;
Iif (column.primaryKey) def += ' PRIMARY KEY';
}
if (!column.nullable) def += ' NOT NULL';
if (column.unique) def += ' UNIQUE';
if (column.defaultRaw !== undefined) {
def += ` DEFAULT ${column.defaultRaw}`;
} else if (column.default !== undefined) {
def += ` DEFAULT ${formatDefault(column.default)}`;
}
return def;
}
function renderForeignKeys(columns) {
return columns
.filter((column) => column.references)
.map((column) => {
const [table, referenced, ...rest] = String(column.references).split('.');
Iif (!referenced || rest.length > 0) {
throw new Error(`references() expects "table.column", got "${column.references}"`);
}
assertIdentifier(table, 'referenced table');
assertIdentifier(referenced, 'referenced column');
return `FOREIGN KEY (${column.name}) REFERENCES ${table}(${referenced})`;
});
}
function renderCreateTable(tableName, columns, dialect) {
const definitions = [
...columns.map((column) => renderColumn(column, dialect)),
...renderForeignKeys(columns)
];
return `CREATE TABLE ${tableName} (\n ${definitions.join(',\n ')}\n)`;
}
function renderAlteration(tableName, alteration) {
switch (alteration.type) {
case 'ADD':
return `ALTER TABLE ${tableName} ADD COLUMN ${alteration.name} ${alteration.columnType}`;
case 'DROP':
return `ALTER TABLE ${tableName} DROP COLUMN ${alteration.name}`;
default:
throw new Error(`Unsupported alteration type: ${alteration.type}`);
}
}
/**
* Chainable column modifiers returned by the table builders' column methods.
*
* @private
*/
function createColumnBuilder(column) {
return {
notNull() {
column.nullable = false;
return this;
},
unique() {
column.unique = true;
return this;
},
/** Literal default value; strings are quoted and escaped. */
default(value) {
column.default = value;
delete column.defaultRaw;
return this;
},
/** SQL expression default, e.g. defaultRaw('CURRENT_TIMESTAMP'). Not escaped. */
defaultRaw(expression) {
column.defaultRaw = expression;
delete column.default;
return this;
},
/** Foreign key to "table.column". */
references(foreignKey) {
column.references = foreignKey;
return this;
}
};
}
function tableBuilderDialect(options) {
return options && typeof options === 'object' ? options.dialect : undefined;
}
// ============================================================================
// Class API (@coherent.js/database/migration)
// ============================================================================
/**
* Migration runner
*
* @param {DatabaseManager} db - Database manager instance
* @param {Object} [config={}] - Migration configuration
* @param {string} [config.directory='./migrations'] - Migrations directory, relative to the working directory
* @param {string} [config.tableName='coherent_migrations'] - Tracking table
* @param {Array<{name: string, up: Function, down?: Function}>} [config.migrations] - Migrations to
* run instead of reading the directory
* @param {'postgresql'|'mysql'|'sqlite'} [config.dialect] - DDL dialect (defaults to `db.config.type`)
* @param {boolean} [config.transactional=true] - Run each migration in a transaction
*
* @example
* const migration = new Migration(db, {
* directory: './migrations',
* tableName: 'coherent_migrations'
* });
*
* const applied = await migration.run(); // ['20240101000000_create_users', ...]
*/
export class Migration {
constructor(db, config = {}) {
this.db = db;
this.config = { directory: './migrations', tableName: 'coherent_migrations', ...config };
assertIdentifier(this.config.tableName, 'migrations table');
this.appliedMigrations = new Set();
this.migrations = [];
}
/** @private */
get dialect() {
return resolveDialect(this.db, this.config);
}
/**
* Create the tracking table if needed and load applied and available migrations.
*/
async initialize() {
await this.ensureMigrationsTable();
await this.loadAppliedMigrations();
const provided = await this.loadMigrations();
if (Array.isArray(provided)) {
this.migrations = provided.map((migration) => {
Iif (!migration || typeof migration.name !== 'string') {
throw new Error('Every migration must have a name');
}
return { ...migration, applied: this.appliedMigrations.has(migration.name) };
});
} else {
await this.loadMigrationFiles();
}
}
/**
* Run pending migrations.
*
* @param {Object} [options={}]
* @param {boolean} [options.continueOnError=false] - Keep going after a failed migration
* @returns {Promise<string[]>} Names of the migrations applied
*/
async run(options = {}) {
await this.initialize();
const pendingMigrations = this.migrations.filter(m => !m.applied);
if (pendingMigrations.length === 0) {
return [];
}
const batch = await this.getNextBatchNumber();
const dialect = this.dialect;
const appliedMigrationsList = [];
for (const migration of pendingMigrations) {
try {
await inMigrationTransaction(this.db, this.config, async (tx) => {
Eif (typeof migration.up === 'function') {
await migration.up(new SchemaBuilder(tx, { dialect }));
}
await tx.query(
`INSERT INTO ${this.config.tableName} (migration, batch) VALUES (?, ?)`,
[migration.name, batch]
);
});
migration.applied = true;
this.appliedMigrations.add(migration.name);
appliedMigrationsList.push(migration.name);
} catch (_error) {
console.error(`Migration ${migration.name} failed: ${_error.message}`);
if (!options.continueOnError) {
throw _error;
}
}
}
return appliedMigrationsList;
}
/**
* Roll back the most recent batches.
*
* @param {number} [steps=1] - Number of batches to roll back
* @returns {Promise<string[]>} Names of the migrations rolled back, newest first
*/
async rollback(steps = 1) {
await this.initialize();
const batches = await this.getLastBatches(steps);
const dialect = this.dialect;
const rolledBackMigrations = [];
for (const batch of batches) {
for (const name of await this.getMigrationsInBatch(batch)) {
const migration = this.migrations.find(m => m.name === name);
if (!migration) {
console.warn(`Migration file not found: ${name}`);
continue;
}
if (!migration.down) {
console.warn(`No rollback method for migration: ${name}`);
continue;
}
try {
await inMigrationTransaction(this.db, this.config, async (tx) => {
await migration.down(new SchemaBuilder(tx, { dialect }));
await tx.query(`DELETE FROM ${this.config.tableName} WHERE migration = ?`, [name]);
});
} catch (_error) {
console.error(`Rollback ${name} failed: ${_error.message}`);
throw _error;
}
migration.applied = false;
this.appliedMigrations.delete(name);
rolledBackMigrations.push(name);
}
}
return rolledBackMigrations;
}
/**
* @returns {Promise<{pending: Array, completed: Array}>} Migration status
*/
async status() {
await this.initialize();
const summarize = migration => ({
name: migration.name,
applied: migration.applied,
file: migration.file || `${migration.name}.js`
});
return {
pending: this.migrations.filter(m => !m.applied).map(summarize),
completed: this.migrations.filter(m => m.applied).map(summarize)
};
}
/**
* Write a new migration file.
*
* @param {string} name - Migration name, e.g. create_users_table
* @returns {Promise<string>} Path of the created file
*/
async create(name, options = {}) {
const fileName = `${migrationTimestamp()}_${name}.js`;
const filePath = join(this.config.directory, fileName);
await this.ensureDirectory();
const isCreateTable = name.startsWith('create_') && name.endsWith('_table');
const template = this.getMigrationTemplate(name, { isCreateTable, ...options });
await writeFile(filePath, template);
return filePath;
}
async ensureDirectory() {
await mkdir(resolveDirectory(this.config.directory), { recursive: true });
}
getMigrationTemplate(name, options = {}) {
const { isCreateTable } = options;
const tableName = isCreateTable
? name.replace('create_', '').replace('_table', '')
: 'table_name';
if (isCreateTable) {
return `/**
* Migration: ${name}
*/
export async function up(schema) {
await schema.createTable('${tableName}', (table) => {
table.id();
table.timestamps();
});
}
export async function down(schema) {
await schema.dropTable('${tableName}');
}
`;
} else {
return `/**
* Migration: ${name}
*/
export async function up(schema) {
// Add your migration logic here
}
export async function down(schema) {
// Add your rollback logic here
}
`;
}
}
async getNextBatchNumber() {
const result = await this.db.query(`SELECT MAX(batch) as max_batch FROM ${this.config.tableName}`);
const maxBatch = result && result.rows && result.rows[0] ? result.rows[0].max_batch : 0;
return (maxBatch || 0) + 1;
}
/**
* @param {number} count - Number of batches
* @returns {Promise<number[]>} The most recent batch numbers, newest first
*/
async getLastBatches(count) {
const result = await this.db.query(
`SELECT DISTINCT batch FROM ${this.config.tableName} ORDER BY batch DESC LIMIT ${assertBatchCount(count)}`
);
return result && result.rows ? result.rows.map(row => row.batch) : [];
}
/**
* @param {number} batch - Batch number
* @returns {Promise<string[]>} Migrations in the batch, most recently applied first
*/
async getMigrationsInBatch(batch) {
const result = await this.db.query(
`SELECT migration FROM ${this.config.tableName} WHERE batch = ? ORDER BY id DESC`,
[batch]
);
return result && result.rows ? result.rows.map(row => row.migration) : [];
}
async ensureMigrationsTable() {
// Check if migrations table exists
try {
await this.db.query(`SELECT 1 FROM ${this.config.tableName} LIMIT 1`);
} catch {
await this.db.query(migrationsTableSQL(this.config.tableName, this.dialect));
}
}
async loadAppliedMigrations() {
const result = await this.db.query(`SELECT migration FROM ${this.config.tableName} ORDER BY id`);
this.appliedMigrations.clear();
Eif (result && result.rows) {
result.rows.forEach(row => {
this.appliedMigrations.add(row.migration);
});
}
}
/**
* Migrations to run instead of the directory's files. Returns `config.migrations`
* when it is an array, otherwise null (read the directory).
*
* @returns {Promise<Array|null>}
*/
async loadMigrations() {
return Array.isArray(this.config.migrations) ? this.config.migrations : null;
}
/**
* Load `<14-digit timestamp>_<name>.js` files from the migrations directory.
*
* @throws {Error} If a migration file cannot be imported
*/
async loadMigrationFiles() {
let files;
try {
files = await readdir(resolveDirectory(this.config.directory));
} catch (_error) {
Eif (_error.code === 'ENOENT') {
// Directory doesn't exist, initialize empty
this.migrations = [];
return;
}
throw _error;
}
const migrations = [];
for (const file of [...files].sort()) {
if (!file.endsWith('.js')) {
continue;
}
if (!/^\d{14}_/.test(file)) {
console.warn(`Failed to load migration ${file}: Invalid migration file name format`);
continue;
}
const migrationName = file.replace(/\.js$/, '');
const migration = await importMigration(this.config.directory, file);
migrations.push({
name: migrationName,
file,
up: migration.up || migration.default?.up,
down: migration.down || migration.default?.down,
applied: this.appliedMigrations.has(migrationName)
});
}
this.migrations = migrations;
}
}
export class SchemaBuilder {
/**
* @param {Object} db - Connection or transaction with query()
* @param {Object} [options={}]
* @param {'postgresql'|'mysql'|'sqlite'} [options.dialect] - DDL dialect
*/
constructor(db, options = {}) {
this.db = db;
this.dialect = options.dialect;
}
async createTable(tableName, callback) {
const table = new TableBuilder(tableName, { dialect: this.dialect });
callback(table);
const sql = table.toCreateSQL();
await this.db.query(sql);
return this;
}
async alterTable(tableName, callback) {
const table = new TableBuilder(tableName, { dialect: this.dialect });
callback(table);
const statements = table.toAlterSQL();
for (const sql of statements) {
await this.db.query(sql);
}
return this;
}
async dropTable(tableName) {
await this.db.query(`DROP TABLE IF EXISTS ${tableName}`);
return this;
}
async raw(sql, params = []) {
return await this.db.query(sql, params);
}
}
export class TableBuilder {
/**
* @param {string} tableName - Table name
* @param {Object} [options={}]
* @param {'postgresql'|'mysql'|'sqlite'} [options.dialect] - DDL dialect
*/
constructor(tableName, options = {}) {
this.tableName = tableName;
this.dialect = tableBuilderDialect(options);
this.columns = [];
this.alterations = [];
}
id(name = 'id') {
const column = {
name,
type: 'INTEGER',
primaryKey: true,
autoIncrement: true
};
this.columns.push(column);
return this;
}
string(name, length = 255) {
const column = {
name,
type: `VARCHAR(${length})`,
nullable: true
};
this.columns.push(column);
return createColumnBuilder(column);
}
text(name) {
const column = {
name,
type: 'TEXT',
nullable: true
};
this.columns.push(column);
return createColumnBuilder(column);
}
integer(name) {
const column = {
name,
type: 'INTEGER',
nullable: true
};
this.columns.push(column);
return createColumnBuilder(column);
}
boolean(name) {
const column = {
name,
type: 'BOOLEAN',
nullable: true,
default: false
};
this.columns.push(column);
return createColumnBuilder(column);
}
datetime(name) {
const column = {
name,
type: 'DATETIME',
nullable: true
};
this.columns.push(column);
return createColumnBuilder(column);
}
timestamps() {
this.datetime('created_at');
this.datetime('updated_at');
return this;
}
addColumn(name, type) {
this.alterations.push({
type: 'ADD',
name,
columnType: type
});
return this;
}
dropColumn(name) {
this.alterations.push({
type: 'DROP',
name
});
return this;
}
toCreateSQL() {
Iif (this.columns.length === 0) {
return `CREATE TABLE ${this.tableName} ();`;
}
return renderCreateTable(this.tableName, this.columns, this.dialect);
}
toAlterSQL() {
Iif (this.alterations.length === 0) {
return [`ALTER TABLE ${this.tableName};`];
}
return this.alterations.map(alteration => renderAlteration(this.tableName, alteration));
}
}
// ============================================================================
// Factory API (@coherent.js/database)
// ============================================================================
/**
* Create migration instance
*
* @param {DatabaseManager} db - Database manager instance
* @param {Object} [config={}] - Migration configuration
* @param {string} [config.directory='./migrations'] - Migrations directory, relative to the working directory
* @param {string} [config.tableName='coherent_migrations'] - Tracking table
* @param {'postgresql'|'mysql'|'sqlite'} [config.dialect] - DDL dialect (defaults to `db.config.type`)
* @param {boolean} [config.transactional=true] - Run each migration in a transaction
* @returns {Object} Migration instance
*
* @example
* const migration = createMigration(db, {
* directory: './migrations',
* tableName: 'coherent_migrations'
* });
*
* await migration.run();
*/
export function createMigration(db, config = {}) {
const migrationConfig = {
directory: './migrations',
tableName: 'coherent_migrations',
...config
};
assertIdentifier(migrationConfig.tableName, 'migrations table');
const migrations = [];
const appliedMigrations = new Set();
// Helper functions
async function ensureMigrationsTable() {
const tableName = migrationConfig.tableName;
try {
await db.query(`SELECT 1 FROM ${tableName} LIMIT 1`);
} catch {
await db.query(migrationsTableSQL(tableName, resolveDialect(db, migrationConfig)));
}
}
async function loadAppliedMigrations() {
const result = await db.query(`SELECT migration FROM ${migrationConfig.tableName} ORDER BY id`);
appliedMigrations.clear();
Eif (result && result.rows) {
result.rows.forEach(row => {
appliedMigrations.add(row.migration);
});
}
}
async function loadMigrationFiles() {
// Reload from scratch: status() followed by run() must not queue every migration twice
migrations.length = 0;
let files;
try {
files = await readdir(resolveDirectory(migrationConfig.directory));
} catch (_error) {
Eif (_error.code === 'ENOENT') {
return;
}
throw _error;
}
const migrationFiles = files
.filter(file => file.endsWith('.js'))
.sort();
for (const file of migrationFiles) {
const migrationName = file.replace(/\.js$/, '');
const migration = await importMigration(migrationConfig.directory, file);
migrations.push({
name: migrationName,
file: join(migrationConfig.directory, file),
up: migration.up || migration.default?.up,
down: migration.down || migration.default?.down,
applied: appliedMigrations.has(migrationName)
});
}
}
async function getNextBatchNumber() {
const result = await db.query(
`SELECT MAX(batch) as max_batch FROM ${migrationConfig.tableName}`
);
const maxBatch = result && result.rows && result.rows[0] ? result.rows[0].max_batch : 0;
return (maxBatch || 0) + 1;
}
async function getLastBatches(count) {
const result = await db.query(
`SELECT DISTINCT batch FROM ${migrationConfig.tableName} ORDER BY batch DESC LIMIT ${assertBatchCount(count)}`
);
return result && result.rows ? result.rows.map(row => row.batch) : [];
}
async function getMigrationsInBatch(batch) {
const result = await db.query(
`SELECT migration FROM ${migrationConfig.tableName} WHERE batch = ? ORDER BY id DESC`,
[batch]
);
return result && result.rows ? result.rows.map(row => row.migration) : [];
}
async function ensureDirectory(dirPath) {
await mkdir(resolveDirectory(dirPath), { recursive: true });
}
function getMigrationTemplate(name, options) {
const tableName = options.table || name.replace(/^create_/, '').replace(/_table$/, '');
if (name.startsWith('create_')) {
return `/**
* Migration: ${name}
* Created: ${new Date().toISOString()}
*/
export async function up(schema) {
await schema.createTable('${tableName}', (table) => {
table.id();
table.string('name').notNull();
table.timestamps();
});
}
export async function down(schema) {
await schema.dropTable('${tableName}');
}
`;
}
return `/**
* Migration: ${name}
* Created: ${new Date().toISOString()}
*/
export async function up(schema) {
// Add your migration logic here
}
export async function down(schema) {
// Add your rollback logic here
}
`;
}
return {
/**
* Initialize migration system
*/
async initialize() {
await ensureMigrationsTable();
await loadAppliedMigrations();
await loadMigrationFiles();
},
/**
* Run pending migrations
*/
async run(options = {}) {
await this.initialize();
const pendingMigrations = migrations.filter(m => !m.applied);
if (pendingMigrations.length === 0) {
return [];
}
const batch = await getNextBatchNumber();
const dialect = resolveDialect(db, migrationConfig);
const appliedMigrationsList = [];
for (const migration of pendingMigrations) {
try {
console.log(`Running migration: ${migration.name}`);
await inMigrationTransaction(db, migrationConfig, async (tx) => {
Eif (typeof migration.up === 'function') {
await migration.up(createSchemaBuilder(tx, { dialect }));
}
await tx.query(
`INSERT INTO ${migrationConfig.tableName} (migration, batch) VALUES (?, ?)`,
[migration.name, batch]
);
});
appliedMigrationsList.push(migration.name);
migration.applied = true;
console.log(`✓ Migration ${migration.name} completed`);
} catch (_error) {
console.error(`✗ Migration ${migration.name} failed: ${_error.message}`);
if (!options.continueOnError) {
throw _error;
}
}
}
return appliedMigrationsList;
},
/**
* Rollback migrations
*/
async rollback(steps = 1) {
await this.initialize();
const batches = await getLastBatches(steps);
Iif (batches.length === 0) {
return [];
}
const dialect = resolveDialect(db, migrationConfig);
const rolledBackMigrations = [];
for (const batch of batches) {
const batchMigrations = await getMigrationsInBatch(batch);
for (const migrationName of batchMigrations) {
const migration = migrations.find(m => m.name === migrationName);
Iif (!migration || !migration.down) {
console.warn(`Cannot rollback migration: ${migrationName}`);
continue;
}
try {
console.log(`Rolling back migration: ${migrationName}`);
await inMigrationTransaction(db, migrationConfig, async (tx) => {
await migration.down(createSchemaBuilder(tx, { dialect }));
await tx.query(
`DELETE FROM ${migrationConfig.tableName} WHERE migration = ?`,
[migrationName]
);
});
rolledBackMigrations.push(migrationName);
migration.applied = false;
console.log(`✓ Migration ${migrationName} rolled back`);
} catch (_error) {
console.error(`✗ Rollback ${migrationName} failed: ${_error.message}`);
throw _error;
}
}
}
return rolledBackMigrations;
},
/**
* Get migration status
*/
async status() {
await this.initialize();
return migrations.map(migration => ({
name: migration.name,
applied: migration.applied,
file: migration.file
}));
},
/**
* Create new migration file
*/
async create(name, options = {}) {
const fileName = `${migrationTimestamp()}_${name}.js`;
const filePath = join(migrationConfig.directory, fileName);
const template = getMigrationTemplate(name, options);
await ensureDirectory(migrationConfig.directory);
await writeFile(filePath, template);
console.log(`Created migration: ${filePath}`);
return filePath;
}
};
}
/**
* Create schema builder instance
*
* @param {Object} db - Connection or transaction with query()
* @param {Object} [options={}]
* @param {'postgresql'|'mysql'|'sqlite'} [options.dialect] - DDL dialect
*/
export function createSchemaBuilder(db, options = {}) {
return {
async createTable(tableName, callback) {
const table = createTableBuilder(tableName, options);
callback(table);
const sql = table.toCreateSQL();
await db.query(sql);
},
async alterTable(tableName, callback) {
const table = createTableBuilder(tableName, options);
callback(table);
const statements = table.toAlterSQL();
for (const sql of statements) {
await db.query(sql);
}
},
async dropTable(tableName) {
await db.query(`DROP TABLE IF EXISTS ${tableName}`);
},
async raw(sql, params = []) {
return await db.query(sql, params);
}
};
}
/**
* Create table builder instance
*
* @param {string} tableName - Table name
* @param {Object} [options={}]
* @param {'postgresql'|'mysql'|'sqlite'} [options.dialect] - DDL dialect
*/
export function createTableBuilder(tableName, options = {}) {
const dialect = tableBuilderDialect(options);
const columns = [];
const alterations = [];
function addColumn(column) {
columns.push(column);
return createColumnBuilder(column);
}
return {
id(name = 'id') {
columns.push({
name,
type: 'INTEGER',
primaryKey: true,
autoIncrement: true
});
return this;
},
string(name, length = 255) {
return addColumn({ name, type: `VARCHAR(${length})`, nullable: true });
},
text(name) {
return addColumn({ name, type: 'TEXT', nullable: true });
},
integer(name) {
return addColumn({ name, type: 'INTEGER', nullable: true });
},
boolean(name) {
return addColumn({ name, type: 'BOOLEAN', nullable: true, default: false });
},
datetime(name) {
return addColumn({ name, type: 'DATETIME', nullable: true });
},
timestamps() {
this.datetime('created_at').defaultRaw('CURRENT_TIMESTAMP');
this.datetime('updated_at').defaultRaw('CURRENT_TIMESTAMP');
return this;
},
addColumn(name, type) {
alterations.push({
type: 'ADD',
name,
columnType: type
});
return this;
},
dropColumn(name) {
alterations.push({
type: 'DROP',
name
});
return this;
},
toCreateSQL() {
return renderCreateTable(tableName, columns, dialect);
},
toAlterSQL() {
return alterations.map(alteration => renderAlteration(tableName, alteration));
}
};
}
|