drizzle-seed 0.4.0-08bb2d5 → 0.4.0-0ec754e

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 (56) hide show
  1. package/SeedService.d.cts +1 -0
  2. package/SeedService.d.mts +1 -0
  3. package/SeedService.d.ts +1 -0
  4. package/cockroach-core/index.d.cts +6 -2
  5. package/cockroach-core/index.d.mts +6 -2
  6. package/cockroach-core/index.d.ts +6 -2
  7. package/common.d.cts +23 -0
  8. package/common.d.mts +23 -0
  9. package/common.d.ts +23 -0
  10. package/generators/GeneratorFuncs.d.cts +888 -28
  11. package/generators/GeneratorFuncs.d.mts +888 -28
  12. package/generators/GeneratorFuncs.d.ts +888 -28
  13. package/generators/Generators.d.cts +149 -44
  14. package/generators/Generators.d.mts +149 -44
  15. package/generators/Generators.d.ts +149 -44
  16. package/generators/apiVersion.d.cts +1 -1
  17. package/generators/apiVersion.d.mts +1 -1
  18. package/generators/apiVersion.d.ts +1 -1
  19. package/generators/versioning/v2.d.cts +13 -6
  20. package/generators/versioning/v2.d.mts +13 -6
  21. package/generators/versioning/v2.d.ts +13 -6
  22. package/generators/versioning/v3.d.cts +10 -0
  23. package/generators/versioning/v3.d.mts +10 -0
  24. package/generators/versioning/v3.d.ts +10 -0
  25. package/index.cjs +1122 -1186
  26. package/index.cjs.map +1 -1
  27. package/index.d.cts +13 -99
  28. package/index.d.mts +13 -99
  29. package/index.d.ts +13 -99
  30. package/index.mjs +1127 -1191
  31. package/index.mjs.map +1 -1
  32. package/mssql-core/index.d.cts +2 -2
  33. package/mssql-core/index.d.mts +2 -2
  34. package/mssql-core/index.d.ts +2 -2
  35. package/mysql-core/index.d.cts +6 -2
  36. package/mysql-core/index.d.mts +6 -2
  37. package/mysql-core/index.d.ts +6 -2
  38. package/package.json +108 -107
  39. package/pg-core/index.d.cts +6 -2
  40. package/pg-core/index.d.mts +6 -2
  41. package/pg-core/index.d.ts +6 -2
  42. package/singlestore-core/index.d.cts +6 -2
  43. package/singlestore-core/index.d.mts +6 -2
  44. package/singlestore-core/index.d.ts +6 -2
  45. package/sqlite-core/index.d.cts +6 -2
  46. package/sqlite-core/index.d.mts +6 -2
  47. package/sqlite-core/index.d.ts +6 -2
  48. package/types/seedService.d.cts +2 -2
  49. package/types/seedService.d.mts +2 -2
  50. package/types/seedService.d.ts +2 -2
  51. package/types/tables.d.cts +18 -0
  52. package/types/tables.d.mts +18 -0
  53. package/types/tables.d.ts +18 -0
  54. package/utils.d.cts +0 -1
  55. package/utils.d.mts +0 -1
  56. package/utils.d.ts +0 -1
package/index.mjs CHANGED
@@ -1,12 +1,195 @@
1
- import { is, entityKind, sql, eq, Relations, getTableName, extractTablesRelationalConfig, createTableRelationsHelpers, One } from 'drizzle-orm';
2
- import { MySqlDatabase, MySqlTable, getTableConfig as getTableConfig$2 } from 'drizzle-orm/mysql-core';
3
- import { PgDatabase, getTableConfig as getTableConfig$3, PgTable } from 'drizzle-orm/pg-core';
4
- import { BaseSQLiteDatabase, SQLiteTable, getTableConfig as getTableConfig$5 } from 'drizzle-orm/sqlite-core';
5
- import { MsSqlDatabase, getTableConfig, MsSqlTable } from 'drizzle-orm/mssql-core';
6
- import { CockroachDatabase, getTableConfig as getTableConfig$1, CockroachTable } from 'drizzle-orm/cockroach-core';
7
- import { SingleStoreDatabase, SingleStoreTable, getTableConfig as getTableConfig$4 } from 'drizzle-orm/singlestore-core';
1
+ import { getTableName, is, getColumnTable, Column, entityKind, sql, eq } from 'drizzle-orm';
2
+ import { MySqlTable, getTableConfig as getTableConfig$2, MySqlDatabase } from 'drizzle-orm/mysql-core';
3
+ import { PgTable, getTableConfig as getTableConfig$1, PgDatabase } from 'drizzle-orm/pg-core';
4
+ import { SQLiteTable, getTableConfig as getTableConfig$3, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
5
+ import { MsSqlTable, getTableConfig as getTableConfig$5, MsSqlDatabase } from 'drizzle-orm/mssql-core';
6
+ import { CockroachTable, getTableConfig as getTableConfig$4, CockroachDatabase } from 'drizzle-orm/cockroach-core';
7
+ import { getTableConfig as getTableConfig$6, SingleStoreDatabase, SingleStoreTable } from 'drizzle-orm/singlestore-core';
8
+ import { extractTablesRelationalConfig, createTableRelationsHelpers, One, Relations } from 'drizzle-orm/_relations';
8
9
  import prand from 'pure-rand';
9
10
 
11
+ const isRelationCyclic = (startRel) => {
12
+ // self relation
13
+ if (startRel.table === startRel.refTable)
14
+ return false;
15
+ // DFS
16
+ const targetTable = startRel.table;
17
+ const queue = [startRel];
18
+ let path = [];
19
+ while (queue.length !== 0) {
20
+ const currRel = queue.shift();
21
+ if (path.includes(currRel.table)) {
22
+ const idx = path.indexOf(currRel.table);
23
+ path = path.slice(0, idx);
24
+ }
25
+ path.push(currRel.table);
26
+ for (const rel of currRel.refTableRels) {
27
+ // self relation
28
+ if (rel.table === rel.refTable)
29
+ continue;
30
+ if (rel.refTable === targetTable)
31
+ return true;
32
+ // found cycle, but not the one we are looking for
33
+ if (path.includes(rel.refTable))
34
+ continue;
35
+ queue.unshift(rel);
36
+ }
37
+ }
38
+ return false;
39
+ };
40
+ const equalSets = (set1, set2) => {
41
+ return set1.size === set2.size && [...set1].every((si) => set2.has(si));
42
+ };
43
+
44
+ const getTableConfig = (table) => {
45
+ if (is(table, PgTable))
46
+ return getTableConfig$1(table);
47
+ else if (is(table, MySqlTable))
48
+ return getTableConfig$2(table);
49
+ else if (is(table, SQLiteTable))
50
+ return getTableConfig$3(table);
51
+ else if (is(table, CockroachTable))
52
+ return getTableConfig$4(table);
53
+ else if (is(table, MsSqlTable))
54
+ return getTableConfig$5(table);
55
+ else
56
+ return getTableConfig$6(table); // if (is(table, SingleStoreTable))
57
+ };
58
+ const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
59
+ const schemaConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
60
+ const relations = [];
61
+ for (const table of Object.values(schemaConfig.tables)) {
62
+ if (table.relations === undefined)
63
+ continue;
64
+ for (const drizzleRel of Object.values(table.relations)) {
65
+ if (!is(drizzleRel, One))
66
+ continue;
67
+ const tableConfig = getTableConfig(drizzleRel.sourceTable);
68
+ const tableDbSchema = tableConfig.schema ?? 'public';
69
+ const tableDbName = tableConfig.name;
70
+ const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
71
+ const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
72
+ const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
73
+ ?? [];
74
+ const refTableConfig = getTableConfig(drizzleRel.referencedTable);
75
+ const refTableDbSchema = refTableConfig.schema ?? 'public';
76
+ const refTableDbName = refTableConfig.name;
77
+ const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
78
+ ?? refTableDbName;
79
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
80
+ const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
81
+ ?? [];
82
+ if (tableRelations[refTableTsName] === undefined) {
83
+ tableRelations[refTableTsName] = [];
84
+ }
85
+ const relation = {
86
+ table: tableTsName,
87
+ columns,
88
+ refTable: refTableTsName,
89
+ refColumns,
90
+ refTableRels: tableRelations[refTableTsName],
91
+ type: 'one',
92
+ };
93
+ // do not add duplicate relation
94
+ if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
95
+ && rel.refTable === relation.refTable)) {
96
+ console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
97
+ + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
98
+ + `In this case, the foreign key constraint will be used.\n`);
99
+ continue;
100
+ }
101
+ relations.push(relation);
102
+ tableRelations[tableTsName].push(relation);
103
+ }
104
+ }
105
+ return relations;
106
+ };
107
+ const getSchemaInfo = (drizzleTablesAndRelations, drizzleTables, mapColumns) => {
108
+ let tableConfig;
109
+ let dbToTsColumnNamesMap;
110
+ const dbToTsTableNamesMap = Object.fromEntries(Object.entries(drizzleTables).map(([key, value]) => [getTableName(value), key]));
111
+ const tables = [];
112
+ const relations = [];
113
+ const dbToTsColumnNamesMapGlobal = {};
114
+ const tableRelations = {};
115
+ const getDbToTsColumnNamesMap = (table) => {
116
+ let dbToTsColumnNamesMap = {};
117
+ const tableName = getTableName(table);
118
+ if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
119
+ dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
120
+ return dbToTsColumnNamesMap;
121
+ }
122
+ const tableConfig = getTableConfig(table);
123
+ for (const [tsCol, col] of Object.entries(getColumnTable(tableConfig.columns[0]))) {
124
+ if (is(col, Column))
125
+ dbToTsColumnNamesMap[col.name] = tsCol;
126
+ }
127
+ dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
128
+ return dbToTsColumnNamesMap;
129
+ };
130
+ for (const table of Object.values(drizzleTables)) {
131
+ tableConfig = getTableConfig(table);
132
+ dbToTsColumnNamesMap = getDbToTsColumnNamesMap(table);
133
+ // might be empty list
134
+ const newRelations = tableConfig.foreignKeys === undefined ? [] : tableConfig.foreignKeys.map((fk) => {
135
+ const table = dbToTsTableNamesMap[tableConfig.name];
136
+ const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)];
137
+ const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
138
+ if (tableRelations[refTable] === undefined) {
139
+ tableRelations[refTable] = [];
140
+ }
141
+ return {
142
+ table,
143
+ columns: fk
144
+ .reference()
145
+ .columns.map((col) => dbToTsColumnNamesMap[col.name]),
146
+ refTable,
147
+ refColumns: fk
148
+ .reference()
149
+ .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
150
+ refTableRels: tableRelations[refTable],
151
+ };
152
+ });
153
+ relations.push(...newRelations);
154
+ if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
155
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
156
+ }
157
+ tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
158
+ const stringsSet = [];
159
+ const uniqueConstraints = [];
160
+ for (const uniCon of tableConfig.uniqueConstraints) {
161
+ const uniConColumns = uniCon.columns.map((col) => dbToTsColumnNamesMap[col.name]);
162
+ const uniConColumnsStr = JSON.stringify(uniConColumns);
163
+ if (!stringsSet.includes(uniConColumnsStr)) {
164
+ stringsSet.push(uniConColumnsStr);
165
+ uniqueConstraints.push(uniConColumns);
166
+ }
167
+ }
168
+ const mappedTable = {
169
+ name: dbToTsTableNamesMap[tableConfig.name],
170
+ uniqueConstraints,
171
+ primaryKeys: tableConfig.columns
172
+ .filter((column) => column.primary)
173
+ .map((column) => dbToTsColumnNamesMap[column.name]),
174
+ columns: mapColumns(tableConfig, dbToTsColumnNamesMap),
175
+ };
176
+ tables.push(mappedTable);
177
+ }
178
+ const transformedDrizzleRelations = transformFromDrizzleRelation(drizzleTablesAndRelations, getDbToTsColumnNamesMap, tableRelations);
179
+ relations.push(...transformedDrizzleRelations);
180
+ const isCyclicRelations = relations.map((relI) => {
181
+ // if (relations.some((relj) => relI.table === relj.refTable && relI.refTable === relj.table)) {
182
+ const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
183
+ if (isRelationCyclic(relI)) {
184
+ tableRel['isCyclic'] = true;
185
+ return { ...relI, isCyclic: true };
186
+ }
187
+ tableRel['isCyclic'] = false;
188
+ return { ...relI, isCyclic: false };
189
+ });
190
+ return { tables, relations: isCyclicRelations, tableRelations };
191
+ };
192
+
10
193
  /**
11
194
  * The original source for the Adjectives data was taken from https://www.kaggle.com/datasets/jordansiem/adjectives-list
12
195
  */
