plugin-data-source-postgres 2.0.0 → 2.0.1

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.
@@ -61,7 +61,7 @@ describe('SQLModel selectQuery', () => {
61
61
  model,
62
62
  );
63
63
 
64
- expect(sql).toContain('SELECT "id" FROM (SELECT id, name FROM orders)');
64
+ expect(sql).toContain('SELECT "id" FROM (SELECT id, name FROM orders\n)');
65
65
  expect(sql).toContain('WHERE "order_summary"."id" = 10');
66
66
  expect(sql).toContain('ORDER BY "order_summary"."id" DESC');
67
67
  expect(sql).toContain('LIMIT 5 OFFSET 10');
@@ -77,7 +77,7 @@ describe('SQLModel selectQuery', () => {
77
77
  model,
78
78
  );
79
79
 
80
- expect(sql).toContain('SELECT * FROM (SELECT id, name FROM orders)');
80
+ expect(sql).toContain('SELECT * FROM (SELECT id, name FROM orders\n)');
81
81
  expect(sql).not.toMatch(/SELECT\s+FROM/);
82
82
  });
83
83
 
@@ -109,7 +109,51 @@ describe('SQLModel selectQuery', () => {
109
109
  { attributes: ['id'], where: { id: 42 } },
110
110
  updatable.model as unknown as typeof SQLModel,
111
111
  );
112
- expect(updatedQuery).toContain('SELECT "id" FROM (SELECT id, name FROM updated_orders)');
112
+ expect(updatedQuery).toContain('SELECT "id" FROM (SELECT id, name FROM updated_orders\n)');
113
113
  expect(updatedQuery).toContain('WHERE "updatable_summary"."id" = 42');
114
114
  });
115
+
116
+ it('normalizes trailing semicolons before comments and isolates trailing line comments from closing parenthesis', () => {
117
+ const withBlockComment = db.collection({
118
+ name: 'commented_block_summary',
119
+ sql: 'SELECT id FROM orders; /* trailing note */',
120
+ fields: [{ name: 'id', type: 'integer', primaryKey: true }],
121
+ }) as PostgresSQLCollection;
122
+
123
+ const withLineComment = db.collection({
124
+ name: 'commented_line_summary',
125
+ sql: "SELECT id, ';' AS sep FROM orders; -- trailing line comment",
126
+ fields: [
127
+ { name: 'id', type: 'integer', primaryKey: true },
128
+ { name: 'sep', type: 'string' },
129
+ ],
130
+ }) as PostgresSQLCollection;
131
+
132
+ const blockSql = (
133
+ withBlockComment.model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub }
134
+ ).queryGenerator.selectQuery(
135
+ 'commented_block_summary',
136
+ { attributes: ['id'], where: { id: 1 }, limit: 10, offset: 0 },
137
+ withBlockComment.model as unknown as typeof SQLModel,
138
+ );
139
+ expect(blockSql).toBe(
140
+ 'SELECT "id" FROM (SELECT id FROM orders /* trailing note */\n) AS "commented_block_summary" WHERE "commented_block_summary"."id" = 1 LIMIT 10 OFFSET 0;',
141
+ );
142
+
143
+ const lineSql = (
144
+ withLineComment.model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub }
145
+ ).queryGenerator.selectQuery(
146
+ 'commented_line_summary',
147
+ { attributes: ['id', 'sep'], where: { id: 1 }, limit: 5 },
148
+ withLineComment.model as unknown as typeof SQLModel,
149
+ );
150
+ expect(lineSql).toBe(
151
+ `SELECT "id", "sep" FROM (SELECT id, ';' AS sep FROM orders -- trailing line comment\n) AS "commented_line_summary" WHERE "commented_line_summary"."id" = 1 LIMIT 5;`,
152
+ );
153
+
154
+ const emptyOptsSql = (
155
+ withLineComment.model.queryInterface as unknown as { queryGenerator: SqlGeneratorStub }
156
+ ).queryGenerator.selectQuery('commented_line_summary', {}, withLineComment.model as unknown as typeof SQLModel);
157
+ expect(emptyOptsSql).toBe("SELECT id, ';' AS sep FROM orders -- trailing line comment\n;");
158
+ });
115
159
  });
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import { describe, expect, it } from 'vitest';
11
- import { checkSQL } from '../utils/sql-validator';
11
+ import { checkSQL, normalizeSqlCollectionQuery } from '../utils/sql-validator';
12
12
  import { PostgresValidationError } from '../utils/validation-error';
13
13
 
14
14
  function expectValidationError(fn: () => void, message?: string) {
@@ -116,4 +116,11 @@ describe('checkSQL', () => {
116
116
  expectValidationError(() => checkSQL(sql), 'SQL statement contains dangerous keyword');
117
117
  }
118
118
  });
119
+
120
+ it('normalizes trailing semicolons across comments without altering semicolons inside literals', () => {
121
+ expect(normalizeSqlCollectionQuery('SELECT 1; /* note */')).toBe('SELECT 1 /* note */');
122
+ expect(normalizeSqlCollectionQuery('SELECT 1; -- note\n')).toBe('SELECT 1 -- note');
123
+ expect(normalizeSqlCollectionQuery("SELECT ';' AS sep; /* note */")).toBe("SELECT ';' AS sep /* note */");
124
+ expect(normalizeSqlCollectionQuery('SELECT $$a;b$$;')).toBe('SELECT $$a;b$$');
125
+ });
119
126
  });
