@loomcore/api 0.1.22 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/README.md +49 -49
- package/dist/__tests__/postgres-test-migrations/001-create-test-entities-table.migration.js +24 -24
- package/dist/__tests__/postgres-test-migrations/002-create-categories-table.migration.js +14 -14
- package/dist/__tests__/postgres-test-migrations/003-create-products-table.migration.js +23 -23
- package/dist/__tests__/postgres-test-migrations/004-create-test-users-table.migration.js +27 -27
- package/dist/__tests__/postgres-test-migrations/005-create-test-items-table.migration.js +22 -22
- package/dist/__tests__/postgres.test-database.js +8 -8
- package/dist/databases/migrations/migration-runner.d.ts +15 -0
- package/dist/databases/migrations/migration-runner.js +118 -0
- package/dist/databases/postgres/commands/postgres-batch-update.command.js +7 -7
- package/dist/databases/postgres/commands/postgres-create-many.command.js +10 -10
- package/dist/databases/postgres/commands/postgres-create.command.js +4 -4
- package/dist/databases/postgres/commands/postgres-full-update-by-id.command.js +13 -13
- package/dist/databases/postgres/commands/postgres-partial-update-by-id.command.js +7 -7
- package/dist/databases/postgres/commands/postgres-update.command.js +7 -7
- package/dist/databases/postgres/migrations/001-create-migrations-table.migration.js +12 -12
- package/dist/databases/postgres/migrations/002-create-organizations-table.migration.js +24 -24
- package/dist/databases/postgres/migrations/003-create-users-table.migration.js +26 -26
- package/dist/databases/postgres/migrations/004-create-refresh-tokens-table.migration.js +18 -18
- package/dist/databases/postgres/migrations/005-create-meta-org.migration.js +7 -7
- package/dist/databases/postgres/migrations/006-create-admin-user.migration.js +3 -3
- package/dist/databases/postgres/migrations/setup-for-auth.migration.js +4 -4
- package/dist/databases/postgres/migrations/setup-for-multitenant.migration.js +4 -4
- package/dist/databases/postgres/utils/build-select-clause.js +6 -6
- package/dist/databases/postgres/utils/does-table-exist.util.js +4 -4
- package/package.json +88 -87
|
@@ -8,12 +8,12 @@ export class CreateCategoriesTableMigration {
|
|
|
8
8
|
async execute(_orgId) {
|
|
9
9
|
const _id = randomUUID().toString();
|
|
10
10
|
try {
|
|
11
|
-
await this.client.query(`
|
|
12
|
-
CREATE TABLE "categories" (
|
|
13
|
-
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
-
"_orgId" VARCHAR(255),
|
|
15
|
-
"name" VARCHAR(255) NOT NULL
|
|
16
|
-
)
|
|
11
|
+
await this.client.query(`
|
|
12
|
+
CREATE TABLE "categories" (
|
|
13
|
+
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
+
"_orgId" VARCHAR(255),
|
|
15
|
+
"name" VARCHAR(255) NOT NULL
|
|
16
|
+
)
|
|
17
17
|
`);
|
|
18
18
|
}
|
|
19
19
|
catch (error) {
|
|
@@ -21,8 +21,8 @@ export class CreateCategoriesTableMigration {
|
|
|
21
21
|
}
|
|
22
22
|
if (_orgId) {
|
|
23
23
|
try {
|
|
24
|
-
await this.client.query(`
|
|
25
|
-
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
24
|
+
await this.client.query(`
|
|
25
|
+
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
26
26
|
`);
|
|
27
27
|
}
|
|
28
28
|
catch (error) {
|
|
@@ -31,8 +31,8 @@ export class CreateCategoriesTableMigration {
|
|
|
31
31
|
}
|
|
32
32
|
else {
|
|
33
33
|
try {
|
|
34
|
-
await this.client.query(`
|
|
35
|
-
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
34
|
+
await this.client.query(`
|
|
35
|
+
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
36
36
|
`);
|
|
37
37
|
}
|
|
38
38
|
catch (error) {
|
|
@@ -43,16 +43,16 @@ export class CreateCategoriesTableMigration {
|
|
|
43
43
|
}
|
|
44
44
|
async revert(_orgId) {
|
|
45
45
|
try {
|
|
46
|
-
await this.client.query(`
|
|
47
|
-
DROP TABLE "categories";
|
|
46
|
+
await this.client.query(`
|
|
47
|
+
DROP TABLE "categories";
|
|
48
48
|
`);
|
|
49
49
|
}
|
|
50
50
|
catch (error) {
|
|
51
51
|
return { success: false, error: new Error(`Error dropping categories table: ${error.message}`) };
|
|
52
52
|
}
|
|
53
53
|
try {
|
|
54
|
-
await this.client.query(`
|
|
55
|
-
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
54
|
+
await this.client.query(`
|
|
55
|
+
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
56
56
|
`);
|
|
57
57
|
}
|
|
58
58
|
catch (error) {
|
|
@@ -8,21 +8,21 @@ export class CreateProductsTableMigration {
|
|
|
8
8
|
async execute(_orgId) {
|
|
9
9
|
const _id = randomUUID().toString();
|
|
10
10
|
try {
|
|
11
|
-
await this.client.query(`
|
|
12
|
-
CREATE TABLE "products" (
|
|
13
|
-
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
-
"_orgId" VARCHAR(255),
|
|
15
|
-
"name" VARCHAR(255) NOT NULL,
|
|
16
|
-
"description" TEXT,
|
|
17
|
-
"internalNumber" VARCHAR(255),
|
|
18
|
-
"categoryId" VARCHAR(255) NOT NULL REFERENCES "categories"("_id"),
|
|
19
|
-
"_created" TIMESTAMP NOT NULL,
|
|
20
|
-
"_createdBy" VARCHAR(255) NOT NULL,
|
|
21
|
-
"_updated" TIMESTAMP NOT NULL,
|
|
22
|
-
"_updatedBy" VARCHAR(255) NOT NULL,
|
|
23
|
-
"_deleted" TIMESTAMP,
|
|
24
|
-
"_deletedBy" VARCHAR(255)
|
|
25
|
-
)
|
|
11
|
+
await this.client.query(`
|
|
12
|
+
CREATE TABLE "products" (
|
|
13
|
+
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
+
"_orgId" VARCHAR(255),
|
|
15
|
+
"name" VARCHAR(255) NOT NULL,
|
|
16
|
+
"description" TEXT,
|
|
17
|
+
"internalNumber" VARCHAR(255),
|
|
18
|
+
"categoryId" VARCHAR(255) NOT NULL REFERENCES "categories"("_id"),
|
|
19
|
+
"_created" TIMESTAMP NOT NULL,
|
|
20
|
+
"_createdBy" VARCHAR(255) NOT NULL,
|
|
21
|
+
"_updated" TIMESTAMP NOT NULL,
|
|
22
|
+
"_updatedBy" VARCHAR(255) NOT NULL,
|
|
23
|
+
"_deleted" TIMESTAMP,
|
|
24
|
+
"_deletedBy" VARCHAR(255)
|
|
25
|
+
)
|
|
26
26
|
`);
|
|
27
27
|
}
|
|
28
28
|
catch (error) {
|
|
@@ -30,8 +30,8 @@ export class CreateProductsTableMigration {
|
|
|
30
30
|
}
|
|
31
31
|
if (_orgId) {
|
|
32
32
|
try {
|
|
33
|
-
await this.client.query(`
|
|
34
|
-
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
33
|
+
await this.client.query(`
|
|
34
|
+
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
35
35
|
`);
|
|
36
36
|
}
|
|
37
37
|
catch (error) {
|
|
@@ -40,8 +40,8 @@ export class CreateProductsTableMigration {
|
|
|
40
40
|
}
|
|
41
41
|
else {
|
|
42
42
|
try {
|
|
43
|
-
await this.client.query(`
|
|
44
|
-
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
43
|
+
await this.client.query(`
|
|
44
|
+
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
45
45
|
`);
|
|
46
46
|
}
|
|
47
47
|
catch (error) {
|
|
@@ -52,16 +52,16 @@ export class CreateProductsTableMigration {
|
|
|
52
52
|
}
|
|
53
53
|
async revert(_orgId) {
|
|
54
54
|
try {
|
|
55
|
-
await this.client.query(`
|
|
56
|
-
DROP TABLE "products";
|
|
55
|
+
await this.client.query(`
|
|
56
|
+
DROP TABLE "products";
|
|
57
57
|
`);
|
|
58
58
|
}
|
|
59
59
|
catch (error) {
|
|
60
60
|
return { success: false, error: new Error(`Error dropping products table: ${error.message}`) };
|
|
61
61
|
}
|
|
62
62
|
try {
|
|
63
|
-
await this.client.query(`
|
|
64
|
-
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
63
|
+
await this.client.query(`
|
|
64
|
+
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
65
65
|
`);
|
|
66
66
|
}
|
|
67
67
|
catch (error) {
|
|
@@ -8,25 +8,25 @@ export class CreateTestUsersTableMigration {
|
|
|
8
8
|
async execute(_orgId) {
|
|
9
9
|
const _id = randomUUID().toString();
|
|
10
10
|
try {
|
|
11
|
-
await this.client.query(`
|
|
12
|
-
CREATE TABLE "testUsers" (
|
|
13
|
-
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
-
"_orgId" VARCHAR(255),
|
|
15
|
-
"email" VARCHAR(255) NOT NULL,
|
|
16
|
-
"password" VARCHAR(255) NOT NULL,
|
|
17
|
-
"firstName" VARCHAR(255),
|
|
18
|
-
"lastName" VARCHAR(255),
|
|
19
|
-
"displayName" VARCHAR(255),
|
|
20
|
-
"roles" TEXT[],
|
|
21
|
-
"_lastLoggedIn" TIMESTAMP,
|
|
22
|
-
"_lastPasswordChange" TIMESTAMP,
|
|
23
|
-
"_created" TIMESTAMP NOT NULL,
|
|
24
|
-
"_createdBy" VARCHAR(255) NOT NULL,
|
|
25
|
-
"_updated" TIMESTAMP NOT NULL,
|
|
26
|
-
"_updatedBy" VARCHAR(255) NOT NULL,
|
|
27
|
-
"_deleted" TIMESTAMP,
|
|
28
|
-
"_deletedBy" VARCHAR(255)
|
|
29
|
-
)
|
|
11
|
+
await this.client.query(`
|
|
12
|
+
CREATE TABLE "testUsers" (
|
|
13
|
+
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
+
"_orgId" VARCHAR(255),
|
|
15
|
+
"email" VARCHAR(255) NOT NULL,
|
|
16
|
+
"password" VARCHAR(255) NOT NULL,
|
|
17
|
+
"firstName" VARCHAR(255),
|
|
18
|
+
"lastName" VARCHAR(255),
|
|
19
|
+
"displayName" VARCHAR(255),
|
|
20
|
+
"roles" TEXT[],
|
|
21
|
+
"_lastLoggedIn" TIMESTAMP,
|
|
22
|
+
"_lastPasswordChange" TIMESTAMP,
|
|
23
|
+
"_created" TIMESTAMP NOT NULL,
|
|
24
|
+
"_createdBy" VARCHAR(255) NOT NULL,
|
|
25
|
+
"_updated" TIMESTAMP NOT NULL,
|
|
26
|
+
"_updatedBy" VARCHAR(255) NOT NULL,
|
|
27
|
+
"_deleted" TIMESTAMP,
|
|
28
|
+
"_deletedBy" VARCHAR(255)
|
|
29
|
+
)
|
|
30
30
|
`);
|
|
31
31
|
}
|
|
32
32
|
catch (error) {
|
|
@@ -34,8 +34,8 @@ export class CreateTestUsersTableMigration {
|
|
|
34
34
|
}
|
|
35
35
|
if (_orgId) {
|
|
36
36
|
try {
|
|
37
|
-
await this.client.query(`
|
|
38
|
-
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
37
|
+
await this.client.query(`
|
|
38
|
+
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
39
39
|
`);
|
|
40
40
|
}
|
|
41
41
|
catch (error) {
|
|
@@ -44,8 +44,8 @@ export class CreateTestUsersTableMigration {
|
|
|
44
44
|
}
|
|
45
45
|
else {
|
|
46
46
|
try {
|
|
47
|
-
await this.client.query(`
|
|
48
|
-
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
47
|
+
await this.client.query(`
|
|
48
|
+
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
49
49
|
`);
|
|
50
50
|
}
|
|
51
51
|
catch (error) {
|
|
@@ -56,16 +56,16 @@ export class CreateTestUsersTableMigration {
|
|
|
56
56
|
}
|
|
57
57
|
async revert(_orgId) {
|
|
58
58
|
try {
|
|
59
|
-
await this.client.query(`
|
|
60
|
-
DROP TABLE "testUsers";
|
|
59
|
+
await this.client.query(`
|
|
60
|
+
DROP TABLE "testUsers";
|
|
61
61
|
`);
|
|
62
62
|
}
|
|
63
63
|
catch (error) {
|
|
64
64
|
return { success: false, error: new Error(`Error dropping test users table: ${error.message}`) };
|
|
65
65
|
}
|
|
66
66
|
try {
|
|
67
|
-
await this.client.query(`
|
|
68
|
-
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
67
|
+
await this.client.query(`
|
|
68
|
+
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
69
69
|
`);
|
|
70
70
|
}
|
|
71
71
|
catch (error) {
|
|
@@ -8,20 +8,20 @@ export class CreateTestItemsTableMigration {
|
|
|
8
8
|
async execute(_orgId) {
|
|
9
9
|
const _id = randomUUID().toString();
|
|
10
10
|
try {
|
|
11
|
-
await this.client.query(`
|
|
12
|
-
CREATE TABLE "testItems" (
|
|
13
|
-
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
-
"_orgId" VARCHAR(255),
|
|
15
|
-
"name" VARCHAR(255) NOT NULL,
|
|
16
|
-
"value" INTEGER,
|
|
17
|
-
"eventDate" TIMESTAMP,
|
|
18
|
-
"_created" TIMESTAMP NOT NULL,
|
|
19
|
-
"_createdBy" VARCHAR(255) NOT NULL,
|
|
20
|
-
"_updated" TIMESTAMP NOT NULL,
|
|
21
|
-
"_updatedBy" VARCHAR(255) NOT NULL,
|
|
22
|
-
"_deleted" TIMESTAMP,
|
|
23
|
-
"_deletedBy" VARCHAR(255)
|
|
24
|
-
)
|
|
11
|
+
await this.client.query(`
|
|
12
|
+
CREATE TABLE "testItems" (
|
|
13
|
+
"_id" VARCHAR(255) PRIMARY KEY,
|
|
14
|
+
"_orgId" VARCHAR(255),
|
|
15
|
+
"name" VARCHAR(255) NOT NULL,
|
|
16
|
+
"value" INTEGER,
|
|
17
|
+
"eventDate" TIMESTAMP,
|
|
18
|
+
"_created" TIMESTAMP NOT NULL,
|
|
19
|
+
"_createdBy" VARCHAR(255) NOT NULL,
|
|
20
|
+
"_updated" TIMESTAMP NOT NULL,
|
|
21
|
+
"_updatedBy" VARCHAR(255) NOT NULL,
|
|
22
|
+
"_deleted" TIMESTAMP,
|
|
23
|
+
"_deletedBy" VARCHAR(255)
|
|
24
|
+
)
|
|
25
25
|
`);
|
|
26
26
|
}
|
|
27
27
|
catch (error) {
|
|
@@ -29,8 +29,8 @@ export class CreateTestItemsTableMigration {
|
|
|
29
29
|
}
|
|
30
30
|
if (_orgId) {
|
|
31
31
|
try {
|
|
32
|
-
await this.client.query(`
|
|
33
|
-
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
32
|
+
await this.client.query(`
|
|
33
|
+
Insert into "migrations" ("_id", "_orgId", "index", "hasRun", "reverted") values ('${_id}', '${_orgId}', ${this.index}, TRUE, FALSE);
|
|
34
34
|
`);
|
|
35
35
|
}
|
|
36
36
|
catch (error) {
|
|
@@ -39,8 +39,8 @@ export class CreateTestItemsTableMigration {
|
|
|
39
39
|
}
|
|
40
40
|
else {
|
|
41
41
|
try {
|
|
42
|
-
await this.client.query(`
|
|
43
|
-
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
42
|
+
await this.client.query(`
|
|
43
|
+
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
44
44
|
`);
|
|
45
45
|
}
|
|
46
46
|
catch (error) {
|
|
@@ -51,16 +51,16 @@ export class CreateTestItemsTableMigration {
|
|
|
51
51
|
}
|
|
52
52
|
async revert(_orgId) {
|
|
53
53
|
try {
|
|
54
|
-
await this.client.query(`
|
|
55
|
-
DROP TABLE "testItems";
|
|
54
|
+
await this.client.query(`
|
|
55
|
+
DROP TABLE "testItems";
|
|
56
56
|
`);
|
|
57
57
|
}
|
|
58
58
|
catch (error) {
|
|
59
59
|
return { success: false, error: new Error(`Error dropping test items table: ${error.message}`) };
|
|
60
60
|
}
|
|
61
61
|
try {
|
|
62
|
-
await this.client.query(`
|
|
63
|
-
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
62
|
+
await this.client.query(`
|
|
63
|
+
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}' AND "_orgId" = '${_orgId}';
|
|
64
64
|
`);
|
|
65
65
|
}
|
|
66
66
|
catch (error) {
|
|
@@ -51,9 +51,9 @@ export class TestPostgresDatabase {
|
|
|
51
51
|
}
|
|
52
52
|
async createIndexes(client) {
|
|
53
53
|
try {
|
|
54
|
-
await client.query(`
|
|
55
|
-
CREATE INDEX IF NOT EXISTS email_index ON users (LOWER(email));
|
|
56
|
-
CREATE UNIQUE INDEX IF NOT EXISTS email_unique_index ON users (LOWER(email));
|
|
54
|
+
await client.query(`
|
|
55
|
+
CREATE INDEX IF NOT EXISTS email_index ON users (LOWER(email));
|
|
56
|
+
CREATE UNIQUE INDEX IF NOT EXISTS email_unique_index ON users (LOWER(email));
|
|
57
57
|
`);
|
|
58
58
|
}
|
|
59
59
|
catch (error) {
|
|
@@ -64,11 +64,11 @@ export class TestPostgresDatabase {
|
|
|
64
64
|
if (!this.postgresClient) {
|
|
65
65
|
throw new Error('Database not initialized');
|
|
66
66
|
}
|
|
67
|
-
const result = await this.postgresClient.query(`
|
|
68
|
-
SELECT "table_name"
|
|
69
|
-
FROM information_schema.tables
|
|
70
|
-
WHERE "table_schema" = 'public'
|
|
71
|
-
AND "table_type" = 'BASE TABLE'
|
|
67
|
+
const result = await this.postgresClient.query(`
|
|
68
|
+
SELECT "table_name"
|
|
69
|
+
FROM information_schema.tables
|
|
70
|
+
WHERE "table_schema" = 'public'
|
|
71
|
+
AND "table_type" = 'BASE TABLE'
|
|
72
72
|
`);
|
|
73
73
|
result.rows.forEach(async (row) => {
|
|
74
74
|
await this.postgresClient?.query(`TRUNCATE TABLE "${row.table_name}" RESTART IDENTITY CASCADE`);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type DbType = 'postgres' | 'mongo';
|
|
2
|
+
export interface MigrationConfig {
|
|
3
|
+
dbType: DbType;
|
|
4
|
+
dbUrl: string;
|
|
5
|
+
migrationsDir: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class MigrationRunner {
|
|
8
|
+
private config;
|
|
9
|
+
constructor(config: MigrationConfig);
|
|
10
|
+
private parseSql;
|
|
11
|
+
private getMigrator;
|
|
12
|
+
private wipeDatabase;
|
|
13
|
+
run(command: 'up' | 'down' | 'reset'): Promise<void>;
|
|
14
|
+
private closeConnection;
|
|
15
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { Umzug, MongoDBStorage } from 'umzug';
|
|
2
|
+
import { Pool } from 'pg';
|
|
3
|
+
import { MongoClient } from 'mongodb';
|
|
4
|
+
import fs from 'fs';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
export class MigrationRunner {
|
|
7
|
+
config;
|
|
8
|
+
constructor(config) {
|
|
9
|
+
this.config = config;
|
|
10
|
+
}
|
|
11
|
+
parseSql(content) {
|
|
12
|
+
const upMatch = content.match(/--\s*up\s([\s\S]+?)(?=--\s*down|$)/i);
|
|
13
|
+
const downMatch = content.match(/--\s*down\s([\s\S]+)/i);
|
|
14
|
+
return {
|
|
15
|
+
up: upMatch ? upMatch[1].trim() : '',
|
|
16
|
+
down: downMatch ? downMatch[1].trim() : ''
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
async getMigrator() {
|
|
20
|
+
const { dbType, dbUrl, migrationsDir } = this.config;
|
|
21
|
+
if (dbType === 'postgres') {
|
|
22
|
+
const pool = new Pool({ connectionString: dbUrl });
|
|
23
|
+
return new Umzug({
|
|
24
|
+
migrations: {
|
|
25
|
+
glob: path.join(migrationsDir, '*.sql'),
|
|
26
|
+
resolve: ({ name, path: filePath, context }) => {
|
|
27
|
+
const content = fs.readFileSync(filePath, 'utf8');
|
|
28
|
+
const { up, down } = this.parseSql(content);
|
|
29
|
+
return {
|
|
30
|
+
name,
|
|
31
|
+
up: async () => context.query(up),
|
|
32
|
+
down: async () => context.query(down)
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
context: pool,
|
|
37
|
+
storage: {
|
|
38
|
+
async executed({ context }) {
|
|
39
|
+
await context.query(`CREATE TABLE IF NOT EXISTS migrations (name text)`);
|
|
40
|
+
const result = await context.query(`SELECT name FROM migrations`);
|
|
41
|
+
return result.rows.map((r) => r.name);
|
|
42
|
+
},
|
|
43
|
+
async logMigration({ name, context }) {
|
|
44
|
+
await context.query(`INSERT INTO migrations (name) VALUES ($1)`, [name]);
|
|
45
|
+
},
|
|
46
|
+
async unlogMigration({ name, context }) {
|
|
47
|
+
await context.query(`DELETE FROM migrations WHERE name = $1`, [name]);
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
logger: console,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
else if (dbType === 'mongo') {
|
|
54
|
+
const client = await MongoClient.connect(dbUrl);
|
|
55
|
+
const db = client.db();
|
|
56
|
+
return new Umzug({
|
|
57
|
+
migrations: { glob: path.join(migrationsDir, '*.ts') },
|
|
58
|
+
context: db,
|
|
59
|
+
storage: new MongoDBStorage({ collection: db.collection('migrations') }),
|
|
60
|
+
logger: console,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`Unsupported DB_TYPE: ${dbType}`);
|
|
64
|
+
}
|
|
65
|
+
async wipeDatabase() {
|
|
66
|
+
const { dbType, dbUrl } = this.config;
|
|
67
|
+
console.log(`⚠️ Wiping ${dbType} database...`);
|
|
68
|
+
if (dbType === 'postgres') {
|
|
69
|
+
const pool = new Pool({ connectionString: dbUrl });
|
|
70
|
+
try {
|
|
71
|
+
await pool.query('DROP SCHEMA public CASCADE; CREATE SCHEMA public;');
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
await pool.end();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
else if (dbType === 'mongo') {
|
|
78
|
+
const client = await MongoClient.connect(dbUrl);
|
|
79
|
+
await client.db().dropDatabase();
|
|
80
|
+
await client.close();
|
|
81
|
+
}
|
|
82
|
+
console.log('✅ Database wiped.');
|
|
83
|
+
}
|
|
84
|
+
async run(command) {
|
|
85
|
+
try {
|
|
86
|
+
if (command === 'reset') {
|
|
87
|
+
await this.wipeDatabase();
|
|
88
|
+
console.log('🚀 Restarting migrations...');
|
|
89
|
+
const migrator = await this.getMigrator();
|
|
90
|
+
await migrator.up();
|
|
91
|
+
await this.closeConnection(migrator);
|
|
92
|
+
console.log('✅ Reset complete.');
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const migrator = await this.getMigrator();
|
|
96
|
+
switch (command) {
|
|
97
|
+
case 'up':
|
|
98
|
+
await migrator.up();
|
|
99
|
+
console.log('✅ Migrations up to date.');
|
|
100
|
+
break;
|
|
101
|
+
case 'down':
|
|
102
|
+
await migrator.down();
|
|
103
|
+
console.log('✅ Reverted last migration.');
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
await this.closeConnection(migrator);
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
console.error('❌ Migration failed:', err);
|
|
110
|
+
process.exit(1);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async closeConnection(migrator) {
|
|
114
|
+
if (this.config.dbType === 'postgres') {
|
|
115
|
+
await migrator.context.end();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -26,10 +26,10 @@ export async function batchUpdate(client, entities, operations, queryObject, plu
|
|
|
26
26
|
const setClause = columns.map((col, index) => `${col} = $${index + 1}`).join(', ');
|
|
27
27
|
queryObject.filters._id = { eq: _id };
|
|
28
28
|
const { whereClause } = buildWhereClause(queryObject, values);
|
|
29
|
-
const query = `
|
|
30
|
-
UPDATE "${pluralResourceName}"
|
|
31
|
-
SET ${setClause}
|
|
32
|
-
${whereClause}
|
|
29
|
+
const query = `
|
|
30
|
+
UPDATE "${pluralResourceName}"
|
|
31
|
+
SET ${setClause}
|
|
32
|
+
${whereClause}
|
|
33
33
|
`;
|
|
34
34
|
await client.query(query, values);
|
|
35
35
|
}
|
|
@@ -39,9 +39,9 @@ export async function batchUpdate(client, entities, operations, queryObject, plu
|
|
|
39
39
|
const tablePrefix = hasJoins ? pluralResourceName : undefined;
|
|
40
40
|
queryObject.filters._id = { in: entityIds };
|
|
41
41
|
const { whereClause, values } = buildWhereClause(queryObject, [], tablePrefix);
|
|
42
|
-
const selectQuery = `
|
|
43
|
-
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
44
|
-
${whereClause}
|
|
42
|
+
const selectQuery = `
|
|
43
|
+
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
44
|
+
${whereClause}
|
|
45
45
|
`;
|
|
46
46
|
const result = await client.query(selectQuery, values);
|
|
47
47
|
return result.rows;
|
|
@@ -12,12 +12,12 @@ export async function createMany(client, pluralResourceName, entities) {
|
|
|
12
12
|
entity._id = entity._id ?? randomUUID().toString();
|
|
13
13
|
return entity;
|
|
14
14
|
});
|
|
15
|
-
const tableColumns = await client.query(`
|
|
16
|
-
SELECT column_name, column_default
|
|
17
|
-
FROM information_schema.columns
|
|
18
|
-
WHERE table_schema = current_schema()
|
|
19
|
-
AND table_name = $1
|
|
20
|
-
ORDER BY ordinal_position
|
|
15
|
+
const tableColumns = await client.query(`
|
|
16
|
+
SELECT column_name, column_default
|
|
17
|
+
FROM information_schema.columns
|
|
18
|
+
WHERE table_schema = current_schema()
|
|
19
|
+
AND table_name = $1
|
|
20
|
+
ORDER BY ordinal_position
|
|
21
21
|
`, [pluralResourceName]);
|
|
22
22
|
if (tableColumns.rows.length === 0) {
|
|
23
23
|
throw new BadRequestError(`Unable to resolve columns for ${pluralResourceName}`);
|
|
@@ -39,10 +39,10 @@ export async function createMany(client, pluralResourceName, entities) {
|
|
|
39
39
|
valueClauses.push(`(${placeholders})`);
|
|
40
40
|
allValues.push(...values);
|
|
41
41
|
});
|
|
42
|
-
const query = `
|
|
43
|
-
INSERT INTO "${pluralResourceName}" (${tableColumns.rows.map(column => `"${column.column_name}"`).join(', ')})
|
|
44
|
-
VALUES ${valueClauses.join(', ')}
|
|
45
|
-
RETURNING _id
|
|
42
|
+
const query = `
|
|
43
|
+
INSERT INTO "${pluralResourceName}" (${tableColumns.rows.map(column => `"${column.column_name}"`).join(', ')})
|
|
44
|
+
VALUES ${valueClauses.join(', ')}
|
|
45
|
+
RETURNING _id
|
|
46
46
|
`;
|
|
47
47
|
const result = await client.query(query, allValues);
|
|
48
48
|
if (result.rows.length !== entitiesWithIds.length) {
|
|
@@ -6,10 +6,10 @@ export async function create(client, pluralResourceName, entity) {
|
|
|
6
6
|
entity._id = entity._id ?? randomUUID().toString();
|
|
7
7
|
const { columns, values } = columnsAndValuesFromEntity(entity);
|
|
8
8
|
const placeholders = columns.map((_, index) => `$${index + 1}`).join(', ');
|
|
9
|
-
const query = `
|
|
10
|
-
INSERT INTO "${pluralResourceName}" (${columns.join(', ')})
|
|
11
|
-
VALUES (${placeholders})
|
|
12
|
-
RETURNING _id
|
|
9
|
+
const query = `
|
|
10
|
+
INSERT INTO "${pluralResourceName}" (${columns.join(', ')})
|
|
11
|
+
VALUES (${placeholders})
|
|
12
|
+
RETURNING _id
|
|
13
13
|
`;
|
|
14
14
|
const result = await client.query(query, values);
|
|
15
15
|
if (result.rows.length === 0) {
|
|
@@ -2,12 +2,12 @@ import { BadRequestError, IdNotFoundError } from "../../../errors/index.js";
|
|
|
2
2
|
import { buildJoinClauses } from '../utils/build-join-clauses.js';
|
|
3
3
|
export async function fullUpdateById(client, operations, id, entity, pluralResourceName) {
|
|
4
4
|
try {
|
|
5
|
-
const tableColumns = await client.query(`
|
|
6
|
-
SELECT column_name, column_default
|
|
7
|
-
FROM information_schema.columns
|
|
8
|
-
WHERE table_schema = current_schema()
|
|
9
|
-
AND table_name = $1
|
|
10
|
-
ORDER BY ordinal_position
|
|
5
|
+
const tableColumns = await client.query(`
|
|
6
|
+
SELECT column_name, column_default
|
|
7
|
+
FROM information_schema.columns
|
|
8
|
+
WHERE table_schema = current_schema()
|
|
9
|
+
AND table_name = $1
|
|
10
|
+
ORDER BY ordinal_position
|
|
11
11
|
`, [pluralResourceName]);
|
|
12
12
|
if (tableColumns.rows.length === 0) {
|
|
13
13
|
throw new BadRequestError(`Unable to resolve columns for ${pluralResourceName}`);
|
|
@@ -40,19 +40,19 @@ export async function fullUpdateById(client, operations, id, entity, pluralResou
|
|
|
40
40
|
throw new BadRequestError('Cannot perform full update with no fields to update');
|
|
41
41
|
}
|
|
42
42
|
const setClause = updateColumns.join(', ');
|
|
43
|
-
const query = `
|
|
44
|
-
UPDATE "${pluralResourceName}"
|
|
45
|
-
SET ${setClause}
|
|
46
|
-
WHERE "_id" = $${paramIndex}
|
|
43
|
+
const query = `
|
|
44
|
+
UPDATE "${pluralResourceName}"
|
|
45
|
+
SET ${setClause}
|
|
46
|
+
WHERE "_id" = $${paramIndex}
|
|
47
47
|
`;
|
|
48
48
|
const result = await client.query(query, [...updateValues, id]);
|
|
49
49
|
if (result.rowCount === 0) {
|
|
50
50
|
throw new IdNotFoundError();
|
|
51
51
|
}
|
|
52
52
|
const joinClauses = buildJoinClauses(operations);
|
|
53
|
-
const selectQuery = `
|
|
54
|
-
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
55
|
-
WHERE "_id" = $1 LIMIT 1
|
|
53
|
+
const selectQuery = `
|
|
54
|
+
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
55
|
+
WHERE "_id" = $1 LIMIT 1
|
|
56
56
|
`;
|
|
57
57
|
const selectResult = await client.query(selectQuery, [id]);
|
|
58
58
|
if (selectResult.rows.length === 0) {
|
|
@@ -10,19 +10,19 @@ export async function partialUpdateById(client, operations, id, entity, pluralRe
|
|
|
10
10
|
throw new BadRequestError('Cannot perform partial update with no fields to update');
|
|
11
11
|
}
|
|
12
12
|
const setClause = updateColumns.map((col, index) => `${col} = $${index + 1}`).join(', ');
|
|
13
|
-
const query = `
|
|
14
|
-
UPDATE "${pluralResourceName}"
|
|
15
|
-
SET ${setClause}
|
|
16
|
-
WHERE "_id" = $${updateValues.length + 1}
|
|
13
|
+
const query = `
|
|
14
|
+
UPDATE "${pluralResourceName}"
|
|
15
|
+
SET ${setClause}
|
|
16
|
+
WHERE "_id" = $${updateValues.length + 1}
|
|
17
17
|
`;
|
|
18
18
|
const result = await client.query(query, [...updateValues, id]);
|
|
19
19
|
if (result.rowCount === 0) {
|
|
20
20
|
throw new IdNotFoundError();
|
|
21
21
|
}
|
|
22
22
|
const joinClauses = buildJoinClauses(operations);
|
|
23
|
-
const selectQuery = `
|
|
24
|
-
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
25
|
-
WHERE "_id" = $1 LIMIT 1
|
|
23
|
+
const selectQuery = `
|
|
24
|
+
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
25
|
+
WHERE "_id" = $1 LIMIT 1
|
|
26
26
|
`;
|
|
27
27
|
const selectResult = await client.query(selectQuery, [id]);
|
|
28
28
|
if (selectResult.rows.length === 0) {
|
|
@@ -17,10 +17,10 @@ export async function update(client, queryObject, entity, operations, pluralReso
|
|
|
17
17
|
const originalIndex = parseInt(num, 10);
|
|
18
18
|
return `$${originalIndex + updateValues.length}`;
|
|
19
19
|
});
|
|
20
|
-
const updateQuery = `
|
|
21
|
-
UPDATE "${pluralResourceName}"
|
|
22
|
-
SET ${setClause}
|
|
23
|
-
${whereClauseWithAdjustedParams}
|
|
20
|
+
const updateQuery = `
|
|
21
|
+
UPDATE "${pluralResourceName}"
|
|
22
|
+
SET ${setClause}
|
|
23
|
+
${whereClauseWithAdjustedParams}
|
|
24
24
|
`;
|
|
25
25
|
const allUpdateValues = [...updateValues, ...whereValues];
|
|
26
26
|
const result = await client.query(updateQuery, allUpdateValues);
|
|
@@ -29,9 +29,9 @@ export async function update(client, queryObject, entity, operations, pluralReso
|
|
|
29
29
|
}
|
|
30
30
|
const joinClauses = buildJoinClauses(operations);
|
|
31
31
|
const orderByClause = buildOrderByClause(queryObject);
|
|
32
|
-
const selectQuery = `
|
|
33
|
-
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
34
|
-
${whereClause} ${orderByClause}
|
|
32
|
+
const selectQuery = `
|
|
33
|
+
SELECT * FROM "${pluralResourceName}" ${joinClauses}
|
|
34
|
+
${whereClause} ${orderByClause}
|
|
35
35
|
`.trim();
|
|
36
36
|
const selectResult = await client.query(selectQuery, whereValues);
|
|
37
37
|
return selectResult.rows;
|