@rvoh/dream 1.4.2 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/dist/cjs/src/Dream.js +12 -16
  2. package/dist/cjs/src/bin/index.js +23 -7
  3. package/dist/cjs/src/cli/index.js +18 -3
  4. package/dist/cjs/src/db/ConnectedToDB.js +0 -8
  5. package/dist/cjs/src/db/DreamDbConnection.js +25 -36
  6. package/dist/cjs/src/db/helpers/dbTypesFilenameForConnection.js +6 -0
  7. package/dist/cjs/src/{bin/helpers/sync.js → db/helpers/syncDbTypesFiles.js} +8 -5
  8. package/dist/cjs/src/db/index.js +3 -2
  9. package/dist/cjs/src/db/migration-helpers/DreamMigrationHelpers.js +36 -0
  10. package/dist/cjs/src/decorators/field/sortable/helpers/setPosition.js +17 -2
  11. package/dist/cjs/src/dream/Query.js +9 -6
  12. package/dist/cjs/src/dream/QueryDriver/Base.js +111 -7
  13. package/dist/cjs/src/dream/QueryDriver/Kysely.js +213 -86
  14. package/dist/cjs/src/dream/QueryDriver/Postgres.js +162 -0
  15. package/dist/cjs/src/{helpers/db → dream/QueryDriver/helpers/kysely}/runMigration.js +22 -17
  16. package/dist/cjs/src/{helpers/db → dream/QueryDriver/helpers/pg}/createDb.js +5 -5
  17. package/dist/cjs/src/{helpers/db → dream/QueryDriver/helpers/pg}/dropDb.js +6 -6
  18. package/dist/cjs/src/{helpers/db → dream/QueryDriver/helpers/pg}/loadPgClient.js +5 -3
  19. package/dist/cjs/src/dream/internal/destroyDream.js +3 -10
  20. package/dist/cjs/src/dream/internal/saveDream.js +1 -1
  21. package/dist/cjs/src/dream/internal/similarity/SimilarityBuilder.js +9 -3
  22. package/dist/cjs/src/dream-app/index.js +47 -64
  23. package/dist/cjs/src/helpers/cli/SchemaBuilder.js +30 -42
  24. package/dist/cjs/src/helpers/cli/generateDream.js +2 -0
  25. package/dist/cjs/src/helpers/cli/generateDreamContent.js +5 -3
  26. package/dist/cjs/src/helpers/cli/generateFactoryContent.js +29 -0
  27. package/dist/cjs/src/helpers/cli/generateMigration.js +7 -5
  28. package/dist/cjs/src/helpers/cli/generateMigrationContent.js +48 -15
  29. package/dist/cjs/src/helpers/db/primaryKeyType.js +4 -22
  30. package/dist/cjs/src/helpers/sqlAttributes.js +4 -1
  31. package/dist/cjs/src/index.js +8 -2
  32. package/dist/esm/src/Dream.js +10 -14
  33. package/dist/esm/src/bin/index.js +23 -7
  34. package/dist/esm/src/cli/index.js +18 -3
  35. package/dist/esm/src/db/ConnectedToDB.js +0 -8
  36. package/dist/esm/src/db/DreamDbConnection.js +22 -34
  37. package/dist/esm/src/db/helpers/dbTypesFilenameForConnection.js +3 -0
  38. package/dist/esm/src/{bin/helpers/sync.js → db/helpers/syncDbTypesFiles.js} +7 -4
  39. package/dist/esm/src/db/index.js +3 -2
  40. package/dist/esm/src/db/migration-helpers/DreamMigrationHelpers.js +36 -0
  41. package/dist/esm/src/decorators/field/sortable/helpers/setPosition.js +16 -2
  42. package/dist/esm/src/dream/Query.js +9 -6
  43. package/dist/esm/src/dream/QueryDriver/Base.js +111 -7
  44. package/dist/esm/src/dream/QueryDriver/Kysely.js +215 -88
  45. package/dist/esm/src/dream/QueryDriver/Postgres.js +162 -0
  46. package/dist/esm/src/{helpers/db → dream/QueryDriver/helpers/kysely}/runMigration.js +16 -11
  47. package/dist/esm/src/{helpers/db → dream/QueryDriver/helpers/pg}/createDb.js +5 -5
  48. package/dist/esm/src/{helpers/db → dream/QueryDriver/helpers/pg}/dropDb.js +6 -6
  49. package/dist/esm/src/{helpers/db → dream/QueryDriver/helpers/pg}/loadPgClient.js +5 -3
  50. package/dist/esm/src/dream/internal/destroyDream.js +3 -10
  51. package/dist/esm/src/dream/internal/saveDream.js +1 -1
  52. package/dist/esm/src/dream/internal/similarity/SimilarityBuilder.js +9 -3
  53. package/dist/esm/src/dream-app/index.js +44 -61
  54. package/dist/esm/src/helpers/cli/SchemaBuilder.js +24 -36
  55. package/dist/esm/src/helpers/cli/generateDream.js +2 -0
  56. package/dist/esm/src/helpers/cli/generateDreamContent.js +5 -3
  57. package/dist/esm/src/helpers/cli/generateFactoryContent.js +29 -0
  58. package/dist/esm/src/helpers/cli/generateMigration.js +7 -5
  59. package/dist/esm/src/helpers/cli/generateMigrationContent.js +48 -15
  60. package/dist/esm/src/helpers/db/primaryKeyType.js +4 -22
  61. package/dist/esm/src/helpers/sqlAttributes.js +4 -1
  62. package/dist/esm/src/index.js +3 -0
  63. package/dist/types/src/Dream.d.ts +5 -3
  64. package/dist/types/src/bin/index.d.ts +3 -1
  65. package/dist/types/src/db/ConnectedToDB.d.ts +0 -2
  66. package/dist/types/src/db/DreamDbConnection.d.ts +7 -3
  67. package/dist/types/src/db/helpers/dbTypesFilenameForConnection.d.ts +1 -0
  68. package/dist/types/src/db/helpers/syncDbTypesFiles.d.ts +1 -0
  69. package/dist/types/src/db/index.d.ts +2 -1
  70. package/dist/types/src/db/migration-helpers/DreamMigrationHelpers.d.ts +36 -0
  71. package/dist/types/src/decorators/field/sortable/helpers/setPosition.d.ts +2 -0
  72. package/dist/types/src/dream/Query.d.ts +5 -20
  73. package/dist/types/src/dream/QueryDriver/Base.d.ts +74 -13
  74. package/dist/types/src/dream/QueryDriver/Kysely.d.ts +75 -9
  75. package/dist/types/src/dream/QueryDriver/Postgres.d.ts +32 -0
  76. package/dist/types/src/dream/QueryDriver/helpers/kysely/foreignKeyTypeFromPrimaryKey.d.ts +2 -0
  77. package/dist/types/src/dream/QueryDriver/helpers/kysely/runMigration.d.ts +9 -0
  78. package/dist/types/src/dream/QueryDriver/helpers/pg/createDb.d.ts +2 -0
  79. package/dist/types/src/dream/QueryDriver/helpers/pg/dropDb.d.ts +2 -0
  80. package/dist/types/src/dream/QueryDriver/helpers/pg/loadPgClient.d.ts +5 -0
  81. package/dist/types/src/dream/internal/destroyOptions.d.ts +3 -3
  82. package/dist/types/src/dream-app/index.d.ts +11 -6
  83. package/dist/types/src/helpers/cli/SchemaBuilder.d.ts +26 -0
  84. package/dist/types/src/helpers/cli/generateDream.d.ts +1 -0
  85. package/dist/types/src/helpers/cli/generateDreamContent.d.ts +2 -1
  86. package/dist/types/src/helpers/cli/generateMigration.d.ts +2 -1
  87. package/dist/types/src/helpers/cli/generateMigrationContent.d.ts +2 -1
  88. package/dist/types/src/helpers/db/primaryKeyType.d.ts +1 -1
  89. package/dist/types/src/index.d.ts +3 -0
  90. package/dist/types/src/types/dream.d.ts +4 -4
  91. package/dist/types/src/types/dream.ts +8 -9
  92. package/docs/assets/navigation.js +1 -1
  93. package/docs/assets/search.js +1 -1
  94. package/docs/classes/Benchmark.html +2 -2
  95. package/docs/classes/CalendarDate.html +2 -2
  96. package/docs/classes/CheckConstraintViolation.html +3 -3
  97. package/docs/classes/CliFileWriter.html +2 -2
  98. package/docs/classes/CreateOrFindByFailedToCreateAndFind.html +3 -3
  99. package/docs/classes/DataTypeColumnTypeMismatch.html +3 -3
  100. package/docs/classes/Decorators.html +19 -19
  101. package/docs/classes/Dream.html +117 -115
  102. package/docs/classes/DreamApp.html +8 -5
  103. package/docs/classes/DreamBin.html +2 -2
  104. package/docs/classes/DreamCLI.html +4 -4
  105. package/docs/classes/DreamImporter.html +2 -2
  106. package/docs/classes/DreamLogos.html +2 -2
  107. package/docs/classes/DreamMigrationHelpers.html +19 -7
  108. package/docs/classes/DreamSerializerBuilder.html +8 -8
  109. package/docs/classes/DreamTransaction.html +2 -2
  110. package/docs/classes/Encrypt.html +2 -2
  111. package/docs/classes/Env.html +2 -2
  112. package/docs/classes/GlobalNameNotSet.html +3 -3
  113. package/docs/classes/KyselyQueryDriver.html +163 -0
  114. package/docs/classes/NonLoadedAssociation.html +3 -3
  115. package/docs/classes/NotNullViolation.html +3 -3
  116. package/docs/classes/ObjectSerializerBuilder.html +8 -8
  117. package/docs/classes/PostgresQueryDriver.html +165 -0
  118. package/docs/classes/Query.html +59 -87
  119. package/docs/classes/QueryDriverBase.html +156 -0
  120. package/docs/classes/Range.html +2 -2
  121. package/docs/classes/RecordNotFound.html +3 -3
  122. package/docs/classes/ValidationError.html +3 -3
  123. package/docs/functions/DreamSerializer.html +1 -1
  124. package/docs/functions/ObjectSerializer.html +1 -1
  125. package/docs/functions/ReplicaSafe.html +1 -1
  126. package/docs/functions/STI.html +1 -1
  127. package/docs/functions/SoftDelete.html +1 -1
  128. package/docs/functions/camelize.html +1 -1
  129. package/docs/functions/capitalize.html +1 -1
  130. package/docs/functions/cloneDeepSafe.html +1 -1
  131. package/docs/functions/closeAllDbConnections.html +1 -1
  132. package/docs/functions/compact.html +1 -1
  133. package/docs/functions/dreamDbConnections.html +1 -1
  134. package/docs/functions/dreamPath.html +1 -1
  135. package/docs/functions/expandStiClasses.html +1 -1
  136. package/docs/functions/generateDream.html +1 -1
  137. package/docs/functions/globalClassNameFromFullyQualifiedModelName.html +1 -1
  138. package/docs/functions/groupBy.html +1 -1
  139. package/docs/functions/hyphenize.html +1 -1
  140. package/docs/functions/inferSerializerFromDreamOrViewModel.html +1 -1
  141. package/docs/functions/inferSerializersFromDreamClassOrViewModelClass.html +1 -1
  142. package/docs/functions/intersection.html +1 -1
  143. package/docs/functions/isDreamSerializer.html +1 -1
  144. package/docs/functions/isEmpty.html +1 -1
  145. package/docs/functions/loadRepl.html +1 -1
  146. package/docs/functions/lookupClassByGlobalName.html +1 -1
  147. package/docs/functions/normalizeUnicode.html +1 -1
  148. package/docs/functions/pascalize.html +1 -1
  149. package/docs/functions/pgErrorType.html +1 -1
  150. package/docs/functions/range-1.html +1 -1
  151. package/docs/functions/relativeDreamPath.html +1 -1
  152. package/docs/functions/round.html +1 -1
  153. package/docs/functions/serializerNameFromFullyQualifiedModelName.html +1 -1
  154. package/docs/functions/sharedPathPrefix.html +1 -1
  155. package/docs/functions/snakeify.html +1 -1
  156. package/docs/functions/sort.html +1 -1
  157. package/docs/functions/sortBy.html +1 -1
  158. package/docs/functions/sortObjectByKey.html +1 -1
  159. package/docs/functions/sortObjectByValue.html +1 -1
  160. package/docs/functions/standardizeFullyQualifiedModelName.html +1 -1
  161. package/docs/functions/uncapitalize.html +1 -1
  162. package/docs/functions/uniq.html +1 -1
  163. package/docs/functions/untypedDb.html +1 -1
  164. package/docs/functions/validateColumn.html +1 -1
  165. package/docs/functions/validateTable.html +1 -1
  166. package/docs/hierarchy.html +1 -0
  167. package/docs/interfaces/BelongsToStatement.html +2 -2
  168. package/docs/interfaces/DecoratorContext.html +2 -2
  169. package/docs/interfaces/DreamAppInitOptions.html +2 -2
  170. package/docs/interfaces/DreamAppOpts.html +2 -2
  171. package/docs/interfaces/EncryptOptions.html +2 -2
  172. package/docs/interfaces/InternalAnyTypedSerializerRendersMany.html +2 -2
  173. package/docs/interfaces/InternalAnyTypedSerializerRendersOne.html +2 -2
  174. package/docs/interfaces/OpenapiDescription.html +2 -2
  175. package/docs/interfaces/OpenapiSchemaProperties.html +1 -1
  176. package/docs/interfaces/OpenapiSchemaPropertiesShorthand.html +1 -1
  177. package/docs/interfaces/OpenapiTypeFieldObject.html +1 -1
  178. package/docs/interfaces/SerializerRendererOpts.html +2 -2
  179. package/docs/modules.html +3 -0
  180. package/docs/types/Camelized.html +1 -1
  181. package/docs/types/CommonOpenapiSchemaObjectFields.html +1 -1
  182. package/docs/types/DateTime.html +1 -1
  183. package/docs/types/DbConnectionType.html +1 -1
  184. package/docs/types/DbTypes.html +1 -1
  185. package/docs/types/DreamAppAllowedPackageManagersEnum.html +1 -1
  186. package/docs/types/DreamAssociationMetadata.html +1 -1
  187. package/docs/types/DreamAttributes.html +1 -1
  188. package/docs/types/DreamClassAssociationAndStatement.html +1 -1
  189. package/docs/types/DreamClassColumn.html +1 -1
  190. package/docs/types/DreamColumn.html +1 -1
  191. package/docs/types/DreamColumnNames.html +1 -1
  192. package/docs/types/DreamLogLevel.html +1 -1
  193. package/docs/types/DreamLogger.html +1 -1
  194. package/docs/types/DreamModelSerializerType.html +1 -1
  195. package/docs/types/DreamOrViewModelClassSerializerKey.html +1 -1
  196. package/docs/types/DreamOrViewModelSerializerKey.html +1 -1
  197. package/docs/types/DreamParamSafeAttributes.html +1 -1
  198. package/docs/types/DreamParamSafeColumnNames.html +1 -1
  199. package/docs/types/DreamSerializable.html +1 -1
  200. package/docs/types/DreamSerializableArray.html +1 -1
  201. package/docs/types/DreamSerializerKey.html +1 -1
  202. package/docs/types/DreamSerializers.html +1 -1
  203. package/docs/types/DreamVirtualColumns.html +1 -1
  204. package/docs/types/EncryptAlgorithm.html +1 -1
  205. package/docs/types/HasManyStatement.html +1 -1
  206. package/docs/types/HasOneStatement.html +1 -1
  207. package/docs/types/Hyphenized.html +1 -1
  208. package/docs/types/OpenapiAllTypes.html +1 -1
  209. package/docs/types/OpenapiFormats.html +1 -1
  210. package/docs/types/OpenapiNumberFormats.html +1 -1
  211. package/docs/types/OpenapiPrimitiveBaseTypes.html +1 -1
  212. package/docs/types/OpenapiPrimitiveTypes.html +1 -1
  213. package/docs/types/OpenapiSchemaArray.html +1 -1
  214. package/docs/types/OpenapiSchemaArrayShorthand.html +1 -1
  215. package/docs/types/OpenapiSchemaBase.html +1 -1
  216. package/docs/types/OpenapiSchemaBody.html +1 -1
  217. package/docs/types/OpenapiSchemaBodyShorthand.html +1 -1
  218. package/docs/types/OpenapiSchemaCommonFields.html +1 -1
  219. package/docs/types/OpenapiSchemaExpressionAllOf.html +1 -1
  220. package/docs/types/OpenapiSchemaExpressionAnyOf.html +1 -1
  221. package/docs/types/OpenapiSchemaExpressionOneOf.html +1 -1
  222. package/docs/types/OpenapiSchemaExpressionRef.html +1 -1
  223. package/docs/types/OpenapiSchemaExpressionRefSchemaShorthand.html +1 -1
  224. package/docs/types/OpenapiSchemaInteger.html +1 -1
  225. package/docs/types/OpenapiSchemaNull.html +1 -1
  226. package/docs/types/OpenapiSchemaNumber.html +1 -1
  227. package/docs/types/OpenapiSchemaObject.html +1 -1
  228. package/docs/types/OpenapiSchemaObjectAllOf.html +1 -1
  229. package/docs/types/OpenapiSchemaObjectAllOfShorthand.html +1 -1
  230. package/docs/types/OpenapiSchemaObjectAnyOf.html +1 -1
  231. package/docs/types/OpenapiSchemaObjectAnyOfShorthand.html +1 -1
  232. package/docs/types/OpenapiSchemaObjectBase.html +1 -1
  233. package/docs/types/OpenapiSchemaObjectBaseShorthand.html +1 -1
  234. package/docs/types/OpenapiSchemaObjectOneOf.html +1 -1
  235. package/docs/types/OpenapiSchemaObjectOneOfShorthand.html +1 -1
  236. package/docs/types/OpenapiSchemaObjectShorthand.html +1 -1
  237. package/docs/types/OpenapiSchemaPrimitiveGeneric.html +1 -1
  238. package/docs/types/OpenapiSchemaShorthandExpressionAllOf.html +1 -1
  239. package/docs/types/OpenapiSchemaShorthandExpressionAnyOf.html +1 -1
  240. package/docs/types/OpenapiSchemaShorthandExpressionOneOf.html +1 -1
  241. package/docs/types/OpenapiSchemaShorthandExpressionSerializableRef.html +1 -1
  242. package/docs/types/OpenapiSchemaShorthandExpressionSerializerRef.html +1 -1
  243. package/docs/types/OpenapiSchemaShorthandPrimitiveGeneric.html +1 -1
  244. package/docs/types/OpenapiSchemaString.html +1 -1
  245. package/docs/types/OpenapiShorthandAllTypes.html +1 -1
  246. package/docs/types/OpenapiShorthandPrimitiveBaseTypes.html +1 -1
  247. package/docs/types/OpenapiShorthandPrimitiveTypes.html +1 -1
  248. package/docs/types/OpenapiTypeField.html +1 -1
  249. package/docs/types/Pascalized.html +1 -1
  250. package/docs/types/RoundingPrecision.html +1 -1
  251. package/docs/types/SerializerCasing.html +1 -1
  252. package/docs/types/SimpleObjectSerializerType.html +1 -1
  253. package/docs/types/Snakeified.html +1 -1
  254. package/docs/types/UpdateableAssociationProperties.html +1 -1
  255. package/docs/types/UpdateableProperties.html +1 -1
  256. package/docs/types/ValidationType.html +1 -1
  257. package/docs/types/ViewModel.html +1 -1
  258. package/docs/types/ViewModelClass.html +1 -1
  259. package/docs/types/WhereStatementForDream.html +1 -1
  260. package/docs/types/WhereStatementForDreamClass.html +1 -1
  261. package/docs/variables/DateTime-1.html +1 -1
  262. package/docs/variables/DreamAppAllowedPackageManagersEnumValues.html +1 -1
  263. package/docs/variables/DreamConst.html +1 -1
  264. package/docs/variables/TRIGRAM_OPERATORS.html +1 -1
  265. package/docs/variables/openapiPrimitiveTypes-1.html +1 -1
  266. package/docs/variables/openapiShorthandPrimitiveTypes-1.html +1 -1
  267. package/docs/variables/ops.html +1 -1
  268. package/docs/variables/primaryKeyTypes.html +1 -1
  269. package/package.json +4 -3
  270. package/CHANGELOG.md +0 -100
  271. package/dist/cjs/src/helpers/db/truncateDb.js +0 -27
  272. package/dist/esm/src/helpers/db/truncateDb.js +0 -24
  273. package/dist/types/src/bin/helpers/sync.d.ts +0 -1
  274. package/dist/types/src/helpers/db/createDb.d.ts +0 -2
  275. package/dist/types/src/helpers/db/dropDb.d.ts +0 -2
  276. package/dist/types/src/helpers/db/foreignKeyTypeFromPrimaryKey.d.ts +0 -2
  277. package/dist/types/src/helpers/db/loadPgClient.d.ts +0 -4
  278. package/dist/types/src/helpers/db/runMigration.d.ts +0 -6
  279. package/dist/types/src/helpers/db/truncateDb.d.ts +0 -1
  280. /package/dist/cjs/src/{helpers/db → dream/QueryDriver/helpers/kysely}/foreignKeyTypeFromPrimaryKey.js +0 -0
  281. /package/dist/esm/src/{helpers/db → dream/QueryDriver/helpers/kysely}/foreignKeyTypeFromPrimaryKey.js +0 -0
