drizzle-seed 0.4.0-08bb2d5 → 0.4.0-08e4e66

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