@@ -10,6 +10,7 @@
10
10
  import { Collection, CollectionContext, CollectionOptions } from '@nocobase/database';
11
11
  import { ModelStatic, QueryInterfaceDropTableOptions } from 'sequelize';
12
12
  import type { Model } from '@nocobase/database';
13
+ import { normalizeSqlCollectionQuery } from '../utils/sql-validator';
13
14
  import { SQLModel } from './sql-model';
14
15
 
15
16
  export class PostgresSQLCollection extends Collection {
@@ -40,8 +41,7 @@ export class PostgresSQLCollection extends Collection {
40
41
  }
41
42
 
42
43
  modelInit() {
43
- const sql = String(this.options.sql || '').trim();
44
- const normalizedSql = sql.endsWith(';') ? sql.slice(0, -1) : sql;
44
+ const normalizedSql = normalizeSqlCollectionQuery(String(this.options.sql || ''));
45
45
  if (this.model) {
46
46
  (this.model as unknown as typeof SQLModel).sql = normalizedSql;
47
47
  return;
@@ -42,7 +42,7 @@ type SqlGenerator = {
42
42
  // Mirrors the host SQL collection's query generator, retaining its filter, order and pagination options.
43
43
  function selectQuery(this: SqlGenerator, _tableName: string, options: SelectOptions, model: typeof SQLModel): string {
44
44
  const queryOptions = options || {};
45
- if (isEmpty(queryOptions)) return `${model.sql};`;
45
+ if (isEmpty(queryOptions)) return `${model.sql}\n;`;
46
46
 
47
47
  let attributes = queryOptions.attributes?.slice();
48
48
  if (attributes) {
@@ -70,7 +70,7 @@ function selectQuery(this: SqlGenerator, _tableName: string, options: SelectOpti
70
70
  }
71
71
  const limit = this.addLimitAndOffset(queryOptions, model);
72
72
  if (limit) clauses.push(limit);
73
- return `SELECT ${selected.join(', ')} FROM (${model.sql}) ${this.getAliasToken()} ${this.quoteIdentifier(
73
+ return `SELECT ${selected.join(', ')} FROM (${model.sql}\n) ${this.getAliasToken()} ${this.quoteIdentifier(
74
74
  model.name,
75
75
  )}${clauses.join('')};`;
76
76
  }
@@ -10,12 +10,17 @@
10
10
  import { Collection } from '@nocobase/database';
11
11
  import { Transaction, Utils } from 'sequelize';
12
12
  import { isEqual } from 'lodash';
13
- import { PostgresCollectionManager } from '../postgres-collection-manager';
13
+ import {
14
+ applyPostgresArrayDataType,
15
+ isPostgresPhysicalArrayRawType,
16
+ PostgresCollectionManager,
17
+ } from '../postgres-collection-manager';
14
18
  import { PostgresValidationError } from '../utils/validation-error';
15
19
 
16
20
  type FieldValues = {
17
21
  name?: string;
18
22
  type?: string;
23
+ dataType?: string;
19
24
  field?: string;
20
25
  interface?: string;
21
26
  allowNull?: boolean;
@@ -437,6 +442,13 @@ export async function syncFieldAction(
437
442
  await ensureBelongsToArray(manager, collectionName, name, values, input, transaction);
438
443
  return;
439
444
  }
445
+ applyPostgresArrayDataType(values);
446
+ if (values.dataType === 'array') {
447
+ input.dataType = 'array';
448
+ if (input.elementType === undefined && typeof values.elementType === 'string') {
449
+ input.elementType = values.elementType;
450
+ }
451
+ }
440
452
  await manager.addField(collectionName, { ...values, name }, transaction);
441
453
  return;
442
454
  }
@@ -490,12 +502,34 @@ export async function syncFieldAction(
490
502
  return;
491
503
  }
492
504
 
505
+ const effectiveType = values.type ?? field.options.type;
506
+ const effectiveElementType = values.elementType ?? field.options.elementType;
507
+ const effectiveDataType = values.dataType !== undefined ? values.dataType : field.options.dataType;
508
+ if (
509
+ (effectiveType === 'array' || effectiveType === 'set') &&
510
+ typeof effectiveElementType === 'string' &&
511
+ effectiveElementType.trim().length > 0 &&
512
+ (effectiveDataType === undefined || effectiveDataType === null || effectiveDataType === '')
513
+ ) {
514
+ const rawTypeIsArray =
515
+ field.options.rawType === undefined ? undefined : isPostgresPhysicalArrayRawType(field.options.rawType);
516
+ const columnIsArray =
517
+ rawTypeIsArray !== undefined
518
+ ? rawTypeIsArray
519
+ : await manager.isPhysicalArrayColumn(collectionName, field.columnName(), transaction);
520
+ if (columnIsArray !== false) {
521
+ values.dataType = 'array';
522
+ input.dataType = 'array';
523
+ }
524
+ }
525
+
493
526
  const changes: Pick<
494
527
  FieldValues,
495
- 'type' | 'allowNull' | 'defaultValue' | 'unique' | 'length' | 'precision' | 'scale' | 'elementType'
528
+ 'type' | 'dataType' | 'allowNull' | 'defaultValue' | 'unique' | 'length' | 'precision' | 'scale' | 'elementType'
496
529
  > = {};
497
530
  for (const key of [
498
531
  'type',
532
+ 'dataType',
499
533
  'allowNull',
500
534
  'defaultValue',
501
535
  'unique',