drizzle-seed 0.4.0-f0d7da2 → 0.4.0

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