sequelize-typescript-generator 13.1.0 → 13.2.0

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.
Files changed (39) hide show
  1. package/README.md +274 -20
  2. package/build/bin/cli.js +3 -3
  3. package/build/bin/utils.d.ts +13 -0
  4. package/build/bin/utils.js +25 -0
  5. package/build/builders/ModelBuilder.d.ts +2 -1
  6. package/build/builders/ModelBuilder.js +135 -16
  7. package/build/builders/NativeModelRenderer.d.ts +4 -3
  8. package/build/builders/NativeModelRenderer.js +31 -11
  9. package/build/builders/enumSupport.d.ts +104 -0
  10. package/build/builders/enumSupport.js +323 -0
  11. package/build/builders/generatedFile.d.ts +2 -1
  12. package/build/builders/generatedFile.js +7 -1
  13. package/build/builders/jsonSupport.d.ts +10 -3
  14. package/build/builders/jsonSupport.js +10 -3
  15. package/build/builders/typeOverrides.d.ts +30 -0
  16. package/build/builders/typeOverrides.js +93 -0
  17. package/build/builders/typeOverridesParser.d.ts +48 -0
  18. package/build/builders/typeOverridesParser.js +305 -0
  19. package/build/builders/unmappedTypes.d.ts +50 -0
  20. package/build/builders/unmappedTypes.js +62 -0
  21. package/build/builders/utils.js +3 -0
  22. package/build/config/IConfig.d.ts +22 -0
  23. package/build/dialects/Dialect.d.ts +56 -3
  24. package/build/dialects/DialectMSSQL.d.ts +2 -2
  25. package/build/dialects/DialectMSSQL.js +1 -6
  26. package/build/dialects/DialectMariaDB.d.ts +2 -2
  27. package/build/dialects/DialectMariaDB.js +1 -6
  28. package/build/dialects/DialectMySQL.d.ts +2 -2
  29. package/build/dialects/DialectMySQL.js +1 -6
  30. package/build/dialects/DialectPostgres.d.ts +33 -2
  31. package/build/dialects/DialectPostgres.js +77 -10
  32. package/build/dialects/DialectSQLite.d.ts +2 -2
  33. package/build/dialects/DialectSQLite.js +1 -6
  34. package/build/dialects/dataTypes.d.ts +8 -0
  35. package/build/dialects/dataTypes.js +32 -4
  36. package/build/dialects/utils.d.ts +0 -6
  37. package/build/dialects/utils.js +0 -10
  38. package/build/index.d.ts +2 -2
  39. package/package.json +3 -3
