@ruiapp/rapid-core 0.8.7 → 0.8.9

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.
@@ -0,0 +1,367 @@
1
+ import { IRpdServer } from "~/core/server";
2
+ import { find, isString, map } from "lodash";
3
+ import { RouteContext } from "~/core/routeContext";
4
+ import { getEntityPropertyByCode, isOneRelationProperty, isRelationProperty } from "~/helpers/metaHelper";
5
+ import { IQueryBuilder, RpdApplicationConfig, RpdDataModel, RpdDataModelIndex, RpdDataPropertyTypes } from "~/types";
6
+ import { convertModelIndexConditionsToRowFilterOptions } from "~/helpers/filterHelper";
7
+ import { pgPropertyTypeColumnMap } from "~/dataAccess/columnTypeMapper";
8
+
9
+ type TableInformation = {
10
+ table_schema: string;
11
+ table_name: string;
12
+ table_description: string;
13
+ };
14
+
15
+ type ColumnInformation = {
16
+ table_schema: string;
17
+ table_name: string;
18
+ column_name: string;
19
+ ordinal_position: number;
20
+ description?: string;
21
+ data_type: string;
22
+ udt_name: string;
23
+ is_nullable: "YES" | "NO";
24
+ column_default: string;
25
+ character_maximum_length: number;
26
+ numeric_precision: number;
27
+ numeric_scale: number;
28
+ };
29
+
30
+ type ConstraintInformation = {
31
+ table_schema: string;
32
+ table_name: string;
33
+ constraint_type: string;
34
+ constraint_name: string;
35
+ };
36
+
37
+ function generateCreateColumnDDL(
38
+ queryBuilder: IQueryBuilder,
39
+ options: {
40
+ schema?: string;
41
+ tableName: string;
42
+ name: string;
43
+ type: RpdDataPropertyTypes;
44
+ autoIncrement?: boolean;
45
+ notNull?: boolean;
46
+ defaultValue?: string;
47
+ },
48
+ ) {
49
+ let columnDDL = `ALTER TABLE ${queryBuilder.quoteTable(options)} ADD`;
50
+ columnDDL += ` ${queryBuilder.quoteObject(options.name)}`;
51
+ if (options.type === "integer" && options.autoIncrement) {
52
+ columnDDL += ` serial`;
53
+ } else {
54
+ const columnType = pgPropertyTypeColumnMap[options.type];
55
+ if (!columnType) {
56
+ throw new Error(`Property type "${options.type}" is not supported.`);
57
+ }
58
+ columnDDL += ` ${columnType}`;
59
+ }
60
+ if (options.notNull) {
61
+ columnDDL += " NOT NULL";
62
+ }
63
+
64
+ if (options.defaultValue) {
65
+ columnDDL += ` DEFAULT ${options.defaultValue}`;
66
+ }
67
+
68
+ return columnDDL;
69
+ }
70
+
71
+ function generateLinkTableDDL(
72
+ queryBuilder: IQueryBuilder,
73
+ options: {
74
+ linkSchema?: string;
75
+ linkTableName: string;
76
+ targetIdColumnName: string;
77
+ selfIdColumnName: string;
78
+ },
79
+ ) {
80
+ let columnDDL = `CREATE TABLE ${queryBuilder.quoteTable({
81
+ schema: options.linkSchema,
82
+ tableName: options.linkTableName,
83
+ })} (`;
84
+ columnDDL += `id serial not null,`;
85
+ columnDDL += `${queryBuilder.quoteObject(options.selfIdColumnName)} integer not null,`;
86
+ columnDDL += `${queryBuilder.quoteObject(options.targetIdColumnName)} integer not null);`;
87
+
88
+ return columnDDL;
89
+ }
90
+
91
+ function generateTableIndexDDL(queryBuilder: IQueryBuilder, server: IRpdServer, model: RpdDataModel, index: RpdDataModelIndex) {
92
+ let indexName = index.name;
93
+ if (!indexName) {
94
+ indexName = model.tableName;
95
+ for (const indexProp of index.properties) {
96
+ const propCode = isString(indexProp) ? indexProp : indexProp.code;
97
+ const property = getEntityPropertyByCode(server, model, propCode);
98
+ if (!isRelationProperty(property)) {
99
+ indexName += "_" + property.columnName;
100
+ } else if (isOneRelationProperty(property)) {
101
+ indexName += "_" + property.targetIdColumnName;
102
+ }
103
+ }
104
+ indexName += index.unique ? "_uindex" : "_index";
105
+ }
106
+
107
+ const indexColumns = map(index.properties, (indexProp) => {
108
+ let columnName: string;
109
+ const propCode = isString(indexProp) ? indexProp : indexProp.code;
110
+ const property = getEntityPropertyByCode(server, model, propCode);
111
+ if (!isRelationProperty(property)) {
112
+ columnName = property.columnName;
113
+ } else if (isOneRelationProperty(property)) {
114
+ columnName = property.targetIdColumnName;
115
+ }
116
+
117
+ if (isString(indexProp)) {
118
+ return columnName;
119
+ }
120
+
121
+ if (indexProp.order === "desc") {
122
+ return `${columnName} desc`;
123
+ }
124
+
125
+ return columnName;
126
+ });
127
+
128
+ let ddl = `CREATE ${index.unique ? "UNIQUE" : ""} INDEX ${indexName} `;
129
+ ddl += `ON ${queryBuilder.quoteTable({
130
+ schema: model.schema,
131
+ tableName: model.tableName,
132
+ })} (${indexColumns.join(", ")})`;
133
+
134
+ if (index.conditions) {
135
+ const logger = server.getLogger();
136
+ const rowFilterOptions = convertModelIndexConditionsToRowFilterOptions(logger, model, index.conditions);
137
+ ddl += ` WHERE ${queryBuilder.buildFiltersExpression(model, rowFilterOptions)}`;
138
+ }
139
+
140
+ return ddl;
141
+ }
142
+
143
+ export default class MetaService {
144
+ #server: IRpdServer;
145
+
146
+ constructor(server: IRpdServer) {
147
+ this.#server = server;
148
+ }
149
+
150
+ async syncDatabaseSchema(applicationConfig: RpdApplicationConfig) {
151
+ const server = this.#server;
152
+ const logger = server.getLogger();
153
+ logger.info("Synchronizing database schema...");
154
+ const sqlQueryTableInformations = `SELECT table_schema, table_name, obj_description((table_schema||'.'||quote_ident(table_name))::regclass) as table_description FROM information_schema.tables`;
155
+ const tablesInDb: TableInformation[] = await server.queryDatabaseObject(sqlQueryTableInformations);
156
+ const { queryBuilder } = server;
157
+
158
+ for (const model of applicationConfig.models) {
159
+ logger.debug(`Checking data table for '${model.namespace}.${model.singularCode}'...`);
160
+
161
+ const expectedTableSchema = model.schema || server.databaseConfig.dbDefaultSchema;
162
+ const expectedTableName = model.tableName;
163
+ const tableInDb = find(tablesInDb, { table_schema: expectedTableSchema, table_name: expectedTableName });
164
+ if (!tableInDb) {
165
+ await server.queryDatabaseObject(`CREATE TABLE IF NOT EXISTS ${queryBuilder.quoteTable(model)} ()`, []);
166
+ }
167
+ if (!tableInDb || tableInDb.table_description != model.name) {
168
+ await server.tryQueryDatabaseObject(`COMMENT ON TABLE ${queryBuilder.quoteTable(model)} IS ${queryBuilder.formatValueToSqlLiteral(model.name)};`, []);
169
+ }
170
+ }
171
+
172
+ const sqlQueryColumnInformations = `SELECT c.table_schema, c.table_name, c.column_name, c.ordinal_position, d.description, c.data_type, c.udt_name, c.is_nullable, c.column_default, c.character_maximum_length, c.numeric_precision, c.numeric_scale
173
+ FROM information_schema.columns c
174
+ INNER JOIN pg_catalog.pg_statio_all_tables st ON (st.schemaname = c.table_schema and st.relname = c.table_name)
175
+ LEFT JOIN pg_catalog.pg_description d ON (d.objoid = st.relid and d.objsubid = c.ordinal_position);`;
176
+ const columnsInDb: ColumnInformation[] = await server.queryDatabaseObject(sqlQueryColumnInformations, []);
177
+
178
+ for (const model of applicationConfig.models) {
179
+ logger.debug(`Checking data columns for '${model.namespace}.${model.singularCode}'...`);
180
+
181
+ for (const property of model.properties) {
182
+ let columnDDL = "";
183
+ if (isRelationProperty(property)) {
184
+ if (property.relation === "one") {
185
+ const targetModel = applicationConfig.models.find((item) => item.singularCode === property.targetSingularCode);
186
+ if (!targetModel) {
187
+ logger.warn(`Cannot find target model with singular code "${property.targetSingularCode}".`);
188
+ }
189
+
190
+ const columnInDb: ColumnInformation | undefined = find(columnsInDb, {
191
+ table_schema: model.schema || "public",
192
+ table_name: model.tableName,
193
+ column_name: property.targetIdColumnName!,
194
+ });
195
+
196
+ if (!columnInDb) {
197
+ columnDDL = generateCreateColumnDDL(queryBuilder, {
198
+ schema: model.schema,
199
+ tableName: model.tableName,
200
+ name: property.targetIdColumnName!,
201
+ type: "integer",
202
+ autoIncrement: false,
203
+ notNull: property.required,
204
+ });
205
+ await server.tryQueryDatabaseObject(columnDDL);
206
+ }
207
+
208
+ if (!columnInDb || columnInDb.description != property.name) {
209
+ await server.tryQueryDatabaseObject(
210
+ `COMMENT ON COLUMN ${queryBuilder.quoteTable(model)}.${queryBuilder.quoteObject(
211
+ property.targetIdColumnName,
212
+ )} IS ${queryBuilder.formatValueToSqlLiteral(property.name)};`,
213
+ [],
214
+ );
215
+ }
216
+ } else if (property.relation === "many") {
217
+ if (property.linkTableName) {
218
+ const tableInDb = find(tablesInDb, {
219
+ table_schema: property.linkSchema || server.databaseConfig.dbDefaultSchema,
220
+ table_name: property.linkTableName,
221
+ });
222
+ if (!tableInDb) {
223
+ columnDDL = generateLinkTableDDL(queryBuilder, {
224
+ linkSchema: property.linkSchema,
225
+ linkTableName: property.linkTableName,
226
+ targetIdColumnName: property.targetIdColumnName!,
227
+ selfIdColumnName: property.selfIdColumnName!,
228
+ });
229
+ }
230
+
231
+ const contraintName = `${property.linkTableName}_pk`;
232
+ columnDDL += `ALTER TABLE ${queryBuilder.quoteTable({
233
+ schema: property.linkSchema,
234
+ tableName: property.linkTableName,
235
+ })} ADD CONSTRAINT ${queryBuilder.quoteObject(contraintName)} PRIMARY KEY (id);`;
236
+ await server.tryQueryDatabaseObject(columnDDL);
237
+ } else {
238
+ const targetModel = applicationConfig.models.find((item) => item.singularCode === property.targetSingularCode);
239
+ if (!targetModel) {
240
+ logger.warn(`Cannot find target model with singular code "${property.targetSingularCode}".`);
241
+ continue;
242
+ }
243
+
244
+ const columnInDb: ColumnInformation | undefined = find(columnsInDb, {
245
+ table_schema: targetModel.schema || "public",
246
+ table_name: targetModel.tableName,
247
+ column_name: property.selfIdColumnName!,
248
+ });
249
+
250
+ if (!columnInDb) {
251
+ columnDDL = generateCreateColumnDDL(queryBuilder, {
252
+ schema: targetModel.schema,
253
+ tableName: targetModel.tableName,
254
+ name: property.selfIdColumnName || "",
255
+ type: "integer",
256
+ autoIncrement: false,
257
+ notNull: property.required,
258
+ });
259
+ await server.tryQueryDatabaseObject(columnDDL);
260
+ }
261
+ }
262
+ } else {
263
+ continue;
264
+ }
265
+ } else {
266
+ const columnName = property.columnName || property.code;
267
+ const columnInDb: ColumnInformation | undefined = find(columnsInDb, {
268
+ table_schema: model.schema || "public",
269
+ table_name: model.tableName,
270
+ column_name: columnName,
271
+ });
272
+
273
+ if (!columnInDb) {
274
+ // create column if not exists
275
+ columnDDL = generateCreateColumnDDL(queryBuilder, {
276
+ schema: model.schema,
277
+ tableName: model.tableName,
278
+ name: columnName,
279
+ type: property.type,
280
+ autoIncrement: property.autoIncrement,
281
+ notNull: property.required,
282
+ defaultValue: property.defaultValue,
283
+ });
284
+ await server.tryQueryDatabaseObject(columnDDL);
285
+ } else {
286
+ const expectedColumnType = pgPropertyTypeColumnMap[property.type];
287
+ if (columnInDb.udt_name !== expectedColumnType) {
288
+ const sqlAlterColumnType = `alter table ${queryBuilder.quoteTable(model)} alter column ${queryBuilder.quoteObject(
289
+ columnName,
290
+ )} type ${expectedColumnType}`;
291
+ await server.tryQueryDatabaseObject(sqlAlterColumnType);
292
+ }
293
+
294
+ if (property.defaultValue) {
295
+ if (!columnInDb.column_default) {
296
+ const sqlSetColumnDefault = `alter table ${queryBuilder.quoteTable(model)} alter column ${queryBuilder.quoteObject(columnName)} set default ${
297
+ property.defaultValue
298
+ }`;
299
+ await server.tryQueryDatabaseObject(sqlSetColumnDefault);
300
+ }
301
+ } else {
302
+ if (columnInDb.column_default && !property.autoIncrement) {
303
+ const sqlDropColumnDefault = `alter table ${queryBuilder.quoteTable(model)} alter column ${queryBuilder.quoteObject(columnName)} drop default`;
304
+ await server.tryQueryDatabaseObject(sqlDropColumnDefault);
305
+ }
306
+ }
307
+
308
+ if (property.required) {
309
+ if (columnInDb.is_nullable === "YES") {
310
+ const sqlSetColumnNotNull = `alter table ${queryBuilder.quoteTable(model)} alter column ${queryBuilder.quoteObject(columnName)} set not null`;
311
+ await server.tryQueryDatabaseObject(sqlSetColumnNotNull);
312
+ }
313
+ } else {
314
+ if (columnInDb.is_nullable === "NO") {
315
+ const sqlDropColumnNotNull = `alter table ${queryBuilder.quoteTable(model)} alter column ${queryBuilder.quoteObject(columnName)} drop not null`;
316
+ await server.tryQueryDatabaseObject(sqlDropColumnNotNull);
317
+ }
318
+ }
319
+ }
320
+
321
+ if (!columnInDb || columnInDb.description != property.name) {
322
+ await server.tryQueryDatabaseObject(
323
+ `COMMENT ON COLUMN ${queryBuilder.quoteTable(model)}.${queryBuilder.quoteObject(
324
+ property.columnName || property.code,
325
+ )} IS ${queryBuilder.formatValueToSqlLiteral(property.name)};`,
326
+ [],
327
+ );
328
+ }
329
+ }
330
+ }
331
+ }
332
+
333
+ const sqlQueryConstraints = `SELECT table_schema, table_name, constraint_type, constraint_name FROM information_schema.table_constraints WHERE constraint_type = 'PRIMARY KEY';`;
334
+ const constraintsInDb: ConstraintInformation[] = await server.queryDatabaseObject(sqlQueryConstraints);
335
+ for (const model of applicationConfig.models) {
336
+ const expectedTableSchema = model.schema || server.databaseConfig.dbDefaultSchema;
337
+ const expectedTableName = model.tableName;
338
+ const expectedContraintName = `${expectedTableName}_pk`;
339
+ logger.debug(`Checking pk for '${expectedTableSchema}.${expectedTableName}'...`);
340
+ const constraintInDb = find(constraintsInDb, {
341
+ table_schema: expectedTableSchema,
342
+ table_name: expectedTableName,
343
+ constraint_type: "PRIMARY KEY",
344
+ constraint_name: expectedContraintName,
345
+ });
346
+ if (!constraintInDb) {
347
+ await server.queryDatabaseObject(
348
+ `ALTER TABLE ${queryBuilder.quoteTable(model)} ADD CONSTRAINT ${queryBuilder.quoteObject(expectedContraintName)} PRIMARY KEY (id);`,
349
+ [],
350
+ );
351
+ }
352
+ }
353
+
354
+ // generate indexes
355
+ for (const model of applicationConfig.models) {
356
+ if (!model.indexes || !model.indexes.length) {
357
+ continue;
358
+ }
359
+
360
+ logger.debug(`Creating indexes of table ${queryBuilder.quoteTable(model)}`);
361
+ for (const index of model.indexes) {
362
+ const sqlCreateIndex = generateTableIndexDDL(queryBuilder, server, model, index);
363
+ await server.tryQueryDatabaseObject(sqlCreateIndex, []);
364
+ }
365
+ }
366
+ }
367
+ }
@@ -516,7 +516,7 @@ function buildRangeFilterQuery(ctx: BuildQueryContext, filter: FindRowRangeFilte
516
516
  function buildContainsFilterQuery(ctx: BuildQueryContext, filter: FindRowRelationalFilterOptions) {
517
517
  let command = ctx.builder.quoteColumn(ctx.model, filter.field, ctx.emitTableAlias);
518
518
 
519
- command += " LIKE ";
519
+ command += " ILIKE ";
520
520
 
521
521
  if (ctx.paramToLiteral) {
522
522
  // TODO: implement it
@@ -531,7 +531,7 @@ function buildContainsFilterQuery(ctx: BuildQueryContext, filter: FindRowRelatio
531
531
  function buildNotContainsFilterQuery(ctx: BuildQueryContext, filter: FindRowRelationalFilterOptions) {
532
532
  let command = ctx.builder.quoteColumn(ctx.model, filter.field, ctx.emitTableAlias);
533
533
 
534
- command += " NOT LIKE ";
534
+ command += " NOT ILIKE ";
535
535
  if (ctx.paramToLiteral) {
536
536
  // TODO: implement it
537
537
  } else {
@@ -545,7 +545,7 @@ function buildNotContainsFilterQuery(ctx: BuildQueryContext, filter: FindRowRela
545
545
  function buildStartsWithFilterQuery(ctx: BuildQueryContext, filter: FindRowRelationalFilterOptions) {
546
546
  let command = ctx.builder.quoteColumn(ctx.model, filter.field, ctx.emitTableAlias);
547
547
 
548
- command += " LIKE ";
548
+ command += " ILIKE ";
549
549
 
550
550
  if (ctx.paramToLiteral) {
551
551
  // TODO: implement it
@@ -560,7 +560,7 @@ function buildStartsWithFilterQuery(ctx: BuildQueryContext, filter: FindRowRelat
560
560
  function buildNotStartsWithFilterQuery(ctx: BuildQueryContext, filter: FindRowRelationalFilterOptions) {
561
561
  let command = ctx.builder.quoteColumn(ctx.model, filter.field, ctx.emitTableAlias);
562
562
 
563
- command += " NOT LIKE ";
563
+ command += " NOT ILIKE ";
564
564
 
565
565
  if (ctx.paramToLiteral) {
566
566
  // TODO: implement it
@@ -575,7 +575,7 @@ function buildNotStartsWithFilterQuery(ctx: BuildQueryContext, filter: FindRowRe
575
575
  function buildEndsWithFilterQuery(ctx: BuildQueryContext, filter: FindRowRelationalFilterOptions) {
576
576
  let command = ctx.builder.quoteColumn(ctx.model, filter.field, ctx.emitTableAlias);
577
577
 
578
- command += " LIKE ";
578
+ command += " ILIKE ";
579
579
 
580
580
  if (ctx.paramToLiteral) {
581
581
  // TODO: implement it
@@ -590,7 +590,7 @@ function buildEndsWithFilterQuery(ctx: BuildQueryContext, filter: FindRowRelatio
590
590
  function buildNotEndsWithFilterQuery(ctx: BuildQueryContext, filter: FindRowRelationalFilterOptions) {
591
591
  let command = ctx.builder.quoteColumn(ctx.model, filter.field, ctx.emitTableAlias);
592
592
 
593
- command += " NOT LIKE ";
593
+ command += " NOT ILIKE ";
594
594
 
595
595
  if (ctx.paramToLiteral) {
596
596
  // TODO: implement it