@@ -1,15 +1,19 @@
1
1
  import { FileMigrationProvider, Migrator } from 'kysely';
2
2
  import * as fs from 'node:fs/promises';
3
3
  import * as path from 'node:path';
4
- import DreamCLI from '../../cli/index.js';
5
- import colorize from '../../cli/logger/loggable/colorize.js';
6
- import DreamDbConnection from '../../db/DreamDbConnection.js';
7
- import db from '../../db/index.js';
8
- import DreamApp from '../../dream-app/index.js';
9
- export default async function runMigration({ mode = 'migrate' } = {}) {
4
+ import colorize from '../../../../cli/logger/loggable/colorize.js';
5
+ import { closeAllConnectionsForConnectionName, closeAllDbConnections, } from '../../../../db/DreamDbConnection.js';
6
+ import db from '../../../../db/index.js';
7
+ import DreamApp from '../../../../dream-app/index.js';
8
+ import DreamCLI from '../../../../cli/index.js';
9
+ export default async function runMigration({ connectionName, mode = 'migrate', dialectProvider, }) {
10
10
  const dreamApp = DreamApp.getOrFail();
11
- const migrationFolder = path.join(dreamApp.projectRoot, dreamApp.paths.db, 'migrations');
12
- const kyselyDb = db('primary');
11
+ const migrationFolder = connectionName === 'default'
12
+ ? path.join(dreamApp.projectRoot, dreamApp.paths.db, 'migrations')
13
+ : path.join(dreamApp.projectRoot, dreamApp.paths.db, 'migrations', connectionName);
14
+ // Ensure the migration folder exists
15
+ await fs.mkdir(migrationFolder, { recursive: true });
16
+ const kyselyDb = db(connectionName, 'primary', dialectProvider);
13
17
  const migrator = new Migrator({
14
18
  db: kyselyDb,
15
19
  allowUnorderedMigrations: true,
@@ -25,7 +29,7 @@ export default async function runMigration({ mode = 'migrate' } = {}) {
25
29
  else if (mode === 'rollback') {
26
30
  await rollback(migrator);
27
31
  }
28
- await DreamDbConnection.dropAllConnections();
32
+ await closeAllConnectionsForConnectionName(connectionName);
29
33
  }
30
34
  async function migrate(migrator) {
31
35
  let nextMigrationRequiringNewTransaction = await findNextMigrationRequiringNewTransaction(migrator);
@@ -59,7 +63,8 @@ async function findNextMigrationRequiringNewTransaction(migrator, { ignore } = {
59
63
  const notYetRunMigrations = (await migrator.getMigrations()).filter(migrationInfo => !migrationInfo.executedAt && migrationInfo.name !== ignore);
60
64
  for (const notYetRunMigration of notYetRunMigrations) {
61
65
  const upAndDownString = notYetRunMigration.migration.up.toString() + (notYetRunMigration.migration.down || '').toString();
62
- const migrationRequiresNewTransaction = upAndDownString.includes('DreamMigrationHelpers.dropEnumValue');
66
+ const migrationRequiresNewTransaction = upAndDownString.includes('DreamMigrationHelpers.dropEnumValue') ||
67
+ upAndDownString.includes('DreamMigrationHelpers.newTransaction');
63
68
  if (migrationRequiresNewTransaction)
64
69
  return notYetRunMigration;
65
70
  }
@@ -71,7 +76,7 @@ async function rollback(migrator) {
71
76
  await handleError(error, 'rollback');
72
77
  }
73
78
  async function handleError(error, mode) {
74
- await DreamDbConnection.dropAllConnections();
79
+ await closeAllDbConnections();
75
80
  DreamApp.logWithLevel('error', `failed to ${migratedActionCurrentTense(mode)}`);
76
81
  DreamApp.logWithLevel('error', error);
77
82
  process.exit(1);
@@ -1,17 +1,17 @@
1
- import DreamApp from '../../dream-app/index.js';
2
- import EnvInternal from '../EnvInternal.js';
1
+ import DreamApp from '../../../../dream-app/index.js';
2
+ import EnvInternal from '../../../../helpers/EnvInternal.js';
3
3
  import loadPgClient from './loadPgClient.js';
4
- export default async function createDb(connection, dbName) {
4
+ export default async function createDb(connectionName, connectionType, dbName) {
5
5
  // this was only ever written to clear the db between tests or in development,
6
6
  // so there is no way to drop in production
7
7
  if (EnvInternal.isProduction)
8
8
  return false;
9
9
  const dreamApp = DreamApp.getOrFail();
10
- const dbConf = dreamApp.dbConnectionConfig(connection);
10
+ const dbConf = dreamApp.dbConnectionConfig(connectionName, connectionType);
11
11
  dbName ||= dbConf.name || null;
12
12
  if (!dbName)
13
13
  throw new Error('Must either pass a dbName to the create function, or else ensure that DB_NAME is set in the env');
14
- const client = await loadPgClient({ useSystemDb: true });
14
+ const client = await loadPgClient({ useSystemDb: true, connectionName });
15
15
  await client.query(`CREATE DATABASE ${dbName};`);
16
16
  await client.end();
17
17
  }
@@ -1,18 +1,18 @@
1
- import DreamCLI from '../../cli/index.js';
2
- import DreamApp from '../../dream-app/index.js';
3
- import EnvInternal from '../EnvInternal.js';
1
+ import DreamCLI from '../../../../cli/index.js';
2
+ import DreamApp from '../../../../dream-app/index.js';
3
+ import EnvInternal from '../../../../helpers/EnvInternal.js';
4
4
  import loadPgClient from './loadPgClient.js';
5
- export default async function dropDb(connection, dbName) {
5
+ export default async function dropDb(connectionName, connection, dbName) {
6
6
  // this was only ever written to clear the db between tests or in development,
7
7
  // so there is no way to drop in production
8
8
  if (EnvInternal.isProduction)
9
9
  return false;
10
10
  const dreamApp = DreamApp.getOrFail();
11
- const dbConf = dreamApp.dbConnectionConfig(connection);
11
+ const dbConf = dreamApp.dbConnectionConfig(connectionName, connection);
12
12
  dbName ||= dbConf.name || null;
13
13
  if (!dbName)
14
14
  throw new Error('Must either pass a dbName to the drop function, or else ensure that DB_NAME is set in the env');
15
- const client = await loadPgClient({ useSystemDb: true });
15
+ const client = await loadPgClient({ useSystemDb: true, connectionName });
16
16
  await maybeDropDuplicateDatabases(client, dbName);
17
17
  await client.query(`DROP DATABASE IF EXISTS ${dbName};`);
18
18
  }
@@ -7,10 +7,12 @@
7
7
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
8
8
  // @ts-ignore
9
9
  import pg from 'pg';
10
- import DreamApp from '../../dream-app/index.js';
11
- export default async function loadPgClient({ useSystemDb } = {}) {
10
+ import DreamApp from '../../../../dream-app/index.js';
11
+ export default async function loadPgClient({ connectionName, useSystemDb, }) {
12
12
  const dreamconf = DreamApp.getOrFail();
13
- const creds = dreamconf.dbCredentials.primary;
13
+ const creds = dreamconf.dbCredentialsFor(connectionName)?.primary;
14
+ if (!creds)
15
+ throw new Error(`failed to load db credentials for connection: ${connectionName}`);
14
16
  const client = new pg.Client({
15
17
  host: creds.host || 'localhost',
16
18
  port: creds.port,
@@ -1,6 +1,6 @@
1
+ import DreamApp from '../../dream-app/index.js';
1
2
  import destroyAssociatedRecords from './destroyAssociatedRecords.js';
2
3
  import runHooksFor from './runHooksFor.js';
3
- import softDeleteDream from './softDeleteDream.js';
4
4
  /**
5
5
  * @internal
6
6
  *
@@ -56,13 +56,6 @@ function shouldSoftDelete(dream, reallyDestroy) {
56
56
  * deleting by one of the beforeDestroy model hooks
57
57
  */
58
58
  async function maybeDestroyDream(dream, txn, reallyDestroy) {
59
- if (shouldSoftDelete(dream, reallyDestroy)) {
60
- await softDeleteDream(dream, txn);
61
- }
62
- else if (!dream['_preventDeletion']) {
63
- await txn.kyselyTransaction
64
- .deleteFrom(dream.table)
65
- .where(dream['_primaryKey'], '=', dream.primaryKeyValue())
66
- .execute();
67
- }
59
+ const dbDriverClass = DreamApp.getOrFail().dbConnectionQueryDriverClass(dream.connectionName);
60
+ await dbDriverClass.destroyDream(dream, txn, reallyDestroy);
68
61
  }
@@ -28,7 +28,7 @@ export default async function saveDream(dream, txn = null, { skipHooks = false }
28
28
  // BeforeSave/Update actions may clear all the data that we intended to save, leaving us with
29
29
  // an invalid update command. The Sortable decorator is an example of this.
30
30
  if (!alreadyPersisted || hasUnsavedData) {
31
- const data = await Query.dbDriverClass().saveDream(dream, txn);
31
+ const data = await Query.dbDriverClass(dream.connectionName || 'default').saveDream(dream, txn);
32
32
  dream['isPersisted'] = true;
33
33
  dream.setAttributes(data);
34
34
  }
@@ -8,6 +8,7 @@ import namespaceColumn from '../../../helpers/namespaceColumn.js';
8
8
  import { TRIGRAM_OPERATORS } from '../../constants.js';
9
9
  import similaritySelectSql from './similaritySelectSql.js';
10
10
  import similarityWhereSql from './similarityWhereSql.js';
11
+ import { getPostgresQueryDriver } from '../../../decorators/field/sortable/helpers/setPosition.js';
11
12
  export default class SimilarityBuilder extends ConnectedToDB {
12
13
  whereStatement;
13
14
  whereNotStatement;
@@ -214,8 +215,9 @@ export default class SimilarityBuilder extends ConnectedToDB {
214
215
  const schema = this.dreamClass.prototype.schema;
215
216
  const primaryKeyName = this.dreamClass.primaryKey;
216
217
  const { tableName, tableAlias, columnName } = similarityStatement;
218
+ const queryDriverClass = getPostgresQueryDriver(this.dreamInstance.connectionName);
217
219
  // eslint-disable-next-line @typescript-eslint/unbound-method
218
- const { ref } = this.dbFor('select').dynamic;
220
+ const { ref } = queryDriverClass.dbFor(this.dreamInstance.connectionName, this.dbConnectionType('select')).dynamic;
219
221
  const validatedTableAlias = validateTableAlias(tableAlias);
220
222
  const validatedPrimaryKey = validateColumn(schema, tableName, primaryKeyName);
221
223
  const nestedQuery = this.buildNestedSelectQuery({
@@ -245,7 +247,9 @@ export default class SimilarityBuilder extends ConnectedToDB {
245
247
  statementType,
246
248
  });
247
249
  const trigramSearchAlias = this.similaritySearchId(tableAlias, columnName);
248
- const selectQuery = this.dbFor('select')
250
+ const queryDriverClass = getPostgresQueryDriver(this.dreamInstance.connectionName);
251
+ const selectQuery = queryDriverClass
252
+ .dbFor(this.dreamInstance.connectionName, this.dbConnectionType('select'))
249
253
  .selectFrom(validatedTableAlias)
250
254
  .select(`${trigramSearchAlias}.trigram_search_id`)
251
255
  .innerJoin(nestedQuery.as(trigramSearchAlias), join => join.onRef(namespaceColumn(validatedPrimaryKey, validatedTableAlias), '=', namespaceColumn('trigram_search_id', trigramSearchAlias)));
@@ -257,7 +261,9 @@ export default class SimilarityBuilder extends ConnectedToDB {
257
261
  const { columnName, opsStatement, tableName } = similarityStatement;
258
262
  const validatedTable = validateTable(schema, tableName);
259
263
  const validatedPrimaryKey = validateColumn(schema, tableName, primaryKeyName);
260
- let nestedQuery = this.dbFor('select')
264
+ const queryDriverClass = getPostgresQueryDriver(this.dreamInstance.connectionName);
265
+ let nestedQuery = queryDriverClass
266
+ .dbFor(this.dreamInstance.connectionName, this.dbConnectionType('select'))
261
267
  .selectFrom(tableName)
262
268
  .select(eb => {
263
269
  const tableNameRef = eb.ref(validatedTable);
@@ -1,26 +1,16 @@
1
- // after building for esm, importing pg using the following:
2
- //
3
- // import * as pg from 'pg'
4
- //
5
- // will crash. This is difficult to discover, since it only happens
6
- // when being imported from our esm build.
7
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
8
- // @ts-ignore
9
- import pg from 'pg';
10
1
  import * as util from 'node:util';
11
- import db from '../db/index.js';
12
2
  import validateTable from '../db/validators/validateTable.js';
3
+ import Query from '../dream/Query.js';
13
4
  import Encrypt from '../encrypt/index.js';
14
5
  import DreamAppInitMissingCallToLoadModels from '../errors/dream-app/DreamAppInitMissingCallToLoadModels.js';
15
6
  import DreamAppInitMissingMissingProjectRoot from '../errors/dream-app/DreamAppInitMissingMissingProjectRoot.js';
16
7
  import CalendarDate from '../helpers/CalendarDate.js';
17
- import { findCitextArrayOid, findCorrespondingArrayOid, findEnumArrayOids, parsePostgresBigint, parsePostgresDate, parsePostgresDatetime, parsePostgresDecimal, } from '../helpers/customPgParsers.js';
18
8
  import { DateTime, Settings } from '../helpers/DateTime.js';
19
9
  import EnvInternal from '../helpers/EnvInternal.js';
20
10
  import { cacheDreamApp, getCachedDreamAppOrFail } from './cache.js';
21
11
  import importModels, { getModelsOrFail } from './helpers/importers/importModels.js';
22
12
  import importSerializers, { getSerializersOrFail, setCachedSerializers, } from './helpers/importers/importSerializers.js';
23
- const pgTypes = pg.types;
13
+ import PostgresQueryDriver from '../dream/QueryDriver/Postgres.js';
24
14
  // this needs to be done top-level to ensure proper configuration
25
15
  Settings.defaultZone = 'UTC';
26
16
  export default class DreamApp {
@@ -44,7 +34,7 @@ export default class DreamApp {
44
34
  setCachedSerializers({});
45
35
  cacheDreamApp(dreamApp);
46
36
  if (!EnvInternal.boolean('BYPASS_DB_CONNECTIONS_DURING_INIT'))
47
- await this.setDatabaseTypeParsers();
37
+ await this.setDatabaseTypeParsers(dreamApp);
48
38
  await deferCb?.(dreamApp);
49
39
  for (const plugin of dreamApp.plugins) {
50
40
  await plugin(dreamApp);
@@ -87,43 +77,10 @@ export default class DreamApp {
87
77
  *
88
78
  *
89
79
  */
90
- static async setDatabaseTypeParsers() {
91
- const kyselyDb = db('primary');
92
- pgTypes.setTypeParser(pgTypes.builtins.DATE, parsePostgresDate);
93
- pgTypes.setTypeParser(pgTypes.builtins.TIMESTAMP, parsePostgresDatetime);
94
- pgTypes.setTypeParser(pgTypes.builtins.TIMESTAMPTZ, parsePostgresDatetime);
95
- pgTypes.setTypeParser(pgTypes.builtins.NUMERIC, parsePostgresDecimal);
96
- pgTypes.setTypeParser(pgTypes.builtins.INT8, parsePostgresBigint);
97
- const textArrayOid = await findCorrespondingArrayOid(kyselyDb, pgTypes.builtins.TEXT);
98
- if (textArrayOid) {
99
- let oid;
100
- const textArrayParser = pgTypes.getTypeParser(textArrayOid);
101
- function transformPostgresArray(transformer) {
102
- return (value) => textArrayParser(value).map(str => transformer(str));
103
- }
104
- const enumArrayOids = await findEnumArrayOids(kyselyDb);
105
- enumArrayOids.forEach((enumArrayOid) => pgTypes.setTypeParser(enumArrayOid, textArrayParser));
106
- oid = await findCitextArrayOid(kyselyDb);
107
- if (oid)
108
- pgTypes.setTypeParser(oid, textArrayParser);
109
- oid = await findCorrespondingArrayOid(kyselyDb, pgTypes.builtins.UUID);
110
- if (oid)
111
- pgTypes.setTypeParser(oid, textArrayParser);
112
- oid = await findCorrespondingArrayOid(kyselyDb, pgTypes.builtins.DATE);
113
- if (oid)
114
- pgTypes.setTypeParser(oid, transformPostgresArray(parsePostgresDate));
115
- oid = await findCorrespondingArrayOid(kyselyDb, pgTypes.builtins.TIMESTAMP);
116
- if (oid)
117
- pgTypes.setTypeParser(oid, transformPostgresArray(parsePostgresDatetime));
118
- oid = await findCorrespondingArrayOid(kyselyDb, pgTypes.builtins.TIMESTAMPTZ);
119
- if (oid)
120
- pgTypes.setTypeParser(oid, transformPostgresArray(parsePostgresDatetime));
121
- oid = await findCorrespondingArrayOid(kyselyDb, pgTypes.builtins.NUMERIC);
122
- if (oid)
123
- pgTypes.setTypeParser(oid, transformPostgresArray(parsePostgresDecimal));
124
- oid = await findCorrespondingArrayOid(kyselyDb, pgTypes.builtins.INT8);
125
- if (oid)
126
- pgTypes.setTypeParser(oid, transformPostgresArray(parsePostgresBigint));
80
+ static async setDatabaseTypeParsers(dreamApp) {
81
+ for (const connectionName of Object.keys(dreamApp._dbCredentials)) {
82
+ const dbDriverClass = Query.dbDriverClass(connectionName);
83
+ await dbDriverClass.setDatabaseTypeParsers(connectionName);
127
84
  }
128
85
  }
129
86
  static checkKey(encryptionIdentifier, key, algorithm) {
@@ -165,10 +122,15 @@ Try setting it to something valid, like:
165
122
  get specialHooks() {
166
123
  return this._specialHooks;
167
124
  }
168
- _dbCredentials;
125
+ _dbCredentials = {};
169
126
  get dbCredentials() {
170
127
  return this._dbCredentials;
171
128
  }
129
+ dbCredentialsFor(connectionName) {
130
+ if (this._dbCredentials[connectionName])
131
+ return this._dbCredentials[connectionName];
132
+ return null;
133
+ }
172
134
  _encryption;
173
135
  get encryption() {
174
136
  return this._encryption;
@@ -224,7 +186,7 @@ Try setting it to something valid, like:
224
186
  loadedModels = false;
225
187
  constructor(opts) {
226
188
  if (opts?.db)
227
- this._dbCredentials = opts.db;
189
+ this._dbCredentials['default'] = opts.db;
228
190
  if (opts?.primaryKeyType)
229
191
  this._primaryKeyType = opts.primaryKeyType;
230
192
  if (opts?.projectRoot)
@@ -251,22 +213,38 @@ Try setting it to something valid, like:
251
213
  get serializers() {
252
214
  return getSerializersOrFail();
253
215
  }
254
- dbName(connection) {
255
- const conf = this.dbConnectionConfig(connection);
216
+ dbName(connectionName, connection) {
217
+ const conf = this.dbConnectionConfig(connectionName, connection);
256
218
  return this.parallelDatabasesEnabled ? `${conf.name}_${process.env.VITEST_POOL_ID}` : conf.name;
257
219
  }
258
- dbConnectionConfig(connection) {
259
- const conf = this.dbCredentials?.[connection] || this.dbCredentials?.primary;
260
- if (!conf)
220
+ dbConnectionConfig(connectionName, connection) {
221
+ const conf = this.dbCredentialsFor(connectionName)?.[connection] || this.dbCredentialsFor(connectionName)?.primary;
222
+ if (!conf) {
261
223
  throw new Error(`
262
224
  Cannot find a connection config given the following connection and node environment:
225
+ connectionName: ${connectionName}
263
226
  connection: ${connection}
264
227
  NODE_ENV: ${EnvInternal.nodeEnv}
265
228
  `);
229
+ }
266
230
  return conf;
267
231
  }
268
- get hasReplicaConfig() {
269
- return !!this.dbCredentials.replica;
232
+ dbConnectionQueryDriverClass(connectionName) {
233
+ const conf = this.dbCredentialsFor(connectionName);
234
+ if (!conf) {
235
+ throw new Error(`
236
+ Cannot find a db credentials for the given connectionName:
237
+ connectionName: ${connectionName}
238
+ NODE_ENV: ${EnvInternal.nodeEnv}
239
+ `);
240
+ }
241
+ return (conf.queryDriverClass) || (PostgresQueryDriver);
242
+ }
243
+ dbConnectionKeys() {
244
+ return Object.keys(this.dbCredentials);
245
+ }
246
+ hasReplicaConfig(connectionName) {
247
+ return !!this.dbCredentials[connectionName]?.replica;
270
248
  }
271
249
  get parallelDatabasesEnabled() {
272
250
  return (!!this.parallelTests &&
@@ -287,10 +265,15 @@ Try setting it to something valid, like:
287
265
  plugin(cb) {
288
266
  this._plugins.push(cb);
289
267
  }
290
- set(applyOption, options) {
268
+ set(applyOption, options, secondaryOptions) {
291
269
  switch (applyOption) {
292
270
  case 'db':
293
- this._dbCredentials = options;
271
+ if (typeof options === 'string') {
272
+ this._dbCredentials[options] = secondaryOptions;
273
+ }
274
+ else {
275
+ this._dbCredentials['default'] = options;
276
+ }
294
277
  break;
295
278
  case 'encryption':
296
279
  this._encryption = options;
@@ -1,11 +1,10 @@
1
- import { sql } from 'kysely';
2
1
  import * as fs from 'node:fs/promises';
3
2
  import * as path from 'node:path';
4
3
  import { CliFileWriter } from '../../cli/CliFileWriter.js';
5
- import { isPrimitiveDataType } from '../../db/dataTypes.js';
6
- import _db from '../../db/index.js';
4
+ import dbTypesFilenameForConnection from '../../db/helpers/dbTypesFilenameForConnection.js';
7
5
  import DreamApp from '../../dream-app/index.js';
8
6
  import { DreamConst } from '../../dream/constants.js';
7
+ import Query from '../../dream/Query.js';
9
8
  import FailedToIdentifyAssociation from '../../errors/schema-builder/FailedToIdentifyAssociation.js';
10
9
  import camelize from '../camelize.js';
11
10
  import compact from '../compact.js';
@@ -16,7 +15,11 @@ import sortBy from '../sortBy.js';
16
15
  import uniq from '../uniq.js';
17
16
  import autogeneratedFileDisclaimer from './autoGeneratedFileDisclaimer.js';
18
17
  export default class SchemaBuilder {
18
+ connectionName;
19
19
  hasForeignKeyError = false;
20
+ constructor(connectionName) {
21
+ this.connectionName = connectionName;
22
+ }
20
23
  async build() {
21
24
  const { schemaConstContent, passthroughColumns, allDefaultScopeNames } = await this.buildSchemaContent();
22
25
  const imports = await this.getSchemaImports(schemaConstContent);
@@ -37,19 +40,27 @@ ${importStr}
37
40
 
38
41
  ${schemaConstContent}
39
42
 
40
- export const globalSchema = {
43
+ export const connectionTypeConfig = {
41
44
  passthroughColumns: ${stringifyArray(uniq(passthroughColumns.sort()), { indent: 4 })},
42
45
  allDefaultScopeNames: ${stringifyArray(uniq(allDefaultScopeNames.sort()), { indent: 4 })},
43
46
  globalNames: {
44
47
  models: ${this.globalModelNames()},
45
- serializers: ${stringifyArray(Object.keys(dreamApp.serializers || {}).sort(), { indent: 6 })},
46
48
  },
47
49
  } as const
48
50
  `;
49
- // const newSchemaFileContents = `\
50
- // ${schemaConstContent}
51
- // `
52
- const schemaPath = path.join(dreamApp.projectRoot, dreamApp.paths.types, 'dream.ts');
51
+ const schemaPath = this.connectionName === 'default'
52
+ ? path.join(dreamApp.projectRoot, dreamApp.paths.types, 'dream.ts')
53
+ : path.join(dreamApp.projectRoot, dreamApp.paths.types, `dream.${camelize(this.connectionName)}.ts`);
54
+ await CliFileWriter.write(schemaPath, newSchemaFileContents);
55
+ }
56
+ static async buildGlobalTypes() {
57
+ const dreamApp = DreamApp.getOrFail();
58
+ const newSchemaFileContents = `\
59
+ export const globalTypeConfig = {
60
+ serializers: ${stringifyArray(Object.keys(dreamApp.serializers || {}).sort(), { indent: 6 })},
61
+ } as const
62
+ `;
63
+ const schemaPath = path.join(dreamApp.projectRoot, dreamApp.paths.types, 'dream.globals.ts');
53
64
  await CliFileWriter.write(schemaPath, newSchemaFileContents);
54
65
  }
55
66
  globalModelNames() {
@@ -57,6 +68,7 @@ export const globalSchema = {
57
68
  const models = dreamApp.models;
58
69
  return `{
59
70
  ${Object.keys(models)
71
+ .filter(key => models[key]?.prototype?.connectionName === this.connectionName)
60
72
  .map(key => `'${key}': '${models[key]?.prototype?.table}'`)
61
73
  .join(',\n ')}
62
74
  }`;
@@ -200,32 +212,8 @@ may need to update the table getter in the corresponding Dream.
200
212
  };
201
213
  }
202
214
  async getColumnData(tableName, associationData) {
203
- const db = _db('primary');
204
- const sqlQuery = sql `SELECT column_name, udt_name::regtype, is_nullable, data_type FROM information_schema.columns WHERE table_name = ${tableName}`;
205
- const columnToDBTypeMap = await sqlQuery.execute(db);
206
- const rows = columnToDBTypeMap.rows;
207
- const columnData = {};
208
- rows.forEach(row => {
209
- const isEnum = ['USER-DEFINED', 'ARRAY'].includes(row.dataType) && !isPrimitiveDataType(row.udtName);
210
- const isArray = ['ARRAY'].includes(row.dataType);
211
- const associationMetadata = associationData[row.columnName];
212
- columnData[camelize(row.columnName)] = {
213
- dbType: row.udtName,
214
- allowNull: row.isNullable === 'YES',
215
- enumType: isEnum ? this.enumType(row) : null,
216
- enumValues: isEnum ? `${this.enumType(row)}Values` : null,
217
- isArray,
218
- foreignKey: associationMetadata?.foreignKey || null,
219
- };
220
- });
221
- return Object.keys(columnData)
222
- .sort()
223
- .reduce((acc, key) => {
224
- if (columnData[key] === undefined)
225
- return acc;
226
- acc[key] = columnData[key];
227
- return acc;
228
- }, {});
215
+ const dbDriverClass = Query.dbDriverClass(this.connectionName);
216
+ return await dbDriverClass.getColumnData(this.connectionName, tableName, associationData);
229
217
  }
230
218
  enumType(row) {
231
219
  const enumName = pascalize(row.udtName.replace(/\[\]$/, ''));
@@ -385,7 +373,7 @@ may need to update the table getter in the corresponding Dream.
385
373
  }
386
374
  async loadDbSyncFile() {
387
375
  const dreamApp = DreamApp.getOrFail();
388
- const dbSyncPath = path.join(dreamApp.projectRoot, dreamApp.paths.types, 'db.ts');
376
+ const dbSyncPath = path.join(dreamApp.projectRoot, dreamApp.paths.types, dbTypesFilenameForConnection(this.connectionName));
389
377
  return (await fs.readFile(dbSyncPath)).toString();
390
378
  }
391
379
  }
@@ -19,6 +19,7 @@ export default async function generateDream({ fullyQualifiedModelName, columnsWi
19
19
  fullyQualifiedParentName,
20
20
  serializer: options.serializer,
21
21
  includeAdminSerializers: options.includeAdminSerializers,
22
+ connectionName: options.connectionName,
22
23
  }));
23
24
  }
24
25
  catch (error) {
@@ -43,6 +44,7 @@ export default async function generateDream({ fullyQualifiedModelName, columnsWi
43
44
  const isSTI = !!fullyQualifiedParentName;
44
45
  if (columnsWithTypes.length || !isSTI) {
45
46
  await generateMigration({
47
+ connectionName: options.connectionName,
46
48
  migrationName: `Create${fullyQualifiedModelName}`,
47
49
  columnsWithTypes,
48
50
  fullyQualifiedModelName,
@@ -6,7 +6,8 @@ import relativeDreamPath from '../path/relativeDreamPath.js';
6
6
  import snakeify from '../snakeify.js';
7
7
  import standardizeFullyQualifiedModelName from '../standardizeFullyQualifiedModelName.js';
8
8
  import uniq from '../uniq.js';
9
- export default function generateDreamContent({ fullyQualifiedModelName, columnsWithTypes, fullyQualifiedParentName, serializer, includeAdminSerializers, }) {
9
+ import pascalize from '../pascalize.js';
10
+ export default function generateDreamContent({ fullyQualifiedModelName, columnsWithTypes, fullyQualifiedParentName, serializer, includeAdminSerializers, connectionName = 'default', }) {
10
11
  fullyQualifiedModelName = standardizeFullyQualifiedModelName(fullyQualifiedModelName);
11
12
  const modelClassName = globalClassNameFromFullyQualifiedModelName(fullyQualifiedModelName);
12
13
  let parentModelClassName;
@@ -20,9 +21,10 @@ export default function generateDreamContent({ fullyQualifiedModelName, columnsW
20
21
  dreamImports.push('STI');
21
22
  }
22
23
  const idTypescriptType = `DreamColumn<${modelClassName}, 'id'>`;
24
+ const applicationModelName = connectionName === 'default' ? 'ApplicationModel' : `${pascalize(connectionName)}ApplicationModel`;
23
25
  const modelImportStatements = isSTI
24
26
  ? [importStatementForModel(fullyQualifiedModelName, fullyQualifiedParentName)]
25
- : [importStatementForModel(fullyQualifiedModelName, 'ApplicationModel')];
27
+ : [importStatementForModel(fullyQualifiedModelName, applicationModelName)];
26
28
  const attributeStatements = columnsWithTypes.map(attribute => {
27
29
  const [attributeName, attributeType, ...descriptors] = attribute.split(':');
28
30
  if (attributeName === undefined)
@@ -78,7 +80,7 @@ import { ${uniq(dreamImports).join(', ')} } from '@rvoh/dream'${uniq(modelImport
78
80
  const deco = new Decorators<typeof ${modelClassName}>()
79
81
 
80
82
  ${isSTI ? `\n@STI(${parentModelClassName})` : ''}
81
- export default class ${modelClassName} extends ${isSTI ? parentModelClassName : 'ApplicationModel'} {
83
+ export default class ${modelClassName} extends ${isSTI ? parentModelClassName : applicationModelName} {
82
84
  ${isSTI
83
85
  ? ''
84
86
  : ` public override get table() {
@@ -44,27 +44,56 @@ export default function generateFactoryContent({ fullyQualifiedModelName, column
44
44
  attributeDefaults.push(`${attributeVariable}: \`${fullyQualifiedModelName} ${attributeVariable} ${counterVariableIncremented ? '${counter}' : '${++counter}'}\`,`);
45
45
  counterVariableIncremented = true;
46
46
  break;
47
+ case 'string[]':
48
+ case 'text[]':
49
+ case 'citext[]':
50
+ attributeDefaults.push(`${attributeVariable}: [\`${fullyQualifiedModelName} ${attributeVariable} ${counterVariableIncremented ? '${counter}' : '${++counter}'}\`],`);
51
+ counterVariableIncremented = true;
52
+ break;
47
53
  case 'enum':
48
54
  attributeDefaults.push(`${attributeVariable}: '${(descriptors.at(-1) || '<tbd>').split(',')[0]}',`);
49
55
  break;
56
+ case 'enum[]':
57
+ attributeDefaults.push(`${attributeVariable}: ['${(descriptors.at(-1) || '<tbd>').split(',')[0]}'],`);
58
+ break;
50
59
  case 'integer':
51
60
  attributeDefaults.push(`${attributeVariable}: 1,`);
52
61
  break;
62
+ case 'integer[]':
63
+ attributeDefaults.push(`${attributeVariable}: [1],`);
64
+ break;
53
65
  case 'bigint':
54
66
  attributeDefaults.push(`${attributeVariable}: '11111111111111111',`);
55
67
  break;
68
+ case 'bigint[]':
69
+ attributeDefaults.push(`${attributeVariable}: ['11111111111111111'],`);
70
+ break;
56
71
  case 'decimal':
57
72
  attributeDefaults.push(`${attributeVariable}: 1.1,`);
58
73
  break;
74
+ case 'decimal[]':
75
+ attributeDefaults.push(`${attributeVariable}: [1.1],`);
76
+ break;
59
77
  case 'date':
60
78
  dreamImports.push('CalendarDate');
61
79
  attributeDefaults.push(`${attributeVariable}: CalendarDate.today(),`);
62
80
  break;
81
+ case 'date[]':
82
+ dreamImports.push('CalendarDate');
83
+ attributeDefaults.push(`${attributeVariable}: [CalendarDate.today()],`);
84
+ break;
63
85
  case 'datetime':
64
86
  dreamImports.push('DateTime');
65
87
  attributeDefaults.push(`${attributeVariable}: DateTime.now(),`);
66
88
  break;
89
+ case 'datetime[]':
90
+ dreamImports.push('DateTime');
91
+ attributeDefaults.push(`${attributeVariable}: [DateTime.now()],`);
92
+ break;
67
93
  default:
94
+ if (/\[\]$/.test(attributeType)) {
95
+ attributeDefaults.push(`${attributeVariable}: [],`);
96
+ }
68
97
  // noop
69
98
  }
70
99
  }
@@ -10,15 +10,17 @@ import dreamFileAndDirPaths from '../path/dreamFileAndDirPaths.js';
10
10
  import dreamPath from '../path/dreamPath.js';
11
11
  import snakeify from '../snakeify.js';
12
12
  import generateStiMigrationContent from './generateStiMigrationContent.js';
13
- export default async function generateMigration({ migrationName, columnsWithTypes, fullyQualifiedModelName, fullyQualifiedParentName, }) {
14
- const { relFilePath, absFilePath } = dreamFileAndDirPaths(path.join(dreamPath('db'), 'migrations'), `${migrationVersion()}-${hyphenize(migrationName).replace(/\//g, '-')}.ts`);
13
+ export default async function generateMigration({ migrationName, columnsWithTypes, connectionName, fullyQualifiedModelName, fullyQualifiedParentName, }) {
14
+ const { relFilePath, absFilePath } = connectionName === 'default'
15
+ ? dreamFileAndDirPaths(path.join(dreamPath('db'), 'migrations'), `${migrationVersion()}-${hyphenize(migrationName).replace(/\//g, '-')}.ts`)
16
+ : dreamFileAndDirPaths(path.join(dreamPath('db'), 'migrations', connectionName), `${migrationVersion()}-${hyphenize(migrationName).replace(/\//g, '-')}.ts`);
15
17
  const isSTI = !!fullyQualifiedParentName;
16
18
  let finalContent = '';
17
19
  if (isSTI) {
18
20
  finalContent = generateStiMigrationContent({
19
21
  table: snakeify(pluralize(pascalizePath(fullyQualifiedParentName))),
20
22
  columnsWithTypes,
21
- primaryKeyType: primaryKeyType(),
23
+ primaryKeyType: primaryKeyType(connectionName),
22
24
  stiChildClassName: pascalizePath(fullyQualifiedModelName),
23
25
  });
24
26
  }
@@ -26,7 +28,7 @@ export default async function generateMigration({ migrationName, columnsWithType
26
28
  finalContent = generateMigrationContent({
27
29
  table: snakeify(pluralize(pascalizePath(fullyQualifiedModelName))),
28
30
  columnsWithTypes,
29
- primaryKeyType: primaryKeyType(),
31
+ primaryKeyType: primaryKeyType(connectionName),
30
32
  });
31
33
  }
32
34
  else {
@@ -34,7 +36,7 @@ export default async function generateMigration({ migrationName, columnsWithType
34
36
  finalContent = generateMigrationContent({
35
37
  table: tableName ? pluralize(snakeify(tableName)) : '<table-name>',
36
38
  columnsWithTypes,
37
- primaryKeyType: primaryKeyType(),
39
+ primaryKeyType: primaryKeyType(connectionName),
38
40
  createOrAlter: 'alter',
39
41
  });
40
42
  }