@@ -7,7 +7,38 @@ import { IColumnMetadata, IIndexMetadata, IForeignKeyConstraintMetadata, Dialect
7
7
  * @class DialectPostgres
8
8
  */
9
9
  export declare class DialectPostgres extends Dialect {
10
+ /**
11
+ * Enum labels per schema, cached for the lifetime of a connection so a run
12
+ * queries the catalogs once per schema.
13
+ */
14
+ private readonly enumLabelsByConnection;
10
15
  constructor();
16
+ /**
17
+ * Query the labels of every enum type defined in a schema, in database sort order.
18
+ * @param {Sequelize} connection
19
+ * @param {string} schema
20
+ * @returns {Promise<EnumLabelsByTypeName>}
21
+ */
22
+ private queryEnumLabels;
23
+ /**
24
+ * Fetch the enum labels of a schema, querying the catalogs only on the first
25
+ * request for that schema on the connection.
26
+ * @param {Sequelize} connection
27
+ * @param {string} schema
28
+ * @returns {Promise<EnumLabelsByTypeName>}
29
+ */
30
+ private fetchEnumLabels;
31
+ /**
32
+ * Resolve the database enum type of a column whose element type has no
33
+ * mapping: the enum named after the element type in the column's UDT schema,
34
+ * or undefined when no such enum exists.
35
+ * @param {Sequelize} connection
36
+ * @param {string} udtSchema
37
+ * @param {string} elementTypeName
38
+ * @param {boolean} isArray
39
+ * @returns {Promise<IColumnEnumType | undefined>}
40
+ */
41
+ private resolveEnumType;
11
42
  /**
12
43
  * Map database data type to sequelize data type
13
44
  * @param {string} dbType
@@ -19,9 +50,9 @@ export declare class DialectPostgres extends Dialect {
19
50
  * element JS type suffixed with `[]`; an array whose element has no scalar
20
51
  * mapping degrades to `unknown[]`.
21
52
  * @param {string} dbType
22
- * @returns {string}
53
+ * @returns {string | undefined}
23
54
  */
24
- mapDbTypeToJs(dbType: string): string;
55
+ mapDbTypeToJs(dbType: string): string | undefined;
25
56
  /**
26
57
  * Map database default values to Sequelize type (e.g. uuid() => DataType.UUIDV4).
27
58
  * @param {string} v
@@ -1,7 +1,6 @@
1
1
  import { QueryTypes } from 'sequelize';
2
2
  import { DataTypes } from 'sequelize';
3
- import { Dialect } from './Dialect.js';
4
- import { warnUnknownMappingForDataType } from './utils.js';
3
+ import { Dialect, } from './Dialect.js';
5
4
  import { buildSequelizeDataType, renderDataTypeExpression, DATA_TYPE_NAMESPACES, } from './dataTypes.js';
6
5
  import { groupForeignKeyRows, mapForeignKeyQueryRow, } from './foreignKeys.js';
7
6
  const sequelizeDataTypesMap = {
@@ -15,6 +14,7 @@ const sequelizeDataTypesMap = {
15
14
  varchar: DataTypes.STRING,
16
15
  bpchar: DataTypes.STRING,
17
16
  text: DataTypes.STRING,
17
+ citext: DataTypes.CITEXT,
18
18
  bytea: DataTypes.BLOB,
19
19
  timestamp: DataTypes.DATE,
20
20
  timestamptz: DataTypes.DATE,
@@ -69,6 +69,7 @@ const jsDataTypesMap = {
69
69
  varchar: 'string',
70
70
  bpchar: 'string',
71
71
  text: 'string',
72
+ citext: 'string',
72
73
  bytea: 'Uint8Array',
73
74
  timestamp: 'Date',
74
75
  timestamptz: 'Date',
@@ -102,9 +103,75 @@ const jsDataTypesMap = {
102
103
  * @class DialectPostgres
103
104
  */
104
105
  export class DialectPostgres extends Dialect {
106
+ /**
107
+ * Enum labels per schema, cached for the lifetime of a connection so a run
108
+ * queries the catalogs once per schema.
109
+ */
110
+ enumLabelsByConnection = new WeakMap();
105
111
  constructor() {
106
112
  super('postgres');
107
113
  }
114
+ /**
115
+ * Query the labels of every enum type defined in a schema, in database sort order.
116
+ * @param {Sequelize} connection
117
+ * @param {string} schema
118
+ * @returns {Promise<EnumLabelsByTypeName>}
119
+ */
120
+ async queryEnumLabels(connection, schema) {
121
+ const rows = await connection.query(`
122
+ SELECT
123
+ t.typname AS type_name,
124
+ e.enumlabel AS label
125
+ FROM pg_catalog.pg_type t
126
+ JOIN pg_catalog.pg_enum e ON e.enumtypid = t.oid
127
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
128
+ WHERE n.nspname = $1
129
+ ORDER BY t.typname, e.enumsortorder;
130
+ `, {
131
+ type: QueryTypes.SELECT,
132
+ raw: true,
133
+ bind: [schema],
134
+ });
135
+ const labelsByTypeName = new Map();
136
+ for (const { type_name, label } of rows) {
137
+ const labels = labelsByTypeName.get(type_name) ?? [];
138
+ labels.push(label);
139
+ labelsByTypeName.set(type_name, labels);
140
+ }
141
+ return labelsByTypeName;
142
+ }
143
+ /**
144
+ * Fetch the enum labels of a schema, querying the catalogs only on the first
145
+ * request for that schema on the connection.
146
+ * @param {Sequelize} connection
147
+ * @param {string} schema
148
+ * @returns {Promise<EnumLabelsByTypeName>}
149
+ */
150
+ fetchEnumLabels(connection, schema) {
151
+ const labelsBySchema = this.enumLabelsByConnection.get(connection) ?? new Map();
152
+ this.enumLabelsByConnection.set(connection, labelsBySchema);
153
+ const cached = labelsBySchema.get(schema);
154
+ if (cached) {
155
+ return cached;
156
+ }
157
+ const pending = this.queryEnumLabels(connection, schema);
158
+ labelsBySchema.set(schema, pending);
159
+ return pending;
160
+ }
161
+ /**
162
+ * Resolve the database enum type of a column whose element type has no
163
+ * mapping: the enum named after the element type in the column's UDT schema,
164
+ * or undefined when no such enum exists.
165
+ * @param {Sequelize} connection
166
+ * @param {string} udtSchema
167
+ * @param {string} elementTypeName
168
+ * @param {boolean} isArray
169
+ * @returns {Promise<IColumnEnumType | undefined>}
170
+ */
171
+ async resolveEnumType(connection, udtSchema, elementTypeName, isArray) {
172
+ const labels = (await this.fetchEnumLabels(connection, udtSchema)).get(elementTypeName);
173
+ return labels ? { schema: udtSchema, name: elementTypeName, labels, isArray } : undefined;
174
+ }
108
175
  /**
109
176
  * Map database data type to sequelize data type
110
177
  * @param {string} dbType
@@ -118,7 +185,7 @@ export class DialectPostgres extends Dialect {
118
185
  * element JS type suffixed with `[]`; an array whose element has no scalar
119
186
  * mapping degrades to `unknown[]`.
120
187
  * @param {string} dbType
121
- * @returns {string}
188
+ * @returns {string | undefined}
122
189
  */
123
190
  mapDbTypeToJs(dbType) {
124
191
  if (isPostgresArrayType(dbType)) {
@@ -224,12 +291,11 @@ export class DialectPostgres extends Dialect {
224
291
  const isArray = isPostgresArrayType(column.udt_name);
225
292
  const elementTypeName = isArray ? stripPostgresArrayPrefix(column.udt_name) : column.udt_name;
226
293
  const elementConstructor = this.mapDbTypeToSequelize(elementTypeName);
227
- // Unknown data type. An array whose element has no scalar mapping is
228
- // reported once and degrades gracefully: no `type` is emitted and the
229
- // TypeScript type falls back to `unknown[]`.
230
- if (!elementConstructor) {
231
- warnUnknownMappingForDataType(column.udt_name);
232
- }
294
+ // An unmapped element type, absent from the type map, may be a
295
+ // user-defined enum, looked up in the schema the type is defined in.
296
+ const enumType = elementConstructor === undefined
297
+ ? await this.resolveEnumType(connection, column.udt_schema, elementTypeName, isArray)
298
+ : undefined;
233
299
  // Data type arguments (precision or length)
234
300
  let dataTypeArgs = [];
235
301
  switch (elementTypeName) {
@@ -250,7 +316,7 @@ export class DialectPostgres extends Dialect {
250
316
  }
251
317
  const elementType = elementConstructor
252
318
  ? buildSequelizeDataType(elementConstructor, dataTypeArgs)
253
- : undefined;
319
+ : enumType && { key: 'ENUM', args: [...enumType.labels] };
254
320
  const sequelizeType = elementType && isArray
255
321
  ? buildSequelizeDataType(DataTypes.ARRAY, [elementType])
256
322
  : elementType;
@@ -264,6 +330,7 @@ export class DialectPostgres extends Dialect {
264
330
  dataType: renderDataTypeExpression(sequelizeType, DATA_TYPE_NAMESPACES.decorators),
265
331
  },
266
332
  ...!isArray && (elementTypeName === 'json' || elementTypeName === 'jsonb') && { isJson: true },
333
+ ...enumType && { enumType },
267
334
  allowNull: column.is_nullable === 'YES' && !column.is_primary,
268
335
  primaryKey: column.is_primary,
269
336
  autoIncrement: column.is_sequence,
@@ -29,9 +29,9 @@ export declare class DialectSQLite extends Dialect {
29
29
  /**
30
30
  * Map database data type to javascript data type
31
31
  * @param {string} dbType
32
- * @returns {string
32
+ * @returns {string | undefined}
33
33
  */
34
- mapDbTypeToJs(dbType: string): string;
34
+ mapDbTypeToJs(dbType: string): string | undefined;
35
35
  /**
36
36
  * Map database default values to Sequelize type (e.g. uuid() => DataType.UUIDV4).
37
37
  * @param {string} v
@@ -1,7 +1,6 @@
1
1
  import { QueryTypes } from 'sequelize';
2
2
  import { DataTypes } from 'sequelize';
3
3
  import { Dialect } from './Dialect.js';
4
- import { warnUnknownMappingForDataType } from './utils.js';
5
4
  import { buildSequelizeDataType, renderDataTypeExpression, DATA_TYPE_NAMESPACES, } from './dataTypes.js';
6
5
  import { groupForeignKeyRows } from './foreignKeys.js';
7
6
  /**
@@ -54,7 +53,7 @@ export class DialectSQLite extends Dialect {
54
53
  /**
55
54
  * Map database data type to javascript data type
56
55
  * @param {string} dbType
57
- * @returns {string
56
+ * @returns {string | undefined}
58
57
  */
59
58
  mapDbTypeToJs(dbType) {
60
59
  // Affinity rules from https://www.sqlite.org/datatype3.html
@@ -113,10 +112,6 @@ export class DialectSQLite extends Dialect {
113
112
  raw: true,
114
113
  });
115
114
  for (const column of columns) {
116
- // Unknown data type
117
- if (!this.mapDbTypeToSequelize(column.type)) {
118
- warnUnknownMappingForDataType(column.type);
119
- }
120
115
  const sequelizeConstructor = this.mapDbTypeToSequelize(column.type);
121
116
  const sequelizeType = sequelizeConstructor
122
117
  ? buildSequelizeDataType(sequelizeConstructor, [])
@@ -37,6 +37,14 @@ export type DataTypeNamespace = typeof DATA_TYPE_NAMESPACES[keyof typeof DATA_TY
37
37
  * @returns {boolean}
38
38
  */
39
39
  export declare const isSequelizeDataTypeKey: (value: string) => value is SequelizeDataTypeKey;
40
+ /**
41
+ * Type guard for a DataTypes key naming a concrete data type usable as a column
42
+ * type: a data type class derived from ABSTRACT. Dialect namespaces (`postgres`,
43
+ * `mysql`, ...) and ABSTRACT itself are rejected.
44
+ * @param {string} value
45
+ * @returns {boolean}
46
+ */
47
+ export declare const isColumnDataTypeKey: (value: string) => value is SequelizeDataTypeKey;
40
48
  /**
41
49
  * Resolve the DataTypes key for a constructor. The first token of the constructor
42
50
  * key is used so that 'DOUBLE PRECISION' resolves to 'DOUBLE'. Returns undefined when
@@ -18,6 +18,20 @@ export const DATA_TYPE_NAMESPACES = {
18
18
  * @returns {boolean}
19
19
  */
20
20
  export const isSequelizeDataTypeKey = (value) => Object.prototype.hasOwnProperty.call(DataTypes, value);
21
+ /**
22
+ * Type guard for a DataTypes key naming a concrete data type usable as a column
23
+ * type: a data type class derived from ABSTRACT. Dialect namespaces (`postgres`,
24
+ * `mysql`, ...) and ABSTRACT itself are rejected.
25
+ * @param {string} value
26
+ * @returns {boolean}
27
+ */
28
+ export const isColumnDataTypeKey = (value) => {
29
+ if (!isSequelizeDataTypeKey(value)) {
30
+ return false;
31
+ }
32
+ const dataType = DataTypes[value];
33
+ return typeof dataType === 'function' && dataType.prototype instanceof DataTypes.ABSTRACT;
34
+ };
21
35
  /**
22
36
  * Resolve the DataTypes key for a constructor. The first token of the constructor
23
37
  * key is used so that 'DOUBLE PRECISION' resolves to 'DOUBLE'. Returns undefined when
@@ -52,9 +66,23 @@ export const buildSequelizeDataType = (ctor, args) => {
52
66
  return { key, args: filteredArgs };
53
67
  };
54
68
  /**
55
- * Render a single data type argument. Numbers render bare; strings render
56
- * single-quoted with internal single quotes doubled; a nested data type renders
57
- * as its own expression under the same namespace.
69
+ * Render a string as a single-quoted TypeScript string literal. Backslashes,
70
+ * single quotes and control characters are backslash-escaped; double quotes
71
+ * stay bare.
72
+ * @param {string} value
73
+ * @returns {string}
74
+ */
75
+ const renderStringLiteral = (value) => {
76
+ const escaped = JSON.stringify(value)
77
+ .slice(1, -1)
78
+ .replace(/\\"/g, '"')
79
+ .replace(/'/g, "\\'");
80
+ return `'${escaped}'`;
81
+ };
82
+ /**
83
+ * Render a single data type argument. Numbers render bare; strings render as
84
+ * single-quoted TypeScript string literals; a nested data type renders as its
85
+ * own expression under the same namespace.
58
86
  * @param {DataTypeArgument} arg
59
87
  * @param {DataTypeNamespace} namespace
60
88
  * @returns {string}
@@ -64,7 +92,7 @@ const renderDataTypeArgument = (arg, namespace) => {
64
92
  return String(arg);
65
93
  }
66
94
  if (typeof arg === 'string') {
67
- return `'${arg.replace(/'/g, "''")}'`;
95
+ return renderStringLiteral(arg);
68
96
  }
69
97
  return renderDataTypeExpression(arg, namespace);
70
98
  };
@@ -27,9 +27,3 @@ export declare const getTransformer: (transformCase: TransformCase | TransformMa
27
27
  * @returns {ITableMetadata}
28
28
  */
29
29
  export declare const caseTransformer: (tableMetadata: ITableMetadata, transformCase: TransformCase | TransformMap | TransformFn) => ITableMetadata;
30
- /**
31
- * Unknown mapping warning
32
- * @param {string} dataType
33
- * @returns {string}
34
- */
35
- export declare const warnUnknownMappingForDataType: (dataType: string) => void;
@@ -140,13 +140,3 @@ export const caseTransformer = (tableMetadata, transformCase) => {
140
140
  }
141
141
  return transformed;
142
142
  };
143
- /**
144
- * Unknown mapping warning
145
- * @param {string} dataType
146
- * @returns {string}
147
- */
148
- export const warnUnknownMappingForDataType = (dataType) => {
149
- console.warn(`[Warning]`, `Unknown data type mapping for type '${dataType}'.
150
- You should define the data type manually.
151
- `);
152
- };
package/build/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  export { Dialect } from './dialects/Dialect.js';
2
- export type { DialectName, ITablesMetadata, ITableMetadata, IColumnMetadata, IIndexMetadata, ITable, IColumnForeignKeyMetadata, IForeignKeyConstraintMetadata, } from './dialects/Dialect.js';
2
+ export type { DialectName, ITablesMetadata, ITableMetadata, IColumnMetadata, IColumnTypeOverride, IIndexMetadata, ITable, IColumnForeignKeyMetadata, IForeignKeyConstraintMetadata, } from './dialects/Dialect.js';
3
3
  export { createDialect } from './dialects/createDialect.js';
4
4
  export type { ReferentialAction } from './dialects/foreignKeys.js';
5
5
  export type { ISequelizeDataType, SequelizeDataTypeKey } from './dialects/dataTypes.js';
6
6
  export type { IAssociationMetadata } from './dialects/AssociationsParser.js';
7
7
  export { ModelBuilder } from './builders/index.js';
8
8
  export { TransformTarget, TransformCases } from './config/IConfig.js';
9
- export type { IConfig, IConfigMetadata, IConfigOutput, TransformCase, TransformMap, TransformFn, } from './config/IConfig.js';
9
+ export type { IConfig, IConfigMetadata, IConfigOutput, TransformCase, TransformMap, TransformFn, ITypeOverride, ITypeOverrides, } from './config/IConfig.js';
10
10
  export { FORMATS, DEFAULT_FORMAT, isFormat } from './config/format.js';
11
11
  export type { Format } from './config/format.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sequelize-typescript-generator",
3
- "version": "13.1.0",
3
+ "version": "13.2.0",
4
4
  "description": "Automatically generate type-safe Sequelize models from your source database via the TypeScript compiler API — native or sequelize-typescript (decorators) format.",
5
5
  "type": "module",
6
6
  "main": "build/index.js",
@@ -63,7 +63,7 @@
63
63
  "reflect-metadata": "^0.2.1",
64
64
  "sequelize-typescript": "^2.1.6",
65
65
  "@vscode/sqlite3": "^5.1.14-vscode",
66
- "tedious": "^18.6.1",
66
+ "tedious": "^20.3.3",
67
67
  "ts-jest": "^29.4.12",
68
68
  "tsx": "^4.23.13",
69
69
  "wkx": "^0.5.0"
@@ -76,7 +76,7 @@
76
76
  "pluralize": "^8.0.0",
77
77
  "sequelize": "^6.37.5",
78
78
  "typescript": ">=5.7 <6.1",
79
- "yargs": "^17.7.2"
79
+ "yargs": "^18.2.0"
80
80
  },
81
81
  "peerDependencies": {
82
82
  "typescript": ">=5.7 <6.1",