@loomcore/api 0.1.51 → 0.1.53
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/100-create-test-entities-table.migration.js +22 -22
- package/dist/__tests__/postgres-test-migrations/101-create-categories-table.migration.js +12 -12
- package/dist/__tests__/postgres-test-migrations/102-create-products-table.migration.js +21 -21
- package/dist/__tests__/postgres-test-migrations/103-create-test-items-table.migration.js +20 -20
- package/dist/__tests__/postgres.test-database.js +8 -8
- package/dist/databases/migrations/migration-runner.d.ts +3 -1
- package/dist/databases/migrations/migration-runner.js +90 -42
- package/dist/databases/mongo-db/migrations/mongo-foundational.d.ts +12 -0
- package/dist/databases/mongo-db/migrations/mongo-foundational.js +30 -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 +9 -9
- package/dist/databases/postgres/migrations/006-create-admin-user.migration.js +3 -3
- package/dist/databases/postgres/migrations/007-create-roles-table.migration.js +14 -14
- package/dist/databases/postgres/migrations/008-create-user-roles-table.migration.js +24 -24
- package/dist/databases/postgres/migrations/009-create-features-table.migration.js +14 -14
- package/dist/databases/postgres/migrations/010-create-authorizations-table.migration.js +26 -26
- package/dist/databases/postgres/migrations/011-create-admin-authorization.migration.js +44 -44
- package/dist/databases/postgres/migrations/database-builder.js +4 -4
- package/dist/databases/postgres/migrations/postgres-foundational.d.ts +12 -0
- package/dist/databases/postgres/migrations/postgres-foundational.js +47 -0
- package/dist/databases/postgres/postgres.database.js +17 -17
- 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 -88
|
@@ -8,29 +8,29 @@ export class CreateProductsTableMigration {
|
|
|
8
8
|
async execute() {
|
|
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) {
|
|
29
29
|
return { success: false, error: new Error(`Error creating products table: ${error.message}`) };
|
|
30
30
|
}
|
|
31
31
|
try {
|
|
32
|
-
await this.client.query(`
|
|
33
|
-
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
32
|
+
await this.client.query(`
|
|
33
|
+
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
34
34
|
`);
|
|
35
35
|
}
|
|
36
36
|
catch (error) {
|
|
@@ -40,16 +40,16 @@ export class CreateProductsTableMigration {
|
|
|
40
40
|
}
|
|
41
41
|
async revert() {
|
|
42
42
|
try {
|
|
43
|
-
await this.client.query(`
|
|
44
|
-
DROP TABLE "products";
|
|
43
|
+
await this.client.query(`
|
|
44
|
+
DROP TABLE "products";
|
|
45
45
|
`);
|
|
46
46
|
}
|
|
47
47
|
catch (error) {
|
|
48
48
|
return { success: false, error: new Error(`Error dropping products table: ${error.message}`) };
|
|
49
49
|
}
|
|
50
50
|
try {
|
|
51
|
-
await this.client.query(`
|
|
52
|
-
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}';
|
|
51
|
+
await this.client.query(`
|
|
52
|
+
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}';
|
|
53
53
|
`);
|
|
54
54
|
}
|
|
55
55
|
catch (error) {
|
|
@@ -8,28 +8,28 @@ export class CreateTestItemsTableMigration {
|
|
|
8
8
|
async execute() {
|
|
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) {
|
|
28
28
|
return { success: false, error: new Error(`Error creating test items table: ${error.message}`) };
|
|
29
29
|
}
|
|
30
30
|
try {
|
|
31
|
-
await this.client.query(`
|
|
32
|
-
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
31
|
+
await this.client.query(`
|
|
32
|
+
Insert into "migrations" ("_id", "index", "hasRun", "reverted") values ('${_id}', ${this.index}, TRUE, FALSE);
|
|
33
33
|
`);
|
|
34
34
|
}
|
|
35
35
|
catch (error) {
|
|
@@ -39,16 +39,16 @@ export class CreateTestItemsTableMigration {
|
|
|
39
39
|
}
|
|
40
40
|
async revert() {
|
|
41
41
|
try {
|
|
42
|
-
await this.client.query(`
|
|
43
|
-
DROP TABLE "testItems";
|
|
42
|
+
await this.client.query(`
|
|
43
|
+
DROP TABLE "testItems";
|
|
44
44
|
`);
|
|
45
45
|
}
|
|
46
46
|
catch (error) {
|
|
47
47
|
return { success: false, error: new Error(`Error dropping test items table: ${error.message}`) };
|
|
48
48
|
}
|
|
49
49
|
try {
|
|
50
|
-
await this.client.query(`
|
|
51
|
-
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}';
|
|
50
|
+
await this.client.query(`
|
|
51
|
+
Update "migrations" SET "reverted" = TRUE WHERE "index" = '${this.index}';
|
|
52
52
|
`);
|
|
53
53
|
}
|
|
54
54
|
catch (error) {
|
|
@@ -39,9 +39,9 @@ export class TestPostgresDatabase {
|
|
|
39
39
|
}
|
|
40
40
|
async createIndexes(client) {
|
|
41
41
|
try {
|
|
42
|
-
await client.query(`
|
|
43
|
-
CREATE INDEX IF NOT EXISTS email_index ON users (LOWER(email));
|
|
44
|
-
CREATE UNIQUE INDEX IF NOT EXISTS email_unique_index ON users (LOWER(email));
|
|
42
|
+
await client.query(`
|
|
43
|
+
CREATE INDEX IF NOT EXISTS email_index ON users (LOWER(email));
|
|
44
|
+
CREATE UNIQUE INDEX IF NOT EXISTS email_unique_index ON users (LOWER(email));
|
|
45
45
|
`);
|
|
46
46
|
}
|
|
47
47
|
catch (error) {
|
|
@@ -52,11 +52,11 @@ export class TestPostgresDatabase {
|
|
|
52
52
|
if (!this.postgresClient) {
|
|
53
53
|
throw new Error('Database not initialized');
|
|
54
54
|
}
|
|
55
|
-
const result = await this.postgresClient.query(`
|
|
56
|
-
SELECT "table_name"
|
|
57
|
-
FROM information_schema.tables
|
|
58
|
-
WHERE "table_schema" = 'public'
|
|
59
|
-
AND "table_type" = 'BASE TABLE'
|
|
55
|
+
const result = await this.postgresClient.query(`
|
|
56
|
+
SELECT "table_name"
|
|
57
|
+
FROM information_schema.tables
|
|
58
|
+
WHERE "table_schema" = 'public'
|
|
59
|
+
AND "table_type" = 'BASE TABLE'
|
|
60
60
|
`);
|
|
61
61
|
result.rows.forEach(async (row) => {
|
|
62
62
|
await this.postgresClient?.query(`TRUNCATE TABLE "${row.table_name}" RESTART IDENTITY CASCADE`);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { IBaseApiConfig } from '../../models/base-api-config.interface.js';
|
|
2
2
|
export declare class MigrationRunner {
|
|
3
|
+
private config;
|
|
3
4
|
private dbType;
|
|
4
5
|
private dbUrl;
|
|
5
6
|
private migrationsDir;
|
|
@@ -9,8 +10,9 @@ export declare class MigrationRunner {
|
|
|
9
10
|
private getTimestamp;
|
|
10
11
|
private parseSql;
|
|
11
12
|
private getMigrator;
|
|
13
|
+
private loadFileMigrations;
|
|
12
14
|
private wipeDatabase;
|
|
13
|
-
run(command
|
|
15
|
+
run(command?: 'up' | 'down' | 'reset', target?: string): Promise<void>;
|
|
14
16
|
private closeConnection;
|
|
15
17
|
create(name: string): Promise<void>;
|
|
16
18
|
}
|
|
@@ -5,13 +5,17 @@ import fs from 'fs';
|
|
|
5
5
|
import path from 'path';
|
|
6
6
|
import { buildMongoUrl } from '../mongo-db/utils/build-mongo-url.util.js';
|
|
7
7
|
import { buildPostgresUrl } from '../postgres/utils/build-postgres-url.util.js';
|
|
8
|
+
import { getPostgresFoundational } from '../postgres/migrations/postgres-foundational.js';
|
|
9
|
+
import { getMongoFoundational } from '../mongo-db/migrations/mongo-foundational.js';
|
|
8
10
|
export class MigrationRunner {
|
|
11
|
+
config;
|
|
9
12
|
dbType;
|
|
10
13
|
dbUrl;
|
|
11
14
|
migrationsDir;
|
|
12
15
|
primaryTimezone;
|
|
13
16
|
dbConnection;
|
|
14
17
|
constructor(config) {
|
|
18
|
+
this.config = config;
|
|
15
19
|
this.dbType = config.app.dbType || 'mongodb';
|
|
16
20
|
this.dbUrl = this.dbType === 'postgres' ? buildPostgresUrl(config) : buildMongoUrl(config);
|
|
17
21
|
this.migrationsDir = path.join(process.cwd(), 'database', 'migrations');
|
|
@@ -50,26 +54,21 @@ export class MigrationRunner {
|
|
|
50
54
|
if (this.dbType === 'postgres') {
|
|
51
55
|
const pool = new Pool({ connectionString: this.dbUrl });
|
|
52
56
|
this.dbConnection = pool;
|
|
53
|
-
const globPattern = path.join(this.migrationsDir, '*.sql').replace(/\\/g, '/');
|
|
54
|
-
console.log(`🔎 Looking for migrations in: ${globPattern}`);
|
|
55
57
|
return new Umzug({
|
|
56
|
-
migrations: {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
}
|
|
58
|
+
migrations: async () => {
|
|
59
|
+
const foundationals = getPostgresFoundational(this.config).map(m => ({
|
|
60
|
+
name: m.name,
|
|
61
|
+
up: async () => {
|
|
62
|
+
console.log(` Running [LIBRARY] ${m.name}...`);
|
|
63
|
+
await m.up({ context: pool });
|
|
64
|
+
},
|
|
65
|
+
down: async () => {
|
|
66
|
+
console.log(` Running [LIBRARY] Undo ${m.name}...`);
|
|
67
|
+
await m.down({ context: pool });
|
|
68
|
+
}
|
|
69
|
+
}));
|
|
70
|
+
const fileMigrations = this.loadFileMigrations(this.migrationsDir, 'sql', pool);
|
|
71
|
+
return [...foundationals, ...fileMigrations].sort((a, b) => a.name.localeCompare(b.name));
|
|
73
72
|
},
|
|
74
73
|
context: pool,
|
|
75
74
|
storage: {
|
|
@@ -95,7 +94,21 @@ export class MigrationRunner {
|
|
|
95
94
|
const globPattern = path.join(this.migrationsDir, '*.ts').replace(/\\/g, '/');
|
|
96
95
|
console.log(`🔎 Looking for migrations in: ${globPattern}`);
|
|
97
96
|
return new Umzug({
|
|
98
|
-
migrations:
|
|
97
|
+
migrations: async () => {
|
|
98
|
+
const foundationals = getMongoFoundational(this.config).map(m => ({
|
|
99
|
+
name: m.name,
|
|
100
|
+
up: async () => {
|
|
101
|
+
console.log(` Running [LIBRARY] ${m.name}...`);
|
|
102
|
+
await m.up({ context: db });
|
|
103
|
+
},
|
|
104
|
+
down: async () => {
|
|
105
|
+
console.log(` Running [LIBRARY] Undo ${m.name}...`);
|
|
106
|
+
await m.down({ context: db });
|
|
107
|
+
}
|
|
108
|
+
}));
|
|
109
|
+
const fileMigrations = this.loadFileMigrations(this.migrationsDir, 'ts', db);
|
|
110
|
+
return [...foundationals, ...fileMigrations].sort((a, b) => a.name.localeCompare(b.name));
|
|
111
|
+
},
|
|
99
112
|
context: db,
|
|
100
113
|
storage: new MongoDBStorage({ collection: db.collection('migrations') }),
|
|
101
114
|
logger: console,
|
|
@@ -103,6 +116,41 @@ export class MigrationRunner {
|
|
|
103
116
|
}
|
|
104
117
|
throw new Error(`Unsupported DB_TYPE: ${this.dbType}`);
|
|
105
118
|
}
|
|
119
|
+
loadFileMigrations(dir, extension, context) {
|
|
120
|
+
return fs.readdirSync(dir)
|
|
121
|
+
.filter(f => f.endsWith(`.${extension}`))
|
|
122
|
+
.map(f => {
|
|
123
|
+
const fullPath = path.join(dir, f);
|
|
124
|
+
if (extension === 'sql') {
|
|
125
|
+
const content = fs.readFileSync(fullPath, 'utf8');
|
|
126
|
+
const { up, down } = this.parseSql(f, content);
|
|
127
|
+
return {
|
|
128
|
+
name: f,
|
|
129
|
+
up: async () => {
|
|
130
|
+
console.log(` Running [FILE] ${f}...`);
|
|
131
|
+
await context.query(up);
|
|
132
|
+
},
|
|
133
|
+
down: async () => {
|
|
134
|
+
console.log(` Running [FILE] Undo ${f}...`);
|
|
135
|
+
await context.query(down);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
return {
|
|
141
|
+
name: f,
|
|
142
|
+
up: async () => {
|
|
143
|
+
const mod = await import(fullPath);
|
|
144
|
+
await mod.up({ context });
|
|
145
|
+
},
|
|
146
|
+
down: async () => {
|
|
147
|
+
const mod = await import(fullPath);
|
|
148
|
+
await mod.down({ context });
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
106
154
|
async wipeDatabase() {
|
|
107
155
|
console.log(`⚠️ Wiping ${this.dbType} database...`);
|
|
108
156
|
if (this.dbType === 'postgres') {
|
|
@@ -121,7 +169,7 @@ export class MigrationRunner {
|
|
|
121
169
|
}
|
|
122
170
|
console.log('✅ Database wiped.');
|
|
123
171
|
}
|
|
124
|
-
async run(command, target) {
|
|
172
|
+
async run(command = 'up', target) {
|
|
125
173
|
try {
|
|
126
174
|
if (command === 'reset') {
|
|
127
175
|
await this.wipeDatabase();
|
|
@@ -189,31 +237,31 @@ export class MigrationRunner {
|
|
|
189
237
|
let content = '';
|
|
190
238
|
if (this.dbType === 'postgres') {
|
|
191
239
|
extension = 'sql';
|
|
192
|
-
content = `-- Migration: ${safeName}
|
|
193
|
-
-- Created: ${new Date().toISOString()}
|
|
194
|
-
|
|
195
|
-
-- up
|
|
196
|
-
-- Write your CREATE/ALTER statements here...
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
-- down
|
|
200
|
-
-- Write your DROP/UNDO statements here...
|
|
240
|
+
content = `-- Migration: ${safeName}
|
|
241
|
+
-- Created: ${new Date().toISOString()}
|
|
242
|
+
|
|
243
|
+
-- up
|
|
244
|
+
-- Write your CREATE/ALTER statements here...
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
-- down
|
|
248
|
+
-- Write your DROP/UNDO statements here...
|
|
201
249
|
`;
|
|
202
250
|
}
|
|
203
251
|
else {
|
|
204
252
|
extension = 'ts';
|
|
205
|
-
content = `import { Db } from 'mongodb';
|
|
206
|
-
|
|
207
|
-
// Migration: ${safeName}
|
|
208
|
-
// Created: ${new Date().toISOString()}
|
|
209
|
-
|
|
210
|
-
export const up = async ({ context: db }: { context: Db }) => {
|
|
211
|
-
// await db.collection('...')....
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
export const down = async ({ context: db }: { context: Db }) => {
|
|
215
|
-
// await db.collection('...')....
|
|
216
|
-
};
|
|
253
|
+
content = `import { Db } from 'mongodb';
|
|
254
|
+
|
|
255
|
+
// Migration: ${safeName}
|
|
256
|
+
// Created: ${new Date().toISOString()}
|
|
257
|
+
|
|
258
|
+
export const up = async ({ context: db }: { context: Db }) => {
|
|
259
|
+
// await db.collection('...')....
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
export const down = async ({ context: db }: { context: Db }) => {
|
|
263
|
+
// await db.collection('...')....
|
|
264
|
+
};
|
|
217
265
|
`;
|
|
218
266
|
}
|
|
219
267
|
const fullPath = path.join(this.migrationsDir, `${filename}.${extension}`);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Db } from 'mongodb';
|
|
2
|
+
import { IBaseApiConfig } from '../../../models/base-api-config.interface.js';
|
|
3
|
+
export interface SyntheticMigration {
|
|
4
|
+
name: string;
|
|
5
|
+
up: (context: {
|
|
6
|
+
context: Db;
|
|
7
|
+
}) => Promise<void>;
|
|
8
|
+
down: (context: {
|
|
9
|
+
context: Db;
|
|
10
|
+
}) => Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
export declare const getMongoFoundational: (config: IBaseApiConfig) => SyntheticMigration[];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export const getMongoFoundational = (config) => {
|
|
2
|
+
const migrations = [];
|
|
3
|
+
const isMultiTenant = config.app.isMultiTenant === true;
|
|
4
|
+
migrations.push({
|
|
5
|
+
name: '00000000000001_base-users',
|
|
6
|
+
up: async ({ context: db }) => {
|
|
7
|
+
await db.createCollection('users');
|
|
8
|
+
await db.collection('users').createIndex({ email: 1 }, { unique: true });
|
|
9
|
+
if (isMultiTenant) {
|
|
10
|
+
await db.collection('users').createIndex({ _orgId: 1 });
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
down: async ({ context: db }) => {
|
|
14
|
+
await db.collection('users').drop();
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
if (isMultiTenant) {
|
|
18
|
+
migrations.push({
|
|
19
|
+
name: '00000000000002_base-organizations',
|
|
20
|
+
up: async ({ context: db }) => {
|
|
21
|
+
await db.createCollection('organizations');
|
|
22
|
+
await db.collection('organizations').createIndex({ name: 1 });
|
|
23
|
+
},
|
|
24
|
+
down: async ({ context: db }) => {
|
|
25
|
+
await db.collection('organizations').drop();
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
return migrations;
|
|
30
|
+
};
|
|
@@ -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;
|
|
@@ -12,18 +12,18 @@ export class CreateMigrationTableMigration {
|
|
|
12
12
|
await this.client.query('BEGIN');
|
|
13
13
|
const tableExists = await doesTableExist(this.client, 'migrations');
|
|
14
14
|
if (!tableExists) {
|
|
15
|
-
await this.client.query(`
|
|
16
|
-
CREATE TABLE "migrations" (
|
|
17
|
-
"_id" VARCHAR(255) PRIMARY KEY,
|
|
18
|
-
"index" INTEGER NOT NULL UNIQUE,
|
|
19
|
-
"hasRun" BOOLEAN NOT NULL,
|
|
20
|
-
"reverted" BOOLEAN NOT NULL
|
|
21
|
-
)
|
|
15
|
+
await this.client.query(`
|
|
16
|
+
CREATE TABLE "migrations" (
|
|
17
|
+
"_id" VARCHAR(255) PRIMARY KEY,
|
|
18
|
+
"index" INTEGER NOT NULL UNIQUE,
|
|
19
|
+
"hasRun" BOOLEAN NOT NULL,
|
|
20
|
+
"reverted" BOOLEAN NOT NULL
|
|
21
|
+
)
|
|
22
22
|
`);
|
|
23
23
|
}
|
|
24
|
-
const result = await this.client.query(`
|
|
25
|
-
INSERT INTO "migrations" ("_id", "index", "hasRun", "reverted")
|
|
26
|
-
VALUES ('${_id}', ${this.index}, TRUE, FALSE);
|
|
24
|
+
const result = await this.client.query(`
|
|
25
|
+
INSERT INTO "migrations" ("_id", "index", "hasRun", "reverted")
|
|
26
|
+
VALUES ('${_id}', ${this.index}, TRUE, FALSE);
|
|
27
27
|
`);
|
|
28
28
|
if (result.rowCount === 0) {
|
|
29
29
|
await this.client.query('ROLLBACK');
|
|
@@ -39,8 +39,8 @@ export class CreateMigrationTableMigration {
|
|
|
39
39
|
}
|
|
40
40
|
async revert() {
|
|
41
41
|
try {
|
|
42
|
-
await this.client.query(`
|
|
43
|
-
DROP TABLE "migrations";
|
|
42
|
+
await this.client.query(`
|
|
43
|
+
DROP TABLE "migrations";
|
|
44
44
|
`);
|
|
45
45
|
}
|
|
46
46
|
catch (error) {
|