@@ -131272,10 +131455,12 @@ const isObject = (value) => {
131272
131455
  class AbstractGenerator {
131273
131456
  static entityKind = 'AbstractGenerator';
131274
131457
  static version = 1;
131458
+ isGeneratorUnique = false;
131275
131459
  isUnique = false;
131276
131460
  notNull = false;
131277
131461
  // param for generators which have a unique version of themselves
131278
131462
  uniqueVersionOfGen;
131463
+ maxUniqueCount = -1;
131279
131464
  dataType;
131280
131465
  timeSpent;
131281
131466
  //
@@ -131287,6 +131472,7 @@ class AbstractGenerator {
131287
131472
  weightedCountSeed;
131288
131473
  maxRepeatedValuesCount;
131289
131474
  typeParams = {};
131475
+ uniqueKey;
131290
131476
  params;
131291
131477
  constructor(params) {
131292
131478
  this.params = params === undefined ? {} : params;
@@ -131309,9 +131495,13 @@ class AbstractGenerator {
131309
131495
  const constructor = this.constructor;
131310
131496
  return constructor.entityKind;
131311
131497
  }
131498
+ getMaxUniqueCount() {
131499
+ // override if you need to initialize this.maxUniqueCount after constructor
131500
+ return this.maxUniqueCount;
131501
+ }
131312
131502
  replaceIfUnique() {
131313
131503
  this.updateParams();
131314
- if (this.uniqueVersionOfGen !== undefined
131504
+ if ((this.uniqueVersionOfGen !== undefined)
131315
131505
  && this.isUnique === true) {
131316
131506
  const uniqueGen = new this.uniqueVersionOfGen({
131317
131507
  ...this.params,
@@ -131342,6 +131532,20 @@ class AbstractGenerator {
131342
131532
  }
131343
131533
  }
131344
131534
  // Generators Classes -----------------------------------------------------------------------------------------------------------------------
131535
+ class GenerateHashFromString extends AbstractGenerator {
131536
+ static entityKind = 'GenerateHashFromString';
131537
+ init() { }
131538
+ generate({ input }) {
131539
+ let hash = 0;
131540
+ // p and m are prime numbers
131541
+ const p = 53;
131542
+ const m = 28871271685163;
131543
+ for (let i = 0; i < input.length; i++) {
131544
+ hash += ((input.codePointAt(i) || 0) * Math.pow(p, i)) % m;
131545
+ }
131546
+ return hash;
131547
+ }
131548
+ }
131345
131549
  class GenerateArray extends AbstractGenerator {
131346
131550
  static entityKind = 'GenerateArray';
131347
131551
  arraySize = 10;
@@ -131401,6 +131605,23 @@ class GenerateValuesFromArray extends AbstractGenerator {
131401
131605
  static entityKind = 'GenerateValuesFromArray';
131402
131606
  state;
131403
131607
  timeSpent = 0;
131608
+ maxUniqueCount;
131609
+ allValuesCount = 0; // TODO rewrite generator
131610
+ constructor(params) {
131611
+ super(params);
131612
+ this.allValuesCount = this.params.values.length;
131613
+ if (isObject(this.params.values[0])) {
131614
+ this.allValuesCount = this.params.values.reduce((acc, currVal) => acc + currVal.values.length, 0);
131615
+ }
131616
+ this.maxUniqueCount = this.allValuesCount;
131617
+ }
131618
+ getMaxUniqueCount() {
131619
+ this.allValuesCount = this.params.values.length;
131620
+ if (isObject(this.params.values[0])) {
131621
+ this.allValuesCount = this.params.values.reduce((acc, currVal) => acc + currVal.values.length, 0);
131622
+ }
131623
+ return this.allValuesCount;
131624
+ }
131404
131625
  checks({ count }) {
131405
131626
  const { values } = this.params;
131406
131627
  const { maxRepeatedValuesCount, notNull, isUnique } = this;
@@ -131418,16 +131639,13 @@ class GenerateValuesFromArray extends AbstractGenerator {
131418
131639
  : obj.count.every((count) => count > 0))))) {
131419
131640
  throw new Error('maxRepeatedValuesCount should be greater than zero.');
131420
131641
  }
131421
- let allValuesCount = values.length;
131422
- if (isObject(values[0])) {
131423
- allValuesCount = values.reduce((acc, currVal) => acc + currVal.values.length, 0);
131424
- }
131425
131642
  if (notNull === true
131426
131643
  && maxRepeatedValuesCount !== undefined
131427
131644
  && ((!isObject(values[0]) && typeof maxRepeatedValuesCount === 'number'
131428
131645
  && maxRepeatedValuesCount * values.length < count)
131429
131646
  || (isObject(values[0]) && typeof maxRepeatedValuesCount === 'number'
131430
- && maxRepeatedValuesCount * allValuesCount < count))) {
131647
+ // eslint-disable-next-line unicorn/consistent-destructuring
131648
+ && maxRepeatedValuesCount * this.allValuesCount < count))) {
131431
131649
  throw new Error("Can't fill notNull column with null values.");
131432
131650
  }
131433
131651
  if (isUnique === true && maxRepeatedValuesCount !== undefined && ((typeof maxRepeatedValuesCount === 'number' && maxRepeatedValuesCount > 1)
@@ -131438,7 +131656,8 @@ class GenerateValuesFromArray extends AbstractGenerator {
131438
131656
  throw new Error("Can't be greater than 1 if column is unique.");
131439
131657
  }
131440
131658
  if (isUnique === true && notNull === true && ((!isObject(values[0]) && values.length < count)
131441
- || (isObject(values[0]) && allValuesCount < count))) {
131659
+ // eslint-disable-next-line unicorn/consistent-destructuring
131660
+ || (isObject(values[0]) && this.allValuesCount < count))) {
131442
131661
  // console.log(maxRepeatedValuesCount, values.length, allValuesCount, count)
131443
131662
  throw new Error('There are no enough values to fill unique column.');
131444
131663
  }
@@ -131574,6 +131793,8 @@ class GenerateSelfRelationsValuesFromArray extends AbstractGenerator {
131574
131793
  class GenerateIntPrimaryKey extends AbstractGenerator {
131575
131794
  static entityKind = 'GenerateIntPrimaryKey';
131576
131795
  maxValue;
131796
+ maxUniqueCount = Number.POSITIVE_INFINITY;
131797
+ isGeneratorUnique = true;
131577
131798
  init({ count }) {
131578
131799
  if (this.maxValue !== undefined && count > this.maxValue) {
131579
131800
  throw new Error('count exceeds max number for this column type.');
@@ -131624,14 +131845,39 @@ class GenerateNumber extends AbstractGenerator {
131624
131845
  class GenerateUniqueNumber extends AbstractGenerator {
131625
131846
  static entityKind = 'GenerateUniqueNumber';
131626
131847
  state;
131627
- isUnique = true;
131628
- init({ count, seed }) {
131848
+ precision;
131849
+ isGeneratorUnique = true;
131850
+ maxUniqueCount;
131851
+ constructor(params) {
131852
+ super(params);
131853
+ let { minValue, maxValue } = this.params;
131854
+ const { precision } = this.params;
131855
+ this.precision = precision ?? 100;
131856
+ if (maxValue === undefined) {
131857
+ this.maxUniqueCount = Number.POSITIVE_INFINITY;
131858
+ return;
131859
+ }
131860
+ else {
131861
+ maxValue *= this.precision;
131862
+ }
131863
+ if (minValue === undefined) {
131864
+ minValue = -maxValue;
131865
+ }
131866
+ else {
131867
+ minValue *= this.precision;
131868
+ }
131869
+ this.maxUniqueCount = maxValue - minValue + 1;
131870
+ }
131871
+ getMaxUniqueCount() {
131872
+ if (this.maxUniqueCount !== undefined)
131873
+ return this.maxUniqueCount;
131629
131874
  let { minValue, maxValue, precision } = this.params;
131630
131875
  if (precision === undefined) {
131631
131876
  precision = 100;
131632
131877
  }
131633
131878
  if (maxValue === undefined) {
131634
- maxValue = count * precision;
131879
+ this.maxUniqueCount = Number.POSITIVE_INFINITY;
131880
+ return this.maxUniqueCount;
131635
131881
  }
131636
131882
  else {
131637
131883
  maxValue *= precision;
@@ -131642,9 +131888,26 @@ class GenerateUniqueNumber extends AbstractGenerator {
131642
131888
  else {
131643
131889
  minValue *= precision;
131644
131890
  }
131891
+ this.maxUniqueCount = maxValue - minValue + 1;
131892
+ return this.maxUniqueCount;
131893
+ }
131894
+ init({ count, seed }) {
131895
+ let { minValue, maxValue } = this.params;
131896
+ if (maxValue === undefined) {
131897
+ maxValue = count * this.precision;
131898
+ }
131899
+ else {
131900
+ maxValue *= this.precision;
131901
+ }
131902
+ if (minValue === undefined) {
131903
+ minValue = -maxValue;
131904
+ }
131905
+ else {
131906
+ minValue *= this.precision;
131907
+ }
131645
131908
  const genUniqueIntObj = new GenerateUniqueInt({ minValue, maxValue });
131646
131909
  genUniqueIntObj.init({ count, seed });
131647
- this.state = { genUniqueIntObj, minValue, maxValue, precision };
131910
+ this.state = { genUniqueIntObj, minValue, maxValue, precision: this.precision };
131648
131911
  }
131649
131912
  generate() {
131650
131913
  if (this.state === undefined) {
@@ -131699,8 +131962,48 @@ class GenerateUniqueInt extends AbstractGenerator {
131699
131962
  genMaxRepeatedValuesCount;
131700
131963
  skipCheck = false;
131701
131964
  state;
131702
- isUnique = true;
131965
+ isGeneratorUnique = true;
131703
131966
  timeSpent = 0;
131967
+ maxUniqueCount;
131968
+ constructor(params) {
131969
+ super(params);
131970
+ let minValue = this.params.minValue, maxValue = this.params.maxValue;
131971
+ if (maxValue === undefined) {
131972
+ this.maxUniqueCount = Number.POSITIVE_INFINITY;
131973
+ return;
131974
+ }
131975
+ if (minValue === undefined) {
131976
+ minValue = -maxValue;
131977
+ }
131978
+ if (typeof minValue === 'number' && typeof maxValue === 'number') {
131979
+ minValue = minValue >= 0 ? Math.ceil(minValue) : Math.floor(minValue);
131980
+ maxValue = maxValue >= 0 ? Math.floor(maxValue) : Math.ceil(maxValue);
131981
+ this.maxUniqueCount = Number(maxValue - minValue) + 1;
131982
+ }
131983
+ else if (typeof minValue === 'bigint' && typeof maxValue === 'bigint') {
131984
+ this.maxUniqueCount = Number(maxValue - minValue) + 1;
131985
+ }
131986
+ else
131987
+ this.maxUniqueCount = Number(Number(maxValue) - Number(minValue)) + 1; // error should be triggered in init method
131988
+ }
131989
+ getMaxUniqueCount() {
131990
+ if (this.maxUniqueCount !== undefined)
131991
+ return this.maxUniqueCount;
131992
+ let minValue = this.params.minValue, maxValue = this.params.maxValue;
131993
+ if (maxValue === undefined) {
131994
+ this.maxUniqueCount = Number.POSITIVE_INFINITY;
131995
+ return this.maxUniqueCount;
131996
+ }
131997
+ if (minValue === undefined) {
131998
+ minValue = -maxValue;
131999
+ }
132000
+ if (typeof minValue === 'number' && typeof maxValue === 'number') {
132001
+ minValue = minValue >= 0 ? Math.ceil(minValue) : Math.floor(minValue);
132002
+ maxValue = maxValue >= 0 ? Math.floor(maxValue) : Math.ceil(maxValue);
132003
+ }
132004
+ this.maxUniqueCount = Number(maxValue - minValue) + 1;
132005
+ return this.maxUniqueCount;
132006
+ }
131704
132007
  init({ count, seed }) {
131705
132008
  const rng = prand.xoroshiro128plus(seed);
131706
132009
  let { minValue, maxValue } = this.params;
@@ -132130,11 +132433,10 @@ class GenerateInterval extends AbstractGenerator {
132130
132433
  return interval;
132131
132434
  }
132132
132435
  }
132133
- // has a newer version
132134
132436
  class GenerateUniqueInterval extends AbstractGenerator {
132135
132437
  static 'entityKind' = 'GenerateUniqueInterval';
132136
132438
  state;
132137
- isUnique = true;
132439
+ isGeneratorUnique = true;
132138
132440
  config = {
132139
132441
  year: {
132140
132442
  from: 0,
@@ -132161,6 +132463,47 @@ class GenerateUniqueInterval extends AbstractGenerator {
132161
132463
  to: 60,
132162
132464
  },
132163
132465
  };
132466
+ maxUniqueCount;
132467
+ constructor(params) {
132468
+ super(params);
132469
+ const allFields = ['year', 'month', 'day', 'hour', 'minute', 'second'];
132470
+ let fieldsToGenerate = allFields;
132471
+ if (this.params.fields !== undefined && this.params.fields?.includes(' to ')) {
132472
+ const tokens = this.params.fields.split(' to ');
132473
+ const endIdx = allFields.indexOf(tokens[1]);
132474
+ fieldsToGenerate = allFields.slice(0, endIdx + 1);
132475
+ }
132476
+ else if (this.params.fields !== undefined) {
132477
+ const endIdx = allFields.indexOf(this.params.fields);
132478
+ fieldsToGenerate = allFields.slice(0, endIdx + 1);
132479
+ }
132480
+ this.maxUniqueCount = 1;
132481
+ for (const field of fieldsToGenerate) {
132482
+ const from = this.config[field].from, to = this.config[field].to;
132483
+ this.maxUniqueCount *= from - to + 1;
132484
+ }
132485
+ }
132486
+ getMaxUniqueCount() {
132487
+ if (this.maxUniqueCount !== undefined)
132488
+ return this.maxUniqueCount;
132489
+ const allFields = ['year', 'month', 'day', 'hour', 'minute', 'second'];
132490
+ let fieldsToGenerate = allFields;
132491
+ if (this.params.fields !== undefined && this.params.fields?.includes(' to ')) {
132492
+ const tokens = this.params.fields.split(' to ');
132493
+ const endIdx = allFields.indexOf(tokens[1]);
132494
+ fieldsToGenerate = allFields.slice(0, endIdx + 1);
132495
+ }
132496
+ else if (this.params.fields !== undefined) {
132497
+ const endIdx = allFields.indexOf(this.params.fields);
132498
+ fieldsToGenerate = allFields.slice(0, endIdx + 1);
132499
+ }
132500
+ this.maxUniqueCount = 1;
132501
+ for (const field of fieldsToGenerate) {
132502
+ const from = this.config[field].from, to = this.config[field].to;
132503
+ this.maxUniqueCount *= from - to + 1;
132504
+ }
132505
+ return this.maxUniqueCount;
132506
+ }
132164
132507
  init({ count, seed }) {
132165
132508
  const allFields = ['year', 'month', 'day', 'hour', 'minute', 'second'];
132166
132509
  let fieldsToGenerate = allFields;
@@ -132229,6 +132572,8 @@ class GenerateString extends AbstractGenerator {
132229
132572
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
132230
132573
  currStr += stringChars[idx];
132231
132574
  }
132575
+ if (this.dataType === 'object')
132576
+ return Buffer.from(currStr);
132232
132577
  return currStr;
132233
132578
  }
132234
132579
  }
@@ -132236,7 +132581,11 @@ class GenerateString extends AbstractGenerator {
132236
132581
  class GenerateUniqueString extends AbstractGenerator {
132237
132582
  static entityKind = 'GenerateUniqueString';
132238
132583
  state;
132239
- isUnique = true;
132584
+ isGeneratorUnique = true;
132585
+ maxUniqueCount = Number.POSITIVE_INFINITY;
132586
+ getMaxUniqueCount() {
132587
+ return Number.POSITIVE_INFINITY;
132588
+ }
132240
132589
  init({ seed }) {
132241
132590
  const rng = prand.xoroshiro128plus(seed);
132242
132591
  this.state = { rng };
@@ -132257,13 +132606,20 @@ class GenerateUniqueString extends AbstractGenerator {
132257
132606
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
132258
132607
  currStr += stringChars[idx];
132259
132608
  }
132260
- return currStr.slice(0, 4) + uniqueStr + currStr.slice(4);
132609
+ currStr = currStr.slice(0, 4) + uniqueStr + currStr.slice(4);
132610
+ if (this.dataType === 'object')
132611
+ return Buffer.from(currStr);
132612
+ return currStr;
132261
132613
  }
132262
132614
  }
132263
132615
  class GenerateUUID extends AbstractGenerator {
132264
132616
  static entityKind = 'GenerateUUID';
132265
- isUnique = true;
132617
+ isGeneratorUnique = true;
132618
+ maxUniqueCount = Number.POSITIVE_INFINITY;
132266
132619
  state;
132620
+ getMaxUniqueCount() {
132621
+ return Number.POSITIVE_INFINITY;
132622
+ }
132267
132623
  init({ count, seed }) {
132268
132624
  super.init({ count, seed });
132269
132625
  const rng = prand.xoroshiro128plus(seed);
@@ -132318,9 +132674,16 @@ class GenerateFirstName extends AbstractGenerator {
132318
132674
  class GenerateUniqueFirstName extends AbstractGenerator {
132319
132675
  static entityKind = 'GenerateUniqueFirstName';
132320
132676
  state;
132321
- isUnique = true;
132677
+ isGeneratorUnique = true;
132678
+ maxUniqueCount = firstNames.length;
132679
+ getMaxUniqueCount() {
132680
+ if (this.maxUniqueCount !== undefined)
132681
+ return this.maxUniqueCount;
132682
+ this.maxUniqueCount = firstNames.length;
132683
+ return firstNames.length;
132684
+ }
132322
132685
  init({ count, seed }) {
132323
- if (count > firstNames.length) {
132686
+ if (count > this.getMaxUniqueCount()) {
132324
132687
  throw new Error('count exceeds max number of unique first names.');
132325
132688
  }
132326
132689
  if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$5) {
@@ -132364,9 +132727,16 @@ class GenerateLastName extends AbstractGenerator {
132364
132727
  class GenerateUniqueLastName extends AbstractGenerator {
132365
132728
  static entityKind = 'GenerateUniqueLastName';
132366
132729
  state;
132367
- isUnique = true;
132730
+ isGeneratorUnique = true;
132731
+ maxUniqueCount = lastNames.length;
132732
+ getMaxUniqueCount() {
132733
+ if (this.maxUniqueCount !== undefined)
132734
+ return this.maxUniqueCount;
132735
+ this.maxUniqueCount = lastNames.length;
132736
+ return lastNames.length;
132737
+ }
132368
132738
  init({ count, seed }) {
132369
- if (count > lastNames.length) {
132739
+ if (count > this.getMaxUniqueCount()) {
132370
132740
  throw new Error('count exceeds max number of unique last names.');
132371
132741
  }
132372
132742
  if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$3) {
@@ -132413,13 +132783,19 @@ class GenerateFullName extends AbstractGenerator {
132413
132783
  class GenerateUniqueFullName extends AbstractGenerator {
132414
132784
  static entityKind = 'GenerateUniqueFullName';
132415
132785
  state;
132416
- isUnique = true;
132786
+ isGeneratorUnique = true;
132417
132787
  timeSpent = 0;
132788
+ maxUniqueCount = firstNames.length * lastNames.length;
132789
+ getMaxUniqueCount() {
132790
+ if (this.maxUniqueCount !== undefined)
132791
+ return this.maxUniqueCount;
132792
+ this.maxUniqueCount = firstNames.length * lastNames.length;
132793
+ return this.maxUniqueCount;
132794
+ }
132418
132795
  init({ count, seed }) {
132419
132796
  const t0 = new Date();
132420
- const maxUniqueFullNamesNumber = firstNames.length * lastNames.length;
132421
- if (count > maxUniqueFullNamesNumber) {
132422
- throw new RangeError(`count exceeds max number of unique full names(${maxUniqueFullNamesNumber}).`);
132797
+ if (count > this.getMaxUniqueCount()) {
132798
+ throw new RangeError(`count exceeds max number of unique full names(${this.getMaxUniqueCount()}).`);
132423
132799
  }
132424
132800
  if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxStringLength$5 + maxStringLength$3 + 1)) {
132425
132801
  throw new Error(`You can't use full name generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxStringLength$5 + maxStringLength$3 + 1}.`);
@@ -132454,13 +132830,17 @@ class GenerateEmail extends AbstractGenerator {
132454
132830
  static entityKind = 'GenerateEmail';
132455
132831
  state;
132456
132832
  timeSpent = 0;
132457
- isUnique = true;
132833
+ isGeneratorUnique = true;
132834
+ maxUniqueCount = adjectives.length * firstNames.length * emailDomains.length;
132835
+ getMaxUniqueCount() {
132836
+ if (this.maxUniqueCount !== undefined)
132837
+ return this.maxUniqueCount;
132838
+ this.maxUniqueCount = adjectives.length * firstNames.length * emailDomains.length;
132839
+ return this.maxUniqueCount;
132840
+ }
132458
132841
  init({ count, seed }) {
132459
132842
  super.init({ count, seed });
132460
- const domainsArray = emailDomains;
132461
- const adjectivesArray = adjectives;
132462
- const namesArray = firstNames;
132463
- const maxUniqueEmailsNumber = adjectivesArray.length * namesArray.length * domainsArray.length;
132843
+ const maxUniqueEmailsNumber = adjectives.length * firstNames.length * emailDomains.length;
132464
132844
  if (count > maxUniqueEmailsNumber) {
132465
132845
  throw new RangeError(`count exceeds max number of unique emails(${maxUniqueEmailsNumber}).`);
132466
132846
  }
@@ -132468,7 +132848,7 @@ class GenerateEmail extends AbstractGenerator {
132468
132848
  if (this.typeParams?.length !== undefined && this.typeParams?.length < maxEmailLength) {
132469
132849
  throw new Error(`You can't use email generator with a db column length restriction of ${this.typeParams?.length}. Set the maximum string length to at least ${maxEmailLength}.`);
132470
132850
  }
132471
- const arraysToGenerateFrom = [adjectivesArray, namesArray, domainsArray];
132851
+ const arraysToGenerateFrom = [adjectives, firstNames, emailDomains];
132472
132852
  const genIndicesObj = new GenerateUniqueInt({
132473
132853
  minValue: 0,
132474
132854
  maxValue: maxUniqueEmailsNumber - 1,
@@ -132492,20 +132872,75 @@ class GenerateEmail extends AbstractGenerator {
132492
132872
  class GeneratePhoneNumber extends AbstractGenerator {
132493
132873
  static entityKind = 'GeneratePhoneNumber';
132494
132874
  state;
132495
- isUnique = true;
132875
+ isGeneratorUnique = true;
132876
+ maxUniqueCount;
132877
+ constructor(params) {
132878
+ super(params);
132879
+ const { template } = this.params;
132880
+ if (template === undefined) {
132881
+ const { generatedDigitsNumbers } = this.prepareWithoutTemplate();
132882
+ this.maxUniqueCount = generatedDigitsNumbers.reduce((a, b) => a + Math.pow(10, b), 0);
132883
+ }
132884
+ else {
132885
+ const { placeholdersCount } = this.prepareWithTemplate();
132886
+ this.maxUniqueCount = Math.pow(10, placeholdersCount);
132887
+ }
132888
+ }
132889
+ prepareWithTemplate() {
132890
+ const { template } = this.params;
132891
+ const iterArray = [...template.matchAll(/#/g)];
132892
+ const placeholdersCount = iterArray.length;
132893
+ return { placeholdersCount };
132894
+ }
132895
+ prepareWithoutTemplate() {
132896
+ let { generatedDigitsNumbers, prefixes } = this.params;
132897
+ if (prefixes === undefined || prefixes.length === 0) {
132898
+ prefixes = phonesInfo.map((phoneInfo) => phoneInfo.split(',').slice(0, -1).join(' '));
132899
+ generatedDigitsNumbers = phonesInfo.map((phoneInfo) => {
132900
+ // tokens = ["380","99","9"] =
132901
+ // = ["country prefix", "operator prefix", "number length including operator prefix and excluding country prefix"]
132902
+ const tokens = phoneInfo.split(',');
132903
+ const operatorPrefixLength = tokens[1].replaceAll(' ', '').length;
132904
+ return Number(tokens[2]) - operatorPrefixLength;
132905
+ });
132906
+ }
132907
+ else {
132908
+ if (typeof generatedDigitsNumbers === 'number') {
132909
+ generatedDigitsNumbers = Array.from({ length: prefixes.length }).fill(generatedDigitsNumbers);
132910
+ }
132911
+ else if (generatedDigitsNumbers === undefined
132912
+ || generatedDigitsNumbers.length === 0) {
132913
+ generatedDigitsNumbers = Array.from({ length: prefixes.length }).fill(7);
132914
+ }
132915
+ }
132916
+ return { prefixes, generatedDigitsNumbers };
132917
+ }
132918
+ getMaxUniqueCount() {
132919
+ if (this.maxUniqueCount !== undefined)
132920
+ return this.maxUniqueCount;
132921
+ const { template } = this.params;
132922
+ if (template === undefined) {
132923
+ const { generatedDigitsNumbers } = this.prepareWithoutTemplate();
132924
+ this.maxUniqueCount = generatedDigitsNumbers.reduce((a, b) => a + Math.pow(10, b), 0);
132925
+ return this.maxUniqueCount;
132926
+ }
132927
+ else {
132928
+ const { placeholdersCount } = this.prepareWithTemplate();
132929
+ this.maxUniqueCount = Math.pow(10, placeholdersCount);
132930
+ return this.maxUniqueCount;
132931
+ }
132932
+ }
132496
132933
  init({ count, seed }) {
132497
132934
  super.init({ count, seed });
132498
- let { generatedDigitsNumbers } = this.params;
132499
- const { prefixes, template } = this.params;
132935
+ const { template } = this.params;
132500
132936
  const rng = prand.xoroshiro128plus(seed);
132501
132937
  if (template !== undefined) {
132502
132938
  if (this.typeParams?.length !== undefined && this.typeParams?.length < template.length) {
132503
132939
  throw new Error(`Length of phone number template is shorter than db column length restriction: ${this.typeParams?.length}.
132504
132940
  Set the maximum string length to at least ${template.length}.`);
132505
132941
  }
132506
- const iterArray = [...template.matchAll(/#/g)];
132507
- const placeholdersCount = iterArray.length;
132508
- const maxUniquePhoneNumbersCount = Math.pow(10, placeholdersCount);
132942
+ const { placeholdersCount } = this.prepareWithTemplate();
132943
+ const maxUniquePhoneNumbersCount = this.getMaxUniqueCount();
132509
132944
  if (maxUniquePhoneNumbersCount < count) {
132510
132945
  throw new RangeError(`count exceeds max number of unique phone numbers(${maxUniquePhoneNumbersCount}).`);
132511
132946
  }
@@ -132522,27 +132957,8 @@ class GeneratePhoneNumber extends AbstractGenerator {
132522
132957
  this.state = { rng, placeholdersCount, generatorsMap, prefixesArray, generatedDigitsNumbers, phoneNumbersSet };
132523
132958
  return;
132524
132959
  }
132525
- let prefixesArray;
132526
- if (prefixes === undefined || prefixes.length === 0) {
132527
- prefixesArray = phonesInfo.map((phoneInfo) => phoneInfo.split(',').slice(0, -1).join(' '));
132528
- generatedDigitsNumbers = phonesInfo.map((phoneInfo) => {
132529
- // tokens = ["380","99","9"] =
132530
- // = ["country prefix", "operator prefix", "number length including operator prefix and excluding country prefix"]
132531
- const tokens = phoneInfo.split(',');
132532
- const operatorPrefixLength = tokens[1].replaceAll(' ', '').length;
132533
- return Number(tokens[2]) - operatorPrefixLength;
132534
- });
132535
- }
132536
- else {
132537
- prefixesArray = prefixes;
132538
- if (typeof generatedDigitsNumbers === 'number') {
132539
- generatedDigitsNumbers = Array.from({ length: prefixes.length }).fill(generatedDigitsNumbers);
132540
- }
132541
- else if (generatedDigitsNumbers === undefined
132542
- || generatedDigitsNumbers.length === 0) {
132543
- generatedDigitsNumbers = Array.from({ length: prefixes.length }).fill(7);
132544
- }
132545
- }
132960
+ const { generatedDigitsNumbers, prefixes } = this.prepareWithoutTemplate();
132961
+ const prefixesArray = [...prefixes];
132546
132962
  const maxPrefixLength = Math.max(...prefixesArray.map((prefix) => prefix.length));
132547
132963
  const maxGeneratedDigits = Math.max(...generatedDigitsNumbers);
132548
132964
  if (this.typeParams?.length !== undefined && this.typeParams?.length < (maxPrefixLength + maxGeneratedDigits)) {
@@ -132551,7 +132967,7 @@ class GeneratePhoneNumber extends AbstractGenerator {
132551
132967
  if (new Set(prefixesArray).size !== prefixesArray.length) {
132552
132968
  throw new Error('prefixes are not unique.');
132553
132969
  }
132554
- const maxUniquePhoneNumbersCount = generatedDigitsNumbers.reduce((a, b) => a + Math.pow(10, b), 0);
132970
+ const maxUniquePhoneNumbersCount = this.getMaxUniqueCount();
132555
132971
  if (maxUniquePhoneNumbersCount < count) {
132556
132972
  throw new RangeError(`count exceeds max number of unique phone numbers(${maxUniquePhoneNumbersCount}).`);
132557
132973
  }
@@ -132641,9 +133057,16 @@ class GenerateCountry extends AbstractGenerator {
132641
133057
  class GenerateUniqueCountry extends AbstractGenerator {
132642
133058
  static entityKind = 'GenerateUniqueCountry';
132643
133059
  state;
132644
- isUnique = true;
133060
+ isGeneratorUnique = true;
133061
+ maxUniqueCount = countries.length;
133062
+ getMaxUniqueCount() {
133063
+ if (this.maxUniqueCount !== undefined)
133064
+ return this.maxUniqueCount;
133065
+ this.maxUniqueCount = countries.length;
133066
+ return this.maxUniqueCount;
133067
+ }
132645
133068
  init({ count, seed }) {
132646
- if (count > countries.length) {
133069
+ if (count > this.getMaxUniqueCount()) {
132647
133070
  throw new Error('count exceeds max number of unique countries.');
132648
133071
  }
132649
133072
  if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$7) {
@@ -132712,11 +133135,17 @@ class GenerateStreetAddress extends AbstractGenerator {
132712
133135
  class GenerateUniqueStreetAddress extends AbstractGenerator {
132713
133136
  static entityKind = 'GenerateUniqueStreetAddress';
132714
133137
  state;
132715
- isUnique = true;
133138
+ isGeneratorUnique = true;
133139
+ streetNumbersCount = 999;
133140
+ maxUniqueCount = this.streetNumbersCount * (firstNames.length + lastNames.length)
133141
+ * streetSuffix.length;
133142
+ getMaxUniqueCount() {
133143
+ return this.maxUniqueCount;
133144
+ }
132716
133145
  init({ count, seed }) {
132717
- const streetNumberStrs = Array.from({ length: 999 }, (_, i) => String(i + 1));
132718
- const maxUniqueStreetnamesNumber = streetNumberStrs.length * firstNames.length * streetSuffix.length
132719
- + streetNumberStrs.length * firstNames.length * streetSuffix.length;
133146
+ const streetNumberStrs = Array.from({ length: this.streetNumbersCount }, (_, i) => String(i + 1));
133147
+ const maxUniqueStreetnamesNumber = streetNumberStrs.length * (firstNames.length + lastNames.length)
133148
+ * streetSuffix.length;
132720
133149
  if (count > maxUniqueStreetnamesNumber) {
132721
133150
  throw new RangeError(`count exceeds max number of unique street names(${maxUniqueStreetnamesNumber}).`);
132722
133151
  }
@@ -132741,7 +133170,7 @@ class GenerateUniqueStreetAddress extends AbstractGenerator {
132741
133170
  minValue: 0,
132742
133171
  maxValue: streetNumberStrs.length * lastNames.length * streetSuffix.length - 1,
132743
133172
  }),
132744
- maxUniqueStreetNamesNumber: streetNumberStrs.length * firstNames.length * streetSuffix.length,
133173
+ maxUniqueStreetNamesNumber: streetNumberStrs.length * lastNames.length * streetSuffix.length,
132745
133174
  count: 0,
132746
133175
  arraysToChooseFrom: [streetNumberStrs, lastNames, streetSuffix],
132747
133176
  },
@@ -132795,9 +133224,10 @@ class GenerateCity extends AbstractGenerator {
132795
133224
  class GenerateUniqueCity extends AbstractGenerator {
132796
133225
  static entityKind = 'GenerateUniqueCity';
132797
133226
  state;
132798
- isUnique = true;
133227
+ isGeneratorUnique = true;
133228
+ maxUniqueCount = cityNames.length;
132799
133229
  init({ count, seed }) {
132800
- if (count > cityNames.length) {
133230
+ if (count > this.maxUniqueCount) {
132801
133231
  throw new Error('count exceeds max number of unique cities.');
132802
133232
  }
132803
133233
  if (this.typeParams?.length !== undefined && this.typeParams?.length < maxStringLength$9) {
@@ -132852,11 +133282,11 @@ class GeneratePostcode extends AbstractGenerator {
132852
133282
  class GenerateUniquePostcode extends AbstractGenerator {
132853
133283
  static entityKind = 'GenerateUniquePostcode';
132854
133284
  state;
132855
- isUnique = true;
133285
+ isGeneratorUnique = true;
133286
+ maxUniqueCount = Math.pow(10, 5) + Math.pow(10, 9);
132856
133287
  init({ count, seed }) {
132857
- const maxUniquePostcodeNumber = Math.pow(10, 5) + Math.pow(10, 9);
132858
- if (count > maxUniquePostcodeNumber) {
132859
- throw new RangeError(`count exceeds max number of unique postcodes(${maxUniquePostcodeNumber}).`);
133288
+ if (count > this.maxUniqueCount) {
133289
+ throw new RangeError(`count exceeds max number of unique postcodes(${this.maxUniqueCount}).`);
132860
133290
  }
132861
133291
  const rng = prand.xoroshiro128plus(seed);
132862
133292
  const templates = [
@@ -132978,12 +133408,12 @@ class GenerateCompanyName extends AbstractGenerator {
132978
133408
  class GenerateUniqueCompanyName extends AbstractGenerator {
132979
133409
  static entityKind = 'GenerateUniqueCompanyName';
132980
133410
  state;
132981
- isUnique = true;
133411
+ isGeneratorUnique = true;
133412
+ maxUniqueCount = lastNames.length * companyNameSuffixes.length + Math.pow(lastNames.length, 2)
133413
+ + Math.pow(lastNames.length, 2) + Math.pow(lastNames.length, 3);
132982
133414
  init({ count, seed }) {
132983
- const maxUniqueCompanyNameNumber = lastNames.length * companyNameSuffixes.length + Math.pow(lastNames.length, 2)
132984
- + Math.pow(lastNames.length, 2) + Math.pow(lastNames.length, 3);
132985
- if (count > maxUniqueCompanyNameNumber) {
132986
- throw new RangeError(`count exceeds max number of unique company names(${maxUniqueCompanyNameNumber}).`);
133415
+ if (count > this.maxUniqueCount) {
133416
+ throw new RangeError(`count exceeds max number of unique company names(${this.maxUniqueCount}).`);
132987
133417
  }
132988
133418
  // max( { template: '#', placeholdersCount: 1 }, { template: '#, # and #', placeholdersCount: 3 } )
132989
133419
  const maxCompanyNameLength = Math.max(maxStringLength$3 + maxStringLength$8 + 1, 3 * maxStringLength$3 + 7);
@@ -133154,7 +133584,7 @@ class GeneratePoint extends AbstractGenerator {
133154
133584
  }
133155
133585
  const x = this.state.xCoordinateGen.generate();
133156
133586
  const y = this.state.yCoordinateGen.generate();
133157
- if (this.dataType === 'json') {
133587
+ if (this.dataType === 'object') {
133158
133588
  return { x, y };
133159
133589
  }
133160
133590
  else if (this.dataType === 'string') {
@@ -133169,22 +133599,29 @@ class GeneratePoint extends AbstractGenerator {
133169
133599
  class GenerateUniquePoint extends AbstractGenerator {
133170
133600
  static entityKind = 'GenerateUniquePoint';
133171
133601
  state;
133172
- isUnique = true;
133173
- init({ count, seed }) {
133174
- // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique points.
133175
- const xCoordinateGen = new GenerateUniqueNumber({
133602
+ isGeneratorUnique = true;
133603
+ xCoordinateGen;
133604
+ yCoordinateGen;
133605
+ maxUniqueCount;
133606
+ constructor(params) {
133607
+ super(params);
133608
+ this.xCoordinateGen = new GenerateUniqueNumber({
133176
133609
  minValue: this.params.minXValue,
133177
133610
  maxValue: this.params.maxXValue,
133178
133611
  precision: 10,
133179
133612
  });
133180
- xCoordinateGen.init({ count, seed });
133181
- const yCoordinateGen = new GenerateUniqueNumber({
133613
+ this.yCoordinateGen = new GenerateUniqueNumber({
133182
133614
  minValue: this.params.minYValue,
133183
133615
  maxValue: this.params.maxYValue,
133184
133616
  precision: 10,
133185
133617
  });
133186
- yCoordinateGen.init({ count, seed });
133187
- this.state = { xCoordinateGen, yCoordinateGen };
133618
+ this.maxUniqueCount = Math.min(this.xCoordinateGen.maxUniqueCount, this.yCoordinateGen.maxUniqueCount);
133619
+ }
133620
+ init({ count, seed }) {
133621
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique points.
133622
+ this.xCoordinateGen.init({ count, seed });
133623
+ this.yCoordinateGen.init({ count, seed });
133624
+ this.state = { xCoordinateGen: this.xCoordinateGen, yCoordinateGen: this.yCoordinateGen };
133188
133625
  }
133189
133626
  generate() {
133190
133627
  if (this.state === undefined) {
@@ -133192,7 +133629,7 @@ class GenerateUniquePoint extends AbstractGenerator {
133192
133629
  }
133193
133630
  const x = this.state.xCoordinateGen.generate();
133194
133631
  const y = this.state.yCoordinateGen.generate();
133195
- if (this.dataType === 'json') {
133632
+ if (this.dataType === 'object') {
133196
133633
  return { x, y };
133197
133634
  }
133198
133635
  else if (this.dataType === 'string') {
@@ -133241,7 +133678,7 @@ class GenerateLine extends AbstractGenerator {
133241
133678
  b = this.state.bCoefficientGen.generate();
133242
133679
  }
133243
133680
  const c = this.state.cCoefficientGen.generate();
133244
- if (this.dataType === 'json') {
133681
+ if (this.dataType === 'object') {
133245
133682
  return { a, b, c };
133246
133683
  }
133247
133684
  else if (this.dataType === 'string') {
@@ -133256,28 +133693,40 @@ class GenerateLine extends AbstractGenerator {
133256
133693
  class GenerateUniqueLine extends AbstractGenerator {
133257
133694
  static entityKind = 'GenerateUniqueLine';
133258
133695
  state;
133259
- isUnique = true;
133260
- init({ count, seed }) {
133261
- // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique triplets(liens).
133262
- const aCoefficientGen = new GenerateUniqueNumber({
133696
+ isGeneratorUnique = true;
133697
+ maxUniqueCount;
133698
+ aCoefficientGen;
133699
+ bCoefficientGen;
133700
+ cCoefficientGen;
133701
+ constructor(params) {
133702
+ super(params);
133703
+ this.aCoefficientGen = new GenerateUniqueNumber({
133263
133704
  minValue: this.params.minAValue,
133264
133705
  maxValue: this.params.maxAValue,
133265
133706
  precision: 10,
133266
133707
  });
133267
- aCoefficientGen.init({ count, seed });
133268
- const bCoefficientGen = new GenerateUniqueNumber({
133708
+ this.bCoefficientGen = new GenerateUniqueNumber({
133269
133709
  minValue: this.params.minBValue,
133270
133710
  maxValue: this.params.maxBValue,
133271
133711
  precision: 10,
133272
133712
  });
133273
- bCoefficientGen.init({ count, seed });
133274
- const cCoefficientGen = new GenerateUniqueNumber({
133713
+ this.cCoefficientGen = new GenerateUniqueNumber({
133275
133714
  minValue: this.params.minCValue,
133276
133715
  maxValue: this.params.maxCValue,
133277
133716
  precision: 10,
133278
133717
  });
133279
- cCoefficientGen.init({ count, seed });
133280
- this.state = { aCoefficientGen, bCoefficientGen, cCoefficientGen };
133718
+ this.maxUniqueCount = Math.min(this.aCoefficientGen.maxUniqueCount, this.bCoefficientGen.maxUniqueCount, this.cCoefficientGen.maxUniqueCount);
133719
+ }
133720
+ init({ count, seed }) {
133721
+ // TODO: rewrite the unique generator to use fastCartesianProduct for generating unique triplets(liens).
133722
+ this.aCoefficientGen.init({ count, seed });
133723
+ this.bCoefficientGen.init({ count, seed });
133724
+ this.cCoefficientGen.init({ count, seed });
133725
+ this.state = {
133726
+ aCoefficientGen: this.aCoefficientGen,
133727
+ bCoefficientGen: this.bCoefficientGen,
133728
+ cCoefficientGen: this.cCoefficientGen,
133729
+ };
133281
133730
  }
133282
133731
  generate() {
133283
133732
  if (this.state === undefined) {
@@ -133290,7 +133739,7 @@ class GenerateUniqueLine extends AbstractGenerator {
133290
133739
  b = this.state.bCoefficientGen.generate();
133291
133740
  }
133292
133741
  const c = this.state.cCoefficientGen.generate();
133293
- if (this.dataType === 'json') {
133742
+ if (this.dataType === 'object') {
133294
133743
  return { a, b, c };
133295
133744
  }
133296
133745
  else if (this.dataType === 'string') {
@@ -133335,7 +133784,15 @@ class GenerateUniqueBitString extends AbstractGenerator {
133335
133784
  static entityKind = 'GenerateUniqueBitString';
133336
133785
  dimensions = 11;
133337
133786
  state;
133338
- isUnique = true;
133787
+ isGeneratorUnique = true;
133788
+ getMaxUniqueCount() {
133789
+ if (this.maxUniqueCount >= 0)
133790
+ return this.maxUniqueCount;
133791
+ this.dimensions = this.params.dimensions ?? this.typeParams?.length ?? this.dimensions;
133792
+ this.maxUniqueCount = Math.pow(2, this.dimensions);
133793
+ // TODO revise: will work incorrect with this.dimensions > 53, due to node js number limitations
133794
+ return this.maxUniqueCount;
133795
+ }
133339
133796
  init({ count, seed }) {
133340
133797
  this.dimensions = this.params.dimensions ?? this.typeParams?.length ?? this.dimensions;
133341
133798
  let intGen;
@@ -133406,18 +133863,35 @@ class GenerateInet extends AbstractGenerator {
133406
133863
  }
133407
133864
  }
133408
133865
  }
133409
- // TODO: add defaults to js doc
133410
133866
  class GenerateUniqueInet extends AbstractGenerator {
133411
133867
  static entityKind = 'GenerateUniqueInet';
133412
133868
  ipAddress = 'ipv4';
133413
133869
  includeCidr = true;
133414
133870
  delimiter = '.';
133415
133871
  state;
133416
- isUnique = true;
133417
- init({ count, seed }) {
133872
+ isGeneratorUnique = true;
133873
+ maxUniqueCount;
133874
+ constructor(params) {
133875
+ super(params);
133418
133876
  this.ipAddress = this.params.ipAddress ?? this.ipAddress;
133419
- this.delimiter = this.ipAddress === 'ipv4' ? '.' : ':';
133420
133877
  this.includeCidr = this.params.includeCidr ?? this.includeCidr;
133878
+ if (this.ipAddress === 'ipv4') {
133879
+ this.maxUniqueCount = 256 ** 4;
133880
+ if (this.includeCidr) {
133881
+ this.maxUniqueCount *= 33;
133882
+ }
133883
+ }
133884
+ else {
133885
+ // this.ipAddress === 'ipv6'
133886
+ // TODO revise: this.maxUniqueCount can exceed Number.MAX_SAFE_INTEGER
133887
+ this.maxUniqueCount = 65535 ** 8;
133888
+ if (this.includeCidr) {
133889
+ this.maxUniqueCount *= 129;
133890
+ }
133891
+ }
133892
+ }
133893
+ init({ count, seed }) {
133894
+ this.delimiter = this.ipAddress === 'ipv4' ? '.' : ':';
133421
133895
  // maxValue - number of combinations for cartesian product: {0…255} × {0…255} × {0…255} × {0…255} × {0…32}
133422
133896
  // where pattern for ipv4 ip is {0–255}.{0–255}.{0–255}.{0–255}[/{0–32}?]
133423
133897
  // or number of combinations for cartesian product: {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…65535} × {0…128}
@@ -133533,11 +134007,42 @@ class GenerateUniqueGeometry extends AbstractGenerator {
133533
134007
  srid = 4326;
133534
134008
  decimalPlaces = 6;
133535
134009
  state;
133536
- isUnique = true;
133537
- init({ count, seed }) {
134010
+ isGeneratorUnique = true;
134011
+ maxUniqueCount;
134012
+ constructor(params) {
134013
+ super(params);
133538
134014
  this.type = this.params.type ?? this.type;
133539
134015
  this.srid = this.params.srid ?? this.srid;
133540
134016
  this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
134017
+ let minXValue, maxXValue, minYValue, maxYValue, denominator;
134018
+ if (this.type === 'point') {
134019
+ if (this.srid === 4326) {
134020
+ // Degrees (latitude / longitude)
134021
+ denominator = 10 ** this.decimalPlaces;
134022
+ minXValue = -180 * denominator;
134023
+ maxXValue = 180 * denominator;
134024
+ minYValue = -90 * denominator;
134025
+ maxYValue = 90 * denominator;
134026
+ }
134027
+ else {
134028
+ // this.srid === 3857
134029
+ // Meters (projected X / Y)
134030
+ denominator = 1;
134031
+ minXValue = -20026376;
134032
+ maxXValue = 20026376;
134033
+ minYValue = -20048966;
134034
+ maxYValue = 20048966;
134035
+ }
134036
+ }
134037
+ else {
134038
+ // error should be triggered in init method
134039
+ this.maxUniqueCount = -1;
134040
+ return;
134041
+ }
134042
+ // TODO revise: can lose accuracy due to exceeding Number.MAX_SAFE_INTEGER
134043
+ this.maxUniqueCount = Number(BigInt(maxXValue - minXValue + 1) * BigInt(maxYValue - minYValue + 1));
134044
+ }
134045
+ init({ count, seed }) {
133541
134046
  let minXValue, maxXValue, minYValue, maxYValue, denominator;
133542
134047
  if (this.type === 'point') {
133543
134048
  if (this.srid === 4326) {
@@ -133644,11 +134149,10 @@ class GenerateUniqueVector extends AbstractGenerator {
133644
134149
  maxValue = 1000;
133645
134150
  decimalPlaces = 2;
133646
134151
  state;
133647
- isUnique = true;
133648
- init({ count, seed }) {
133649
- this.dimensions = this.params.dimensions ?? this.typeParams.length ?? this.dimensions;
134152
+ isGeneratorUnique = true;
134153
+ constructor(params) {
134154
+ super(params);
133650
134155
  this.decimalPlaces = this.params.decimalPlaces ?? this.decimalPlaces;
133651
- const denominator = 10 ** this.decimalPlaces;
133652
134156
  this.minValue = this.params.minValue ?? this.minValue;
133653
134157
  this.maxValue = this.params.maxValue ?? this.maxValue;
133654
134158
  if (this.minValue > this.maxValue) {
@@ -133658,6 +134162,18 @@ class GenerateUniqueVector extends AbstractGenerator {
133658
134162
  if (this.decimalPlaces < 0) {
133659
134163
  throw new Error(`decimalPlaces value must be greater than or equal to zero.`);
133660
134164
  }
134165
+ }
134166
+ getMaxUniqueCount() {
134167
+ if (this.maxUniqueCount >= 0)
134168
+ return this.maxUniqueCount;
134169
+ this.dimensions = this.params.dimensions ?? this.typeParams.length ?? this.dimensions;
134170
+ const denominator = 10 ** this.decimalPlaces;
134171
+ this.maxUniqueCount = (this.maxValue * denominator - this.minValue * denominator + 1) ** this.dimensions;
134172
+ return this.maxUniqueCount;
134173
+ }
134174
+ init({ count, seed }) {
134175
+ this.dimensions = this.params.dimensions ?? this.typeParams.length ?? this.dimensions;
134176
+ const denominator = 10 ** this.decimalPlaces;
133661
134177
  if (abs(BigInt(this.minValue) * BigInt(denominator)) > Number.MAX_SAFE_INTEGER
133662
134178
  || abs(BigInt(this.maxValue) * BigInt(denominator)) > Number.MAX_SAFE_INTEGER) {
133663
134179
  console.warn(`vector generator: minValue or maxValue multiplied by 10^decimalPlaces exceeds Number.MAX_SAFE_INTEGER (2^53 -1).\n`
@@ -133693,13 +134209,80 @@ class GenerateUniqueVector extends AbstractGenerator {
133693
134209
  return vector;
133694
134210
  }
133695
134211
  }
134212
+ class GenerateCompositeUniqueKey extends AbstractGenerator {
134213
+ static entityKind = 'GenerateCompositeUniqueKey';
134214
+ columnGenerators = [];
134215
+ isInitialized = false;
134216
+ state;
134217
+ addGenerator(columnName, generator) {
134218
+ this.columnGenerators.push({ columnName, generator });
134219
+ }
134220
+ init({ count, seed }) {
134221
+ if (this.isInitialized)
134222
+ return;
134223
+ if (this.columnGenerators.length === 0) {
134224
+ throw new Error(`composite unique key generator has no generators to work with.`);
134225
+ }
134226
+ let countPerGen = Math.ceil(count ** (1 / this.columnGenerators.length));
134227
+ // const gensMaxUniqueCount: { columnName: string; count: number; maxUniqueCount: number }[] = [];
134228
+ for (const colGen of this.columnGenerators) {
134229
+ colGen.maxUniqueCount = colGen.generator.getMaxUniqueCount();
134230
+ }
134231
+ this.columnGenerators.sort((a, b) => a.maxUniqueCount - b.maxUniqueCount);
134232
+ let currCount = count;
134233
+ let canGenerate = false;
134234
+ for (const [idx, colGen] of this.columnGenerators.entries()) {
134235
+ if (colGen.maxUniqueCount < countPerGen) {
134236
+ colGen.count = colGen.maxUniqueCount;
134237
+ currCount /= colGen.count;
134238
+ countPerGen = Math.ceil(currCount ** (1 / (this.columnGenerators.length - idx - 1)));
134239
+ canGenerate = false;
134240
+ }
134241
+ else {
134242
+ colGen.count = countPerGen;
134243
+ canGenerate = true;
134244
+ }
134245
+ }
134246
+ if (!canGenerate) {
134247
+ const colGensCountInfo = this.columnGenerators.map((colGen) => `generator:${colGen.generator.getEntityKind()};count:${colGen.count}`).join('\n');
134248
+ throw new Error(`There are no enough unique values in each generator to generate ${count} values; \n${colGensCountInfo}`);
134249
+ }
134250
+ const sets = [];
134251
+ for (const colGen of this.columnGenerators) {
134252
+ colGen.generator.init({ count: colGen.count, seed });
134253
+ const setI = [];
134254
+ for (let i = 0; i < countPerGen; i++) {
134255
+ setI.push(colGen.generator.generate({ i }));
134256
+ }
134257
+ sets.push(setI);
134258
+ }
134259
+ this.state = { sets, currI: -1, currValue: {} };
134260
+ this.isInitialized = true;
134261
+ }
134262
+ generate({ i, columnName }) {
134263
+ if (this.state === undefined) {
134264
+ throw new Error('state is not defined.');
134265
+ }
134266
+ if (i > this.state.currI) {
134267
+ const rowI = fastCartesianProduct(this.state.sets, i);
134268
+ const newCurrValue = {};
134269
+ for (const [idx, colGen] of this.columnGenerators.entries()) {
134270
+ newCurrValue[colGen.columnName] = rowI[idx];
134271
+ }
134272
+ this.state.currValue = newCurrValue;
134273
+ this.state.currI = i;
134274
+ }
134275
+ return this.state.currValue[columnName];
134276
+ }
134277
+ }
133696
134278
 
133697
134279
  /* eslint-disable drizzle-internal/require-entity-kind */
133698
134280
  class GenerateUniqueIntervalV2 extends AbstractGenerator {
133699
134281
  static 'entityKind' = 'GenerateUniqueInterval';
133700
134282
  static version = 2;
133701
134283
  state;
133702
- isUnique = true;
134284
+ isGeneratorUnique = true;
134285
+ maxUniqueCount;
133703
134286
  config = {
133704
134287
  year: {
133705
134288
  from: 0,
@@ -133726,29 +134309,33 @@ class GenerateUniqueIntervalV2 extends AbstractGenerator {
133726
134309
  to: 59,
133727
134310
  },
133728
134311
  };
133729
- init({ count, seed }) {
134312
+ fieldsToGenerate;
134313
+ constructor(params) {
134314
+ super(params);
133730
134315
  const allFields = ['year', 'month', 'day', 'hour', 'minute', 'second'];
133731
- let fieldsToGenerate = allFields;
134316
+ this.fieldsToGenerate = allFields;
133732
134317
  if (this.params.fields !== undefined && this.params.fields?.includes(' to ')) {
133733
134318
  const tokens = this.params.fields.split(' to ');
133734
134319
  const endIdx = allFields.indexOf(tokens[1]);
133735
- fieldsToGenerate = allFields.slice(0, endIdx + 1);
134320
+ this.fieldsToGenerate = allFields.slice(0, endIdx + 1);
133736
134321
  }
133737
134322
  else if (this.params.fields !== undefined) {
133738
134323
  const endIdx = allFields.indexOf(this.params.fields);
133739
- fieldsToGenerate = allFields.slice(0, endIdx + 1);
134324
+ this.fieldsToGenerate = allFields.slice(0, endIdx + 1);
133740
134325
  }
133741
- let maxUniqueIntervalsNumber = 1;
133742
- for (const field of fieldsToGenerate) {
134326
+ this.maxUniqueCount = 1;
134327
+ for (const field of this.fieldsToGenerate) {
133743
134328
  const from = this.config[field].from, to = this.config[field].to;
133744
- maxUniqueIntervalsNumber *= from - to + 1;
134329
+ this.maxUniqueCount *= from - to + 1;
133745
134330
  }
133746
- if (count > maxUniqueIntervalsNumber) {
133747
- throw new RangeError(`count exceeds max number of unique intervals(${maxUniqueIntervalsNumber})`);
134331
+ }
134332
+ init({ count, seed }) {
134333
+ if (count > this.maxUniqueCount) {
134334
+ throw new RangeError(`count exceeds max number of unique intervals(${this.maxUniqueCount})`);
133748
134335
  }
133749
134336
  const rng = prand.xoroshiro128plus(seed);
133750
134337
  const intervalSet = new Set();
133751
- this.state = { rng, fieldsToGenerate, intervalSet };
134338
+ this.state = { rng, fieldsToGenerate: this.fieldsToGenerate, intervalSet };
133752
134339
  }
133753
134340
  generate() {
133754
134341
  if (this.state === undefined) {
@@ -133770,6 +134357,7 @@ class GenerateUniqueIntervalV2 extends AbstractGenerator {
133770
134357
  return interval;
133771
134358
  }
133772
134359
  }
134360
+ // TODO need to rework this generator
133773
134361
  class GenerateStringV2 extends AbstractGenerator {
133774
134362
  static 'entityKind' = 'GenerateString';
133775
134363
  static version = 2;
@@ -133802,7 +134390,7 @@ class GenerateStringV2 extends AbstractGenerator {
133802
134390
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
133803
134391
  currStr += stringChars[idx];
133804
134392
  }
133805
- if (this.dataType === 'buffer')
134393
+ if (this.dataType === 'object')
133806
134394
  return Buffer.from(currStr);
133807
134395
  return currStr;
133808
134396
  }
@@ -133811,21 +134399,27 @@ class GenerateUniqueStringV2 extends AbstractGenerator {
133811
134399
  static 'entityKind' = 'GenerateUniqueString';
133812
134400
  static version = 2;
133813
134401
  state;
133814
- isUnique = true;
134402
+ isGeneratorUnique = true;
134403
+ maxStringLength = 20;
134404
+ minStringLength = 7;
134405
+ getMaxUniqueCount() {
134406
+ if (this.maxUniqueCount >= 0)
134407
+ return this.maxUniqueCount;
134408
+ this.maxStringLength = this.typeParams?.length ?? this.maxStringLength;
134409
+ this.maxUniqueCount = Number.parseInt('f'.repeat(this.maxStringLength), 16);
134410
+ return this.maxUniqueCount;
134411
+ }
133815
134412
  init({ seed, count }) {
133816
134413
  const rng = prand.xoroshiro128plus(seed);
133817
- let minStringLength = 7;
133818
- let maxStringLength = 20;
133819
134414
  // TODO: revise later
133820
- if (this.typeParams?.length !== undefined) {
133821
- maxStringLength = this.typeParams?.length;
133822
- if (maxStringLength === 1 || maxStringLength < minStringLength)
133823
- minStringLength = maxStringLength;
134415
+ this.maxStringLength = this.typeParams?.length ?? this.maxStringLength;
134416
+ if (this.maxStringLength === 1 || this.maxStringLength < this.minStringLength) {
134417
+ this.minStringLength = this.maxStringLength;
133824
134418
  }
133825
- if (maxStringLength < count.toString(16).length) {
133826
- throw new Error(`You can't generate ${count} unique strings, with a maximum string length of ${maxStringLength}.`);
134419
+ if (count > this.getMaxUniqueCount()) {
134420
+ throw new Error(`You can't generate ${count} unique strings, with a maximum string length of ${this.maxStringLength}.`);
133827
134421
  }
133828
- this.state = { rng, minStringLength, maxStringLength };
134422
+ this.state = { rng, minStringLength: this.minStringLength, maxStringLength: this.maxStringLength };
133829
134423
  }
133830
134424
  generate({ i }) {
133831
134425
  if (this.state === undefined) {
@@ -133842,10 +134436,31 @@ class GenerateUniqueStringV2 extends AbstractGenerator {
133842
134436
  [idx, this.state.rng] = prand.uniformIntDistribution(0, stringChars.length - 1, this.state.rng);
133843
134437
  currStr += stringChars[idx];
133844
134438
  }
134439
+ if (this.dataType === 'object')
134440
+ return Buffer.from(uniqueStr + currStr);
133845
134441
  return uniqueStr + currStr;
133846
134442
  }
133847
134443
  }
133848
134444
 
134445
+ /* eslint-disable drizzle-internal/require-entity-kind */
134446
+ class GenerateHashFromStringV3 extends AbstractGenerator {
134447
+ static entityKind = 'GenerateHashFromString';
134448
+ static version = 3;
134449
+ init() { }
134450
+ generate({ input }) {
134451
+ let hash = 0n;
134452
+ // p and m are prime numbers
134453
+ const p = 53n;
134454
+ const m = 28871271685163n; // < 2^53
134455
+ let power = 1n; // will track p^i, where i is character index
134456
+ for (const ch of input) {
134457
+ hash = (hash + (BigInt(ch.codePointAt(0) || 0) * power)) % m;
134458
+ power = (power * p) % m;
134459
+ }
134460
+ return Number(hash);
134461
+ }
134462
+ }
134463
+
133849
134464
  function createGenerator(generatorConstructor) {
133850
134465
  return (...args) => {
133851
134466
  let params = args[0];
@@ -134641,7 +135256,14 @@ const generatorsFuncs = {
134641
135256
  const generatorsFuncsV2 = {
134642
135257
  ...generatorsFuncs,
134643
135258
  };
135259
+ ({
135260
+ ...generatorsFuncs,
135261
+ });
134644
135262
  const generatorsMap = {
135263
+ GenerateHashFromString: [
135264
+ GenerateHashFromString,
135265
+ GenerateHashFromStringV3,
135266
+ ],
134645
135267
  HollowGenerator: [
134646
135268
  HollowGenerator,
134647
135269
  ],
@@ -134819,6 +135441,9 @@ const generatorsMap = {
134819
135441
  GenerateUniqueVector: [
134820
135442
  GenerateUniqueVector,
134821
135443
  ],
135444
+ GenerateCompositeUniqueKey: [
135445
+ GenerateCompositeUniqueKey,
135446
+ ],
134822
135447
  };
134823
135448
 
134824
135449
  // TODO: revise serial part generators
@@ -134974,8 +135599,8 @@ const selectGeneratorForCockroachColumn = (table, col) => {
134974
135599
  const generator = new generatorsMap.GenerateUUID[0]();
134975
135600
  return generator;
134976
135601
  }
134977
- // BOOLEAN
134978
- if (col.columnType === 'boolean') {
135602
+ // BOOL
135603
+ if (col.columnType === 'bool') {
134979
135604
  const generator = new generatorsMap.GenerateBoolean[0]();
134980
135605
  return generator;
134981
135606
  }
@@ -135037,7 +135662,7 @@ const selectGeneratorForCockroachColumn = (table, col) => {
135037
135662
  return generator;
135038
135663
  };
135039
135664
 
135040
- const latestVersion = 2;
135665
+ const latestVersion = 3;
135041
135666
 
135042
135667
  const selectGeneratorForMssqlColumn = (table, col) => {
135043
135668
  const pickGenerator = (table, col) => {
@@ -135803,7 +136428,7 @@ const selectGeneratorForSqlite = (table, col) => {
135803
136428
  const generator = new generatorsMap.GenerateBoolean[0]();
135804
136429
  return generator;
135805
136430
  }
135806
- if ((col.columnType === 'integer' && col.dataType === 'date')) {
136431
+ if ((col.columnType === 'integer' && col.dataType === 'object')) {
135807
136432
  const generator = new generatorsMap.GenerateTimestamp[0]();
135808
136433
  return generator;
135809
136434
  }
@@ -135874,49 +136499,6 @@ const selectGeneratorForSqlite = (table, col) => {
135874
136499
  return generator;
135875
136500
  };
135876
136501
 
135877
- const isRelationCyclic = (startRel) => {
135878
- // self relation
135879
- if (startRel.table === startRel.refTable)
135880
- return false;
135881
- // DFS
135882
- const targetTable = startRel.table;
135883
- const queue = [startRel];
135884
- let path = [];
135885
- while (queue.length !== 0) {
135886
- const currRel = queue.shift();
135887
- if (path.includes(currRel.table)) {
135888
- const idx = path.indexOf(currRel.table);
135889
- path = path.slice(0, idx);
135890
- }
135891
- path.push(currRel.table);
135892
- for (const rel of currRel.refTableRels) {
135893
- // self relation
135894
- if (rel.table === rel.refTable)
135895
- continue;
135896
- if (rel.refTable === targetTable)
135897
- return true;
135898
- // found cycle, but not the one we are looking for
135899
- if (path.includes(rel.refTable))
135900
- continue;
135901
- queue.unshift(rel);
135902
- }
135903
- }
135904
- return false;
135905
- };
135906
- const generateHashFromString = (s) => {
135907
- let hash = 0;
135908
- // p and m are prime numbers
135909
- const p = 53;
135910
- const m = 28871271685163;
135911
- for (let i = 0; i < s.length; i++) {
135912
- hash += ((s.codePointAt(i) || 0) * Math.pow(p, i)) % m;
135913
- }
135914
- return hash;
135915
- };
135916
- const equalSets = (set1, set2) => {
135917
- return set1.size === set2.size && [...set1].every((si) => set2.has(si));
135918
- };
135919
-
135920
136502
  /* eslint-disable drizzle-internal/require-entity-kind */
135921
136503
  class SeedService {
135922
136504
  static entityKind = 'SeedService';
@@ -135929,6 +136511,7 @@ class SeedService {
135929
136511
  sqliteMaxParametersNumber = 32766;
135930
136512
  mssqlMaxParametersNumber = 2100;
135931
136513
  version;
136514
+ hashFromStringGenerator;
135932
136515
  generatePossibleGenerators = (connectionType, tables, relations, refinements, options) => {
135933
136516
  let columnPossibleGenerator;
135934
136517
  let tablePossibleGenerators;
@@ -135937,6 +136520,7 @@ class SeedService {
135937
136520
  if (Number.isNaN(this.version) || this.version < 1 || this.version > latestVersion) {
135938
136521
  throw new Error(`Version should be in range [1, ${latestVersion}].`);
135939
136522
  }
136523
+ this.hashFromStringGenerator = this.selectVersionOfGenerator(new generatorsMap.GenerateHashFromString[0]());
135940
136524
  // sorting table in order which they will be filled up (tables with foreign keys case)
135941
136525
  const { tablesInOutRelations } = this.getInfoFromRelations(relations);
135942
136526
  const orderedTablesNames = this.getOrderedTablesList(tablesInOutRelations);
@@ -135956,6 +136540,7 @@ class SeedService {
135956
136540
  withFromTable: {},
135957
136541
  }));
135958
136542
  for (const [i, table] of tables.entries()) {
136543
+ const compositeUniqueKeyGenMap = {};
135959
136544
  // get foreignKey columns relations
135960
136545
  const foreignKeyColumns = {};
135961
136546
  for (const rel of relations
@@ -135997,7 +136582,7 @@ class SeedService {
135997
136582
  const weightedRepeatedValuesCount = refinements[table.name]
135998
136583
  .with[fkTableName];
135999
136584
  weightedCountSeed = customSeed
136000
- + generateHashFromString(`${table.name}.${fkTableName}`);
136585
+ + this.hashFromStringGenerator.generate({ input: `${table.name}.${fkTableName}` });
136001
136586
  newTableWithCount = this.getWeightedWithCount(weightedRepeatedValuesCount, (tablesPossibleGenerators[i].withCount
136002
136587
  || tablesPossibleGenerators[i].count), weightedCountSeed);
136003
136588
  }
@@ -136033,6 +136618,18 @@ class SeedService {
136033
136618
  && refinements[table.name].columns !== undefined
136034
136619
  && refinements[table.name].columns[col.name] !== undefined) {
136035
136620
  const genObj = refinements[table.name].columns[col.name];
136621
+ if (genObj === false) {
136622
+ if (col.notNull === true && col.hasDefault === false) {
136623
+ throw new Error(`You cannot set the '${col.name}' column in the '${table.name}' table to false in your refinements.`
136624
+ + `\nDoing so will result in a null value being inserted into the '${col.name}' column,`
136625
+ + `\nwhich will cause an error because the column has a not null constraint and no default value.`);
136626
+ }
136627
+ // Generating undefined as a value for a column and then inserting it via drizzle-orm
136628
+ // will result in the value not being inserted into that column.
136629
+ columnPossibleGenerator.generator = new generatorsMap.GenerateDefault[0]({ defaultValue: undefined });
136630
+ columnPossibleGenerator.wasRefined = true;
136631
+ continue;
136632
+ }
136036
136633
  if (col.columnType.match(/\[\w*]/g) !== null) {
136037
136634
  if ((col.baseColumn?.dataType === 'array' && col.baseColumn.columnType.match(/\[\w*]/g) !== null)
136038
136635
  // studio case
@@ -136104,16 +136701,66 @@ class SeedService {
136104
136701
  columnPossibleGenerator.generator = arrayGen;
136105
136702
  }
136106
136703
  columnPossibleGenerator.generator.isUnique = col.isUnique;
136704
+ // composite unique keys handling
136705
+ let compositeKeyColumnNames = table.uniqueConstraints.filter((colNames) => colNames.includes(col.name));
136706
+ if (compositeKeyColumnNames.some((colNames) => colNames.length === 1)) {
136707
+ // composite unique key contains only one column, therefore it equals to just unique column
136708
+ columnPossibleGenerator.generator.isUnique = true;
136709
+ }
136710
+ // removing column from composite unique keys if current column is unique
136711
+ if (columnPossibleGenerator.generator.isUnique && compositeKeyColumnNames.length > 0) {
136712
+ const newUniqueConstraints = [];
136713
+ for (const colNames of table.uniqueConstraints) {
136714
+ if (colNames.includes(col.name)) {
136715
+ const newColNames = colNames.filter((colName) => colName !== col.name);
136716
+ if (newColNames.length === 0)
136717
+ continue;
136718
+ newUniqueConstraints.push(newColNames);
136719
+ }
136720
+ else {
136721
+ newUniqueConstraints.push(colNames);
136722
+ }
136723
+ }
136724
+ table.uniqueConstraints = newUniqueConstraints;
136725
+ }
136726
+ compositeKeyColumnNames = table.uniqueConstraints.filter((colNames) => colNames.includes(col.name));
136727
+ if (compositeKeyColumnNames.length > 1) {
136728
+ throw new Error('Currently, multiple composite unique keys that share the same column are not supported.');
136729
+ }
136730
+ // to handle composite unique key generation, I will need a unique generator for each column in the composite key
136731
+ if (compositeKeyColumnNames.length === 1) {
136732
+ if (columnPossibleGenerator.generator.params.isUnique === false) {
136733
+ throw new Error(`To handle the composite unique key on columns: ${compositeKeyColumnNames[0]}, `
136734
+ + `column: ${col.name} should either be assigned a generator with isUnique set to true, or have isUnique omitted.`);
136735
+ }
136736
+ columnPossibleGenerator.generator.params.isUnique = true;
136737
+ }
136107
136738
  const uniqueGen = columnPossibleGenerator.generator.replaceIfUnique();
136108
136739
  if (uniqueGen !== undefined) {
136109
136740
  columnPossibleGenerator.generator = uniqueGen;
136110
136741
  }
136742
+ if (compositeKeyColumnNames.length === 1 && !columnPossibleGenerator.generator.isGeneratorUnique
136743
+ && !(columnPossibleGenerator.generator.getEntityKind() === 'GenerateValuesFromArray')) {
136744
+ throw new Error(`To handle the composite unique key on columns: ${compositeKeyColumnNames[0]}, `
136745
+ + `column: ${col.name} should be assigned a generator with its own unique version.`);
136746
+ }
136111
136747
  // selecting version of generator
136112
136748
  columnPossibleGenerator.generator = this.selectVersionOfGenerator(columnPossibleGenerator.generator);
136113
136749
  // TODO: for now only GenerateValuesFromArray support notNull property
136114
136750
  columnPossibleGenerator.generator.notNull = col.notNull;
136115
136751
  columnPossibleGenerator.generator.dataType = col.dataType;
136116
- // columnPossibleGenerator.generator.stringLength = col.typeParams.length;
136752
+ // assigning composite key generator
136753
+ if (compositeKeyColumnNames.length === 1) {
136754
+ const key = compositeKeyColumnNames[0].join('_');
136755
+ if (compositeUniqueKeyGenMap[key] === undefined) {
136756
+ let compositeUniqueKeyGen = new generatorsMap.GenerateCompositeUniqueKey[0]();
136757
+ compositeUniqueKeyGen.uniqueKey = key;
136758
+ compositeUniqueKeyGen = this.selectVersionOfGenerator(compositeUniqueKeyGen);
136759
+ compositeUniqueKeyGenMap[key] = compositeUniqueKeyGen;
136760
+ }
136761
+ compositeUniqueKeyGenMap[key].addGenerator(col.name, columnPossibleGenerator.generator);
136762
+ columnPossibleGenerator.generator = compositeUniqueKeyGenMap[key];
136763
+ }
136117
136764
  tablePossibleGenerators.columnsPossibleGenerators.push(columnPossibleGenerator);
136118
136765
  }
136119
136766
  }
@@ -136142,6 +136789,7 @@ class SeedService {
136142
136789
  newGenerator.dataType = generator.dataType;
136143
136790
  // newGenerator.stringLength = generator.stringLength;
136144
136791
  newGenerator.typeParams = generator.typeParams ?? newGenerator.typeParams;
136792
+ newGenerator.uniqueKey = generator.uniqueKey;
136145
136793
  return newGenerator;
136146
136794
  };
136147
136795
  cyclicTablesCompare = (table1, table2, relation, reverseRelation) => {
@@ -136302,8 +136950,13 @@ class SeedService {
136302
136950
  const columnRelations = filteredRelations.filter((rel) => rel.columns.includes(col.columnName));
136303
136951
  pRNGSeed = (columnRelations.length !== 0
136304
136952
  && columnRelations[0].columns.length >= 2)
136305
- ? (customSeed + generateHashFromString(`${columnRelations[0].table}.${columnRelations[0].columns.join('_')}`))
136306
- : (customSeed + generateHashFromString(`${table.tableName}.${col.columnName}`));
136953
+ ? (customSeed
136954
+ + this.hashFromStringGenerator.generate({
136955
+ input: `${columnRelations[0].table}.${columnRelations[0].columns.join('_')}`,
136956
+ }))
136957
+ : col.generator?.uniqueKey === undefined
136958
+ ? (customSeed + this.hashFromStringGenerator.generate({ input: `${table.tableName}.${col.columnName}` }))
136959
+ : (customSeed + this.hashFromStringGenerator.generate({ input: col.generator.uniqueKey }));
136307
136960
  tableGenerators[col.columnName] = {
136308
136961
  pRNGSeed,
136309
136962
  ...col,
@@ -136325,7 +136978,9 @@ class SeedService {
136325
136978
  if (rel.table === rel.refTable
136326
136979
  && tableGenerators[rel.columns[colIdx]]?.wasRefined === false) {
136327
136980
  const refColName = rel.refColumns[colIdx];
136328
- pRNGSeed = generateHashFromString(`${table.tableName}.${refColName}`);
136981
+ pRNGSeed = this.hashFromStringGenerator.generate({
136982
+ input: `${table.tableName}.${refColName}`,
136983
+ });
136329
136984
  const refColumnGenerator = {};
136330
136985
  refColumnGenerator[refColName] = {
136331
136986
  ...tableGenerators[refColName],
@@ -136474,11 +137129,7 @@ class SeedService {
136474
137129
  row = {};
136475
137130
  generatedValues.push(row);
136476
137131
  for (const columnName of Object.keys(columnsGenerators)) {
136477
- // generatedValue = columnsGenerators[columnName].next().value as
136478
- // | string
136479
- // | number
136480
- // | boolean;
136481
- generatedValue = columnsGenerators[columnName].generate({ i });
137132
+ generatedValue = columnsGenerators[columnName].generate({ i, columnName });
136482
137133
  row[columnName] = generatedValue;
136483
137134
  }
136484
137135
  if ((insertDataInDb === true || updateDataInDb === true)
@@ -136551,7 +137202,7 @@ class SeedService {
136551
137202
  let schemaDbName;
136552
137203
  let tableDbName;
136553
137204
  if (override === true) {
136554
- const tableConfig = getTableConfig(schema[tableName]);
137205
+ const tableConfig = getTableConfig$5(schema[tableName]);
136555
137206
  schemaDbName = tableConfig.schema ?? 'dbo';
136556
137207
  tableDbName = tableConfig.name;
136557
137208
  await db.execute(sql.raw(`SET IDENTITY_INSERT [${schemaDbName}].[${tableDbName}] ON;`));
@@ -136611,7 +137262,7 @@ class SeedService {
136611
137262
  // Cockroach-----------------------------------------------------------------------------------------------------------
136612
137263
  const resetCockroach = async (db, cockroachTables) => {
136613
137264
  const tablesToTruncate = Object.entries(cockroachTables).map(([_, table]) => {
136614
- const config = getTableConfig$1(table);
137265
+ const config = getTableConfig$4(table);
136615
137266
  config.schema = config.schema === undefined ? 'public' : config.schema;
136616
137267
  return `"${config.schema}"."${config.name}"`;
136617
137268
  });
@@ -136625,7 +137276,7 @@ const filterCockroachSchema = (schema) => {
136625
137276
  const seedCockroach = async (db, schema, options = {}, refinements) => {
136626
137277
  const seedService = new SeedService();
136627
137278
  const { cockroachSchema, cockroachTables } = filterCockroachSchema(schema);
136628
- const { tables, relations } = getCockroachInfo(cockroachSchema, cockroachTables);
137279
+ const { tables, relations } = getSchemaInfo(cockroachSchema, cockroachTables, mapCockroachColumns);
136629
137280
  const generatedTablesGenerators = seedService.generatePossibleGenerators('cockroach', tables, relations, refinements, options);
136630
137281
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
136631
137282
  const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, cockroachTables, { ...options, preserveCyclicTablesData });
@@ -136633,203 +137284,82 @@ const seedCockroach = async (db, schema, options = {}, refinements) => {
136633
137284
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136634
137285
  await seedService.generateTablesValues(relations, filteredTablesGenerators, db, cockroachTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136635
137286
  };
136636
- const getCockroachInfo = (cockroachSchema, cockroachTables) => {
136637
- let tableConfig;
136638
- let dbToTsColumnNamesMap;
136639
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(cockroachTables).map(([key, value]) => [getTableName(value), key]));
136640
- const tables = [];
136641
- const relations = [];
136642
- const dbToTsColumnNamesMapGlobal = {};
136643
- const tableRelations = {};
136644
- const getDbToTsColumnNamesMap = (table) => {
136645
- let dbToTsColumnNamesMap = {};
136646
- const tableName = getTableName(table);
136647
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
136648
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
136649
- return dbToTsColumnNamesMap;
136650
- }
136651
- const tableConfig = getTableConfig$1(table);
136652
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136653
- dbToTsColumnNamesMap[col.name] = tsCol;
136654
- }
136655
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
136656
- return dbToTsColumnNamesMap;
137287
+ const mapCockroachColumns = (tableConfig, dbToTsColumnNamesMap) => {
137288
+ const getAllBaseColumns = (baseColumn) => {
137289
+ const baseColumnResult = {
137290
+ name: baseColumn.name,
137291
+ columnType: baseColumn.getSQLType(),
137292
+ typeParams: getTypeParams(baseColumn.getSQLType()),
137293
+ dataType: baseColumn.dataType.split(' ')[0],
137294
+ size: baseColumn.length,
137295
+ hasDefault: baseColumn.hasDefault,
137296
+ enumValues: baseColumn.enumValues,
137297
+ default: baseColumn.default,
137298
+ isUnique: baseColumn.isUnique,
137299
+ notNull: baseColumn.notNull,
137300
+ primary: baseColumn.primary,
137301
+ baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
137302
+ };
137303
+ return baseColumnResult;
136657
137304
  };
136658
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
136659
- const schemaConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
136660
- const relations = [];
136661
- for (const table of Object.values(schemaConfig.tables)) {
136662
- if (table.relations === undefined)
136663
- continue;
136664
- for (const drizzleRel of Object.values(table.relations)) {
136665
- if (!is(drizzleRel, One))
136666
- continue;
136667
- const tableConfig = getTableConfig$1(drizzleRel.sourceTable);
136668
- const tableDbSchema = tableConfig.schema ?? 'public';
136669
- const tableDbName = tableConfig.name;
136670
- const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
136671
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136672
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136673
- ?? [];
136674
- const refTableConfig = getTableConfig$1(drizzleRel.referencedTable);
136675
- const refTableDbSchema = refTableConfig.schema ?? 'public';
136676
- const refTableDbName = refTableConfig.name;
136677
- const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
136678
- ?? refTableDbName;
136679
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
136680
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
136681
- ?? [];
136682
- if (tableRelations[refTableTsName] === undefined) {
136683
- tableRelations[refTableTsName] = [];
136684
- }
136685
- const relation = {
136686
- table: tableTsName,
136687
- columns,
136688
- refTable: refTableTsName,
136689
- refColumns,
136690
- refTableRels: tableRelations[refTableTsName],
136691
- type: 'one',
136692
- };
136693
- // do not add duplicate relation
136694
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
136695
- && rel.refTable === relation.refTable)) {
136696
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
136697
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
136698
- + `In this case, the foreign key constraint will be used.\n`);
136699
- continue;
136700
- }
136701
- relations.push(relation);
136702
- tableRelations[tableTsName].push(relation);
137305
+ const getTypeParams = (sqlType) => {
137306
+ // get type params
137307
+ const typeParams = {};
137308
+ // handle dimensions
137309
+ if (sqlType.includes('[')) {
137310
+ const match = sqlType.match(/\[\w*]/g);
137311
+ if (match) {
137312
+ typeParams['dimensions'] = match.length;
136703
137313
  }
136704
137314
  }
136705
- return relations;
136706
- };
136707
- for (const table of Object.values(cockroachTables)) {
136708
- tableConfig = getTableConfig$1(table);
136709
- dbToTsColumnNamesMap = {};
136710
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136711
- dbToTsColumnNamesMap[col.name] = tsCol;
136712
- }
136713
- // might be empty list
136714
- const newRelations = tableConfig.foreignKeys.map((fk) => {
136715
- const table = dbToTsTableNamesMap[tableConfig.name];
136716
- const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)];
136717
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
136718
- if (tableRelations[refTable] === undefined) {
136719
- tableRelations[refTable] = [];
137315
+ if (sqlType.startsWith('numeric')
137316
+ || sqlType.startsWith('decimal')
137317
+ || sqlType.startsWith('double precision')
137318
+ || sqlType.startsWith('real')) {
137319
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137320
+ if (match) {
137321
+ typeParams['precision'] = Number(match[1]);
137322
+ typeParams['scale'] = Number(match[2]);
136720
137323
  }
136721
- return {
136722
- table,
136723
- columns: fk
136724
- .reference()
136725
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
136726
- refTable,
136727
- refColumns: fk
136728
- .reference()
136729
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
136730
- refTableRels: tableRelations[refTable],
136731
- };
136732
- });
136733
- relations.push(...newRelations);
136734
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
136735
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
136736
137324
  }
136737
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
136738
- const getAllBaseColumns = (baseColumn) => {
136739
- const baseColumnResult = {
136740
- name: baseColumn.name,
136741
- columnType: baseColumn.getSQLType(),
136742
- typeParams: getTypeParams(baseColumn.getSQLType()),
136743
- dataType: baseColumn.dataType,
136744
- size: baseColumn.size,
136745
- hasDefault: baseColumn.hasDefault,
136746
- enumValues: baseColumn.enumValues,
136747
- default: baseColumn.default,
136748
- isUnique: baseColumn.isUnique,
136749
- notNull: baseColumn.notNull,
136750
- primary: baseColumn.primary,
136751
- baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
136752
- };
136753
- return baseColumnResult;
136754
- };
136755
- const getTypeParams = (sqlType) => {
136756
- // get type params
136757
- const typeParams = {};
136758
- // handle dimensions
136759
- if (sqlType.includes('[')) {
136760
- const match = sqlType.match(/\[\w*]/g);
136761
- if (match) {
136762
- typeParams['dimensions'] = match.length;
136763
- }
136764
- }
136765
- if (sqlType.startsWith('numeric')
136766
- || sqlType.startsWith('decimal')
136767
- || sqlType.startsWith('double precision')
136768
- || sqlType.startsWith('real')) {
136769
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
136770
- if (match) {
136771
- typeParams['precision'] = Number(match[1]);
136772
- typeParams['scale'] = Number(match[2]);
136773
- }
137325
+ else if (sqlType.startsWith('varchar')
137326
+ || sqlType.startsWith('char')
137327
+ || sqlType.startsWith('bit')
137328
+ || sqlType.startsWith('vector')
137329
+ || sqlType.startsWith('time')
137330
+ || sqlType.startsWith('timestamp')
137331
+ || sqlType.startsWith('interval')) {
137332
+ const match = sqlType.match(/\((\d+)\)/);
137333
+ if (match) {
137334
+ typeParams['length'] = Number(match[1]);
136774
137335
  }
136775
- else if (sqlType.startsWith('varchar')
136776
- || sqlType.startsWith('char')
136777
- || sqlType.startsWith('bit')
136778
- || sqlType.startsWith('vector')
136779
- || sqlType.startsWith('time')
136780
- || sqlType.startsWith('timestamp')
136781
- || sqlType.startsWith('interval')) {
136782
- const match = sqlType.match(/\((\d+)\)/);
136783
- if (match) {
136784
- typeParams['length'] = Number(match[1]);
136785
- }
136786
- }
136787
- return typeParams;
136788
- };
136789
- // console.log(tableConfig.columns);
136790
- tables.push({
136791
- name: dbToTsTableNamesMap[tableConfig.name],
136792
- columns: tableConfig.columns.map((column) => ({
136793
- name: dbToTsColumnNamesMap[column.name],
136794
- columnType: column.getSQLType(),
136795
- typeParams: getTypeParams(column.getSQLType()),
136796
- dataType: column.dataType,
136797
- size: column.size,
136798
- hasDefault: column.hasDefault,
136799
- default: column.default,
136800
- enumValues: column.enumValues,
136801
- isUnique: column.isUnique,
136802
- notNull: column.notNull,
136803
- primary: column.primary,
136804
- generatedIdentityType: column.generatedIdentity?.type,
136805
- baseColumn: (column.baseColumn === undefined)
136806
- ? undefined
136807
- : getAllBaseColumns(column.baseColumn),
136808
- })),
136809
- primaryKeys: tableConfig.columns
136810
- .filter((column) => column.primary)
136811
- .map((column) => dbToTsColumnNamesMap[column.name]),
136812
- });
136813
- }
136814
- const transformedDrizzleRelations = transformFromDrizzleRelation(cockroachSchema, getDbToTsColumnNamesMap, tableRelations);
136815
- relations.push(...transformedDrizzleRelations);
136816
- const isCyclicRelations = relations.map((relI) => {
136817
- // if (relations.some((relj) => relI.table === relj.refTable && relI.refTable === relj.table)) {
136818
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
136819
- if (isRelationCyclic(relI)) {
136820
- tableRel['isCyclic'] = true;
136821
- return { ...relI, isCyclic: true };
136822
137336
  }
136823
- tableRel['isCyclic'] = false;
136824
- return { ...relI, isCyclic: false };
136825
- });
136826
- return { tables, relations: isCyclicRelations, tableRelations };
137337
+ return typeParams;
137338
+ };
137339
+ const mappedColumns = tableConfig.columns.map((column) => ({
137340
+ name: dbToTsColumnNamesMap[column.name],
137341
+ columnType: column.getSQLType(),
137342
+ typeParams: getTypeParams(column.getSQLType()),
137343
+ dataType: column.dataType.split(' ')[0],
137344
+ size: column.length,
137345
+ hasDefault: column.hasDefault,
137346
+ default: column.default,
137347
+ enumValues: column.enumValues,
137348
+ isUnique: column.isUnique,
137349
+ notNull: column.notNull,
137350
+ primary: column.primary,
137351
+ generatedIdentityType: column.generatedIdentity?.type,
137352
+ baseColumn: (column.baseColumn === undefined)
137353
+ ? undefined
137354
+ : getAllBaseColumns(column.baseColumn),
137355
+ }));
137356
+ return mappedColumns;
136827
137357
  };
136828
137358
 
136829
137359
  // MySql-----------------------------------------------------------------------------------------------------
136830
137360
  const resetMsSql = async (db, schema) => {
136831
137361
  const tablesToTruncate = Object.entries(schema).map(([_tsTableName, table]) => {
136832
- const tableConfig = getTableConfig(table);
137362
+ const tableConfig = getTableConfig$5(table);
136833
137363
  return { dbName: tableConfig.name, dbSchema: tableConfig.schema ?? 'dbo' };
136834
137364
  });
136835
137365
  const allFkConstraints = {};
@@ -136912,7 +137442,7 @@ const filterMsSqlTables = (schema) => {
136912
137442
  };
136913
137443
  const seedMsSql = async (db, schema, options = {}, refinements) => {
136914
137444
  const { mssqlSchema, mssqlTables } = filterMsSqlTables(schema);
136915
- const { tables, relations } = getMsSqlInfo(mssqlSchema, mssqlTables);
137445
+ const { tables, relations } = getSchemaInfo(mssqlSchema, mssqlTables, mapMsSqlColumns);
136916
137446
  const seedService = new SeedService();
136917
137447
  const generatedTablesGenerators = seedService.generatePossibleGenerators('mssql', tables, relations, refinements, options);
136918
137448
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
@@ -136921,163 +137451,45 @@ const seedMsSql = async (db, schema, options = {}, refinements) => {
136921
137451
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
136922
137452
  await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mssqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
136923
137453
  };
136924
- const getMsSqlInfo = (mssqlSchema, mssqlTables) => {
136925
- let tableConfig;
136926
- let dbToTsColumnNamesMap;
136927
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(mssqlTables).map(([key, value]) => [getTableName(value), key]));
136928
- const tables = [];
136929
- const relations = [];
136930
- const dbToTsColumnNamesMapGlobal = {};
136931
- const tableRelations = {};
136932
- const getDbToTsColumnNamesMap = (table) => {
136933
- let dbToTsColumnNamesMap = {};
136934
- const tableName = getTableName(table);
136935
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
136936
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
136937
- return dbToTsColumnNamesMap;
136938
- }
136939
- const tableConfig = getTableConfig(table);
136940
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136941
- dbToTsColumnNamesMap[col.name] = tsCol;
136942
- }
136943
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
136944
- return dbToTsColumnNamesMap;
136945
- };
136946
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
136947
- const schemaConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
136948
- const relations = [];
136949
- for (const table of Object.values(schemaConfig.tables)) {
136950
- if (table.relations === undefined)
136951
- continue;
136952
- for (const drizzleRel of Object.values(table.relations)) {
136953
- if (!is(drizzleRel, One))
136954
- continue;
136955
- const tableConfig = getTableConfig(drizzleRel.sourceTable);
136956
- const tableDbSchema = tableConfig.schema ?? 'public';
136957
- const tableDbName = tableConfig.name;
136958
- const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
136959
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
136960
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
136961
- ?? [];
136962
- const refTableConfig = getTableConfig(drizzleRel.referencedTable);
136963
- const refTableDbSchema = refTableConfig.schema ?? 'public';
136964
- const refTableDbName = refTableConfig.name;
136965
- const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
136966
- ?? refTableDbName;
136967
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
136968
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
136969
- ?? [];
136970
- if (tableRelations[refTableTsName] === undefined) {
136971
- tableRelations[refTableTsName] = [];
136972
- }
136973
- const relation = {
136974
- table: tableTsName,
136975
- columns,
136976
- refTable: refTableTsName,
136977
- refColumns,
136978
- refTableRels: tableRelations[refTableTsName],
136979
- type: 'one',
136980
- };
136981
- // do not add duplicate relation
136982
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
136983
- && rel.refTable === relation.refTable)) {
136984
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
136985
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
136986
- + `In this case, the foreign key constraint will be used.\n`);
136987
- continue;
136988
- }
136989
- relations.push(relation);
136990
- tableRelations[tableTsName].push(relation);
137454
+ const mapMsSqlColumns = (tableConfig, dbToTsColumnNamesMap) => {
137455
+ // TODO: rewrite
137456
+ const getTypeParams = (sqlType) => {
137457
+ // get type params and set only type
137458
+ const typeParams = {};
137459
+ if (sqlType.startsWith('decimal')
137460
+ || sqlType.startsWith('real')
137461
+ || sqlType.startsWith('float')) {
137462
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137463
+ if (match) {
137464
+ typeParams['precision'] = Number(match[1]);
137465
+ typeParams['scale'] = Number(match[2]);
136991
137466
  }
136992
137467
  }
136993
- return relations;
136994
- };
136995
- for (const table of Object.values(mssqlTables)) {
136996
- tableConfig = getTableConfig(table);
136997
- dbToTsColumnNamesMap = {};
136998
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
136999
- dbToTsColumnNamesMap[col.name] = tsCol;
137000
- }
137001
- const newRelations = tableConfig.foreignKeys.map((fk) => {
137002
- const table = dbToTsTableNamesMap[tableConfig.name];
137003
- const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)];
137004
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
137005
- if (tableRelations[refTable] === undefined) {
137006
- tableRelations[refTable] = [];
137007
- }
137008
- return {
137009
- table,
137010
- columns: fk
137011
- .reference()
137012
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
137013
- refTable,
137014
- refColumns: fk
137015
- .reference()
137016
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
137017
- refTableRels: tableRelations[refTable],
137018
- };
137019
- });
137020
- relations.push(...newRelations);
137021
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
137022
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
137023
- }
137024
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137025
- // TODO: rewrite
137026
- const getTypeParams = (sqlType) => {
137027
- // get type params and set only type
137028
- const typeParams = {};
137029
- if (sqlType.startsWith('decimal')
137030
- || sqlType.startsWith('real')
137031
- || sqlType.startsWith('float')) {
137032
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
137033
- if (match) {
137034
- typeParams['precision'] = Number(match[1]);
137035
- typeParams['scale'] = Number(match[2]);
137036
- }
137037
- }
137038
- else if (sqlType.startsWith('char')
137039
- || sqlType.startsWith('varchar')
137040
- || sqlType.startsWith('binary')
137041
- || sqlType.startsWith('varbinary')) {
137042
- const match = sqlType.match(/\((\d+)\)/);
137043
- if (match) {
137044
- typeParams['length'] = Number(match[1]);
137045
- }
137468
+ else if (sqlType.startsWith('char')
137469
+ || sqlType.startsWith('varchar')
137470
+ || sqlType.startsWith('binary')
137471
+ || sqlType.startsWith('varbinary')) {
137472
+ const match = sqlType.match(/\((\d+)\)/);
137473
+ if (match) {
137474
+ typeParams['length'] = Number(match[1]);
137046
137475
  }
137047
- return typeParams;
137048
- };
137049
- tables.push({
137050
- name: dbToTsTableNamesMap[tableConfig.name],
137051
- columns: tableConfig.columns.map((column) => ({
137052
- name: dbToTsColumnNamesMap[column.name],
137053
- columnType: column.getSQLType(),
137054
- typeParams: getTypeParams(column.getSQLType()),
137055
- dataType: column.dataType,
137056
- hasDefault: column.hasDefault,
137057
- default: column.default,
137058
- enumValues: column.enumValues,
137059
- isUnique: column.isUnique,
137060
- notNull: column.notNull,
137061
- primary: column.primary,
137062
- identity: column.identity ? true : false,
137063
- })),
137064
- primaryKeys: tableConfig.columns
137065
- .filter((column) => column.primary)
137066
- .map((column) => dbToTsColumnNamesMap[column.name]),
137067
- });
137068
- }
137069
- const transformedDrizzleRelations = transformFromDrizzleRelation(mssqlSchema, getDbToTsColumnNamesMap, tableRelations);
137070
- relations.push(...transformedDrizzleRelations);
137071
- const modifiedRelations = relations.map((relI) => {
137072
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
137073
- if (isRelationCyclic(relI)) {
137074
- tableRel['isCyclic'] = true;
137075
- return { ...relI, isCyclic: true };
137076
137476
  }
137077
- tableRel['isCyclic'] = false;
137078
- return { ...relI, isCyclic: false };
137079
- });
137080
- return { tables, relations: modifiedRelations, tableRelations };
137477
+ return typeParams;
137478
+ };
137479
+ const mappedColumns = tableConfig.columns.map((column) => ({
137480
+ name: dbToTsColumnNamesMap[column.name],
137481
+ columnType: column.getSQLType(),
137482
+ typeParams: getTypeParams(column.getSQLType()),
137483
+ dataType: column.dataType.split(' ')[0],
137484
+ hasDefault: column.hasDefault,
137485
+ default: column.default,
137486
+ enumValues: column.enumValues,
137487
+ isUnique: column.isUnique,
137488
+ notNull: column.notNull,
137489
+ primary: column.primary,
137490
+ identity: column.identity ? true : false,
137491
+ }));
137492
+ return mappedColumns;
137081
137493
  };
137082
137494
 
137083
137495
  // MySql-----------------------------------------------------------------------------------------------------
@@ -137100,7 +137512,7 @@ const filterMysqlTables = (schema) => {
137100
137512
  };
137101
137513
  const seedMySql = async (db, schema, options = {}, refinements) => {
137102
137514
  const { mysqlSchema, mysqlTables } = filterMysqlTables(schema);
137103
- const { tables, relations } = getMySqlInfo(mysqlSchema, mysqlTables);
137515
+ const { tables, relations } = getSchemaInfo(mysqlSchema, mysqlTables, mapMySqlColumns);
137104
137516
  const seedService = new SeedService();
137105
137517
  const generatedTablesGenerators = seedService.generatePossibleGenerators('mysql', tables, relations, refinements, options);
137106
137518
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
@@ -137109,168 +137521,50 @@ const seedMySql = async (db, schema, options = {}, refinements) => {
137109
137521
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137110
137522
  await seedService.generateTablesValues(relations, filteredTablesGenerators, db, mysqlTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137111
137523
  };
137112
- const getMySqlInfo = (mysqlSchema, mysqlTables) => {
137113
- let tableConfig;
137114
- let dbToTsColumnNamesMap;
137115
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(mysqlTables).map(([key, value]) => [getTableName(value), key]));
137116
- const tables = [];
137117
- const relations = [];
137118
- const dbToTsColumnNamesMapGlobal = {};
137119
- const tableRelations = {};
137120
- const getDbToTsColumnNamesMap = (table) => {
137121
- let dbToTsColumnNamesMap = {};
137122
- const tableName = getTableName(table);
137123
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
137124
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
137125
- return dbToTsColumnNamesMap;
137126
- }
137127
- const tableConfig = getTableConfig$2(table);
137128
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137129
- dbToTsColumnNamesMap[col.name] = tsCol;
137130
- }
137131
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
137132
- return dbToTsColumnNamesMap;
137133
- };
137134
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
137135
- const schemaConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
137136
- const relations = [];
137137
- for (const table of Object.values(schemaConfig.tables)) {
137138
- if (table.relations === undefined)
137139
- continue;
137140
- for (const drizzleRel of Object.values(table.relations)) {
137141
- if (!is(drizzleRel, One))
137142
- continue;
137143
- const tableConfig = getTableConfig$2(drizzleRel.sourceTable);
137144
- const tableDbSchema = tableConfig.schema ?? 'public';
137145
- const tableDbName = tableConfig.name;
137146
- const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
137147
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
137148
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
137149
- ?? [];
137150
- const refTableConfig = getTableConfig$2(drizzleRel.referencedTable);
137151
- const refTableDbSchema = refTableConfig.schema ?? 'public';
137152
- const refTableDbName = refTableConfig.name;
137153
- const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
137154
- ?? refTableDbName;
137155
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
137156
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
137157
- ?? [];
137158
- if (tableRelations[refTableTsName] === undefined) {
137159
- tableRelations[refTableTsName] = [];
137160
- }
137161
- const relation = {
137162
- table: tableTsName,
137163
- columns,
137164
- refTable: refTableTsName,
137165
- refColumns,
137166
- refTableRels: tableRelations[refTableTsName],
137167
- type: 'one',
137168
- };
137169
- // do not add duplicate relation
137170
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
137171
- && rel.refTable === relation.refTable)) {
137172
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
137173
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
137174
- + `In this case, the foreign key constraint will be used.\n`);
137175
- continue;
137176
- }
137177
- relations.push(relation);
137178
- tableRelations[tableTsName].push(relation);
137524
+ const mapMySqlColumns = (tableConfig, dbToTsColumnNamesMap) => {
137525
+ const getTypeParams = (sqlType) => {
137526
+ // get type params and set only type
137527
+ const typeParams = {};
137528
+ if (sqlType.startsWith('decimal')
137529
+ || sqlType.startsWith('real')
137530
+ || sqlType.startsWith('double')
137531
+ || sqlType.startsWith('float')) {
137532
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137533
+ if (match) {
137534
+ typeParams['precision'] = Number(match[1]);
137535
+ typeParams['scale'] = Number(match[2]);
137179
137536
  }
137180
137537
  }
137181
- return relations;
137182
- };
137183
- for (const table of Object.values(mysqlTables)) {
137184
- tableConfig = getTableConfig$2(table);
137185
- dbToTsColumnNamesMap = {};
137186
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137187
- dbToTsColumnNamesMap[col.name] = tsCol;
137188
- }
137189
- const newRelations = tableConfig.foreignKeys.map((fk) => {
137190
- const table = dbToTsTableNamesMap[tableConfig.name];
137191
- const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)];
137192
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
137193
- if (tableRelations[refTable] === undefined) {
137194
- tableRelations[refTable] = [];
137195
- }
137196
- return {
137197
- table,
137198
- columns: fk
137199
- .reference()
137200
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
137201
- refTable,
137202
- refColumns: fk
137203
- .reference()
137204
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
137205
- refTableRels: tableRelations[refTable],
137206
- };
137207
- });
137208
- relations.push(...newRelations);
137209
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
137210
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
137211
- }
137212
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137213
- const getTypeParams = (sqlType) => {
137214
- // get type params and set only type
137215
- const typeParams = {};
137216
- if (sqlType.startsWith('decimal')
137217
- || sqlType.startsWith('real')
137218
- || sqlType.startsWith('double')
137219
- || sqlType.startsWith('float')) {
137220
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
137221
- if (match) {
137222
- typeParams['precision'] = Number(match[1]);
137223
- typeParams['scale'] = Number(match[2]);
137224
- }
137538
+ else if (sqlType.startsWith('char')
137539
+ || sqlType.startsWith('varchar')
137540
+ || sqlType.startsWith('binary')
137541
+ || sqlType.startsWith('varbinary')) {
137542
+ const match = sqlType.match(/\((\d+)\)/);
137543
+ if (match) {
137544
+ typeParams['length'] = Number(match[1]);
137225
137545
  }
137226
- else if (sqlType.startsWith('char')
137227
- || sqlType.startsWith('varchar')
137228
- || sqlType.startsWith('binary')
137229
- || sqlType.startsWith('varbinary')) {
137230
- const match = sqlType.match(/\((\d+)\)/);
137231
- if (match) {
137232
- typeParams['length'] = Number(match[1]);
137233
- }
137234
- }
137235
- return typeParams;
137236
- };
137237
- tables.push({
137238
- name: dbToTsTableNamesMap[tableConfig.name],
137239
- columns: tableConfig.columns.map((column) => ({
137240
- name: dbToTsColumnNamesMap[column.name],
137241
- columnType: column.getSQLType(),
137242
- typeParams: getTypeParams(column.getSQLType()),
137243
- dataType: column.dataType,
137244
- hasDefault: column.hasDefault,
137245
- default: column.default,
137246
- enumValues: column.enumValues,
137247
- isUnique: column.isUnique,
137248
- notNull: column.notNull,
137249
- primary: column.primary,
137250
- })),
137251
- primaryKeys: tableConfig.columns
137252
- .filter((column) => column.primary)
137253
- .map((column) => dbToTsColumnNamesMap[column.name]),
137254
- });
137255
- }
137256
- const transformedDrizzleRelations = transformFromDrizzleRelation(mysqlSchema, getDbToTsColumnNamesMap, tableRelations);
137257
- relations.push(...transformedDrizzleRelations);
137258
- const isCyclicRelations = relations.map((relI) => {
137259
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
137260
- if (isRelationCyclic(relI)) {
137261
- tableRel['isCyclic'] = true;
137262
- return { ...relI, isCyclic: true };
137263
137546
  }
137264
- tableRel['isCyclic'] = false;
137265
- return { ...relI, isCyclic: false };
137266
- });
137267
- return { tables, relations: isCyclicRelations, tableRelations };
137547
+ return typeParams;
137548
+ };
137549
+ const mappedColumns = tableConfig.columns.map((column) => ({
137550
+ name: dbToTsColumnNamesMap[column.name],
137551
+ columnType: column.getSQLType(),
137552
+ typeParams: getTypeParams(column.getSQLType()),
137553
+ dataType: column.dataType.split(' ')[0],
137554
+ hasDefault: column.hasDefault,
137555
+ default: column.default,
137556
+ enumValues: column.enumValues,
137557
+ isUnique: column.isUnique,
137558
+ notNull: column.notNull,
137559
+ primary: column.primary,
137560
+ }));
137561
+ return mappedColumns;
137268
137562
  };
137269
137563
 
137270
137564
  // Postgres-----------------------------------------------------------------------------------------------------------
137271
137565
  const resetPostgres = async (db, pgTables) => {
137272
137566
  const tablesToTruncate = Object.entries(pgTables).map(([_, table]) => {
137273
- const config = getTableConfig$3(table);
137567
+ const config = getTableConfig$1(table);
137274
137568
  config.schema = config.schema === undefined ? 'public' : config.schema;
137275
137569
  return `"${config.schema}"."${config.name}"`;
137276
137570
  });
@@ -137284,7 +137578,8 @@ const filterPgSchema = (schema) => {
137284
137578
  const seedPostgres = async (db, schema, options = {}, refinements) => {
137285
137579
  const seedService = new SeedService();
137286
137580
  const { pgSchema, pgTables } = filterPgSchema(schema);
137287
- const { tables, relations } = getPostgresInfo(pgSchema, pgTables);
137581
+ const { tables, relations } = getSchemaInfo(pgSchema, pgTables, mapPgColumns);
137582
+ // const { tables, relations } = getPostgresInfo(pgSchema, pgTables);
137288
137583
  const generatedTablesGenerators = seedService.generatePossibleGenerators('postgresql', tables, relations, refinements, options);
137289
137584
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
137290
137585
  const tablesValues = await seedService.generateTablesValues(relations, generatedTablesGenerators, db, pgTables, { ...options, preserveCyclicTablesData });
@@ -137292,198 +137587,77 @@ const seedPostgres = async (db, schema, options = {}, refinements) => {
137292
137587
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137293
137588
  await seedService.generateTablesValues(relations, filteredTablesGenerators, db, pgTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137294
137589
  };
137295
- const getPostgresInfo = (pgSchema, pgTables) => {
137296
- let tableConfig;
137297
- let dbToTsColumnNamesMap;
137298
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(pgTables).map(([key, value]) => [getTableName(value), key]));
137299
- const tables = [];
137300
- const relations = [];
137301
- const dbToTsColumnNamesMapGlobal = {};
137302
- const tableRelations = {};
137303
- const getDbToTsColumnNamesMap = (table) => {
137304
- let dbToTsColumnNamesMap = {};
137305
- const tableName = getTableName(table);
137306
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
137307
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
137308
- return dbToTsColumnNamesMap;
137309
- }
137310
- const tableConfig = getTableConfig$3(table);
137311
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137312
- dbToTsColumnNamesMap[col.name] = tsCol;
137313
- }
137314
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
137315
- return dbToTsColumnNamesMap;
137590
+ const mapPgColumns = (tableConfig, dbToTsColumnNamesMap) => {
137591
+ const getAllBaseColumns = (baseColumn) => {
137592
+ const baseColumnResult = {
137593
+ name: baseColumn.name,
137594
+ columnType: baseColumn.getSQLType(),
137595
+ typeParams: getTypeParams(baseColumn.getSQLType()),
137596
+ dataType: baseColumn.dataType.split(' ')[0],
137597
+ size: baseColumn.length,
137598
+ hasDefault: baseColumn.hasDefault,
137599
+ enumValues: baseColumn.enumValues,
137600
+ default: baseColumn.default,
137601
+ isUnique: baseColumn.isUnique,
137602
+ notNull: baseColumn.notNull,
137603
+ primary: baseColumn.primary,
137604
+ baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
137605
+ };
137606
+ return baseColumnResult;
137316
137607
  };
137317
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
137318
- const schemaConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
137319
- const relations = [];
137320
- for (const table of Object.values(schemaConfig.tables)) {
137321
- if (table.relations === undefined)
137322
- continue;
137323
- for (const drizzleRel of Object.values(table.relations)) {
137324
- if (!is(drizzleRel, One))
137325
- continue;
137326
- const tableConfig = getTableConfig$3(drizzleRel.sourceTable);
137327
- const tableDbSchema = tableConfig.schema ?? 'public';
137328
- const tableDbName = tableConfig.name;
137329
- const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
137330
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
137331
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
137332
- ?? [];
137333
- const refTableConfig = getTableConfig$3(drizzleRel.referencedTable);
137334
- const refTableDbSchema = refTableConfig.schema ?? 'public';
137335
- const refTableDbName = refTableConfig.name;
137336
- const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
137337
- ?? refTableDbName;
137338
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
137339
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
137340
- ?? [];
137341
- if (tableRelations[refTableTsName] === undefined) {
137342
- tableRelations[refTableTsName] = [];
137343
- }
137344
- const relation = {
137345
- table: tableTsName,
137346
- columns,
137347
- refTable: refTableTsName,
137348
- refColumns,
137349
- refTableRels: tableRelations[refTableTsName],
137350
- type: 'one',
137351
- };
137352
- // do not add duplicate relation
137353
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
137354
- && rel.refTable === relation.refTable)) {
137355
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
137356
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
137357
- + `In this case, the foreign key constraint will be used.\n`);
137358
- continue;
137359
- }
137360
- relations.push(relation);
137361
- tableRelations[tableTsName].push(relation);
137608
+ const getTypeParams = (sqlType) => {
137609
+ // get type params
137610
+ const typeParams = {};
137611
+ // handle dimensions
137612
+ if (sqlType.includes('[')) {
137613
+ const match = sqlType.match(/\[\w*]/g);
137614
+ if (match) {
137615
+ typeParams['dimensions'] = match.length;
137362
137616
  }
137363
137617
  }
137364
- return relations;
137365
- };
137366
- for (const table of Object.values(pgTables)) {
137367
- tableConfig = getTableConfig$3(table);
137368
- dbToTsColumnNamesMap = {};
137369
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137370
- dbToTsColumnNamesMap[col.name] = tsCol;
137371
- }
137372
- // might be empty list
137373
- const newRelations = tableConfig.foreignKeys.map((fk) => {
137374
- const table = dbToTsTableNamesMap[tableConfig.name];
137375
- const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)];
137376
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
137377
- if (tableRelations[refTable] === undefined) {
137378
- tableRelations[refTable] = [];
137618
+ if (sqlType.startsWith('numeric')
137619
+ || sqlType.startsWith('decimal')
137620
+ || sqlType.startsWith('double precision')
137621
+ || sqlType.startsWith('real')) {
137622
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137623
+ if (match) {
137624
+ typeParams['precision'] = Number(match[1]);
137625
+ typeParams['scale'] = Number(match[2]);
137379
137626
  }
137380
- return {
137381
- table,
137382
- columns: fk
137383
- .reference()
137384
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
137385
- refTable,
137386
- refColumns: fk
137387
- .reference()
137388
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
137389
- refTableRels: tableRelations[refTable],
137390
- };
137391
- });
137392
- relations.push(...newRelations);
137393
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
137394
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
137395
137627
  }
137396
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137397
- const getAllBaseColumns = (baseColumn) => {
137398
- const baseColumnResult = {
137399
- name: baseColumn.name,
137400
- columnType: baseColumn.getSQLType(),
137401
- typeParams: getTypeParams(baseColumn.getSQLType()),
137402
- dataType: baseColumn.dataType,
137403
- size: baseColumn.size,
137404
- hasDefault: baseColumn.hasDefault,
137405
- enumValues: baseColumn.enumValues,
137406
- default: baseColumn.default,
137407
- isUnique: baseColumn.isUnique,
137408
- notNull: baseColumn.notNull,
137409
- primary: baseColumn.primary,
137410
- baseColumn: baseColumn.baseColumn === undefined ? undefined : getAllBaseColumns(baseColumn.baseColumn),
137411
- };
137412
- return baseColumnResult;
137413
- };
137414
- const getTypeParams = (sqlType) => {
137415
- // get type params
137416
- const typeParams = {};
137417
- // handle dimensions
137418
- if (sqlType.includes('[')) {
137419
- const match = sqlType.match(/\[\w*]/g);
137420
- if (match) {
137421
- typeParams['dimensions'] = match.length;
137422
- }
137628
+ else if (sqlType.startsWith('varchar')
137629
+ || sqlType.startsWith('bpchar')
137630
+ || sqlType.startsWith('char')
137631
+ || sqlType.startsWith('bit')
137632
+ || sqlType.startsWith('vector')
137633
+ || sqlType.startsWith('time')
137634
+ || sqlType.startsWith('timestamp')
137635
+ || sqlType.startsWith('interval')) {
137636
+ const match = sqlType.match(/\((\d+)\)/);
137637
+ if (match) {
137638
+ typeParams['length'] = Number(match[1]);
137423
137639
  }
137424
- if (sqlType.startsWith('numeric')
137425
- || sqlType.startsWith('decimal')
137426
- || sqlType.startsWith('double precision')
137427
- || sqlType.startsWith('real')) {
137428
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
137429
- if (match) {
137430
- typeParams['precision'] = Number(match[1]);
137431
- typeParams['scale'] = Number(match[2]);
137432
- }
137433
- }
137434
- else if (sqlType.startsWith('varchar')
137435
- || sqlType.startsWith('bpchar')
137436
- || sqlType.startsWith('char')
137437
- || sqlType.startsWith('bit')
137438
- || sqlType.startsWith('vector')
137439
- || sqlType.startsWith('time')
137440
- || sqlType.startsWith('timestamp')
137441
- || sqlType.startsWith('interval')) {
137442
- const match = sqlType.match(/\((\d+)\)/);
137443
- if (match) {
137444
- typeParams['length'] = Number(match[1]);
137445
- }
137446
- }
137447
- return typeParams;
137448
- };
137449
- // console.log(tableConfig.columns);
137450
- tables.push({
137451
- name: dbToTsTableNamesMap[tableConfig.name],
137452
- columns: tableConfig.columns.map((column) => ({
137453
- name: dbToTsColumnNamesMap[column.name],
137454
- columnType: column.getSQLType(),
137455
- typeParams: getTypeParams(column.getSQLType()),
137456
- dataType: column.dataType,
137457
- size: column.size,
137458
- hasDefault: column.hasDefault,
137459
- default: column.default,
137460
- enumValues: column.enumValues,
137461
- isUnique: column.isUnique,
137462
- notNull: column.notNull,
137463
- primary: column.primary,
137464
- generatedIdentityType: column.generatedIdentity?.type,
137465
- baseColumn: (column.baseColumn === undefined)
137466
- ? undefined
137467
- : getAllBaseColumns(column.baseColumn),
137468
- })),
137469
- primaryKeys: tableConfig.columns
137470
- .filter((column) => column.primary)
137471
- .map((column) => dbToTsColumnNamesMap[column.name]),
137472
- });
137473
- }
137474
- const transformedDrizzleRelations = transformFromDrizzleRelation(pgSchema, getDbToTsColumnNamesMap, tableRelations);
137475
- relations.push(...transformedDrizzleRelations);
137476
- const isCyclicRelations = relations.map((relI) => {
137477
- // if (relations.some((relj) => relI.table === relj.refTable && relI.refTable === relj.table)) {
137478
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
137479
- if (isRelationCyclic(relI)) {
137480
- tableRel['isCyclic'] = true;
137481
- return { ...relI, isCyclic: true };
137482
137640
  }
137483
- tableRel['isCyclic'] = false;
137484
- return { ...relI, isCyclic: false };
137485
- });
137486
- return { tables, relations: isCyclicRelations, tableRelations };
137641
+ return typeParams;
137642
+ };
137643
+ const mappedColumns = tableConfig.columns.map((column) => ({
137644
+ name: dbToTsColumnNamesMap[column.name],
137645
+ columnType: column.getSQLType(),
137646
+ typeParams: getTypeParams(column.getSQLType()),
137647
+ dataType: column.dataType.split(' ')[0],
137648
+ size: column.length,
137649
+ hasDefault: column.hasDefault,
137650
+ default: column.default,
137651
+ enumValues: column.enumValues,
137652
+ isUnique: column.isUnique,
137653
+ notNull: column.notNull,
137654
+ primary: column.primary,
137655
+ generatedIdentityType: column.generatedIdentity?.type,
137656
+ baseColumn: (column.baseColumn === undefined)
137657
+ ? undefined
137658
+ : getAllBaseColumns(column.baseColumn),
137659
+ }));
137660
+ return mappedColumns;
137487
137661
  };
137488
137662
 
137489
137663
  // SingleStore-----------------------------------------------------------------------------------------------------
@@ -137506,7 +137680,7 @@ const filterSingleStoreTables = (schema) => {
137506
137680
  };
137507
137681
  const seedSingleStore = async (db, schema, options = {}, refinements) => {
137508
137682
  const { singleStoreSchema, singleStoreTables } = filterSingleStoreTables(schema);
137509
- const { tables, relations } = getSingleStoreInfo(singleStoreSchema, singleStoreTables);
137683
+ const { tables, relations } = getSchemaInfo(singleStoreSchema, singleStoreTables, mapSingleStoreColumns);
137510
137684
  const seedService = new SeedService();
137511
137685
  const generatedTablesGenerators = seedService.generatePossibleGenerators('singlestore', tables, relations, refinements, options);
137512
137686
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
@@ -137515,175 +137689,52 @@ const seedSingleStore = async (db, schema, options = {}, refinements) => {
137515
137689
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137516
137690
  await seedService.generateTablesValues(relations, filteredTablesGenerators, db, singleStoreTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137517
137691
  };
137518
- const getSingleStoreInfo = (singleStoreSchema, singleStoreTables) => {
137519
- let tableConfig;
137520
- let dbToTsColumnNamesMap;
137521
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(singleStoreTables).map(([key, value]) => [getTableName(value), key]));
137522
- const tables = [];
137523
- const relations = [];
137524
- const dbToTsColumnNamesMapGlobal = {};
137525
- const tableRelations = {};
137526
- const getDbToTsColumnNamesMap = (table) => {
137527
- let dbToTsColumnNamesMap = {};
137528
- const tableName = getTableName(table);
137529
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
137530
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
137531
- return dbToTsColumnNamesMap;
137532
- }
137533
- const tableConfig = getTableConfig$4(table);
137534
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137535
- dbToTsColumnNamesMap[col.name] = tsCol;
137536
- }
137537
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
137538
- return dbToTsColumnNamesMap;
137539
- };
137540
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
137541
- const schemaConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
137542
- const relations = [];
137543
- for (const table of Object.values(schemaConfig.tables)) {
137544
- if (table.relations === undefined)
137545
- continue;
137546
- for (const drizzleRel of Object.values(table.relations)) {
137547
- if (!is(drizzleRel, One))
137548
- continue;
137549
- const tableConfig = getTableConfig$4(drizzleRel.sourceTable);
137550
- const tableDbSchema = tableConfig.schema ?? 'public';
137551
- const tableDbName = tableConfig.name;
137552
- const tableTsName = schemaConfig.tableNamesMap[`${tableDbSchema}.${tableDbName}`] ?? tableDbName;
137553
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
137554
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
137555
- ?? [];
137556
- const refTableConfig = getTableConfig$4(drizzleRel.referencedTable);
137557
- const refTableDbSchema = refTableConfig.schema ?? 'public';
137558
- const refTableDbName = refTableConfig.name;
137559
- const refTableTsName = schemaConfig.tableNamesMap[`${refTableDbSchema}.${refTableDbName}`]
137560
- ?? refTableDbName;
137561
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
137562
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
137563
- ?? [];
137564
- if (tableRelations[refTableTsName] === undefined) {
137565
- tableRelations[refTableTsName] = [];
137566
- }
137567
- const relation = {
137568
- table: tableTsName,
137569
- columns,
137570
- refTable: refTableTsName,
137571
- refColumns,
137572
- refTableRels: tableRelations[refTableTsName],
137573
- type: 'one',
137574
- };
137575
- // do not add duplicate relation
137576
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
137577
- && rel.refTable === relation.refTable)) {
137578
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
137579
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
137580
- + `In this case, the foreign key constraint will be used.\n`);
137581
- continue;
137582
- }
137583
- relations.push(relation);
137584
- tableRelations[tableTsName].push(relation);
137692
+ const mapSingleStoreColumns = (tableConfig, dbToTsColumnNamesMap) => {
137693
+ const getTypeParams = (sqlType) => {
137694
+ // get type params and set only type
137695
+ const typeParams = {};
137696
+ if (sqlType.startsWith('decimal')
137697
+ || sqlType.startsWith('real')
137698
+ || sqlType.startsWith('double')
137699
+ || sqlType.startsWith('float')) {
137700
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137701
+ if (match) {
137702
+ typeParams['precision'] = Number(match[1]);
137703
+ typeParams['scale'] = Number(match[2]);
137585
137704
  }
137586
137705
  }
137587
- return relations;
137588
- };
137589
- for (const table of Object.values(singleStoreTables)) {
137590
- tableConfig = getTableConfig$4(table);
137591
- dbToTsColumnNamesMap = {};
137592
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137593
- dbToTsColumnNamesMap[col.name] = tsCol;
137594
- }
137595
- // const newRelations = tableConfig.foreignKeys.map((fk) => {
137596
- // const table = dbToTsTableNamesMap[tableConfig.name] as string;
137597
- // const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)] as string;
137598
- // const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(
137599
- // fk.reference().foreignTable,
137600
- // );
137601
- // if (tableRelations[refTable] === undefined) {
137602
- // tableRelations[refTable] = [];
137603
- // }
137604
- // return {
137605
- // table,
137606
- // columns: fk
137607
- // .reference()
137608
- // .columns.map((col) => dbToTsColumnNamesMap[col.name] as string),
137609
- // refTable,
137610
- // refColumns: fk
137611
- // .reference()
137612
- // .foreignColumns.map(
137613
- // (fCol) => dbToTsColumnNamesMapForRefTable[fCol.name] as string,
137614
- // ),
137615
- // refTableRels: tableRelations[refTable],
137616
- // };
137617
- // });
137618
- // relations.push(
137619
- // ...newRelations,
137620
- // );
137621
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
137622
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
137623
- }
137624
- // tableRelations[dbToTsTableNamesMap[tableConfig.name] as string]!.push(...newRelations);
137625
- const getTypeParams = (sqlType) => {
137626
- // get type params and set only type
137627
- const typeParams = {};
137628
- if (sqlType.startsWith('decimal')
137629
- || sqlType.startsWith('real')
137630
- || sqlType.startsWith('double')
137631
- || sqlType.startsWith('float')) {
137632
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
137633
- if (match) {
137634
- typeParams['precision'] = Number(match[1]);
137635
- typeParams['scale'] = Number(match[2]);
137636
- }
137706
+ else if (sqlType.startsWith('char')
137707
+ || sqlType.startsWith('varchar')
137708
+ || sqlType.startsWith('text')
137709
+ || sqlType.startsWith('binary')
137710
+ || sqlType.startsWith('varbinary')) {
137711
+ const match = sqlType.match(/\((\d+)\)/);
137712
+ if (match) {
137713
+ typeParams['length'] = Number(match[1]);
137637
137714
  }
137638
- else if (sqlType.startsWith('char')
137639
- || sqlType.startsWith('varchar')
137640
- || sqlType.startsWith('binary')
137641
- || sqlType.startsWith('varbinary')) {
137642
- const match = sqlType.match(/\((\d+)\)/);
137643
- if (match) {
137644
- typeParams['length'] = Number(match[1]);
137645
- }
137646
- }
137647
- else if (sqlType.startsWith('vector')) {
137648
- const match = sqlType.match(/\((\d+),? ?((F|I)\d{1,2})?\)/);
137649
- if (match) {
137650
- typeParams['length'] = Number(match[1]);
137651
- typeParams['vectorValueType'] = match[2];
137652
- }
137715
+ }
137716
+ else if (sqlType.startsWith('vector')) {
137717
+ const match = sqlType.match(/\((\d+),? ?((F|I)\d{1,2})?\)/);
137718
+ if (match) {
137719
+ typeParams['length'] = Number(match[1]);
137720
+ typeParams['vectorValueType'] = match[2];
137653
137721
  }
137654
- return typeParams;
137655
- };
137656
- tables.push({
137657
- name: dbToTsTableNamesMap[tableConfig.name],
137658
- columns: tableConfig.columns.map((column) => ({
137659
- name: dbToTsColumnNamesMap[column.name],
137660
- columnType: column.getSQLType(),
137661
- typeParams: getTypeParams(column.getSQLType()),
137662
- dataType: column.dataType,
137663
- hasDefault: column.hasDefault,
137664
- default: column.default,
137665
- enumValues: column.enumValues,
137666
- isUnique: column.isUnique,
137667
- notNull: column.notNull,
137668
- primary: column.primary,
137669
- })),
137670
- primaryKeys: tableConfig.columns
137671
- .filter((column) => column.primary)
137672
- .map((column) => dbToTsColumnNamesMap[column.name]),
137673
- });
137674
- }
137675
- const transformedDrizzleRelations = transformFromDrizzleRelation(singleStoreSchema, getDbToTsColumnNamesMap, tableRelations);
137676
- relations.push(...transformedDrizzleRelations);
137677
- const isCyclicRelations = relations.map((relI) => {
137678
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
137679
- if (isRelationCyclic(relI)) {
137680
- tableRel['isCyclic'] = true;
137681
- return { ...relI, isCyclic: true };
137682
137722
  }
137683
- tableRel['isCyclic'] = false;
137684
- return { ...relI, isCyclic: false };
137685
- });
137686
- return { tables, relations: isCyclicRelations, tableRelations };
137723
+ return typeParams;
137724
+ };
137725
+ const mappedColumns = tableConfig.columns.map((column) => ({
137726
+ name: dbToTsColumnNamesMap[column.name],
137727
+ columnType: column.getSQLType(),
137728
+ typeParams: getTypeParams(column.getSQLType()),
137729
+ dataType: column.dataType.split(' ')[0],
137730
+ hasDefault: column.hasDefault,
137731
+ default: column.default,
137732
+ enumValues: column.enumValues,
137733
+ isUnique: column.isUnique,
137734
+ notNull: column.notNull,
137735
+ primary: column.primary,
137736
+ }));
137737
+ return mappedColumns;
137687
137738
  };
137688
137739
 
137689
137740
  // Sqlite------------------------------------------------------------------------------------------------------------------------
@@ -137706,7 +137757,7 @@ const filterSqliteTables = (schema) => {
137706
137757
  };
137707
137758
  const seedSqlite = async (db, schema, options = {}, refinements) => {
137708
137759
  const { sqliteSchema, sqliteTables } = filterSqliteTables(schema);
137709
- const { tables, relations } = getSqliteInfo(sqliteSchema, sqliteTables);
137760
+ const { tables, relations } = getSchemaInfo(sqliteSchema, sqliteTables, mapSqliteColumns);
137710
137761
  const seedService = new SeedService();
137711
137762
  const generatedTablesGenerators = seedService.generatePossibleGenerators('sqlite', tables, relations, refinements, options);
137712
137763
  const preserveCyclicTablesData = relations.some((rel) => rel.isCyclic === true);
@@ -137715,159 +137766,43 @@ const seedSqlite = async (db, schema, options = {}, refinements) => {
137715
137766
  const updateDataInDb = filteredTablesGenerators.length === 0 ? false : true;
137716
137767
  await seedService.generateTablesValues(relations, filteredTablesGenerators, db, sqliteTables, { ...options, tablesValues, updateDataInDb, tablesUniqueNotNullColumn });
137717
137768
  };
137718
- const getSqliteInfo = (sqliteSchema, sqliteTables) => {
137719
- let tableConfig;
137720
- let dbToTsColumnNamesMap;
137721
- const dbToTsTableNamesMap = Object.fromEntries(Object.entries(sqliteTables).map(([key, value]) => [getTableName(value), key]));
137722
- const tables = [];
137723
- const relations = [];
137724
- const dbToTsColumnNamesMapGlobal = {};
137725
- const tableRelations = {};
137726
- const getDbToTsColumnNamesMap = (table) => {
137727
- let dbToTsColumnNamesMap = {};
137728
- const tableName = getTableName(table);
137729
- if (Object.hasOwn(dbToTsColumnNamesMapGlobal, tableName)) {
137730
- dbToTsColumnNamesMap = dbToTsColumnNamesMapGlobal[tableName];
137731
- return dbToTsColumnNamesMap;
137732
- }
137733
- const tableConfig = getTableConfig$5(table);
137734
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137735
- dbToTsColumnNamesMap[col.name] = tsCol;
137736
- }
137737
- dbToTsColumnNamesMapGlobal[tableName] = dbToTsColumnNamesMap;
137738
- return dbToTsColumnNamesMap;
137739
- };
137740
- const transformFromDrizzleRelation = (schema, getDbToTsColumnNamesMap, tableRelations) => {
137741
- const schemaConfig = extractTablesRelationalConfig(schema, createTableRelationsHelpers);
137742
- const relations = [];
137743
- for (const table of Object.values(schemaConfig.tables)) {
137744
- if (table.relations === undefined)
137745
- continue;
137746
- for (const drizzleRel of Object.values(table.relations)) {
137747
- if (!is(drizzleRel, One))
137748
- continue;
137749
- const tableConfig = getTableConfig$5(drizzleRel.sourceTable);
137750
- const tableDbName = tableConfig.name;
137751
- // TODO: tableNamesMap: have {public.customer: 'customer'} structure in sqlite
137752
- const tableTsName = schemaConfig.tableNamesMap[`public.${tableDbName}`] ?? tableDbName;
137753
- const dbToTsColumnNamesMap = getDbToTsColumnNamesMap(drizzleRel.sourceTable);
137754
- const columns = drizzleRel.config?.fields.map((field) => dbToTsColumnNamesMap[field.name])
137755
- ?? [];
137756
- const refTableConfig = getTableConfig$5(drizzleRel.referencedTable);
137757
- const refTableDbName = refTableConfig.name;
137758
- const refTableTsName = schemaConfig.tableNamesMap[`public.${refTableDbName}`]
137759
- ?? refTableDbName;
137760
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(drizzleRel.referencedTable);
137761
- const refColumns = drizzleRel.config?.references.map((ref) => dbToTsColumnNamesMapForRefTable[ref.name])
137762
- ?? [];
137763
- if (tableRelations[refTableTsName] === undefined) {
137764
- tableRelations[refTableTsName] = [];
137765
- }
137766
- const relation = {
137767
- table: tableTsName,
137768
- columns,
137769
- refTable: refTableTsName,
137770
- refColumns,
137771
- refTableRels: tableRelations[refTableTsName],
137772
- type: 'one',
137773
- };
137774
- // do not add duplicate relation
137775
- if (tableRelations[tableTsName]?.some((rel) => rel.table === relation.table
137776
- && rel.refTable === relation.refTable)) {
137777
- console.warn(`You are providing a one-to-many relation between the '${relation.refTable}' and '${relation.table}' tables,\n`
137778
- + `while the '${relation.table}' table object already has foreign key constraint in the schema referencing '${relation.refTable}' table.\n`
137779
- + `In this case, the foreign key constraint will be used.\n`);
137780
- continue;
137781
- }
137782
- relations.push(relation);
137783
- tableRelations[tableTsName].push(relation);
137769
+ const mapSqliteColumns = (tableConfig, dbToTsColumnNamesMap) => {
137770
+ const getTypeParams = (sqlType) => {
137771
+ // get type params and set only type
137772
+ const typeParams = {};
137773
+ if (sqlType.startsWith('decimal')) {
137774
+ const match = sqlType.match(/\((\d+), *(\d+)\)/);
137775
+ if (match) {
137776
+ typeParams['precision'] = Number(match[1]);
137777
+ typeParams['scale'] = Number(match[2]);
137784
137778
  }
137785
137779
  }
137786
- return relations;
137787
- };
137788
- for (const table of Object.values(sqliteTables)) {
137789
- tableConfig = getTableConfig$5(table);
137790
- dbToTsColumnNamesMap = {};
137791
- for (const [tsCol, col] of Object.entries(tableConfig.columns[0].table)) {
137792
- dbToTsColumnNamesMap[col.name] = tsCol;
137793
- }
137794
- const newRelations = tableConfig.foreignKeys.map((fk) => {
137795
- const table = dbToTsTableNamesMap[tableConfig.name];
137796
- const refTable = dbToTsTableNamesMap[getTableName(fk.reference().foreignTable)];
137797
- const dbToTsColumnNamesMapForRefTable = getDbToTsColumnNamesMap(fk.reference().foreignTable);
137798
- if (tableRelations[refTable] === undefined) {
137799
- tableRelations[refTable] = [];
137780
+ else if (sqlType.startsWith('char')
137781
+ || sqlType.startsWith('varchar')
137782
+ || sqlType.startsWith('text')) {
137783
+ const match = sqlType.match(/\((\d+)\)/);
137784
+ if (match) {
137785
+ typeParams['length'] = Number(match[1]);
137800
137786
  }
137801
- return {
137802
- table,
137803
- columns: fk
137804
- .reference()
137805
- .columns.map((col) => dbToTsColumnNamesMap[col.name]),
137806
- refTable,
137807
- refColumns: fk
137808
- .reference()
137809
- .foreignColumns.map((fCol) => dbToTsColumnNamesMapForRefTable[fCol.name]),
137810
- refTableRels: tableRelations[refTable],
137811
- };
137812
- });
137813
- relations.push(...newRelations);
137814
- if (tableRelations[dbToTsTableNamesMap[tableConfig.name]] === undefined) {
137815
- tableRelations[dbToTsTableNamesMap[tableConfig.name]] = [];
137816
137787
  }
137817
- tableRelations[dbToTsTableNamesMap[tableConfig.name]].push(...newRelations);
137818
- const getTypeParams = (sqlType) => {
137819
- // get type params and set only type
137820
- const typeParams = {};
137821
- if (sqlType.startsWith('decimal')) {
137822
- const match = sqlType.match(/\((\d+), *(\d+)\)/);
137823
- if (match) {
137824
- typeParams['precision'] = Number(match[1]);
137825
- typeParams['scale'] = Number(match[2]);
137826
- }
137827
- }
137828
- else if (sqlType.startsWith('char')
137829
- || sqlType.startsWith('varchar')
137830
- || sqlType.startsWith('text')) {
137831
- const match = sqlType.match(/\((\d+)\)/);
137832
- if (match) {
137833
- typeParams['length'] = Number(match[1]);
137834
- }
137835
- }
137836
- return typeParams;
137837
- };
137838
- tables.push({
137839
- name: dbToTsTableNamesMap[tableConfig.name],
137840
- columns: tableConfig.columns.map((column) => ({
137841
- name: dbToTsColumnNamesMap[column.name],
137842
- columnType: column.getSQLType(),
137843
- typeParams: getTypeParams(column.getSQLType()),
137844
- dataType: column.dataType,
137845
- hasDefault: column.hasDefault,
137846
- default: column.default,
137847
- enumValues: column.enumValues,
137848
- isUnique: column.isUnique,
137849
- notNull: column.notNull,
137850
- primary: column.primary,
137851
- })),
137852
- primaryKeys: tableConfig.columns
137853
- .filter((column) => column.primary)
137854
- .map((column) => dbToTsColumnNamesMap[column.name]),
137855
- });
137856
- }
137857
- const transformedDrizzleRelations = transformFromDrizzleRelation(sqliteSchema, getDbToTsColumnNamesMap, tableRelations);
137858
- relations.push(...transformedDrizzleRelations);
137859
- const isCyclicRelations = relations.map((relI) => {
137860
- const tableRel = tableRelations[relI.table].find((relJ) => relJ.refTable === relI.refTable);
137861
- if (isRelationCyclic(relI)) {
137862
- tableRel['isCyclic'] = true;
137863
- return { ...relI, isCyclic: true };
137864
- }
137865
- tableRel['isCyclic'] = false;
137866
- return { ...relI, isCyclic: false };
137867
- });
137868
- return { tables, relations: isCyclicRelations, tableRelations };
137788
+ return typeParams;
137789
+ };
137790
+ const mappedColumns = tableConfig.columns.map((column) => ({
137791
+ name: dbToTsColumnNamesMap[column.name],
137792
+ columnType: column.getSQLType(),
137793
+ typeParams: getTypeParams(column.getSQLType()),
137794
+ dataType: column.dataType.split(' ')[0],
137795
+ hasDefault: column.hasDefault,
137796
+ default: column.default,
137797
+ enumValues: column.enumValues,
137798
+ isUnique: column.isUnique,
137799
+ notNull: column.notNull,
137800
+ primary: column.primary,
137801
+ }));
137802
+ return mappedColumns;
137869
137803
  };
137870
137804
 
137805
+ /* eslint-disable drizzle-internal/require-entity-kind */
137871
137806
  class SeedPromise {
137872
137807
  db;
137873
137808
  schema;
@@ -137928,6 +137863,7 @@ async function seedForDrizzleStudio({ sqlDialect, drizzleStudioObject, drizzleSt
137928
137863
  name: tableName,
137929
137864
  columns,
137930
137865
  primaryKeys: drizzleStudioColumns.filter((col) => col.primaryKey === true).map((col) => col.name),
137866
+ uniqueConstraints: [], // TODO change later
137931
137867
  });
137932
137868
  }
137933
137869
  relations = drizzleStudioRelations.filter((rel) => rel.schema === schemaName && rel.refSchema === schemaName);