@rvoh/dream 0.29.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 (1019) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +382 -0
  3. package/boilerplate/app/models/ApplicationModel.ts +14 -0
  4. package/boilerplate/app/serializers/.gitkeep +0 -0
  5. package/boilerplate/bin/esm.js +19 -0
  6. package/boilerplate/cli/helpers/initializeDreamApplication.ts +6 -0
  7. package/boilerplate/cli/index.ts +22 -0
  8. package/boilerplate/conf/inflections.ts +5 -0
  9. package/boilerplate/conf/loadEnv.ts +4 -0
  10. package/boilerplate/conf/repl.ts +11 -0
  11. package/boilerplate/eslint.config.js +21 -0
  12. package/boilerplate/package.json +42 -0
  13. package/boilerplate/tsconfig.build.json +41 -0
  14. package/boilerplate/tsconfig.json +12 -0
  15. package/boilerplate/types/db.ts +5 -0
  16. package/boilerplate/types/dream.ts +3 -0
  17. package/dist/cjs/boilerplate/package.json +42 -0
  18. package/dist/cjs/src/Dream.js +2984 -0
  19. package/dist/cjs/src/bin/helpers/sync.js +109 -0
  20. package/dist/cjs/src/bin/index.js +107 -0
  21. package/dist/cjs/src/cli/index.js +155 -0
  22. package/dist/cjs/src/db/ConnectedToDB.js +43 -0
  23. package/dist/cjs/src/db/ConnectionConfRetriever.js +22 -0
  24. package/dist/cjs/src/db/DreamDbConnection.js +77 -0
  25. package/dist/cjs/src/db/dataTypes.js +58 -0
  26. package/dist/cjs/src/db/errors.js +17 -0
  27. package/dist/cjs/src/db/index.js +12 -0
  28. package/dist/cjs/src/db/migration-helpers/DreamMigrationHelpers.js +193 -0
  29. package/dist/cjs/src/db/reflections.js +2 -0
  30. package/dist/cjs/src/db/types.js +2 -0
  31. package/dist/cjs/src/db/validators/validateColumn.js +11 -0
  32. package/dist/cjs/src/db/validators/validateTable.js +9 -0
  33. package/dist/cjs/src/db/validators/validateTableAlias.js +55 -0
  34. package/dist/cjs/src/decorators/DecoratorContextType.js +2 -0
  35. package/dist/cjs/src/decorators/Decorators.js +326 -0
  36. package/dist/cjs/src/decorators/Encrypted.js +83 -0
  37. package/dist/cjs/src/decorators/ReplicaSafe.js +12 -0
  38. package/dist/cjs/src/decorators/STI.js +35 -0
  39. package/dist/cjs/src/decorators/Scope.js +31 -0
  40. package/dist/cjs/src/decorators/SoftDelete.js +54 -0
  41. package/dist/cjs/src/decorators/Virtual.js +28 -0
  42. package/dist/cjs/src/decorators/associations/BelongsTo.js +77 -0
  43. package/dist/cjs/src/decorators/associations/HasMany.js +100 -0
  44. package/dist/cjs/src/decorators/associations/HasOne.js +96 -0
  45. package/dist/cjs/src/decorators/associations/associationToGetterSetterProp.js +6 -0
  46. package/dist/cjs/src/decorators/associations/shared.js +132 -0
  47. package/dist/cjs/src/decorators/helpers/freezeBaseClassArrayMap.js +10 -0
  48. package/dist/cjs/src/decorators/hooks/AfterCreate.js +26 -0
  49. package/dist/cjs/src/decorators/hooks/AfterCreateCommit.js +43 -0
  50. package/dist/cjs/src/decorators/hooks/AfterDestroy.js +25 -0
  51. package/dist/cjs/src/decorators/hooks/AfterDestroyCommit.js +40 -0
  52. package/dist/cjs/src/decorators/hooks/AfterSave.js +26 -0
  53. package/dist/cjs/src/decorators/hooks/AfterSaveCommit.js +43 -0
  54. package/dist/cjs/src/decorators/hooks/AfterUpdate.js +26 -0
  55. package/dist/cjs/src/decorators/hooks/AfterUpdateCommit.js +43 -0
  56. package/dist/cjs/src/decorators/hooks/BeforeCreate.js +26 -0
  57. package/dist/cjs/src/decorators/hooks/BeforeDestroy.js +25 -0
  58. package/dist/cjs/src/decorators/hooks/BeforeSave.js +26 -0
  59. package/dist/cjs/src/decorators/hooks/BeforeUpdate.js +26 -0
  60. package/dist/cjs/src/decorators/hooks/shared.js +23 -0
  61. package/dist/cjs/src/decorators/sortable/Sortable.js +160 -0
  62. package/dist/cjs/src/decorators/sortable/helpers/applySortableScopeToQuery.js +17 -0
  63. package/dist/cjs/src/decorators/sortable/helpers/clearCachedSortableValues.js +11 -0
  64. package/dist/cjs/src/decorators/sortable/helpers/decrementScopedRecordsGreaterThanPosition.js +26 -0
  65. package/dist/cjs/src/decorators/sortable/helpers/getColumnForSortableScope.js +18 -0
  66. package/dist/cjs/src/decorators/sortable/helpers/isSortedCorrectly.js +7 -0
  67. package/dist/cjs/src/decorators/sortable/helpers/positionIsInvalid.js +11 -0
  68. package/dist/cjs/src/decorators/sortable/helpers/resortAllRecords.js +38 -0
  69. package/dist/cjs/src/decorators/sortable/helpers/scopeArray.js +10 -0
  70. package/dist/cjs/src/decorators/sortable/helpers/setPosition.js +158 -0
  71. package/dist/cjs/src/decorators/sortable/helpers/sortableCacheKeyName.js +7 -0
  72. package/dist/cjs/src/decorators/sortable/helpers/sortableCacheValuesName.js +7 -0
  73. package/dist/cjs/src/decorators/sortable/helpers/sortableQueryExcludingDream.js +10 -0
  74. package/dist/cjs/src/decorators/sortable/hooks/afterSortableCreate.js +18 -0
  75. package/dist/cjs/src/decorators/sortable/hooks/afterSortableDestroy.js +14 -0
  76. package/dist/cjs/src/decorators/sortable/hooks/afterSortableUpdate.js +31 -0
  77. package/dist/cjs/src/decorators/sortable/hooks/beforeSortableSave.js +65 -0
  78. package/dist/cjs/src/decorators/validations/Validate.js +22 -0
  79. package/dist/cjs/src/decorators/validations/Validates.js +70 -0
  80. package/dist/cjs/src/decorators/validations/shared.js +2 -0
  81. package/dist/cjs/src/dream/DreamClassTransactionBuilder.js +592 -0
  82. package/dist/cjs/src/dream/DreamInstanceTransactionBuilder.js +480 -0
  83. package/dist/cjs/src/dream/DreamTransaction.js +26 -0
  84. package/dist/cjs/src/dream/LeftJoinLoadBuilder.js +77 -0
  85. package/dist/cjs/src/dream/LoadBuilder.js +68 -0
  86. package/dist/cjs/src/dream/Query.js +2618 -0
  87. package/dist/cjs/src/dream/internal/applyScopeBypassingSettingsToQuery.js +11 -0
  88. package/dist/cjs/src/dream/internal/associations/associationQuery.js +23 -0
  89. package/dist/cjs/src/dream/internal/associations/associationUpdateQuery.js +36 -0
  90. package/dist/cjs/src/dream/internal/associations/createAssociation.js +55 -0
  91. package/dist/cjs/src/dream/internal/associations/destroyAssociation.js +17 -0
  92. package/dist/cjs/src/dream/internal/associations/undestroyAssociation.js +12 -0
  93. package/dist/cjs/src/dream/internal/checkSingleValidation.js +52 -0
  94. package/dist/cjs/src/dream/internal/destroyAssociatedRecords.js +21 -0
  95. package/dist/cjs/src/dream/internal/destroyDream.js +72 -0
  96. package/dist/cjs/src/dream/internal/destroyOptions.js +32 -0
  97. package/dist/cjs/src/dream/internal/ensureSTITypeFieldIsSet.js +10 -0
  98. package/dist/cjs/src/dream/internal/executeDatabaseQuery.js +24 -0
  99. package/dist/cjs/src/dream/internal/extractAssociationMetadataFromAssociationName.js +8 -0
  100. package/dist/cjs/src/dream/internal/orderByDirection.js +15 -0
  101. package/dist/cjs/src/dream/internal/reload.js +21 -0
  102. package/dist/cjs/src/dream/internal/runHooksFor.js +99 -0
  103. package/dist/cjs/src/dream/internal/runValidations.js +16 -0
  104. package/dist/cjs/src/dream/internal/safelyRunCommitHooks.js +15 -0
  105. package/dist/cjs/src/dream/internal/saveDream.js +67 -0
  106. package/dist/cjs/src/dream/internal/scopeHelpers.js +13 -0
  107. package/dist/cjs/src/dream/internal/shouldBypassDefaultScope.js +12 -0
  108. package/dist/cjs/src/dream/internal/similarity/SimilarityBuilder.js +331 -0
  109. package/dist/cjs/src/dream/internal/similarity/similaritySelectSql.js +21 -0
  110. package/dist/cjs/src/dream/internal/similarity/similarityWhereSql.js +21 -0
  111. package/dist/cjs/src/dream/internal/softDeleteDream.js +22 -0
  112. package/dist/cjs/src/dream/internal/sqlResultToDreamInstance.js +38 -0
  113. package/dist/cjs/src/dream/internal/undestroyDream.js +90 -0
  114. package/dist/cjs/src/dream/types.js +98 -0
  115. package/dist/cjs/src/dream-application/cache.js +13 -0
  116. package/dist/cjs/src/dream-application/helpers/DreamImporter.js +52 -0
  117. package/dist/cjs/src/dream-application/helpers/globalModelKeyFromPath.js +10 -0
  118. package/dist/cjs/src/dream-application/helpers/globalSerializerKeyFromPath.js +17 -0
  119. package/dist/cjs/src/dream-application/helpers/globalServiceKeyFromPath.js +11 -0
  120. package/dist/cjs/src/dream-application/helpers/importers/importModels.js +81 -0
  121. package/dist/cjs/src/dream-application/helpers/importers/importSerializers.js +63 -0
  122. package/dist/cjs/src/dream-application/helpers/importers/importServices.js +43 -0
  123. package/dist/cjs/src/dream-application/helpers/lookupClassByGlobalName.js +17 -0
  124. package/dist/cjs/src/dream-application/helpers/lookupModelByGlobalName.js +13 -0
  125. package/dist/cjs/src/dream-application/helpers/lookupModelByGlobalNameOrNames.js +10 -0
  126. package/dist/cjs/src/dream-application/index.js +284 -0
  127. package/dist/cjs/src/encrypt/InternalEncrypt.js +32 -0
  128. package/dist/cjs/src/encrypt/algorithms/aes-gcm/decryptAESGCM.js +26 -0
  129. package/dist/cjs/src/encrypt/algorithms/aes-gcm/encryptAESGCM.js +12 -0
  130. package/dist/cjs/src/encrypt/algorithms/aes-gcm/generateKeyAESGCM.js +7 -0
  131. package/dist/cjs/src/encrypt/algorithms/aes-gcm/validateKeyAESGCM.js +11 -0
  132. package/dist/cjs/src/encrypt/index.js +95 -0
  133. package/dist/cjs/src/errors/AttemptingToMarshalInvalidArrayType.js +20 -0
  134. package/dist/cjs/src/errors/CannotCallUndestroyOnANonSoftDeleteModel.js +21 -0
  135. package/dist/cjs/src/errors/CannotDefineAssociationWithBothDependentAndPassthrough.js +19 -0
  136. package/dist/cjs/src/errors/CannotDefineAssociationWithBothDependentAndRequiredOnClause.js +19 -0
  137. package/dist/cjs/src/errors/CannotNegateSimilarityClause.js +22 -0
  138. package/dist/cjs/src/errors/CannotPassAdditionalFieldsToPluckEachAfterCallback.js +22 -0
  139. package/dist/cjs/src/errors/CannotPassUndefinedAsAValueToAWhereClause.js +20 -0
  140. package/dist/cjs/src/errors/CannotReloadUnsavedDream.js +16 -0
  141. package/dist/cjs/src/errors/ConstructorOnlyForInternalUse.js +9 -0
  142. package/dist/cjs/src/errors/CreateOrFindByFailedToCreateAndFind.js +18 -0
  143. package/dist/cjs/src/errors/DoNotSetEncryptedFieldsDirectly.js +23 -0
  144. package/dist/cjs/src/errors/InvalidColumnName.js +19 -0
  145. package/dist/cjs/src/errors/InvalidDecimalFieldPassedToGenerator.js +19 -0
  146. package/dist/cjs/src/errors/InvalidTableAlias.js +30 -0
  147. package/dist/cjs/src/errors/InvalidTableName.js +23 -0
  148. package/dist/cjs/src/errors/LeftJoinPreloadIncompatibleWithFindEach.js +12 -0
  149. package/dist/cjs/src/errors/MissingDB.js +10 -0
  150. package/dist/cjs/src/errors/MissingDeletedAtFieldForSoftDelete.js +24 -0
  151. package/dist/cjs/src/errors/MissingRequiredCallbackFunctionToPluckEach.js +22 -0
  152. package/dist/cjs/src/errors/MissingSerializersDefinition.js +26 -0
  153. package/dist/cjs/src/errors/MissingTable.js +27 -0
  154. package/dist/cjs/src/errors/NoUpdateAllOnJoins.js +13 -0
  155. package/dist/cjs/src/errors/NoUpdateOnAssociationQuery.js +10 -0
  156. package/dist/cjs/src/errors/NonBelongsToAssociationProvidedAsSortableDecoratorScope.js +23 -0
  157. package/dist/cjs/src/errors/NonExistentScopeProvidedToResort.js +23 -0
  158. package/dist/cjs/src/errors/PrototypePollutingAssignment.js +13 -0
  159. package/dist/cjs/src/errors/RecordNotFound.js +15 -0
  160. package/dist/cjs/src/errors/SortableDecoratorRequiresColumnOrBelongsToAssociation.js +26 -0
  161. package/dist/cjs/src/errors/ValidationError.js +19 -0
  162. package/dist/cjs/src/errors/associations/CanOnlyPassBelongsToModelParam.js +20 -0
  163. package/dist/cjs/src/errors/associations/CannotAssociateThroughPolymorphic.js +19 -0
  164. package/dist/cjs/src/errors/associations/CannotCreateAssociationWithThroughContext.js +19 -0
  165. package/dist/cjs/src/errors/associations/CannotJoinPolymorphicBelongsToError.js +27 -0
  166. package/dist/cjs/src/errors/associations/CannotPassNullOrUndefinedToRequiredBelongsTo.js +19 -0
  167. package/dist/cjs/src/errors/associations/InvalidComputedForeignKey.js +64 -0
  168. package/dist/cjs/src/errors/associations/JoinAttemptedOnMissingAssociation.js +27 -0
  169. package/dist/cjs/src/errors/associations/MissingRequiredAssociationOnClause.js +19 -0
  170. package/dist/cjs/src/errors/associations/MissingRequiredPassthroughForAssociationOnClause.js +16 -0
  171. package/dist/cjs/src/errors/associations/MissingThroughAssociation.js +27 -0
  172. package/dist/cjs/src/errors/associations/MissingThroughAssociationSource.js +42 -0
  173. package/dist/cjs/src/errors/associations/NonLoadedAssociation.js +18 -0
  174. package/dist/cjs/src/errors/dream-application/DreamApplicationInitMissingCallToLoadModels.js +18 -0
  175. package/dist/cjs/src/errors/dream-application/DreamApplicationInitMissingMissingProjectRoot.js +19 -0
  176. package/dist/cjs/src/errors/dream-application/GlobalNameNotSet.js +14 -0
  177. package/dist/cjs/src/errors/dream-application/SerializerNameConflict.js +15 -0
  178. package/dist/cjs/src/errors/encrypt/MissingColumnEncryptionOpts.js +27 -0
  179. package/dist/cjs/src/errors/encrypt/MissingEncryptionKey.js +12 -0
  180. package/dist/cjs/src/errors/environment/MissingRequiredEnvironmentVariable.js +13 -0
  181. package/dist/cjs/src/errors/ops/AnyRequiresArrayColumn.js +18 -0
  182. package/dist/cjs/src/errors/ops/ScoreMustBeANormalNumber.js +17 -0
  183. package/dist/cjs/src/errors/schema-builder/FailedToIdentifyAssociation.js +80 -0
  184. package/dist/cjs/src/errors/serializers/FailedToRenderThroughAssociationForSerializer.js +17 -0
  185. package/dist/cjs/src/errors/sortable/CannotCallSortableOnSTIChild.js +18 -0
  186. package/dist/cjs/src/errors/sti/STIChildMissing.js +23 -0
  187. package/dist/cjs/src/errors/sti/StiChildCannotDefineNewAssociations.js +20 -0
  188. package/dist/cjs/src/errors/sti/StiChildIncompatibleWithReplicaSafeDecorator.js +17 -0
  189. package/dist/cjs/src/errors/sti/StiChildIncompatibleWithSoftDeleteDecorator.js +17 -0
  190. package/dist/cjs/src/global-cli/dream.js +46 -0
  191. package/dist/cjs/src/global-cli/file-builders/DreamtsBuilder.js +69 -0
  192. package/dist/cjs/src/global-cli/file-builders/EnvBuilder.js +27 -0
  193. package/dist/cjs/src/global-cli/file-builders/EslintConfBuilder.js +29 -0
  194. package/dist/cjs/src/global-cli/file-builders/PackagejsonBuilder.js +9 -0
  195. package/dist/cjs/src/global-cli/helpers/argAndValue.js +15 -0
  196. package/dist/cjs/src/global-cli/helpers/autogeneratedFileMessage.js +71 -0
  197. package/dist/cjs/src/global-cli/helpers/buildNewDreamApp.js +63 -0
  198. package/dist/cjs/src/global-cli/helpers/copyRecursive.js +20 -0
  199. package/dist/cjs/src/global-cli/helpers/filterObjectByKey.js +23 -0
  200. package/dist/cjs/src/global-cli/helpers/generateEncryptionKey.js +26 -0
  201. package/dist/cjs/src/global-cli/helpers/globalCliSnakeify.js +1 -0
  202. package/dist/cjs/src/global-cli/helpers/initDreamAppIntoExistingProject.js +85 -0
  203. package/dist/cjs/src/global-cli/helpers/log.js +28 -0
  204. package/dist/cjs/src/global-cli/helpers/logo.js +81 -0
  205. package/dist/cjs/src/global-cli/helpers/primaryKeyTypes.js +13 -0
  206. package/dist/cjs/src/global-cli/helpers/prompt.js +33 -0
  207. package/dist/cjs/src/global-cli/helpers/select.js +113 -0
  208. package/dist/cjs/src/global-cli/helpers/sleep.js +10 -0
  209. package/dist/cjs/src/global-cli/helpers/sspawn.js +21 -0
  210. package/dist/cjs/src/global-cli/helpers/welcomeMessage.js +41 -0
  211. package/dist/cjs/src/global-cli/init.js +56 -0
  212. package/dist/cjs/src/global-cli/new.js +10 -0
  213. package/dist/cjs/src/helpers/CalendarDate.js +172 -0
  214. package/dist/cjs/src/helpers/Env.js +78 -0
  215. package/dist/cjs/src/helpers/EnvInternal.js +5 -0
  216. package/dist/cjs/src/helpers/allNestedObjectKeys.js +12 -0
  217. package/dist/cjs/src/helpers/benchmark.js +18 -0
  218. package/dist/cjs/src/helpers/camelize.js +15 -0
  219. package/dist/cjs/src/helpers/capitalize.js +6 -0
  220. package/dist/cjs/src/helpers/cli/SchemaBuilder.js +378 -0
  221. package/dist/cjs/src/helpers/cli/generateDream.js +48 -0
  222. package/dist/cjs/src/helpers/cli/generateDreamContent.js +107 -0
  223. package/dist/cjs/src/helpers/cli/generateFactory.js +26 -0
  224. package/dist/cjs/src/helpers/cli/generateFactoryContent.js +58 -0
  225. package/dist/cjs/src/helpers/cli/generateMigration.js +56 -0
  226. package/dist/cjs/src/helpers/cli/generateMigrationContent.js +196 -0
  227. package/dist/cjs/src/helpers/cli/generateSerializer.js +26 -0
  228. package/dist/cjs/src/helpers/cli/generateSerializerContent.js +130 -0
  229. package/dist/cjs/src/helpers/cli/generateStiMigrationContent.js +7 -0
  230. package/dist/cjs/src/helpers/cli/generateUnitSpec.js +26 -0
  231. package/dist/cjs/src/helpers/cli/generateUnitSpecContent.js +10 -0
  232. package/dist/cjs/src/helpers/cloneDeepSafe.js +69 -0
  233. package/dist/cjs/src/helpers/compact.js +14 -0
  234. package/dist/cjs/src/helpers/customPgParsers.js +39 -0
  235. package/dist/cjs/src/helpers/db/cachedTypeForAttribute.js +6 -0
  236. package/dist/cjs/src/helpers/db/createDb.js +20 -0
  237. package/dist/cjs/src/helpers/db/dropDb.js +36 -0
  238. package/dist/cjs/src/helpers/db/foreignKeyTypeFromPrimaryKey.js +11 -0
  239. package/dist/cjs/src/helpers/db/loadPgClient.js +20 -0
  240. package/dist/cjs/src/helpers/db/primaryKeyType.js +23 -0
  241. package/dist/cjs/src/helpers/db/runMigration.js +97 -0
  242. package/dist/cjs/src/helpers/db/truncateDb.js +27 -0
  243. package/dist/cjs/src/helpers/db/types/isDatabaseArrayColumn.js +6 -0
  244. package/dist/cjs/src/helpers/db/types/isDateColumn.js +6 -0
  245. package/dist/cjs/src/helpers/db/types/isDateTimeColumn.js +6 -0
  246. package/dist/cjs/src/helpers/db/types/isJsonColumn.js +6 -0
  247. package/dist/cjs/src/helpers/debug.js +11 -0
  248. package/dist/cjs/src/helpers/dreamOrPsychicCoreDevelopment.js +10 -0
  249. package/dist/cjs/src/helpers/filterObjectByKey.js +14 -0
  250. package/dist/cjs/src/helpers/getFiles.js +20 -0
  251. package/dist/cjs/src/helpers/globalClassNameFromFullyQualifiedModelName.js +7 -0
  252. package/dist/cjs/src/helpers/hyphenize.js +11 -0
  253. package/dist/cjs/src/helpers/inferSerializerFromDreamOrViewModel.js +16 -0
  254. package/dist/cjs/src/helpers/isEmpty.js +8 -0
  255. package/dist/cjs/src/helpers/loadEnv.js +37 -0
  256. package/dist/cjs/src/helpers/loadRepl.js +25 -0
  257. package/dist/cjs/src/helpers/migrationVersion.js +6 -0
  258. package/dist/cjs/src/helpers/namespaceColumn.js +8 -0
  259. package/dist/cjs/src/helpers/objectPathsToArrays.js +19 -0
  260. package/dist/cjs/src/helpers/pascalize.js +12 -0
  261. package/dist/cjs/src/helpers/pascalizePath.js +10 -0
  262. package/dist/cjs/src/helpers/path/dreamFileAndDirPaths.js +16 -0
  263. package/dist/cjs/src/helpers/path/dreamPath.js +25 -0
  264. package/dist/cjs/src/helpers/path/relativeDreamPath.js +50 -0
  265. package/dist/cjs/src/helpers/path/sharedPathPrefix.js +14 -0
  266. package/dist/cjs/src/helpers/propertyNameFromFullyQualifiedModelName.js +8 -0
  267. package/dist/cjs/src/helpers/protectAgainstPollutingAssignment.js +14 -0
  268. package/dist/cjs/src/helpers/range.js +20 -0
  269. package/dist/cjs/src/helpers/round.js +7 -0
  270. package/dist/cjs/src/helpers/serializerNameFromFullyQualifiedModelName.js +13 -0
  271. package/dist/cjs/src/helpers/snakeify.js +14 -0
  272. package/dist/cjs/src/helpers/sortBy.js +31 -0
  273. package/dist/cjs/src/helpers/sqlAttributes.js +28 -0
  274. package/dist/cjs/src/helpers/sspawn.js +21 -0
  275. package/dist/cjs/src/helpers/standardizeFullyQualifiedModelName.js +10 -0
  276. package/dist/cjs/src/helpers/stringCasing.js +34 -0
  277. package/dist/cjs/src/helpers/typechecks.js +16 -0
  278. package/dist/cjs/src/helpers/typeutils.js +2 -0
  279. package/dist/cjs/src/helpers/uncapitalize.js +6 -0
  280. package/dist/cjs/src/helpers/uniq.js +21 -0
  281. package/dist/cjs/src/index.js +154 -0
  282. package/dist/cjs/src/openapi/types.js +26 -0
  283. package/dist/cjs/src/ops/curried-ops-statement.js +12 -0
  284. package/dist/cjs/src/ops/index.js +42 -0
  285. package/dist/cjs/src/ops/ops-statement.js +38 -0
  286. package/dist/cjs/src/serializer/decorators/associations/RendersMany.js +84 -0
  287. package/dist/cjs/src/serializer/decorators/associations/RendersOne.js +87 -0
  288. package/dist/cjs/src/serializer/decorators/associations/shared.js +10 -0
  289. package/dist/cjs/src/serializer/decorators/attribute.js +161 -0
  290. package/dist/cjs/src/serializer/decorators/helpers/dreamAttributeOpenapiShape.js +78 -0
  291. package/dist/cjs/src/serializer/decorators/helpers/hasSerializersGetter.js +11 -0
  292. package/dist/cjs/src/serializer/decorators/helpers/maybeSerializableToDreamSerializerCallbackFunction.js +20 -0
  293. package/dist/cjs/src/serializer/index.js +271 -0
  294. package/dist/esm/boilerplate/package.json +42 -0
  295. package/dist/esm/src/Dream.js +2981 -0
  296. package/dist/esm/src/bin/helpers/sync.js +106 -0
  297. package/dist/esm/src/bin/index.js +104 -0
  298. package/dist/esm/src/cli/index.js +152 -0
  299. package/dist/esm/src/db/ConnectedToDB.js +40 -0
  300. package/dist/esm/src/db/ConnectionConfRetriever.js +19 -0
  301. package/dist/esm/src/db/DreamDbConnection.js +72 -0
  302. package/dist/esm/src/db/dataTypes.js +53 -0
  303. package/dist/esm/src/db/errors.js +13 -0
  304. package/dist/esm/src/db/index.js +9 -0
  305. package/dist/esm/src/db/migration-helpers/DreamMigrationHelpers.js +190 -0
  306. package/dist/esm/src/db/reflections.js +1 -0
  307. package/dist/esm/src/db/types.js +1 -0
  308. package/dist/esm/src/db/validators/validateColumn.js +8 -0
  309. package/dist/esm/src/db/validators/validateTable.js +6 -0
  310. package/dist/esm/src/db/validators/validateTableAlias.js +52 -0
  311. package/dist/esm/src/decorators/DecoratorContextType.js +1 -0
  312. package/dist/esm/src/decorators/Decorators.js +323 -0
  313. package/dist/esm/src/decorators/Encrypted.js +80 -0
  314. package/dist/esm/src/decorators/ReplicaSafe.js +9 -0
  315. package/dist/esm/src/decorators/STI.js +31 -0
  316. package/dist/esm/src/decorators/Scope.js +27 -0
  317. package/dist/esm/src/decorators/SoftDelete.js +50 -0
  318. package/dist/esm/src/decorators/Virtual.js +25 -0
  319. package/dist/esm/src/decorators/associations/BelongsTo.js +74 -0
  320. package/dist/esm/src/decorators/associations/HasMany.js +97 -0
  321. package/dist/esm/src/decorators/associations/HasOne.js +93 -0
  322. package/dist/esm/src/decorators/associations/associationToGetterSetterProp.js +3 -0
  323. package/dist/esm/src/decorators/associations/shared.js +123 -0
  324. package/dist/esm/src/decorators/helpers/freezeBaseClassArrayMap.js +7 -0
  325. package/dist/esm/src/decorators/hooks/AfterCreate.js +22 -0
  326. package/dist/esm/src/decorators/hooks/AfterCreateCommit.js +39 -0
  327. package/dist/esm/src/decorators/hooks/AfterDestroy.js +21 -0
  328. package/dist/esm/src/decorators/hooks/AfterDestroyCommit.js +36 -0
  329. package/dist/esm/src/decorators/hooks/AfterSave.js +22 -0
  330. package/dist/esm/src/decorators/hooks/AfterSaveCommit.js +39 -0
  331. package/dist/esm/src/decorators/hooks/AfterUpdate.js +22 -0
  332. package/dist/esm/src/decorators/hooks/AfterUpdateCommit.js +39 -0
  333. package/dist/esm/src/decorators/hooks/BeforeCreate.js +22 -0
  334. package/dist/esm/src/decorators/hooks/BeforeDestroy.js +21 -0
  335. package/dist/esm/src/decorators/hooks/BeforeSave.js +22 -0
  336. package/dist/esm/src/decorators/hooks/BeforeUpdate.js +22 -0
  337. package/dist/esm/src/decorators/hooks/shared.js +20 -0
  338. package/dist/esm/src/decorators/sortable/Sortable.js +157 -0
  339. package/dist/esm/src/decorators/sortable/helpers/applySortableScopeToQuery.js +14 -0
  340. package/dist/esm/src/decorators/sortable/helpers/clearCachedSortableValues.js +8 -0
  341. package/dist/esm/src/decorators/sortable/helpers/decrementScopedRecordsGreaterThanPosition.js +23 -0
  342. package/dist/esm/src/decorators/sortable/helpers/getColumnForSortableScope.js +15 -0
  343. package/dist/esm/src/decorators/sortable/helpers/isSortedCorrectly.js +4 -0
  344. package/dist/esm/src/decorators/sortable/helpers/positionIsInvalid.js +8 -0
  345. package/dist/esm/src/decorators/sortable/helpers/resortAllRecords.js +35 -0
  346. package/dist/esm/src/decorators/sortable/helpers/scopeArray.js +7 -0
  347. package/dist/esm/src/decorators/sortable/helpers/setPosition.js +154 -0
  348. package/dist/esm/src/decorators/sortable/helpers/sortableCacheKeyName.js +4 -0
  349. package/dist/esm/src/decorators/sortable/helpers/sortableCacheValuesName.js +4 -0
  350. package/dist/esm/src/decorators/sortable/helpers/sortableQueryExcludingDream.js +7 -0
  351. package/dist/esm/src/decorators/sortable/hooks/afterSortableCreate.js +15 -0
  352. package/dist/esm/src/decorators/sortable/hooks/afterSortableDestroy.js +11 -0
  353. package/dist/esm/src/decorators/sortable/hooks/afterSortableUpdate.js +28 -0
  354. package/dist/esm/src/decorators/sortable/hooks/beforeSortableSave.js +62 -0
  355. package/dist/esm/src/decorators/validations/Validate.js +19 -0
  356. package/dist/esm/src/decorators/validations/Validates.js +64 -0
  357. package/dist/esm/src/decorators/validations/shared.js +1 -0
  358. package/dist/esm/src/dream/DreamClassTransactionBuilder.js +589 -0
  359. package/dist/esm/src/dream/DreamInstanceTransactionBuilder.js +477 -0
  360. package/dist/esm/src/dream/DreamTransaction.js +23 -0
  361. package/dist/esm/src/dream/LeftJoinLoadBuilder.js +74 -0
  362. package/dist/esm/src/dream/LoadBuilder.js +65 -0
  363. package/dist/esm/src/dream/Query.js +2615 -0
  364. package/dist/esm/src/dream/internal/applyScopeBypassingSettingsToQuery.js +8 -0
  365. package/dist/esm/src/dream/internal/associations/associationQuery.js +20 -0
  366. package/dist/esm/src/dream/internal/associations/associationUpdateQuery.js +33 -0
  367. package/dist/esm/src/dream/internal/associations/createAssociation.js +52 -0
  368. package/dist/esm/src/dream/internal/associations/destroyAssociation.js +14 -0
  369. package/dist/esm/src/dream/internal/associations/undestroyAssociation.js +9 -0
  370. package/dist/esm/src/dream/internal/checkSingleValidation.js +49 -0
  371. package/dist/esm/src/dream/internal/destroyAssociatedRecords.js +18 -0
  372. package/dist/esm/src/dream/internal/destroyDream.js +69 -0
  373. package/dist/esm/src/dream/internal/destroyOptions.js +27 -0
  374. package/dist/esm/src/dream/internal/ensureSTITypeFieldIsSet.js +7 -0
  375. package/dist/esm/src/dream/internal/executeDatabaseQuery.js +21 -0
  376. package/dist/esm/src/dream/internal/extractAssociationMetadataFromAssociationName.js +5 -0
  377. package/dist/esm/src/dream/internal/orderByDirection.js +12 -0
  378. package/dist/esm/src/dream/internal/reload.js +18 -0
  379. package/dist/esm/src/dream/internal/runHooksFor.js +95 -0
  380. package/dist/esm/src/dream/internal/runValidations.js +13 -0
  381. package/dist/esm/src/dream/internal/safelyRunCommitHooks.js +12 -0
  382. package/dist/esm/src/dream/internal/saveDream.js +64 -0
  383. package/dist/esm/src/dream/internal/scopeHelpers.js +9 -0
  384. package/dist/esm/src/dream/internal/shouldBypassDefaultScope.js +9 -0
  385. package/dist/esm/src/dream/internal/similarity/SimilarityBuilder.js +327 -0
  386. package/dist/esm/src/dream/internal/similarity/similaritySelectSql.js +18 -0
  387. package/dist/esm/src/dream/internal/similarity/similarityWhereSql.js +18 -0
  388. package/dist/esm/src/dream/internal/softDeleteDream.js +19 -0
  389. package/dist/esm/src/dream/internal/sqlResultToDreamInstance.js +34 -0
  390. package/dist/esm/src/dream/internal/undestroyDream.js +87 -0
  391. package/dist/esm/src/dream/types.js +95 -0
  392. package/dist/esm/src/dream-application/cache.js +9 -0
  393. package/dist/esm/src/dream-application/helpers/DreamImporter.js +49 -0
  394. package/dist/esm/src/dream-application/helpers/globalModelKeyFromPath.js +7 -0
  395. package/dist/esm/src/dream-application/helpers/globalSerializerKeyFromPath.js +14 -0
  396. package/dist/esm/src/dream-application/helpers/globalServiceKeyFromPath.js +8 -0
  397. package/dist/esm/src/dream-application/helpers/importers/importModels.js +75 -0
  398. package/dist/esm/src/dream-application/helpers/importers/importSerializers.js +57 -0
  399. package/dist/esm/src/dream-application/helpers/importers/importServices.js +37 -0
  400. package/dist/esm/src/dream-application/helpers/lookupClassByGlobalName.js +14 -0
  401. package/dist/esm/src/dream-application/helpers/lookupModelByGlobalName.js +10 -0
  402. package/dist/esm/src/dream-application/helpers/lookupModelByGlobalNameOrNames.js +7 -0
  403. package/dist/esm/src/dream-application/index.js +281 -0
  404. package/dist/esm/src/encrypt/InternalEncrypt.js +29 -0
  405. package/dist/esm/src/encrypt/algorithms/aes-gcm/decryptAESGCM.js +23 -0
  406. package/dist/esm/src/encrypt/algorithms/aes-gcm/encryptAESGCM.js +9 -0
  407. package/dist/esm/src/encrypt/algorithms/aes-gcm/generateKeyAESGCM.js +4 -0
  408. package/dist/esm/src/encrypt/algorithms/aes-gcm/validateKeyAESGCM.js +8 -0
  409. package/dist/esm/src/encrypt/index.js +92 -0
  410. package/dist/esm/src/errors/AttemptingToMarshalInvalidArrayType.js +17 -0
  411. package/dist/esm/src/errors/CannotCallUndestroyOnANonSoftDeleteModel.js +18 -0
  412. package/dist/esm/src/errors/CannotDefineAssociationWithBothDependentAndPassthrough.js +16 -0
  413. package/dist/esm/src/errors/CannotDefineAssociationWithBothDependentAndRequiredOnClause.js +16 -0
  414. package/dist/esm/src/errors/CannotNegateSimilarityClause.js +19 -0
  415. package/dist/esm/src/errors/CannotPassAdditionalFieldsToPluckEachAfterCallback.js +19 -0
  416. package/dist/esm/src/errors/CannotPassUndefinedAsAValueToAWhereClause.js +17 -0
  417. package/dist/esm/src/errors/CannotReloadUnsavedDream.js +13 -0
  418. package/dist/esm/src/errors/ConstructorOnlyForInternalUse.js +6 -0
  419. package/dist/esm/src/errors/CreateOrFindByFailedToCreateAndFind.js +15 -0
  420. package/dist/esm/src/errors/DoNotSetEncryptedFieldsDirectly.js +20 -0
  421. package/dist/esm/src/errors/InvalidColumnName.js +16 -0
  422. package/dist/esm/src/errors/InvalidDecimalFieldPassedToGenerator.js +16 -0
  423. package/dist/esm/src/errors/InvalidTableAlias.js +27 -0
  424. package/dist/esm/src/errors/InvalidTableName.js +20 -0
  425. package/dist/esm/src/errors/LeftJoinPreloadIncompatibleWithFindEach.js +9 -0
  426. package/dist/esm/src/errors/MissingDB.js +7 -0
  427. package/dist/esm/src/errors/MissingDeletedAtFieldForSoftDelete.js +21 -0
  428. package/dist/esm/src/errors/MissingRequiredCallbackFunctionToPluckEach.js +19 -0
  429. package/dist/esm/src/errors/MissingSerializersDefinition.js +23 -0
  430. package/dist/esm/src/errors/MissingTable.js +24 -0
  431. package/dist/esm/src/errors/NoUpdateAllOnJoins.js +10 -0
  432. package/dist/esm/src/errors/NoUpdateOnAssociationQuery.js +7 -0
  433. package/dist/esm/src/errors/NonBelongsToAssociationProvidedAsSortableDecoratorScope.js +20 -0
  434. package/dist/esm/src/errors/NonExistentScopeProvidedToResort.js +20 -0
  435. package/dist/esm/src/errors/PrototypePollutingAssignment.js +10 -0
  436. package/dist/esm/src/errors/RecordNotFound.js +12 -0
  437. package/dist/esm/src/errors/SortableDecoratorRequiresColumnOrBelongsToAssociation.js +23 -0
  438. package/dist/esm/src/errors/ValidationError.js +16 -0
  439. package/dist/esm/src/errors/associations/CanOnlyPassBelongsToModelParam.js +17 -0
  440. package/dist/esm/src/errors/associations/CannotAssociateThroughPolymorphic.js +16 -0
  441. package/dist/esm/src/errors/associations/CannotCreateAssociationWithThroughContext.js +16 -0
  442. package/dist/esm/src/errors/associations/CannotJoinPolymorphicBelongsToError.js +24 -0
  443. package/dist/esm/src/errors/associations/CannotPassNullOrUndefinedToRequiredBelongsTo.js +16 -0
  444. package/dist/esm/src/errors/associations/InvalidComputedForeignKey.js +58 -0
  445. package/dist/esm/src/errors/associations/JoinAttemptedOnMissingAssociation.js +24 -0
  446. package/dist/esm/src/errors/associations/MissingRequiredAssociationOnClause.js +16 -0
  447. package/dist/esm/src/errors/associations/MissingRequiredPassthroughForAssociationOnClause.js +13 -0
  448. package/dist/esm/src/errors/associations/MissingThroughAssociation.js +24 -0
  449. package/dist/esm/src/errors/associations/MissingThroughAssociationSource.js +39 -0
  450. package/dist/esm/src/errors/associations/NonLoadedAssociation.js +15 -0
  451. package/dist/esm/src/errors/dream-application/DreamApplicationInitMissingCallToLoadModels.js +15 -0
  452. package/dist/esm/src/errors/dream-application/DreamApplicationInitMissingMissingProjectRoot.js +16 -0
  453. package/dist/esm/src/errors/dream-application/GlobalNameNotSet.js +11 -0
  454. package/dist/esm/src/errors/dream-application/SerializerNameConflict.js +12 -0
  455. package/dist/esm/src/errors/encrypt/MissingColumnEncryptionOpts.js +24 -0
  456. package/dist/esm/src/errors/encrypt/MissingEncryptionKey.js +9 -0
  457. package/dist/esm/src/errors/environment/MissingRequiredEnvironmentVariable.js +10 -0
  458. package/dist/esm/src/errors/ops/AnyRequiresArrayColumn.js +15 -0
  459. package/dist/esm/src/errors/ops/ScoreMustBeANormalNumber.js +14 -0
  460. package/dist/esm/src/errors/schema-builder/FailedToIdentifyAssociation.js +77 -0
  461. package/dist/esm/src/errors/serializers/FailedToRenderThroughAssociationForSerializer.js +14 -0
  462. package/dist/esm/src/errors/sortable/CannotCallSortableOnSTIChild.js +15 -0
  463. package/dist/esm/src/errors/sti/STIChildMissing.js +20 -0
  464. package/dist/esm/src/errors/sti/StiChildCannotDefineNewAssociations.js +17 -0
  465. package/dist/esm/src/errors/sti/StiChildIncompatibleWithReplicaSafeDecorator.js +14 -0
  466. package/dist/esm/src/errors/sti/StiChildIncompatibleWithSoftDeleteDecorator.js +14 -0
  467. package/dist/esm/src/global-cli/dream.js +44 -0
  468. package/dist/esm/src/global-cli/file-builders/DreamtsBuilder.js +66 -0
  469. package/dist/esm/src/global-cli/file-builders/EnvBuilder.js +24 -0
  470. package/dist/esm/src/global-cli/file-builders/EslintConfBuilder.js +26 -0
  471. package/dist/esm/src/global-cli/file-builders/PackagejsonBuilder.js +6 -0
  472. package/dist/esm/src/global-cli/helpers/argAndValue.js +12 -0
  473. package/dist/esm/src/global-cli/helpers/autogeneratedFileMessage.js +68 -0
  474. package/dist/esm/src/global-cli/helpers/buildNewDreamApp.js +60 -0
  475. package/dist/esm/src/global-cli/helpers/copyRecursive.js +17 -0
  476. package/dist/esm/src/global-cli/helpers/filterObjectByKey.js +20 -0
  477. package/dist/esm/src/global-cli/helpers/generateEncryptionKey.js +23 -0
  478. package/dist/esm/src/global-cli/helpers/globalCliSnakeify.js +1 -0
  479. package/dist/esm/src/global-cli/helpers/initDreamAppIntoExistingProject.js +82 -0
  480. package/dist/esm/src/global-cli/helpers/log.js +24 -0
  481. package/dist/esm/src/global-cli/helpers/logo.js +77 -0
  482. package/dist/esm/src/global-cli/helpers/primaryKeyTypes.js +10 -0
  483. package/dist/esm/src/global-cli/helpers/prompt.js +30 -0
  484. package/dist/esm/src/global-cli/helpers/select.js +110 -0
  485. package/dist/esm/src/global-cli/helpers/sleep.js +7 -0
  486. package/dist/esm/src/global-cli/helpers/sspawn.js +17 -0
  487. package/dist/esm/src/global-cli/helpers/welcomeMessage.js +38 -0
  488. package/dist/esm/src/global-cli/init.js +53 -0
  489. package/dist/esm/src/global-cli/new.js +7 -0
  490. package/dist/esm/src/helpers/CalendarDate.js +169 -0
  491. package/dist/esm/src/helpers/Env.js +75 -0
  492. package/dist/esm/src/helpers/EnvInternal.js +3 -0
  493. package/dist/esm/src/helpers/allNestedObjectKeys.js +9 -0
  494. package/dist/esm/src/helpers/benchmark.js +15 -0
  495. package/dist/esm/src/helpers/camelize.js +11 -0
  496. package/dist/esm/src/helpers/capitalize.js +3 -0
  497. package/dist/esm/src/helpers/cli/SchemaBuilder.js +375 -0
  498. package/dist/esm/src/helpers/cli/generateDream.js +45 -0
  499. package/dist/esm/src/helpers/cli/generateDreamContent.js +104 -0
  500. package/dist/esm/src/helpers/cli/generateFactory.js +23 -0
  501. package/dist/esm/src/helpers/cli/generateFactoryContent.js +55 -0
  502. package/dist/esm/src/helpers/cli/generateMigration.js +53 -0
  503. package/dist/esm/src/helpers/cli/generateMigrationContent.js +193 -0
  504. package/dist/esm/src/helpers/cli/generateSerializer.js +23 -0
  505. package/dist/esm/src/helpers/cli/generateSerializerContent.js +127 -0
  506. package/dist/esm/src/helpers/cli/generateStiMigrationContent.js +4 -0
  507. package/dist/esm/src/helpers/cli/generateUnitSpec.js +23 -0
  508. package/dist/esm/src/helpers/cli/generateUnitSpecContent.js +7 -0
  509. package/dist/esm/src/helpers/cloneDeepSafe.js +64 -0
  510. package/dist/esm/src/helpers/compact.js +11 -0
  511. package/dist/esm/src/helpers/customPgParsers.js +31 -0
  512. package/dist/esm/src/helpers/db/cachedTypeForAttribute.js +3 -0
  513. package/dist/esm/src/helpers/db/createDb.js +17 -0
  514. package/dist/esm/src/helpers/db/dropDb.js +33 -0
  515. package/dist/esm/src/helpers/db/foreignKeyTypeFromPrimaryKey.js +8 -0
  516. package/dist/esm/src/helpers/db/loadPgClient.js +17 -0
  517. package/dist/esm/src/helpers/db/primaryKeyType.js +20 -0
  518. package/dist/esm/src/helpers/db/runMigration.js +94 -0
  519. package/dist/esm/src/helpers/db/truncateDb.js +24 -0
  520. package/dist/esm/src/helpers/db/types/isDatabaseArrayColumn.js +3 -0
  521. package/dist/esm/src/helpers/db/types/isDateColumn.js +3 -0
  522. package/dist/esm/src/helpers/db/types/isDateTimeColumn.js +3 -0
  523. package/dist/esm/src/helpers/db/types/isJsonColumn.js +3 -0
  524. package/dist/esm/src/helpers/debug.js +8 -0
  525. package/dist/esm/src/helpers/dreamOrPsychicCoreDevelopment.js +7 -0
  526. package/dist/esm/src/helpers/filterObjectByKey.js +11 -0
  527. package/dist/esm/src/helpers/getFiles.js +17 -0
  528. package/dist/esm/src/helpers/globalClassNameFromFullyQualifiedModelName.js +4 -0
  529. package/dist/esm/src/helpers/hyphenize.js +8 -0
  530. package/dist/esm/src/helpers/inferSerializerFromDreamOrViewModel.js +12 -0
  531. package/dist/esm/src/helpers/isEmpty.js +5 -0
  532. package/dist/esm/src/helpers/loadEnv.js +35 -0
  533. package/dist/esm/src/helpers/loadRepl.js +22 -0
  534. package/dist/esm/src/helpers/migrationVersion.js +3 -0
  535. package/dist/esm/src/helpers/namespaceColumn.js +5 -0
  536. package/dist/esm/src/helpers/objectPathsToArrays.js +16 -0
  537. package/dist/esm/src/helpers/pascalize.js +9 -0
  538. package/dist/esm/src/helpers/pascalizePath.js +7 -0
  539. package/dist/esm/src/helpers/path/dreamFileAndDirPaths.js +13 -0
  540. package/dist/esm/src/helpers/path/dreamPath.js +22 -0
  541. package/dist/esm/src/helpers/path/relativeDreamPath.js +46 -0
  542. package/dist/esm/src/helpers/path/sharedPathPrefix.js +11 -0
  543. package/dist/esm/src/helpers/propertyNameFromFullyQualifiedModelName.js +5 -0
  544. package/dist/esm/src/helpers/protectAgainstPollutingAssignment.js +11 -0
  545. package/dist/esm/src/helpers/range.js +15 -0
  546. package/dist/esm/src/helpers/round.js +4 -0
  547. package/dist/esm/src/helpers/serializerNameFromFullyQualifiedModelName.js +10 -0
  548. package/dist/esm/src/helpers/snakeify.js +10 -0
  549. package/dist/esm/src/helpers/sortBy.js +26 -0
  550. package/dist/esm/src/helpers/sqlAttributes.js +25 -0
  551. package/dist/esm/src/helpers/sspawn.js +17 -0
  552. package/dist/esm/src/helpers/standardizeFullyQualifiedModelName.js +7 -0
  553. package/dist/esm/src/helpers/stringCasing.js +31 -0
  554. package/dist/esm/src/helpers/typechecks.js +12 -0
  555. package/dist/esm/src/helpers/typeutils.js +1 -0
  556. package/dist/esm/src/helpers/uncapitalize.js +3 -0
  557. package/dist/esm/src/helpers/uniq.js +18 -0
  558. package/dist/esm/src/index.js +73 -0
  559. package/dist/esm/src/openapi/types.js +23 -0
  560. package/dist/esm/src/ops/curried-ops-statement.js +9 -0
  561. package/dist/esm/src/ops/index.js +40 -0
  562. package/dist/esm/src/ops/ops-statement.js +35 -0
  563. package/dist/esm/src/serializer/decorators/associations/RendersMany.js +81 -0
  564. package/dist/esm/src/serializer/decorators/associations/RendersOne.js +84 -0
  565. package/dist/esm/src/serializer/decorators/associations/shared.js +7 -0
  566. package/dist/esm/src/serializer/decorators/attribute.js +158 -0
  567. package/dist/esm/src/serializer/decorators/helpers/dreamAttributeOpenapiShape.js +73 -0
  568. package/dist/esm/src/serializer/decorators/helpers/hasSerializersGetter.js +8 -0
  569. package/dist/esm/src/serializer/decorators/helpers/maybeSerializableToDreamSerializerCallbackFunction.js +17 -0
  570. package/dist/esm/src/serializer/index.js +268 -0
  571. package/dist/types/src/Dream.d.ts +2211 -0
  572. package/dist/types/src/bin/helpers/sync.d.ts +2 -0
  573. package/dist/types/src/bin/index.d.ts +20 -0
  574. package/dist/types/src/cli/index.d.ts +20 -0
  575. package/dist/types/src/db/ConnectedToDB.d.ts +26 -0
  576. package/dist/types/src/db/ConnectionConfRetriever.d.ts +6 -0
  577. package/dist/types/src/db/DreamDbConnection.d.ts +10 -0
  578. package/dist/types/src/db/dataTypes.d.ts +6 -0
  579. package/dist/types/src/db/errors.d.ts +6 -0
  580. package/dist/types/src/db/index.d.ts +5 -0
  581. package/dist/types/src/db/migration-helpers/DreamMigrationHelpers.d.ts +116 -0
  582. package/dist/types/src/db/reflections.d.ts +5 -0
  583. package/dist/types/src/db/types.d.ts +1 -0
  584. package/dist/types/src/db/validators/validateColumn.d.ts +1 -0
  585. package/dist/types/src/db/validators/validateTable.d.ts +1 -0
  586. package/dist/types/src/db/validators/validateTableAlias.d.ts +1 -0
  587. package/dist/types/src/decorators/DecoratorContextType.d.ts +13 -0
  588. package/dist/types/src/decorators/Decorators.d.ts +214 -0
  589. package/dist/types/src/decorators/Encrypted.d.ts +5 -0
  590. package/dist/types/src/decorators/ReplicaSafe.d.ts +1 -0
  591. package/dist/types/src/decorators/STI.d.ts +5 -0
  592. package/dist/types/src/decorators/Scope.d.ts +11 -0
  593. package/dist/types/src/decorators/SoftDelete.d.ts +37 -0
  594. package/dist/types/src/decorators/Virtual.d.ts +6 -0
  595. package/dist/types/src/decorators/associations/BelongsTo.d.ts +33 -0
  596. package/dist/types/src/decorators/associations/HasMany.d.ts +19 -0
  597. package/dist/types/src/decorators/associations/HasOne.d.ts +11 -0
  598. package/dist/types/src/decorators/associations/associationToGetterSetterProp.d.ts +5 -0
  599. package/dist/types/src/decorators/associations/shared.d.ts +118 -0
  600. package/dist/types/src/decorators/helpers/freezeBaseClassArrayMap.d.ts +1 -0
  601. package/dist/types/src/decorators/hooks/AfterCreate.d.ts +4 -0
  602. package/dist/types/src/decorators/hooks/AfterCreateCommit.d.ts +21 -0
  603. package/dist/types/src/decorators/hooks/AfterDestroy.d.ts +3 -0
  604. package/dist/types/src/decorators/hooks/AfterDestroyCommit.d.ts +18 -0
  605. package/dist/types/src/decorators/hooks/AfterSave.d.ts +4 -0
  606. package/dist/types/src/decorators/hooks/AfterSaveCommit.d.ts +21 -0
  607. package/dist/types/src/decorators/hooks/AfterUpdate.d.ts +4 -0
  608. package/dist/types/src/decorators/hooks/AfterUpdateCommit.d.ts +21 -0
  609. package/dist/types/src/decorators/hooks/BeforeCreate.d.ts +4 -0
  610. package/dist/types/src/decorators/hooks/BeforeDestroy.d.ts +3 -0
  611. package/dist/types/src/decorators/hooks/BeforeSave.d.ts +4 -0
  612. package/dist/types/src/decorators/hooks/BeforeUpdate.d.ts +4 -0
  613. package/dist/types/src/decorators/hooks/shared.d.ts +34 -0
  614. package/dist/types/src/decorators/sortable/Sortable.d.ts +9 -0
  615. package/dist/types/src/decorators/sortable/helpers/applySortableScopeToQuery.d.ts +9 -0
  616. package/dist/types/src/decorators/sortable/helpers/clearCachedSortableValues.d.ts +2 -0
  617. package/dist/types/src/decorators/sortable/helpers/decrementScopedRecordsGreaterThanPosition.d.ts +8 -0
  618. package/dist/types/src/decorators/sortable/helpers/getColumnForSortableScope.d.ts +2 -0
  619. package/dist/types/src/decorators/sortable/helpers/isSortedCorrectly.d.ts +1 -0
  620. package/dist/types/src/decorators/sortable/helpers/positionIsInvalid.d.ts +8 -0
  621. package/dist/types/src/decorators/sortable/helpers/resortAllRecords.d.ts +2 -0
  622. package/dist/types/src/decorators/sortable/helpers/scopeArray.d.ts +1 -0
  623. package/dist/types/src/decorators/sortable/helpers/setPosition.d.ts +14 -0
  624. package/dist/types/src/decorators/sortable/helpers/sortableCacheKeyName.d.ts +1 -0
  625. package/dist/types/src/decorators/sortable/helpers/sortableCacheValuesName.d.ts +1 -0
  626. package/dist/types/src/decorators/sortable/helpers/sortableQueryExcludingDream.d.ts +9 -0
  627. package/dist/types/src/decorators/sortable/hooks/afterSortableCreate.d.ts +10 -0
  628. package/dist/types/src/decorators/sortable/hooks/afterSortableDestroy.d.ts +8 -0
  629. package/dist/types/src/decorators/sortable/hooks/afterSortableUpdate.d.ts +10 -0
  630. package/dist/types/src/decorators/sortable/hooks/beforeSortableSave.d.ts +8 -0
  631. package/dist/types/src/decorators/validations/Validate.d.ts +1 -0
  632. package/dist/types/src/decorators/validations/Validates.d.ts +18 -0
  633. package/dist/types/src/decorators/validations/shared.d.ts +19 -0
  634. package/dist/types/src/dream/DreamClassTransactionBuilder.d.ts +549 -0
  635. package/dist/types/src/dream/DreamInstanceTransactionBuilder.d.ts +316 -0
  636. package/dist/types/src/dream/DreamTransaction.d.ts +15 -0
  637. package/dist/types/src/dream/LeftJoinLoadBuilder.d.ts +48 -0
  638. package/dist/types/src/dream/LoadBuilder.d.ts +47 -0
  639. package/dist/types/src/dream/Query.d.ts +1132 -0
  640. package/dist/types/src/dream/internal/applyScopeBypassingSettingsToQuery.d.ts +13 -0
  641. package/dist/types/src/dream/internal/associations/associationQuery.d.ts +9 -0
  642. package/dist/types/src/dream/internal/associations/associationUpdateQuery.d.ts +9 -0
  643. package/dist/types/src/dream/internal/associations/createAssociation.d.ts +4 -0
  644. package/dist/types/src/dream/internal/associations/destroyAssociation.d.ts +11 -0
  645. package/dist/types/src/dream/internal/associations/undestroyAssociation.d.ts +10 -0
  646. package/dist/types/src/dream/internal/checkSingleValidation.d.ts +3 -0
  647. package/dist/types/src/dream/internal/destroyAssociatedRecords.d.ts +10 -0
  648. package/dist/types/src/dream/internal/destroyDream.d.ts +19 -0
  649. package/dist/types/src/dream/internal/destroyOptions.d.ts +46 -0
  650. package/dist/types/src/dream/internal/ensureSTITypeFieldIsSet.d.ts +2 -0
  651. package/dist/types/src/dream/internal/executeDatabaseQuery.d.ts +1 -0
  652. package/dist/types/src/dream/internal/extractAssociationMetadataFromAssociationName.d.ts +4 -0
  653. package/dist/types/src/dream/internal/orderByDirection.d.ts +2 -0
  654. package/dist/types/src/dream/internal/reload.d.ts +3 -0
  655. package/dist/types/src/dream/internal/runHooksFor.d.ts +8 -0
  656. package/dist/types/src/dream/internal/runValidations.d.ts +2 -0
  657. package/dist/types/src/dream/internal/safelyRunCommitHooks.d.ts +7 -0
  658. package/dist/types/src/dream/internal/saveDream.d.ts +5 -0
  659. package/dist/types/src/dream/internal/scopeHelpers.d.ts +7 -0
  660. package/dist/types/src/dream/internal/shouldBypassDefaultScope.d.ts +4 -0
  661. package/dist/types/src/dream/internal/similarity/SimilarityBuilder.d.ts +38 -0
  662. package/dist/types/src/dream/internal/similarity/similaritySelectSql.d.ts +11 -0
  663. package/dist/types/src/dream/internal/similarity/similarityWhereSql.d.ts +10 -0
  664. package/dist/types/src/dream/internal/softDeleteDream.d.ts +3 -0
  665. package/dist/types/src/dream/internal/sqlResultToDreamInstance.d.ts +4 -0
  666. package/dist/types/src/dream/internal/undestroyDream.d.ts +16 -0
  667. package/dist/types/src/dream/types.d.ts +184 -0
  668. package/dist/types/src/dream-application/cache.d.ts +3 -0
  669. package/dist/types/src/dream-application/helpers/DreamImporter.d.ts +8 -0
  670. package/dist/types/src/dream-application/helpers/globalModelKeyFromPath.d.ts +1 -0
  671. package/dist/types/src/dream-application/helpers/globalSerializerKeyFromPath.d.ts +1 -0
  672. package/dist/types/src/dream-application/helpers/globalServiceKeyFromPath.d.ts +1 -0
  673. package/dist/types/src/dream-application/helpers/importers/importModels.d.ts +5 -0
  674. package/dist/types/src/dream-application/helpers/importers/importSerializers.d.ts +5 -0
  675. package/dist/types/src/dream-application/helpers/importers/importServices.d.ts +4 -0
  676. package/dist/types/src/dream-application/helpers/lookupClassByGlobalName.d.ts +1 -0
  677. package/dist/types/src/dream-application/helpers/lookupModelByGlobalName.d.ts +1 -0
  678. package/dist/types/src/dream-application/helpers/lookupModelByGlobalNameOrNames.d.ts +1 -0
  679. package/dist/types/src/dream-application/index.d.ts +143 -0
  680. package/dist/types/src/encrypt/InternalEncrypt.d.ts +6 -0
  681. package/dist/types/src/encrypt/algorithms/aes-gcm/decryptAESGCM.d.ts +2 -0
  682. package/dist/types/src/encrypt/algorithms/aes-gcm/encryptAESGCM.d.ts +2 -0
  683. package/dist/types/src/encrypt/algorithms/aes-gcm/generateKeyAESGCM.d.ts +2 -0
  684. package/dist/types/src/encrypt/algorithms/aes-gcm/validateKeyAESGCM.d.ts +2 -0
  685. package/dist/types/src/encrypt/index.d.ts +26 -0
  686. package/dist/types/src/errors/AttemptingToMarshalInvalidArrayType.d.ts +5 -0
  687. package/dist/types/src/errors/CannotCallUndestroyOnANonSoftDeleteModel.d.ts +6 -0
  688. package/dist/types/src/errors/CannotDefineAssociationWithBothDependentAndPassthrough.d.ts +7 -0
  689. package/dist/types/src/errors/CannotDefineAssociationWithBothDependentAndRequiredOnClause.d.ts +7 -0
  690. package/dist/types/src/errors/CannotNegateSimilarityClause.d.ts +7 -0
  691. package/dist/types/src/errors/CannotPassAdditionalFieldsToPluckEachAfterCallback.d.ts +6 -0
  692. package/dist/types/src/errors/CannotPassUndefinedAsAValueToAWhereClause.d.ts +7 -0
  693. package/dist/types/src/errors/CannotReloadUnsavedDream.d.ts +6 -0
  694. package/dist/types/src/errors/ConstructorOnlyForInternalUse.d.ts +3 -0
  695. package/dist/types/src/errors/CreateOrFindByFailedToCreateAndFind.d.ts +6 -0
  696. package/dist/types/src/errors/DoNotSetEncryptedFieldsDirectly.d.ts +8 -0
  697. package/dist/types/src/errors/InvalidColumnName.d.ts +6 -0
  698. package/dist/types/src/errors/InvalidDecimalFieldPassedToGenerator.d.ts +5 -0
  699. package/dist/types/src/errors/InvalidTableAlias.d.ts +5 -0
  700. package/dist/types/src/errors/InvalidTableName.d.ts +6 -0
  701. package/dist/types/src/errors/LeftJoinPreloadIncompatibleWithFindEach.d.ts +3 -0
  702. package/dist/types/src/errors/MissingDB.d.ts +3 -0
  703. package/dist/types/src/errors/MissingDeletedAtFieldForSoftDelete.d.ts +6 -0
  704. package/dist/types/src/errors/MissingRequiredCallbackFunctionToPluckEach.d.ts +6 -0
  705. package/dist/types/src/errors/MissingSerializersDefinition.d.ts +6 -0
  706. package/dist/types/src/errors/MissingTable.d.ts +6 -0
  707. package/dist/types/src/errors/NoUpdateAllOnJoins.d.ts +3 -0
  708. package/dist/types/src/errors/NoUpdateOnAssociationQuery.d.ts +3 -0
  709. package/dist/types/src/errors/NonBelongsToAssociationProvidedAsSortableDecoratorScope.d.ts +7 -0
  710. package/dist/types/src/errors/NonExistentScopeProvidedToResort.d.ts +7 -0
  711. package/dist/types/src/errors/PrototypePollutingAssignment.d.ts +5 -0
  712. package/dist/types/src/errors/RecordNotFound.d.ts +5 -0
  713. package/dist/types/src/errors/SortableDecoratorRequiresColumnOrBelongsToAssociation.d.ts +7 -0
  714. package/dist/types/src/errors/ValidationError.d.ts +11 -0
  715. package/dist/types/src/errors/associations/CanOnlyPassBelongsToModelParam.d.ts +9 -0
  716. package/dist/types/src/errors/associations/CannotAssociateThroughPolymorphic.d.ts +12 -0
  717. package/dist/types/src/errors/associations/CannotCreateAssociationWithThroughContext.d.ts +12 -0
  718. package/dist/types/src/errors/associations/CannotJoinPolymorphicBelongsToError.d.ts +15 -0
  719. package/dist/types/src/errors/associations/CannotPassNullOrUndefinedToRequiredBelongsTo.d.ts +8 -0
  720. package/dist/types/src/errors/associations/InvalidComputedForeignKey.d.ts +19 -0
  721. package/dist/types/src/errors/associations/JoinAttemptedOnMissingAssociation.d.ts +10 -0
  722. package/dist/types/src/errors/associations/MissingRequiredAssociationOnClause.d.ts +8 -0
  723. package/dist/types/src/errors/associations/MissingRequiredPassthroughForAssociationOnClause.d.ts +5 -0
  724. package/dist/types/src/errors/associations/MissingThroughAssociation.d.ts +12 -0
  725. package/dist/types/src/errors/associations/MissingThroughAssociationSource.d.ts +14 -0
  726. package/dist/types/src/errors/associations/NonLoadedAssociation.d.ts +10 -0
  727. package/dist/types/src/errors/dream-application/DreamApplicationInitMissingCallToLoadModels.d.ts +3 -0
  728. package/dist/types/src/errors/dream-application/DreamApplicationInitMissingMissingProjectRoot.d.ts +3 -0
  729. package/dist/types/src/errors/dream-application/GlobalNameNotSet.d.ts +5 -0
  730. package/dist/types/src/errors/dream-application/SerializerNameConflict.d.ts +5 -0
  731. package/dist/types/src/errors/encrypt/MissingColumnEncryptionOpts.d.ts +3 -0
  732. package/dist/types/src/errors/encrypt/MissingEncryptionKey.d.ts +3 -0
  733. package/dist/types/src/errors/environment/MissingRequiredEnvironmentVariable.d.ts +5 -0
  734. package/dist/types/src/errors/ops/AnyRequiresArrayColumn.d.ts +7 -0
  735. package/dist/types/src/errors/ops/ScoreMustBeANormalNumber.d.ts +5 -0
  736. package/dist/types/src/errors/schema-builder/FailedToIdentifyAssociation.d.ts +9 -0
  737. package/dist/types/src/errors/serializers/FailedToRenderThroughAssociationForSerializer.d.ts +6 -0
  738. package/dist/types/src/errors/sortable/CannotCallSortableOnSTIChild.d.ts +6 -0
  739. package/dist/types/src/errors/sti/STIChildMissing.d.ts +8 -0
  740. package/dist/types/src/errors/sti/StiChildCannotDefineNewAssociations.d.ts +7 -0
  741. package/dist/types/src/errors/sti/StiChildIncompatibleWithReplicaSafeDecorator.d.ts +6 -0
  742. package/dist/types/src/errors/sti/StiChildIncompatibleWithSoftDeleteDecorator.d.ts +6 -0
  743. package/dist/types/src/global-cli/dream.d.ts +2 -0
  744. package/dist/types/src/global-cli/file-builders/DreamtsBuilder.d.ts +4 -0
  745. package/dist/types/src/global-cli/file-builders/EnvBuilder.d.ts +6 -0
  746. package/dist/types/src/global-cli/file-builders/EslintConfBuilder.d.ts +3 -0
  747. package/dist/types/src/global-cli/file-builders/PackagejsonBuilder.d.ts +3 -0
  748. package/dist/types/src/global-cli/helpers/argAndValue.d.ts +1 -0
  749. package/dist/types/src/global-cli/helpers/autogeneratedFileMessage.d.ts +1 -0
  750. package/dist/types/src/global-cli/helpers/buildNewDreamApp.d.ts +2 -0
  751. package/dist/types/src/global-cli/helpers/copyRecursive.d.ts +1 -0
  752. package/dist/types/src/global-cli/helpers/filterObjectByKey.d.ts +1 -0
  753. package/dist/types/src/global-cli/helpers/generateEncryptionKey.d.ts +1 -0
  754. package/dist/types/src/global-cli/helpers/globalCliSnakeify.d.ts +0 -0
  755. package/dist/types/src/global-cli/helpers/initDreamAppIntoExistingProject.d.ts +2 -0
  756. package/dist/types/src/global-cli/helpers/log.d.ts +10 -0
  757. package/dist/types/src/global-cli/helpers/logo.d.ts +2 -0
  758. package/dist/types/src/global-cli/helpers/primaryKeyTypes.d.ts +22 -0
  759. package/dist/types/src/global-cli/helpers/prompt.d.ts +8 -0
  760. package/dist/types/src/global-cli/helpers/select.d.ts +17 -0
  761. package/dist/types/src/global-cli/helpers/sleep.d.ts +1 -0
  762. package/dist/types/src/global-cli/helpers/sspawn.d.ts +2 -0
  763. package/dist/types/src/global-cli/helpers/welcomeMessage.d.ts +1 -0
  764. package/dist/types/src/global-cli/init.d.ts +2 -0
  765. package/dist/types/src/global-cli/new.d.ts +2 -0
  766. package/dist/types/src/helpers/CalendarDate.d.ts +51 -0
  767. package/dist/types/src/helpers/Env.d.ts +37 -0
  768. package/dist/types/src/helpers/EnvInternal.d.ts +6 -0
  769. package/dist/types/src/helpers/allNestedObjectKeys.d.ts +1 -0
  770. package/dist/types/src/helpers/benchmark.d.ts +6 -0
  771. package/dist/types/src/helpers/camelize.d.ts +3 -0
  772. package/dist/types/src/helpers/capitalize.d.ts +1 -0
  773. package/dist/types/src/helpers/cli/SchemaBuilder.d.ts +17 -0
  774. package/dist/types/src/helpers/cli/generateDream.d.ts +8 -0
  775. package/dist/types/src/helpers/cli/generateDreamContent.d.ts +6 -0
  776. package/dist/types/src/helpers/cli/generateFactory.d.ts +4 -0
  777. package/dist/types/src/helpers/cli/generateFactoryContent.d.ts +4 -0
  778. package/dist/types/src/helpers/cli/generateMigration.d.ts +6 -0
  779. package/dist/types/src/helpers/cli/generateMigrationContent.d.ts +7 -0
  780. package/dist/types/src/helpers/cli/generateSerializer.d.ts +5 -0
  781. package/dist/types/src/helpers/cli/generateSerializerContent.d.ts +5 -0
  782. package/dist/types/src/helpers/cli/generateStiMigrationContent.d.ts +6 -0
  783. package/dist/types/src/helpers/cli/generateUnitSpec.d.ts +3 -0
  784. package/dist/types/src/helpers/cli/generateUnitSpecContent.d.ts +3 -0
  785. package/dist/types/src/helpers/cloneDeepSafe.d.ts +18 -0
  786. package/dist/types/src/helpers/compact.d.ts +19 -0
  787. package/dist/types/src/helpers/customPgParsers.d.ts +9 -0
  788. package/dist/types/src/helpers/db/cachedTypeForAttribute.d.ts +2 -0
  789. package/dist/types/src/helpers/db/createDb.d.ts +2 -0
  790. package/dist/types/src/helpers/db/dropDb.d.ts +2 -0
  791. package/dist/types/src/helpers/db/foreignKeyTypeFromPrimaryKey.d.ts +2 -0
  792. package/dist/types/src/helpers/db/loadPgClient.d.ts +3 -0
  793. package/dist/types/src/helpers/db/primaryKeyType.d.ts +1 -0
  794. package/dist/types/src/helpers/db/runMigration.d.ts +6 -0
  795. package/dist/types/src/helpers/db/truncateDb.d.ts +1 -0
  796. package/dist/types/src/helpers/db/types/isDatabaseArrayColumn.d.ts +2 -0
  797. package/dist/types/src/helpers/db/types/isDateColumn.d.ts +2 -0
  798. package/dist/types/src/helpers/db/types/isDateTimeColumn.d.ts +2 -0
  799. package/dist/types/src/helpers/db/types/isJsonColumn.d.ts +2 -0
  800. package/dist/types/src/helpers/debug.d.ts +4 -0
  801. package/dist/types/src/helpers/dreamOrPsychicCoreDevelopment.d.ts +1 -0
  802. package/dist/types/src/helpers/filterObjectByKey.d.ts +1 -0
  803. package/dist/types/src/helpers/getFiles.d.ts +1 -0
  804. package/dist/types/src/helpers/globalClassNameFromFullyQualifiedModelName.d.ts +1 -0
  805. package/dist/types/src/helpers/hyphenize.d.ts +2 -0
  806. package/dist/types/src/helpers/inferSerializerFromDreamOrViewModel.d.ts +4 -0
  807. package/dist/types/src/helpers/isEmpty.d.ts +1 -0
  808. package/dist/types/src/helpers/loadEnv.d.ts +1 -0
  809. package/dist/types/src/helpers/loadRepl.d.ts +2 -0
  810. package/dist/types/src/helpers/migrationVersion.d.ts +1 -0
  811. package/dist/types/src/helpers/namespaceColumn.d.ts +1 -0
  812. package/dist/types/src/helpers/objectPathsToArrays.d.ts +2 -0
  813. package/dist/types/src/helpers/pascalize.d.ts +2 -0
  814. package/dist/types/src/helpers/pascalizePath.d.ts +1 -0
  815. package/dist/types/src/helpers/path/dreamFileAndDirPaths.d.ts +5 -0
  816. package/dist/types/src/helpers/path/dreamPath.d.ts +3 -0
  817. package/dist/types/src/helpers/path/relativeDreamPath.d.ts +3 -0
  818. package/dist/types/src/helpers/path/sharedPathPrefix.d.ts +1 -0
  819. package/dist/types/src/helpers/propertyNameFromFullyQualifiedModelName.d.ts +1 -0
  820. package/dist/types/src/helpers/protectAgainstPollutingAssignment.d.ts +1 -0
  821. package/dist/types/src/helpers/range.d.ts +7 -0
  822. package/dist/types/src/helpers/round.d.ts +2 -0
  823. package/dist/types/src/helpers/serializerNameFromFullyQualifiedModelName.d.ts +1 -0
  824. package/dist/types/src/helpers/snakeify.d.ts +3 -0
  825. package/dist/types/src/helpers/sortBy.d.ts +8 -0
  826. package/dist/types/src/helpers/sqlAttributes.d.ts +4 -0
  827. package/dist/types/src/helpers/sspawn.d.ts +2 -0
  828. package/dist/types/src/helpers/standardizeFullyQualifiedModelName.d.ts +1 -0
  829. package/dist/types/src/helpers/stringCasing.d.ts +28 -0
  830. package/dist/types/src/helpers/typechecks.d.ts +2 -0
  831. package/dist/types/src/helpers/typeutils.d.ts +115 -0
  832. package/dist/types/src/helpers/uncapitalize.d.ts +1 -0
  833. package/dist/types/src/helpers/uniq.d.ts +1 -0
  834. package/dist/types/src/index.d.ts +78 -0
  835. package/dist/types/src/openapi/types.d.ts +139 -0
  836. package/dist/types/src/ops/curried-ops-statement.d.ts +7 -0
  837. package/dist/types/src/ops/index.d.ts +49 -0
  838. package/dist/types/src/ops/ops-statement.d.ts +14 -0
  839. package/dist/types/src/serializer/decorators/associations/RendersMany.d.ts +42 -0
  840. package/dist/types/src/serializer/decorators/associations/RendersOne.d.ts +46 -0
  841. package/dist/types/src/serializer/decorators/associations/shared.d.ts +23 -0
  842. package/dist/types/src/serializer/decorators/attribute.d.ts +29 -0
  843. package/dist/types/src/serializer/decorators/helpers/dreamAttributeOpenapiShape.d.ts +7 -0
  844. package/dist/types/src/serializer/decorators/helpers/hasSerializersGetter.d.ts +2 -0
  845. package/dist/types/src/serializer/decorators/helpers/maybeSerializableToDreamSerializerCallbackFunction.d.ts +2 -0
  846. package/dist/types/src/serializer/index.d.ts +56 -0
  847. package/docs/.nojekyll +1 -0
  848. package/docs/assets/highlight.css +92 -0
  849. package/docs/assets/icons.js +18 -0
  850. package/docs/assets/icons.svg +1 -0
  851. package/docs/assets/main.js +60 -0
  852. package/docs/assets/navigation.js +1 -0
  853. package/docs/assets/search.js +1 -0
  854. package/docs/assets/style.css +1448 -0
  855. package/docs/classes/Benchmark.html +4 -0
  856. package/docs/classes/CalendarDate.html +34 -0
  857. package/docs/classes/CreateOrFindByFailedToCreateAndFind.html +12 -0
  858. package/docs/classes/Decorators.html +81 -0
  859. package/docs/classes/Dream.html +896 -0
  860. package/docs/classes/DreamApplication.html +37 -0
  861. package/docs/classes/DreamBin.html +11 -0
  862. package/docs/classes/DreamCLI.html +7 -0
  863. package/docs/classes/DreamImporter.html +6 -0
  864. package/docs/classes/DreamMigrationHelpers.html +32 -0
  865. package/docs/classes/DreamSerializer.html +19 -0
  866. package/docs/classes/DreamTransaction.html +5 -0
  867. package/docs/classes/Encrypt.html +8 -0
  868. package/docs/classes/Env.html +20 -0
  869. package/docs/classes/GlobalNameNotSet.html +12 -0
  870. package/docs/classes/NonLoadedAssociation.html +14 -0
  871. package/docs/classes/Query.html +383 -0
  872. package/docs/classes/Range.html +5 -0
  873. package/docs/classes/RecordNotFound.html +13 -0
  874. package/docs/classes/ValidationError.html +14 -0
  875. package/docs/functions/AfterCreate.html +1 -0
  876. package/docs/functions/AfterCreateCommit.html +13 -0
  877. package/docs/functions/AfterDestroy.html +1 -0
  878. package/docs/functions/AfterDestroyCommit.html +13 -0
  879. package/docs/functions/AfterSave.html +1 -0
  880. package/docs/functions/AfterSaveCommit.html +13 -0
  881. package/docs/functions/AfterUpdate.html +1 -0
  882. package/docs/functions/AfterUpdateCommit.html +13 -0
  883. package/docs/functions/Attribute.html +1 -0
  884. package/docs/functions/BeforeCreate.html +1 -0
  885. package/docs/functions/BeforeDestroy.html +1 -0
  886. package/docs/functions/BeforeSave.html +1 -0
  887. package/docs/functions/BeforeUpdate.html +1 -0
  888. package/docs/functions/RendersMany.html +16 -0
  889. package/docs/functions/RendersOne.html +16 -0
  890. package/docs/functions/ReplicaSafe.html +1 -0
  891. package/docs/functions/STI.html +1 -0
  892. package/docs/functions/Scope.html +1 -0
  893. package/docs/functions/SoftDelete.html +19 -0
  894. package/docs/functions/Sortable.html +1 -0
  895. package/docs/functions/Validate.html +1 -0
  896. package/docs/functions/Validates.html +1 -0
  897. package/docs/functions/Virtual.html +1 -0
  898. package/docs/functions/camelize.html +1 -0
  899. package/docs/functions/capitalize.html +1 -0
  900. package/docs/functions/closeAllDbConnections.html +1 -0
  901. package/docs/functions/compact.html +1 -0
  902. package/docs/functions/db.html +1 -0
  903. package/docs/functions/debug.html +1 -0
  904. package/docs/functions/dreamDbConnections.html +1 -0
  905. package/docs/functions/dreamPath.html +1 -0
  906. package/docs/functions/generateDream.html +1 -0
  907. package/docs/functions/globalClassNameFromFullyQualifiedModelName.html +1 -0
  908. package/docs/functions/hyphenize.html +1 -0
  909. package/docs/functions/inferSerializerFromDreamClassOrViewModelClass.html +1 -0
  910. package/docs/functions/inferSerializerFromDreamOrViewModel.html +1 -0
  911. package/docs/functions/isEmpty.html +1 -0
  912. package/docs/functions/loadRepl.html +1 -0
  913. package/docs/functions/lookupClassByGlobalName.html +1 -0
  914. package/docs/functions/pascalize.html +1 -0
  915. package/docs/functions/pgErrorType.html +1 -0
  916. package/docs/functions/range-1.html +1 -0
  917. package/docs/functions/relativeDreamPath.html +1 -0
  918. package/docs/functions/round.html +1 -0
  919. package/docs/functions/serializerNameFromFullyQualifiedModelName.html +1 -0
  920. package/docs/functions/sharedPathPrefix.html +1 -0
  921. package/docs/functions/snakeify.html +1 -0
  922. package/docs/functions/sortBy.html +1 -0
  923. package/docs/functions/standardizeFullyQualifiedModelName.html +1 -0
  924. package/docs/functions/uncapitalize.html +1 -0
  925. package/docs/functions/uniq.html +1 -0
  926. package/docs/functions/validateColumn.html +1 -0
  927. package/docs/functions/validateTable.html +1 -0
  928. package/docs/index.html +123 -0
  929. package/docs/interfaces/AttributeStatement.html +6 -0
  930. package/docs/interfaces/DecoratorContext.html +8 -0
  931. package/docs/interfaces/DreamApplicationInitOptions.html +2 -0
  932. package/docs/interfaces/DreamApplicationOpts.html +8 -0
  933. package/docs/interfaces/DreamSerializerAssociationStatement.html +11 -0
  934. package/docs/interfaces/EncryptOptions.html +3 -0
  935. package/docs/interfaces/OpenapiSchemaProperties.html +1 -0
  936. package/docs/interfaces/OpenapiSchemaPropertiesShorthand.html +1 -0
  937. package/docs/interfaces/OpenapiTypeFieldObject.html +1 -0
  938. package/docs/modules.html +163 -0
  939. package/docs/types/Camelized.html +1 -0
  940. package/docs/types/CommonOpenapiSchemaObjectFields.html +1 -0
  941. package/docs/types/DreamAssociationMetadata.html +1 -0
  942. package/docs/types/DreamAttributes.html +1 -0
  943. package/docs/types/DreamClassColumn.html +1 -0
  944. package/docs/types/DreamColumn.html +1 -0
  945. package/docs/types/DreamColumnNames.html +1 -0
  946. package/docs/types/DreamLogLevel.html +1 -0
  947. package/docs/types/DreamLogger.html +1 -0
  948. package/docs/types/DreamOrViewModelSerializerKey.html +1 -0
  949. package/docs/types/DreamParamSafeAttributes.html +1 -0
  950. package/docs/types/DreamParamSafeColumnNames.html +1 -0
  951. package/docs/types/DreamSerializerKey.html +1 -0
  952. package/docs/types/DreamSerializers.html +1 -0
  953. package/docs/types/DreamTableSchema.html +1 -0
  954. package/docs/types/DreamVirtualColumns.html +1 -0
  955. package/docs/types/EncryptAlgorithm.html +1 -0
  956. package/docs/types/Hyphenized.html +1 -0
  957. package/docs/types/IdType.html +1 -0
  958. package/docs/types/OpenapiAllTypes.html +1 -0
  959. package/docs/types/OpenapiFormats.html +1 -0
  960. package/docs/types/OpenapiNumberFormats.html +1 -0
  961. package/docs/types/OpenapiPrimitiveTypes.html +1 -0
  962. package/docs/types/OpenapiSchemaArray.html +1 -0
  963. package/docs/types/OpenapiSchemaArrayShorthand.html +1 -0
  964. package/docs/types/OpenapiSchemaBase.html +1 -0
  965. package/docs/types/OpenapiSchemaBody.html +1 -0
  966. package/docs/types/OpenapiSchemaBodyShorthand.html +1 -0
  967. package/docs/types/OpenapiSchemaCommonFields.html +1 -0
  968. package/docs/types/OpenapiSchemaExpressionAllOf.html +1 -0
  969. package/docs/types/OpenapiSchemaExpressionAnyOf.html +1 -0
  970. package/docs/types/OpenapiSchemaExpressionOneOf.html +1 -0
  971. package/docs/types/OpenapiSchemaExpressionRef.html +1 -0
  972. package/docs/types/OpenapiSchemaExpressionRefSchemaShorthand.html +1 -0
  973. package/docs/types/OpenapiSchemaInteger.html +1 -0
  974. package/docs/types/OpenapiSchemaNull.html +1 -0
  975. package/docs/types/OpenapiSchemaNumber.html +1 -0
  976. package/docs/types/OpenapiSchemaObject.html +1 -0
  977. package/docs/types/OpenapiSchemaObjectAllOf.html +1 -0
  978. package/docs/types/OpenapiSchemaObjectAllOfShorthand.html +1 -0
  979. package/docs/types/OpenapiSchemaObjectAnyOf.html +1 -0
  980. package/docs/types/OpenapiSchemaObjectAnyOfShorthand.html +1 -0
  981. package/docs/types/OpenapiSchemaObjectBase.html +1 -0
  982. package/docs/types/OpenapiSchemaObjectBaseShorthand.html +1 -0
  983. package/docs/types/OpenapiSchemaObjectOneOf.html +1 -0
  984. package/docs/types/OpenapiSchemaObjectOneOfShorthand.html +1 -0
  985. package/docs/types/OpenapiSchemaObjectShorthand.html +1 -0
  986. package/docs/types/OpenapiSchemaPartialSegment.html +1 -0
  987. package/docs/types/OpenapiSchemaPrimitiveGeneric.html +1 -0
  988. package/docs/types/OpenapiSchemaShorthandExpressionAllOf.html +1 -0
  989. package/docs/types/OpenapiSchemaShorthandExpressionAnyOf.html +1 -0
  990. package/docs/types/OpenapiSchemaShorthandExpressionOneOf.html +1 -0
  991. package/docs/types/OpenapiSchemaShorthandExpressionSerializableRef.html +1 -0
  992. package/docs/types/OpenapiSchemaShorthandExpressionSerializerRef.html +1 -0
  993. package/docs/types/OpenapiSchemaShorthandPrimitiveGeneric.html +1 -0
  994. package/docs/types/OpenapiSchemaString.html +1 -0
  995. package/docs/types/OpenapiShorthandAllTypes.html +1 -0
  996. package/docs/types/OpenapiShorthandPrimitiveTypes.html +1 -0
  997. package/docs/types/OpenapiTypeField.html +1 -0
  998. package/docs/types/Pascalized.html +1 -0
  999. package/docs/types/PrimaryKeyType.html +1 -0
  1000. package/docs/types/RoundingPrecision.html +1 -0
  1001. package/docs/types/SerializableClassOrSerializerCallback.html +1 -0
  1002. package/docs/types/SerializableDreamClassOrViewModelClass.html +1 -0
  1003. package/docs/types/SerializableDreamOrViewModel.html +1 -0
  1004. package/docs/types/SerializableTypes.html +1 -0
  1005. package/docs/types/Snakeified.html +1 -0
  1006. package/docs/types/Timestamp.html +1 -0
  1007. package/docs/types/UpdateableAssociationProperties.html +1 -0
  1008. package/docs/types/UpdateableProperties.html +1 -0
  1009. package/docs/types/ValidationType.html +1 -0
  1010. package/docs/types/ViewModelSerializerKey.html +1 -0
  1011. package/docs/types/WhereStatementForDream.html +1 -0
  1012. package/docs/types/WhereStatementForDreamClass.html +1 -0
  1013. package/docs/variables/DreamConst.html +1 -0
  1014. package/docs/variables/TRIGRAM_OPERATORS.html +1 -0
  1015. package/docs/variables/openapiPrimitiveTypes-1.html +1 -0
  1016. package/docs/variables/openapiShorthandPrimitiveTypes-1.html +1 -0
  1017. package/docs/variables/ops.html +1 -0
  1018. package/docs/variables/primaryKeyTypes.html +1 -0
  1019. package/package.json +83 -0
@@ -0,0 +1,2618 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const kysely_1 = require("kysely");
4
+ const luxon_1 = require("luxon");
5
+ const pluralize_esm_1 = require("pluralize-esm");
6
+ const ConnectedToDB_js_1 = require("../db/ConnectedToDB.js");
7
+ const associationToGetterSetterProp_js_1 = require("../decorators/associations/associationToGetterSetterProp.js");
8
+ const SoftDelete_js_1 = require("../decorators/SoftDelete.js");
9
+ const CannotAssociateThroughPolymorphic_js_1 = require("../errors/associations/CannotAssociateThroughPolymorphic.js");
10
+ const CannotJoinPolymorphicBelongsToError_js_1 = require("../errors/associations/CannotJoinPolymorphicBelongsToError.js");
11
+ const JoinAttemptedOnMissingAssociation_js_1 = require("../errors/associations/JoinAttemptedOnMissingAssociation.js");
12
+ const MissingRequiredAssociationOnClause_js_1 = require("../errors/associations/MissingRequiredAssociationOnClause.js");
13
+ const MissingRequiredPassthroughForAssociationOnClause_js_1 = require("../errors/associations/MissingRequiredPassthroughForAssociationOnClause.js");
14
+ const MissingThroughAssociation_js_1 = require("../errors/associations/MissingThroughAssociation.js");
15
+ const MissingThroughAssociationSource_js_1 = require("../errors/associations/MissingThroughAssociationSource.js");
16
+ const CannotCallUndestroyOnANonSoftDeleteModel_js_1 = require("../errors/CannotCallUndestroyOnANonSoftDeleteModel.js");
17
+ const CannotNegateSimilarityClause_js_1 = require("../errors/CannotNegateSimilarityClause.js");
18
+ const CannotPassAdditionalFieldsToPluckEachAfterCallback_js_1 = require("../errors/CannotPassAdditionalFieldsToPluckEachAfterCallback.js");
19
+ const CannotPassUndefinedAsAValueToAWhereClause_js_1 = require("../errors/CannotPassUndefinedAsAValueToAWhereClause.js");
20
+ const LeftJoinPreloadIncompatibleWithFindEach_js_1 = require("../errors/LeftJoinPreloadIncompatibleWithFindEach.js");
21
+ const MissingRequiredCallbackFunctionToPluckEach_js_1 = require("../errors/MissingRequiredCallbackFunctionToPluckEach.js");
22
+ const NoUpdateAllOnJoins_js_1 = require("../errors/NoUpdateAllOnJoins.js");
23
+ const NoUpdateOnAssociationQuery_js_1 = require("../errors/NoUpdateOnAssociationQuery.js");
24
+ const RecordNotFound_js_1 = require("../errors/RecordNotFound.js");
25
+ const CalendarDate_js_1 = require("../helpers/CalendarDate.js");
26
+ const camelize_js_1 = require("../helpers/camelize.js");
27
+ const cloneDeepSafe_js_1 = require("../helpers/cloneDeepSafe.js");
28
+ const compact_js_1 = require("../helpers/compact.js");
29
+ const isEmpty_js_1 = require("../helpers/isEmpty.js");
30
+ const namespaceColumn_js_1 = require("../helpers/namespaceColumn.js");
31
+ const objectPathsToArrays_js_1 = require("../helpers/objectPathsToArrays.js");
32
+ const protectAgainstPollutingAssignment_js_1 = require("../helpers/protectAgainstPollutingAssignment.js");
33
+ const range_js_1 = require("../helpers/range.js");
34
+ const snakeify_js_1 = require("../helpers/snakeify.js");
35
+ const typechecks_js_1 = require("../helpers/typechecks.js");
36
+ const uniq_js_1 = require("../helpers/uniq.js");
37
+ const curried_ops_statement_js_1 = require("../ops/curried-ops-statement.js");
38
+ const index_js_1 = require("../ops/index.js");
39
+ const ops_statement_js_1 = require("../ops/ops-statement.js");
40
+ const executeDatabaseQuery_js_1 = require("./internal/executeDatabaseQuery.js");
41
+ const extractAssociationMetadataFromAssociationName_js_1 = require("./internal/extractAssociationMetadataFromAssociationName.js");
42
+ const orderByDirection_js_1 = require("./internal/orderByDirection.js");
43
+ const shouldBypassDefaultScope_js_1 = require("./internal/shouldBypassDefaultScope.js");
44
+ const SimilarityBuilder_js_1 = require("./internal/similarity/SimilarityBuilder.js");
45
+ const sqlResultToDreamInstance_js_1 = require("./internal/sqlResultToDreamInstance.js");
46
+ const types_js_1 = require("./types.js");
47
+ class Query extends ConnectedToDB_js_1.default {
48
+ /**
49
+ * @internal
50
+ *
51
+ * stores the default batch sizes for various
52
+ * provided batching methods
53
+ */
54
+ static BATCH_SIZES = {
55
+ FIND_EACH: 1000,
56
+ PLUCK_EACH: 10000,
57
+ PLUCK_EACH_THROUGH: 1000,
58
+ };
59
+ /**
60
+ * @internal
61
+ * purely for typing
62
+ */
63
+ queryTypeOpts;
64
+ /**
65
+ * @internal
66
+ *
67
+ * stores the dream transaction applied to the
68
+ * current Query instance
69
+ */
70
+ dreamTransaction = null;
71
+ /**
72
+ * @internal
73
+ *
74
+ * stores the passthrough on statements applied to the
75
+ * current Query instance
76
+ */
77
+ passthroughOnStatement = Object.freeze({});
78
+ /**
79
+ * @internal
80
+ *
81
+ * stores the where statements applied to the
82
+ * current Query instance
83
+ */
84
+ whereStatements = Object.freeze([]);
85
+ /**
86
+ * @internal
87
+ *
88
+ * stores the where not statements applied to the
89
+ * current Query instance
90
+ */
91
+ whereNotStatements = Object.freeze([]);
92
+ /**
93
+ * @internal
94
+ *
95
+ * stores the limit statements applied to the
96
+ * current Query instance
97
+ */
98
+ limitStatement;
99
+ /**
100
+ * @internal
101
+ *
102
+ * stores the offset statements applied to the
103
+ * current Query instance
104
+ */
105
+ offsetStatement;
106
+ /**
107
+ * @internal
108
+ *
109
+ * stores the or statements applied to the
110
+ * current Query instance
111
+ */
112
+ whereAnyStatements = Object.freeze([]);
113
+ /**
114
+ * @internal
115
+ *
116
+ * stores the order statements applied to the
117
+ * current Query instance
118
+ */
119
+ orderStatements = Object.freeze([]);
120
+ /**
121
+ * @internal
122
+ *
123
+ * whether or not to turn joins into load statements
124
+ */
125
+ joinLoadActivated = false;
126
+ /**
127
+ * @internal
128
+ *
129
+ * stores the preload statements applied to the
130
+ * current Query instance
131
+ */
132
+ preloadStatements = Object.freeze({});
133
+ /**
134
+ * @internal
135
+ *
136
+ * stores the preload on statements applied to the
137
+ * current Query instance
138
+ */
139
+ preloadOnStatements = Object.freeze({});
140
+ /**
141
+ * @internal
142
+ *
143
+ * stores the joins statements applied to the
144
+ * current Query instance
145
+ */
146
+ innerJoinStatements = Object.freeze({});
147
+ /**
148
+ * @internal
149
+ *
150
+ * stores the joins on statements applied to the
151
+ * current Query instance
152
+ */
153
+ innerJoinOnStatements = Object.freeze({});
154
+ /**
155
+ * @internal
156
+ *
157
+ * stores the joins statements applied to the
158
+ * current Query instance
159
+ */
160
+ leftJoinStatements = Object.freeze({});
161
+ /**
162
+ * @internal
163
+ *
164
+ * stores the joins on statements applied to the
165
+ * current Query instance
166
+ */
167
+ leftJoinOnStatements = Object.freeze({});
168
+ /**
169
+ * @internal
170
+ *
171
+ * Whether or not to bypass all default scopes for this Query
172
+ */
173
+ bypassAllDefaultScopes = false;
174
+ /**
175
+ * @internal
176
+ *
177
+ * Whether or not to bypass all default scopes for this Query, but not associations
178
+ */
179
+ bypassAllDefaultScopesExceptOnAssociations = false;
180
+ /**
181
+ * @internal
182
+ *
183
+ * Specific default scopes to bypass
184
+ */
185
+ defaultScopesToBypass = [];
186
+ /**
187
+ * @internal
188
+ *
189
+ * Specific default scopes to bypass, but not associations
190
+ */
191
+ defaultScopesToBypassExceptOnAssociations = [];
192
+ /**
193
+ * @internal
194
+ *
195
+ * Whether or not to bypass SoftDelete and really destroy a record
196
+ * when calling destroy.
197
+ */
198
+ shouldReallyDestroy = false;
199
+ /**
200
+ * @internal
201
+ *
202
+ * The distinct column to apply to the Query
203
+ */
204
+ distinctColumn = null;
205
+ /**
206
+ * @internal
207
+ *
208
+ * The base sql alias to use for the base model
209
+ * of this Query
210
+ */
211
+ baseSqlAlias;
212
+ get tableName() {
213
+ return this.dreamClass.table;
214
+ }
215
+ get namespacedPrimaryKey() {
216
+ return (0, namespaceColumn_js_1.default)(this.dreamClass.primaryKey, this.baseSqlAlias);
217
+ }
218
+ /**
219
+ * @internal
220
+ *
221
+ * Used for unscoping Query instances. In most cases, this will be null,
222
+ * but when calling `removeAllDefaultScopes`, a removeAllDefaultScopes Query is stored as
223
+ * baseSelectQuery.
224
+ */
225
+ baseSelectQuery;
226
+ constructor(dreamInstance, opts = {}) {
227
+ super(dreamInstance, opts);
228
+ this.passthroughOnStatement = Object.freeze(opts.passthroughOnStatement || {});
229
+ this.whereStatements = Object.freeze(opts.where || []);
230
+ this.whereNotStatements = Object.freeze(opts.whereNot || []);
231
+ this.whereAnyStatements = Object.freeze(opts.or || []);
232
+ this.orderStatements = Object.freeze(opts.order || []);
233
+ this.joinLoadActivated = opts.loadFromJoins || false;
234
+ this.preloadStatements = Object.freeze(opts.preloadStatements || {});
235
+ this.preloadOnStatements = Object.freeze(opts.preloadOnStatements || {});
236
+ this.innerJoinStatements = Object.freeze(opts.innerJoinStatements || {});
237
+ this.innerJoinOnStatements = Object.freeze(opts.innerJoinOnStatements || {});
238
+ this.leftJoinStatements = Object.freeze(opts.leftJoinStatements || {});
239
+ this.leftJoinOnStatements = Object.freeze(opts.leftJoinOnStatements || {});
240
+ this.baseSqlAlias = opts.baseSqlAlias || this.tableName;
241
+ this.baseSelectQuery = opts.baseSelectQuery || null;
242
+ this.limitStatement = opts.limit || null;
243
+ this.offsetStatement = opts.offset || null;
244
+ this.bypassAllDefaultScopes = opts.bypassAllDefaultScopes || false;
245
+ this.bypassAllDefaultScopesExceptOnAssociations = opts.bypassAllDefaultScopesExceptOnAssociations || false;
246
+ this.defaultScopesToBypass = opts.defaultScopesToBypass || [];
247
+ this.defaultScopesToBypassExceptOnAssociations = opts.defaultScopesToBypassExceptOnAssociations || [];
248
+ this.dreamTransaction = opts.transaction || null;
249
+ this.distinctColumn = opts.distinctColumn || null;
250
+ this.connectionOverride = opts.connection;
251
+ this.shouldReallyDestroy = opts.shouldReallyDestroy || false;
252
+ }
253
+ /**
254
+ * Returns true. Useful for distinguishing Query instances
255
+ * from other objects.
256
+ *
257
+ * @returns true
258
+ */
259
+ get isDreamQuery() {
260
+ return true;
261
+ }
262
+ /**
263
+ * @internal
264
+ *
265
+ * Used for applying preload and load statements
266
+ *
267
+ * @returns An associated Query
268
+ */
269
+ dreamClassQueryWithScopeBypasses(dreamClass, { bypassAllDefaultScopesExceptOnAssociations = false, defaultScopesToBypassExceptOnAssociations = [], } = {}) {
270
+ const associationQuery = dreamClass.query().clone({
271
+ passthroughOnStatement: this.passthroughOnStatement,
272
+ bypassAllDefaultScopes: this.bypassAllDefaultScopes,
273
+ bypassAllDefaultScopesExceptOnAssociations,
274
+ defaultScopesToBypass: this.defaultScopesToBypass,
275
+ defaultScopesToBypassExceptOnAssociations,
276
+ });
277
+ return (this.dreamTransaction ? associationQuery.txn(this.dreamTransaction) : associationQuery);
278
+ }
279
+ /**
280
+ * @internal
281
+ *
282
+ * Returns a cloned version of the Query
283
+ *
284
+ * ```ts
285
+ * const clonedQuery = User.query().clone()
286
+ * ```
287
+ *
288
+ * @param opts - Statements to override when cloning the Query
289
+ * @returns A cloned Query with the provided overrides clause applied
290
+ */
291
+ clone(opts = {}) {
292
+ return new Query(this.dreamInstance, {
293
+ baseSqlAlias: opts.baseSqlAlias || this.baseSqlAlias,
294
+ baseSelectQuery: opts.baseSelectQuery || this.baseSelectQuery,
295
+ passthroughOnStatement: {
296
+ ...this.passthroughOnStatement,
297
+ ...(opts.passthroughOnStatement || {}),
298
+ },
299
+ where: opts.where === null ? [] : [...this.whereStatements, ...(opts.where || [])],
300
+ whereNot: opts.whereNot === null ? [] : [...this.whereNotStatements, ...(opts.whereNot || [])],
301
+ limit: opts.limit === null ? null : opts.limit !== undefined ? opts.limit : this.limitStatement || null,
302
+ offset: opts.limit === null || opts.offset === null
303
+ ? null
304
+ : opts.offset !== undefined
305
+ ? opts.offset
306
+ : this.offsetStatement || null,
307
+ or: opts.or === null ? [] : [...this.whereAnyStatements, ...(opts.or || [])],
308
+ order: opts.order === null ? [] : [...this.orderStatements, ...(opts.order || [])],
309
+ distinctColumn: opts.distinctColumn !== undefined ? opts.distinctColumn : this.distinctColumn,
310
+ loadFromJoins: opts.loadFromJoins !== undefined ? opts.loadFromJoins : this.joinLoadActivated,
311
+ // when passed, preloadStatements, preloadOnStatements, innerJoinStatements, and innerJoinOnStatements are already
312
+ // cloned versions of the `this.` versions, handled in the `preload` and `joins` methods
313
+ preloadStatements: opts.preloadStatements || this.preloadStatements,
314
+ preloadOnStatements: opts.preloadOnStatements || this.preloadOnStatements,
315
+ innerJoinDreamClasses: opts.innerJoinDreamClasses || this.innerJoinDreamClasses,
316
+ innerJoinStatements: opts.innerJoinStatements || this.innerJoinStatements,
317
+ innerJoinOnStatements: opts.innerJoinOnStatements || this.innerJoinOnStatements,
318
+ leftJoinStatements: opts.leftJoinStatements || this.leftJoinStatements,
319
+ leftJoinOnStatements: opts.leftJoinOnStatements || this.leftJoinOnStatements,
320
+ // end:when passed, preloadStatements, preloadOnStatements, innerJoinStatements, and innerJoinOnStatements are already...
321
+ bypassAllDefaultScopes: opts.bypassAllDefaultScopes !== undefined ? opts.bypassAllDefaultScopes : this.bypassAllDefaultScopes,
322
+ bypassAllDefaultScopesExceptOnAssociations: opts.bypassAllDefaultScopesExceptOnAssociations !== undefined
323
+ ? opts.bypassAllDefaultScopesExceptOnAssociations
324
+ : this.bypassAllDefaultScopesExceptOnAssociations,
325
+ defaultScopesToBypass: opts.defaultScopesToBypass !== undefined ? opts.defaultScopesToBypass : this.defaultScopesToBypass,
326
+ defaultScopesToBypassExceptOnAssociations: opts.defaultScopesToBypassExceptOnAssociations !== undefined
327
+ ? opts.defaultScopesToBypassExceptOnAssociations
328
+ : this.defaultScopesToBypassExceptOnAssociations,
329
+ transaction: opts.transaction || this.dreamTransaction,
330
+ connection: opts.connection || this.connectionOverride,
331
+ shouldReallyDestroy: opts.shouldReallyDestroy !== undefined ? opts.shouldReallyDestroy : this.shouldReallyDestroy,
332
+ });
333
+ }
334
+ /**
335
+ * Finds a record matching the Query with the
336
+ * specified primary key. If not found, null
337
+ * is returned.
338
+ *
339
+ * ```ts
340
+ * await User.query().find(123)
341
+ * // User{id: 123}
342
+ * ```
343
+ *
344
+ * @param primaryKey - The primary key of the record to look up
345
+ * @returns Either the found record, or else null
346
+ */
347
+ async find(primaryKey) {
348
+ if (!primaryKey)
349
+ return null;
350
+ return await this.where({
351
+ [this.dreamInstance.primaryKey]: primaryKey,
352
+ }).first();
353
+ }
354
+ /**
355
+ * Finds a record matching the Query with the
356
+ * specified primary key. If not found, an exception
357
+ * is raised.
358
+ *
359
+ * ```ts
360
+ * await User.query().findOrFail(123)
361
+ * // User{id: 123}
362
+ * ```
363
+ *
364
+ * @param primaryKey - The primary key of the record to look up
365
+ * @returns The found record
366
+ */
367
+ async findOrFail(primaryKey) {
368
+ const record = await this.find(primaryKey);
369
+ if (!record)
370
+ throw new RecordNotFound_js_1.default(this.dreamInstance.constructor.name);
371
+ return record;
372
+ }
373
+ /**
374
+ * Finds a record matching the Query and the
375
+ * specified where statement. If not found, null
376
+ * is returned.
377
+ *
378
+ * ```ts
379
+ * await User.query().findBy({ email: 'how@yadoin' })
380
+ * // User{email: 'how@yadoin'}
381
+ * ```
382
+ *
383
+ * @param whereStatement - The where statement used to locate the record
384
+ * @returns Either the first record found matching the attributes, or else null
385
+ */
386
+ async findBy(whereStatement) {
387
+ return await this._where(whereStatement, 'where').first();
388
+ }
389
+ /**
390
+ * Finds a record matching the Query and the
391
+ * specified where statement. If not found, an exception
392
+ * is raised.
393
+ *
394
+ * ```ts
395
+ * await User.query().findOrFailBy({ email: 'how@yadoin' })
396
+ * // User{email: 'how@yadoin'}
397
+ * ```
398
+ *
399
+ * @param whereStatement - The where statement used to locate the record
400
+ * @returns The first record found matching the attributes
401
+ */
402
+ async findOrFailBy(whereStatement) {
403
+ const record = await this.findBy(whereStatement);
404
+ if (!record)
405
+ throw new RecordNotFound_js_1.default(this.dreamInstance.constructor.name);
406
+ return record;
407
+ }
408
+ /**
409
+ * Finds all records matching the Query in batches,
410
+ * and then calls the provided callback for each found record.
411
+ * Once all records have been passed for a given batch, the next set of
412
+ * records will be fetched and passed to your callback, until all
413
+ * records matching the Query have been fetched.
414
+ *
415
+ * ```ts
416
+ * await User.order('id').findEach(user => {
417
+ * DreamApplication.log(user)
418
+ * })
419
+ * // User{id: 1}
420
+ * // User{id: 2}
421
+ * ```
422
+ *
423
+ * @param cb - The callback to call for each found record
424
+ * @param options - Options for destroying the instance
425
+ * @param options.batchSize - The batch size you wish to collect records in. If not provided, it will default to 1000
426
+ * @returns void
427
+ */
428
+ async findEach(cb, { batchSize = Query.BATCH_SIZES.FIND_EACH } = {}) {
429
+ if (this.joinLoadActivated)
430
+ throw new LeftJoinPreloadIncompatibleWithFindEach_js_1.default();
431
+ let records;
432
+ const query = this.order(null)
433
+ .order(this.namespacedPrimaryKey)
434
+ .limit(batchSize);
435
+ let lastId = null;
436
+ do {
437
+ if (lastId)
438
+ records = await query.where({ [this.dreamInstance.primaryKey]: index_js_1.default.greaterThan(lastId) }).all();
439
+ else
440
+ records = await query.all();
441
+ for (const record of records) {
442
+ await cb(record);
443
+ }
444
+ lastId = records[records.length - 1]?.primaryKeyValue;
445
+ } while (records.length > 0 && records.length === batchSize);
446
+ }
447
+ /**
448
+ * Load each specified association using a single SQL query.
449
+ * See {@link #preload} for preloading in separate queries.
450
+ *
451
+ * Note: since leftJoinPreload loads via single query, it has
452
+ * some downsides and that may be avoided using {@link #preload}:
453
+ * 1. `limit` and `offset` will be automatically removed
454
+ * 2. `through` associations will bring additional namespaces into the query that can conflict with through associations from other associations, creating an invalid query
455
+ * 3. each nested association will result in an additional record which duplicates data from the outer record. E.g., given `.leftJoinPreload('a', 'b', 'c')`, if each `a` has 10 `b` and each `b` has 10 `c`, then for one `a`, 100 records will be returned, each of which has all of the columns of `a`. `.preload('a', 'b', 'c')` would perform three separate SQL queries, but the data for a single `a` would only be returned once.
456
+ * 4. the individual query becomes more complex the more associations are included
457
+ * 5. associations loading associations loading associations could result in exponential amounts of data; in those cases, `.preload(...).findEach(...)` avoids instantiating massive amounts of data at once
458
+ *
459
+ *
460
+ * ```ts
461
+ * const posts = await user.associationQuery('posts').leftJoinPreload('comments', { visibilty: 'public' }, 'replies').all()
462
+ * console.log(posts[0].comments[0].replies[0])
463
+ * // [Reply{id: 1}, Reply{id: 2}]
464
+ * ```
465
+ *
466
+ * @param args - A chain of association names and on/notOn/onAny clauses
467
+ * @returns A cloned Query with the joinLoad statement applied
468
+ */
469
+ leftJoinPreload(...args) {
470
+ const untypedArgs = [...args];
471
+ const lastAssociations = [untypedArgs.pop()].flat();
472
+ let joinedClone = this;
473
+ lastAssociations.forEach(associationName => {
474
+ joinedClone = joinedClone.leftJoin(...untypedArgs, associationName);
475
+ });
476
+ return joinedClone.clone({ loadFromJoins: true });
477
+ }
478
+ /**
479
+ * Load each specified association using a separate SQL query.
480
+ * See {@link #leftJoinPreload} for preloading in a single query.
481
+ *
482
+ * ```ts
483
+ * const user = await User.query().preload('posts', 'comments', { visibilty: 'public' }, 'replies').first()
484
+ * console.log(user.posts[0].comments[0].replies[0])
485
+ * // [Reply{id: 1}, Reply{id: 2}]
486
+ * ```
487
+ *
488
+ * @param args - A chain of association names and on/notOn/onAny clauses
489
+ * @returns A cloned Query with the preload statement applied
490
+ */
491
+ preload(...args) {
492
+ const preloadStatements = (0, cloneDeepSafe_js_1.default)(this.preloadStatements);
493
+ const preloadOnStatements = (0, cloneDeepSafe_js_1.default)(this.preloadOnStatements);
494
+ this.fleshOutJoinStatements([], preloadStatements, preloadOnStatements, null, [...args]);
495
+ return this.clone({ preloadStatements, preloadOnStatements: preloadOnStatements });
496
+ }
497
+ /**
498
+ * Returns a new Query instance, with the provided
499
+ * joins statement attached
500
+ *
501
+ * ```ts
502
+ * await User.query().innerJoin('posts').first()
503
+ * ```
504
+ *
505
+ * @param args - A chain of association names and on/notOn/onAny clauses
506
+ * @returns A cloned Query with the joins clause applied
507
+ */
508
+ innerJoin(...args) {
509
+ const innerJoinDreamClasses = [...this.innerJoinDreamClasses];
510
+ const innerJoinStatements = (0, cloneDeepSafe_js_1.default)(this.innerJoinStatements);
511
+ const innerJoinOnStatements = (0, cloneDeepSafe_js_1.default)(this.innerJoinOnStatements);
512
+ this.fleshOutJoinStatements(innerJoinDreamClasses, innerJoinStatements, innerJoinOnStatements, null, [...args]);
513
+ return this.clone({ innerJoinDreamClasses, innerJoinStatements, innerJoinOnStatements });
514
+ }
515
+ /**
516
+ * @internal
517
+ *
518
+ * @param args - A chain of association names and on/notOn/onAny clauses
519
+ * @returns A cloned Query with the joins clause applied
520
+ */
521
+ leftJoin(...args) {
522
+ const innerJoinDreamClasses = [...this.innerJoinDreamClasses];
523
+ const leftJoinStatements = (0, cloneDeepSafe_js_1.default)(this.leftJoinStatements);
524
+ const leftJoinOnStatements = (0, cloneDeepSafe_js_1.default)(this.leftJoinOnStatements);
525
+ this.fleshOutJoinStatements(innerJoinDreamClasses, leftJoinStatements, leftJoinOnStatements, null, [
526
+ ...args,
527
+ ]);
528
+ return this.clone({ innerJoinDreamClasses, leftJoinStatements, leftJoinOnStatements });
529
+ }
530
+ /**
531
+ * @internal
532
+ *
533
+ */
534
+ fleshOutJoinStatements(innerJoinDreamClasses, joinStatements, joinOnStatements, previousAssociationName, associationStatements, previousDreamClass = this.dreamClass) {
535
+ const nextAssociationStatement = associationStatements.shift();
536
+ if (nextAssociationStatement === undefined) {
537
+ // just satisfying typing
538
+ }
539
+ else if ((0, typechecks_js_1.isString)(nextAssociationStatement)) {
540
+ const nextStatement = nextAssociationStatement;
541
+ if (!joinStatements[nextStatement])
542
+ joinStatements[(0, protectAgainstPollutingAssignment_js_1.default)(nextStatement)] = {};
543
+ if (!joinOnStatements[nextStatement])
544
+ joinOnStatements[(0, protectAgainstPollutingAssignment_js_1.default)(nextStatement)] = {};
545
+ const nextDreamClass = this.addAssociatedDreamClassToInnerJoinDreamClasses(previousDreamClass, nextStatement, innerJoinDreamClasses);
546
+ const nextJoinsStatements = joinStatements[nextStatement];
547
+ const nextJoinsOnStatements = joinOnStatements[nextStatement];
548
+ this.fleshOutJoinStatements(innerJoinDreamClasses, nextJoinsStatements, nextJoinsOnStatements, nextStatement, associationStatements, nextDreamClass);
549
+ //
550
+ }
551
+ else if (Array.isArray(nextAssociationStatement)) {
552
+ // this supports the final argument of load/preload statements
553
+ nextAssociationStatement.forEach((associationName) => {
554
+ this.addAssociatedDreamClassToInnerJoinDreamClasses(previousDreamClass, associationName, innerJoinDreamClasses);
555
+ });
556
+ nextAssociationStatement.forEach(associationStatement => {
557
+ joinStatements[(0, protectAgainstPollutingAssignment_js_1.default)(associationStatement)] = {};
558
+ });
559
+ //
560
+ }
561
+ else if ((0, typechecks_js_1.isObject)(nextAssociationStatement) && previousAssociationName) {
562
+ const clonedNextAssociationStatement = (0, cloneDeepSafe_js_1.default)(nextAssociationStatement);
563
+ const keys = Object.keys(clonedNextAssociationStatement);
564
+ keys.forEach((key) => {
565
+ joinOnStatements[(0, protectAgainstPollutingAssignment_js_1.default)(key)] = clonedNextAssociationStatement[key];
566
+ });
567
+ this.fleshOutJoinStatements(innerJoinDreamClasses, joinStatements, joinOnStatements, previousAssociationName, associationStatements, previousDreamClass);
568
+ }
569
+ }
570
+ /**
571
+ * @internal
572
+ *
573
+ *
574
+ */
575
+ associationNamesToDreamClassesMap(associationNames, associationsToDreamClassesMap = {}) {
576
+ const namesToAssociationsAndDreamClasses = this.associationNamesToAssociationDataAndDreamClassesMap(associationNames);
577
+ return Object.keys(namesToAssociationsAndDreamClasses).reduce((remap, associationName) => {
578
+ remap[associationName] = namesToAssociationsAndDreamClasses[associationName].dreamClass;
579
+ return remap;
580
+ }, associationsToDreamClassesMap);
581
+ }
582
+ /**
583
+ * @internal
584
+ *
585
+ *
586
+ */
587
+ associationNamesToAssociationsMap(associationNames, associationsToAssociations = {}) {
588
+ const namesToAssociationsAndDreamClasses = this.associationNamesToAssociationDataAndDreamClassesMap(associationNames);
589
+ return Object.keys(namesToAssociationsAndDreamClasses).reduce((remap, associationName) => {
590
+ remap[associationName] = namesToAssociationsAndDreamClasses[associationName].association;
591
+ return remap;
592
+ }, associationsToAssociations);
593
+ }
594
+ /**
595
+ * @internal
596
+ */
597
+ associationNamesToAssociationDataAndDreamClassesMap(associationNames) {
598
+ const associationsToDreamClassesMap = {};
599
+ associationNames.reduce((dreamClass, associationName) => {
600
+ const { name, alias } = (0, extractAssociationMetadataFromAssociationName_js_1.default)(associationName);
601
+ const association = dreamClass['getAssociationMetadata'](name);
602
+ const through = association.through;
603
+ if (through) {
604
+ const { throughAssociation, throughAssociationDreamClass } = this.throughAssociationDetails(dreamClass, through);
605
+ associationsToDreamClassesMap[through] = {
606
+ association: throughAssociation,
607
+ dreamClass: throughAssociationDreamClass,
608
+ };
609
+ }
610
+ const nextDreamClass = association.modelCB();
611
+ associationsToDreamClassesMap[alias] = { association, dreamClass: nextDreamClass };
612
+ return nextDreamClass;
613
+ }, this.dreamClass);
614
+ return associationsToDreamClassesMap;
615
+ }
616
+ /**
617
+ * @internal
618
+ */
619
+ throughAssociationDetails(dreamClass, through) {
620
+ const throughAssociation = dreamClass['getAssociationMetadata'](through);
621
+ const throughAssociationDreamClass = throughAssociation.modelCB();
622
+ return { throughAssociation, throughAssociationDreamClass };
623
+ }
624
+ /**
625
+ * @internal
626
+ *
627
+ *
628
+ */
629
+ joinStatementsToDreamClassesMap(joinStatements) {
630
+ const associationsToDreamClassesMap = {};
631
+ (0, objectPathsToArrays_js_1.default)(joinStatements).forEach(associationChain => this.associationNamesToDreamClassesMap(associationChain, associationsToDreamClassesMap));
632
+ return associationsToDreamClassesMap;
633
+ }
634
+ /**
635
+ * @internal
636
+ *
637
+ *
638
+ */
639
+ joinStatementsToAssociationsMap(joinStatements) {
640
+ const associationsToAssociationsMap = {};
641
+ (0, objectPathsToArrays_js_1.default)(joinStatements).forEach(associationChain => this.associationNamesToAssociationsMap(associationChain, associationsToAssociationsMap));
642
+ return associationsToAssociationsMap;
643
+ }
644
+ /**
645
+ * @internal
646
+ *
647
+ * Adds Dream class to temporary innerJoinDreamClasses array based on association name
648
+ *
649
+ */
650
+ addAssociatedDreamClassToInnerJoinDreamClasses(previousDreamClass, associationName, innerJoinDreamClasses) {
651
+ if (!previousDreamClass)
652
+ return null;
653
+ const association = previousDreamClass['associationMetadataMap']()[associationName];
654
+ if (!association)
655
+ return null;
656
+ this.addThroughAssociatedDreamClassToInnerJoinDreamClasses(previousDreamClass, association, innerJoinDreamClasses);
657
+ const dreamClasses = [association.modelCB()].flat();
658
+ dreamClasses.forEach(dreamClass => innerJoinDreamClasses.push(dreamClass));
659
+ return dreamClasses[0];
660
+ }
661
+ addThroughAssociatedDreamClassToInnerJoinDreamClasses(dreamClass, _association, innerJoinDreamClasses) {
662
+ const association = _association;
663
+ const throughAssociationName = association.through;
664
+ if (!throughAssociationName)
665
+ return;
666
+ const throughAssociation = dreamClass['associationMetadataMap']()[throughAssociationName];
667
+ if (!throughAssociation)
668
+ return;
669
+ const throughDreamClass = [throughAssociation.modelCB()].flat()[0];
670
+ innerJoinDreamClasses.push(throughDreamClass);
671
+ this.addThroughAssociatedDreamClassToInnerJoinDreamClasses(dreamClass, throughAssociation, innerJoinDreamClasses);
672
+ }
673
+ /**
674
+ * @internal
675
+ *
676
+ * Changes the base sql alias
677
+ *
678
+ */
679
+ setBaseSQLAlias(baseSqlAlias) {
680
+ return this.clone({ baseSqlAlias });
681
+ }
682
+ /**
683
+ * @internal
684
+ *
685
+ * Association queries start from the table corresponding to an instance
686
+ * of a Dream and join the association. However, the Dream may have
687
+ * default scopes that would preclude finding that instance, so the
688
+ * Query that forms the base of an association query must be unscoped,
689
+ * but that unscoping should not carry through to other associations
690
+ * (thus the use of `removeAllDefaultScopesExceptOnAssociations` instead of
691
+ * `removeAllDefaultScopes`).
692
+ *
693
+ * The association that this query is loading leverages `joins`, and the
694
+ * joining code explicitly handles applying / omitting default scopes.
695
+ * We set `bypassAllDefaultScopesExceptOnAssociations: true` on this Query
696
+ * to let that code do its work. This keeps the implementation DRY and simpler
697
+ * (without `bypassAllDefaultScopesExceptOnAssociations`, the default scopes would
698
+ * be applied twice, and when the association attempts to remove a default
699
+ * association would be foiled because it would be applied outside of the context
700
+ * where the association is modifying the query).
701
+ *
702
+ */
703
+ setAssociationQueryBase(baseSelectQuery) {
704
+ return this.clone({
705
+ baseSelectQuery: baseSelectQuery.removeAllDefaultScopesExceptOnAssociations(),
706
+ bypassAllDefaultScopesExceptOnAssociations: true,
707
+ });
708
+ }
709
+ /**
710
+ * Prevents default scopes from applying when
711
+ * the Query is executed
712
+ *
713
+ * @returns A new Query which will prevent default scopes from applying
714
+ */
715
+ removeAllDefaultScopes() {
716
+ return this.clone({
717
+ bypassAllDefaultScopes: true,
718
+ baseSelectQuery: this.baseSelectQuery?.removeAllDefaultScopes(),
719
+ });
720
+ }
721
+ /**
722
+ * Prevents default scopes from applying when
723
+ * the Query is executed, but not when applying to associations
724
+ *
725
+ * @returns A new Query which will prevent default scopes from applying, but not when applying to asociations
726
+ */
727
+ removeAllDefaultScopesExceptOnAssociations() {
728
+ return this.clone({
729
+ bypassAllDefaultScopesExceptOnAssociations: true,
730
+ baseSelectQuery: this.baseSelectQuery?.removeAllDefaultScopesExceptOnAssociations(),
731
+ });
732
+ }
733
+ /**
734
+ * Prevents a specific default scope from applying when
735
+ * the Query is executed
736
+ *
737
+ * @returns A new Query which will prevent a specific default scope from applying
738
+ */
739
+ removeDefaultScope(scopeName) {
740
+ return this.clone({
741
+ defaultScopesToBypass: [...this.defaultScopesToBypass, scopeName],
742
+ baseSelectQuery: this.baseSelectQuery?.removeDefaultScope(scopeName),
743
+ });
744
+ }
745
+ /**
746
+ * Prevents a specific default scope from applying when
747
+ * the Query is executed, but not when applying to asociations
748
+ *
749
+ * @returns A new Query which will prevent a specific default scope from applying, but not when applying to asociations
750
+ */
751
+ removeDefaultScopeExceptOnAssociations(scopeName) {
752
+ return this.clone({
753
+ defaultScopesToBypassExceptOnAssociations: [
754
+ ...this.defaultScopesToBypassExceptOnAssociations,
755
+ scopeName,
756
+ ],
757
+ baseSelectQuery: this.baseSelectQuery?.removeDefaultScopeExceptOnAssociations(scopeName),
758
+ });
759
+ }
760
+ /**
761
+ * Sends data through for use as passthrough data
762
+ * for the associations that require it.
763
+ *
764
+ * ```ts
765
+ * class Post {
766
+ * @Deco.HasMany('LocalizedText')
767
+ * public localizedTexts: LocalizedText[]
768
+ *
769
+ * @Deco.HasOne('LocalizedText', {
770
+ * on: { locale: DreamConst.passthrough },
771
+ * })
772
+ * public currentLocalizedText: LocalizedText
773
+ * }
774
+ *
775
+ * await User.query().passthrough({ locale: 'es-ES' })
776
+ * .preload('posts', 'currentLocalizedText')
777
+ * .first()
778
+ * ```
779
+ *
780
+ * @param passthroughOnStatement - where statement used for associations that require passthrough data
781
+ * @returns A cloned Query with the passthrough data
782
+ */
783
+ passthrough(passthroughOnStatement) {
784
+ return this.clone({ passthroughOnStatement: passthroughOnStatement });
785
+ }
786
+ /**
787
+ * Applies a where statement to the Query instance
788
+ *
789
+ * ```ts
790
+ * await User.where({ email: 'how@yadoin' }).first()
791
+ * // User{email: 'how@yadoin'}
792
+ * ```
793
+ *
794
+ * @param whereStatement - Where statement to apply to the Query
795
+ * @returns A cloned Query with the where clause applied
796
+ */
797
+ where(whereStatement) {
798
+ return this._where(whereStatement, 'where');
799
+ }
800
+ /**
801
+ * Accepts a list of where statements, each of
802
+ * which is combined via `OR`
803
+ *
804
+ * ```ts
805
+ * await User.query().whereAny([{ email: 'how@yadoin' }, { name: 'fred' }]).first()
806
+ * // [User{email: 'how@yadoin'}, User{name: 'fred'}, User{name: 'fred'}]
807
+ * ```
808
+ *
809
+ * @param whereStatements - a list of where statements to `OR` together
810
+ * @returns A cloned Query with the whereAny clause applied
811
+ */
812
+ whereAny(whereStatements) {
813
+ return this.clone({
814
+ or: whereStatements ? [whereStatements.map((obj) => ({ ...obj }))] : whereStatements,
815
+ });
816
+ }
817
+ /**
818
+ * Applies a whereNot statement to the Query instance
819
+ *
820
+ * ```ts
821
+ * await User.query().whereNot({ email: 'how@yadoin' }).first()
822
+ * // User{email: 'hello@world'}
823
+ * ```
824
+ *
825
+ * @param whereStatement - A where statement to negate and apply to the Query
826
+ * @returns A cloned Query with the whereNot clause applied
827
+ */
828
+ whereNot(whereStatement) {
829
+ return this._where(whereStatement, 'whereNot');
830
+ }
831
+ /**
832
+ * @internal
833
+ *
834
+ * Applies a where clause
835
+ */
836
+ _where(whereStatement, typeOfWhere) {
837
+ return this.clone({
838
+ [typeOfWhere]: whereStatement === null ? null : [{ ...whereStatement }],
839
+ });
840
+ }
841
+ /**
842
+ * Returns a new Kysely SelectQueryBuilder instance to be used
843
+ * in a sub Query
844
+ *
845
+ * ```ts
846
+ * const records = await User.where({
847
+ * id: Post.query().nestedSelect('userId'),
848
+ * }).all()
849
+ * // [User{id: 1}, ...]
850
+ * ```
851
+ *
852
+ * @param selection - the column to use for your nested Query
853
+ * @returns A Kysely SelectQueryBuilder instance
854
+ */
855
+ nestedSelect(selection) {
856
+ const query = this.buildSelect({ bypassSelectAll: true, bypassOrder: true });
857
+ return query.select(this.namespaceColumn(selection));
858
+ }
859
+ /**
860
+ * Returns a new Query instance, attaching the provided
861
+ * order statement
862
+ *
863
+ * ```ts
864
+ * await User.query().order('id').all()
865
+ * // [User{id: 1}, User{id: 2}, ...]
866
+ * ```
867
+ *
868
+ * ```ts
869
+ * await User.query().order({ name: 'asc', id: 'desc' }).all()
870
+ * // [User{name: 'a', id: 99}, User{name: 'a', id: 97}, User{ name: 'b', id: 98 } ...]
871
+ * ```
872
+ *
873
+ * @param orderStatement - Either a string or an object specifying order. If a string, the order is implicitly ascending. If the orderStatement is an object, statements will be provided in the order of the keys set in the object
874
+ * @returns A cloned Query with the order clause applied
875
+ */
876
+ order(arg) {
877
+ if (arg === null)
878
+ return this.clone({ order: null });
879
+ if ((0, typechecks_js_1.isString)(arg))
880
+ return this.clone({ order: [{ column: arg, direction: 'asc' }] });
881
+ let query = this.clone();
882
+ Object.keys(arg).forEach(key => {
883
+ const column = key;
884
+ const direction = arg[key];
885
+ query = query.clone({
886
+ order: [{ column: column, direction }],
887
+ });
888
+ });
889
+ return query;
890
+ }
891
+ /**
892
+ * Returns a new Query instance, specifying a limit
893
+ *
894
+ * ```ts
895
+ * await User.order('id').limit(2).all()
896
+ * // [User{id: 1}, User{id: 2}]
897
+ * ```
898
+ *
899
+ * @returns A cloned Query with the limit clause applied
900
+ */
901
+ limit(limit) {
902
+ return this.clone({ limit });
903
+ }
904
+ /**
905
+ * Returns a new Query instance, specifying an offset
906
+ *
907
+ * ```ts
908
+ * await User.order('id').offset(2).limit(2).all()
909
+ * // [User{id: 3}, User{id: 4}]
910
+ * ```
911
+ *
912
+ * @returns A cloned Query with the offset clause applied
913
+ */
914
+ offset(offset) {
915
+ return this.clone({ offset });
916
+ }
917
+ /**
918
+ * Returns the sql that would be executed by this Query
919
+ *
920
+ * ```ts
921
+ * User.where({ email: 'how@yadoin' }).sql()
922
+ * // {
923
+ * // query: {
924
+ * // kind: 'SelectQueryNode',
925
+ * // from: { kind: 'FromNode', froms: [Array] },
926
+ * // selections: [ [Object] ],
927
+ * // distinctOn: undefined,
928
+ * // joins: undefined,
929
+ * // groupBy: undefined,
930
+ * // orderBy: undefined,
931
+ * // where: { kind: 'WhereNode', where: [Object] },
932
+ * // frontModifiers: undefined,
933
+ * // endModifiers: undefined,
934
+ * // limit: undefined,
935
+ * // offset: undefined,
936
+ * // with: undefined,
937
+ * // having: undefined,
938
+ * // explain: undefined,
939
+ * // setOperations: undefined
940
+ * // },
941
+ * // sql: 'select "users".* from "users" where ("users"."email" = $1 and "users"."deleted_at" is null)',
942
+ * // parameters: [ 'how@yadoin' ]
943
+ * //}
944
+ * ```
945
+ *
946
+ * @returns An object representing the underlying sql statement
947
+ *
948
+ */
949
+ sql() {
950
+ const kyselyQuery = this.buildSelect();
951
+ return kyselyQuery.compile();
952
+ }
953
+ /**
954
+ * Converts the given dream class into a Kysely query, enabling
955
+ * you to build custom queries using the Kysely API
956
+ *
957
+ * ```ts
958
+ * await User.query().toKysely('select').where('email', '=', 'how@yadoin').execute()
959
+ * ```
960
+ *
961
+ * @param type - the type of Kysely query builder instance you would like to obtain
962
+ * @returns A Kysely query. Depending on the type passed, it will return either a SelectQueryBuilder, DeleteQueryBuilder, or an UpdateQueryBuilder
963
+ */
964
+ toKysely(type) {
965
+ switch (type) {
966
+ case 'select':
967
+ return this.buildSelect();
968
+ case 'delete':
969
+ return this.buildDelete();
970
+ case 'update':
971
+ return this.buildUpdate({});
972
+ // TODO: in the future, we should support insert type, but don't yet, since inserts are done outside
973
+ // the query class for some reason.
974
+ default:
975
+ throw new Error('never');
976
+ }
977
+ }
978
+ /**
979
+ * Applies transaction to the Query instance
980
+ *
981
+ * ```ts
982
+ * await ApplicationModel.transaction(async txn => {
983
+ * await User.query().txn(txn).create({ email: 'how@yadoin' })
984
+ * })
985
+ * ```
986
+ *
987
+ * @param txn - A DreamTransaction instance (usually collected by calling `ApplicationModel.transaction`)
988
+ * @returns A cloned Query with the transaction applied
989
+ *
990
+ */
991
+ txn(dreamTransaction) {
992
+ return this.clone({ transaction: dreamTransaction });
993
+ }
994
+ /**
995
+ * Retrieves the number of records in the database
996
+ *
997
+ * ```ts
998
+ * await User.query().count()
999
+ * ```
1000
+ *
1001
+ * @returns The number of records in the database
1002
+ */
1003
+ async count() {
1004
+ // eslint-disable-next-line @typescript-eslint/unbound-method
1005
+ const { count } = this.dbFor('select').fn;
1006
+ const distinctColumn = this.distinctColumn;
1007
+ const query = this.clone({ distinctColumn: null });
1008
+ let kyselyQuery = query.buildSelect({ bypassSelectAll: true, bypassOrder: true });
1009
+ const countClause = distinctColumn
1010
+ ? count((0, kysely_1.sql) `DISTINCT ${distinctColumn}`)
1011
+ : count(query.namespaceColumn(query.dreamInstance.primaryKey));
1012
+ kyselyQuery = kyselyQuery.select(countClause.as('tablecount'));
1013
+ const data = await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'executeTakeFirstOrThrow');
1014
+ return parseInt(data.tablecount.toString());
1015
+ }
1016
+ /**
1017
+ * Returns new Query with distinct clause applied
1018
+ *
1019
+ * ```ts
1020
+ * await User.query().distinct('name').pluck('name')
1021
+ * ```
1022
+ *
1023
+ * @returns A cloned Query with the distinct clause applied
1024
+ */
1025
+ distinct(column = true) {
1026
+ if (column === true) {
1027
+ return this.clone({
1028
+ distinctColumn: this.namespaceColumn(this.dreamInstance.primaryKey),
1029
+ });
1030
+ }
1031
+ else if (column === false) {
1032
+ return this.clone({ distinctColumn: null });
1033
+ }
1034
+ else {
1035
+ return this.clone({ distinctColumn: this.namespaceColumn(column) });
1036
+ }
1037
+ }
1038
+ /**
1039
+ * @internal
1040
+ *
1041
+ * Returns a namespaced column name
1042
+ *
1043
+ * @returns A string
1044
+ */
1045
+ namespaceColumn(column, alias = this.baseSqlAlias) {
1046
+ return (0, namespaceColumn_js_1.default)(column, alias);
1047
+ }
1048
+ /**
1049
+ * Retrieves the max value of the specified column
1050
+ * for this Query
1051
+ *
1052
+ * ```ts
1053
+ * await User.query().max('id')
1054
+ * // 99
1055
+ * ```
1056
+ *
1057
+ * @param columnName - a column name on the model
1058
+ * @returns the max value of the specified column for this Query
1059
+ *
1060
+ */
1061
+ async max(columnName) {
1062
+ // eslint-disable-next-line @typescript-eslint/unbound-method
1063
+ const { max } = this.dbFor('select').fn;
1064
+ let kyselyQuery = this.buildSelect({ bypassSelectAll: true, bypassOrder: true });
1065
+ kyselyQuery = kyselyQuery.select(max(columnName));
1066
+ const data = await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'executeTakeFirstOrThrow');
1067
+ return data.max;
1068
+ }
1069
+ /**
1070
+ * Retrieves the min value of the specified column
1071
+ * for this Query
1072
+ *
1073
+ * ```ts
1074
+ * await User.query().min('id')
1075
+ * // 1
1076
+ * ```
1077
+ *
1078
+ * @param columnName - a column name on the model
1079
+ * @returns the min value of the specified column for this Query
1080
+ */
1081
+ async min(columnName) {
1082
+ // eslint-disable-next-line @typescript-eslint/unbound-method
1083
+ const { min } = this.dbFor('select').fn;
1084
+ let kyselyQuery = this.buildSelect({ bypassSelectAll: true, bypassOrder: true });
1085
+ kyselyQuery = kyselyQuery.select(min(columnName));
1086
+ const data = await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'executeTakeFirstOrThrow');
1087
+ return data.min;
1088
+ }
1089
+ /**
1090
+ * @internal
1091
+ *
1092
+ * Runs the query and extracts plucked values
1093
+ *
1094
+ * @returns An array of plucked values
1095
+ */
1096
+ async executePluck(...fields) {
1097
+ let kyselyQuery = this.removeAllDefaultScopesExceptOnAssociations().buildSelect({ bypassSelectAll: true });
1098
+ const aliases = [];
1099
+ fields.forEach((field) => {
1100
+ // field will already be namespaced in a join situation, but when the field to pluck is on the
1101
+ // base model, it will be underscored (to match the table name), but when the selected column
1102
+ // comes back from Kysely camelCased
1103
+ aliases.push(field.includes('_') ? (0, camelize_js_1.default)(field) : field);
1104
+ kyselyQuery = kyselyQuery.select(`${this.namespaceColumn(field)} as ${field}`);
1105
+ });
1106
+ return (await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'execute')).map(singleResult => aliases.map(alias => singleResult[alias]));
1107
+ }
1108
+ /**
1109
+ * @internal
1110
+ *
1111
+ */
1112
+ async executeJoinLoad(options = {}) {
1113
+ const query = this.limit(null).offset(null);
1114
+ let kyselyQuery = query.buildSelect({ bypassSelectAll: true });
1115
+ const aliasToDreamClassesMap = {
1116
+ [this.baseSqlAlias]: this.dreamClass,
1117
+ ...this.joinStatementsToDreamClassesMap(this.leftJoinStatements),
1118
+ };
1119
+ const associationAliasToColumnAliasMap = {};
1120
+ const aliasToAssociationsMap = this.joinStatementsToAssociationsMap(this.leftJoinStatements);
1121
+ const aliases = Object.keys(aliasToDreamClassesMap);
1122
+ let nextColumnAliasCounter = 0;
1123
+ aliases.forEach((aliasOrExpression) => {
1124
+ const alias = (0, extractAssociationMetadataFromAssociationName_js_1.default)(aliasOrExpression).alias;
1125
+ associationAliasToColumnAliasMap[alias] ||= {};
1126
+ const aliasedDreamClass = aliasToDreamClassesMap[alias];
1127
+ const association = aliasToAssociationsMap[alias];
1128
+ const columns = alias === this.baseSqlAlias
1129
+ ? options.columns
1130
+ ? this.columnsWithRequiredLoadColumns(options.columns)
1131
+ : this.dreamClass.columns()
1132
+ : aliasedDreamClass.columns();
1133
+ columns.forEach((column) => {
1134
+ const columnAlias = `dr${nextColumnAliasCounter++}`;
1135
+ kyselyQuery = kyselyQuery.select(`${this.namespaceColumn(column, alias)} as ${columnAlias}`);
1136
+ associationAliasToColumnAliasMap[alias][column] = columnAlias;
1137
+ });
1138
+ if (association?.type === 'HasOne' || association?.type === 'HasMany') {
1139
+ const setupPreloadData = (dbColumnName) => {
1140
+ const columnAlias = `dr${nextColumnAliasCounter++}`;
1141
+ associationAliasToColumnAliasMap[association.through][dbColumnName] = columnAlias;
1142
+ kyselyQuery = kyselyQuery.select(`${this.namespaceColumn(dbColumnName, association.through)} as ${columnAlias}`);
1143
+ };
1144
+ if (association.through && association.preloadThroughColumns) {
1145
+ if ((0, typechecks_js_1.isObject)(association.preloadThroughColumns)) {
1146
+ const preloadMap = association.preloadThroughColumns;
1147
+ Object.keys(preloadMap).forEach(columnName => setupPreloadData(columnName));
1148
+ }
1149
+ else {
1150
+ const preloadArray = association.preloadThroughColumns;
1151
+ preloadArray.forEach(columnName => setupPreloadData(columnName));
1152
+ }
1153
+ }
1154
+ }
1155
+ });
1156
+ const queryResults = await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'execute');
1157
+ const aliasToDreamIdMap = queryResults.reduce((aliasToDreamIdMap, singleSqlResult) => {
1158
+ this.fleshOutJoinLoadExecutionResults({
1159
+ currentAlias: this.baseSqlAlias,
1160
+ singleSqlResult,
1161
+ aliasToDreamIdMap,
1162
+ associationAliasToColumnAliasMap,
1163
+ aliasToAssociationsMap,
1164
+ aliasToDreamClassesMap,
1165
+ leftJoinStatements: this.leftJoinStatements,
1166
+ });
1167
+ return aliasToDreamIdMap;
1168
+ }, {});
1169
+ const baseModelIdToDreamMap = aliasToDreamIdMap[this.baseSqlAlias] || new Map();
1170
+ return (0, compact_js_1.default)(Array.from(baseModelIdToDreamMap.values()));
1171
+ }
1172
+ fleshOutJoinLoadExecutionResults({ currentAlias, singleSqlResult, aliasToDreamIdMap, associationAliasToColumnAliasMap, aliasToAssociationsMap, aliasToDreamClassesMap, leftJoinStatements, }) {
1173
+ const dreamClass = aliasToDreamClassesMap[currentAlias];
1174
+ const columnToColumnAliasMap = associationAliasToColumnAliasMap[currentAlias];
1175
+ const primaryKeyValue = singleSqlResult[columnToColumnAliasMap[dreamClass.primaryKey]];
1176
+ if (!primaryKeyValue)
1177
+ return null;
1178
+ aliasToDreamIdMap[currentAlias] ||= new Map();
1179
+ if (!aliasToDreamIdMap[currentAlias].get(primaryKeyValue)) {
1180
+ const columnValueMap = Object.keys(columnToColumnAliasMap).reduce((columnNameValueMap, columnName) => {
1181
+ columnNameValueMap[columnName] = singleSqlResult[columnToColumnAliasMap[columnName]];
1182
+ return columnNameValueMap;
1183
+ }, {});
1184
+ const dream = (0, sqlResultToDreamInstance_js_1.default)(dreamClass, columnValueMap);
1185
+ const association = aliasToAssociationsMap[currentAlias];
1186
+ if (association && association.through && association.preloadThroughColumns) {
1187
+ const throughAssociationColumnToColumnAliasMap = associationAliasToColumnAliasMap[association.through];
1188
+ this.hydratePreloadedThroughColumns({
1189
+ association,
1190
+ columnToColumnAliasMap: throughAssociationColumnToColumnAliasMap,
1191
+ dream,
1192
+ singleSqlResult,
1193
+ });
1194
+ }
1195
+ aliasToDreamIdMap[(0, protectAgainstPollutingAssignment_js_1.default)(currentAlias)].set(primaryKeyValue, dream);
1196
+ }
1197
+ const dream = aliasToDreamIdMap[currentAlias].get(primaryKeyValue);
1198
+ Object.keys(leftJoinStatements).forEach(nextAlias => {
1199
+ const { name: associationName, alias } = (0, extractAssociationMetadataFromAssociationName_js_1.default)(nextAlias);
1200
+ const association = dreamClass['getAssociationMetadata'](associationName);
1201
+ const associatedDream = this.fleshOutJoinLoadExecutionResults({
1202
+ currentAlias: alias,
1203
+ singleSqlResult,
1204
+ aliasToDreamIdMap,
1205
+ associationAliasToColumnAliasMap,
1206
+ aliasToAssociationsMap,
1207
+ aliasToDreamClassesMap,
1208
+ leftJoinStatements: leftJoinStatements[nextAlias],
1209
+ });
1210
+ const hasMany = association.type === 'HasMany';
1211
+ // initialize by trying to access the association, which throws an exception if not yet initialized
1212
+ try {
1213
+ ;
1214
+ dream[association.as];
1215
+ }
1216
+ catch {
1217
+ if (hasMany)
1218
+ dream[association.as] = [];
1219
+ else
1220
+ dream[(0, associationToGetterSetterProp_js_1.default)(association)] = null;
1221
+ }
1222
+ if (!associatedDream)
1223
+ return;
1224
+ if (hasMany) {
1225
+ if (!dream[association.as].includes(associatedDream))
1226
+ dream[association.as].push(associatedDream);
1227
+ }
1228
+ else
1229
+ dream[(0, associationToGetterSetterProp_js_1.default)(association)] = associatedDream;
1230
+ });
1231
+ return dream;
1232
+ }
1233
+ hydratePreloadedThroughColumns({ association, columnToColumnAliasMap, dream, singleSqlResult, }) {
1234
+ if (!association.through)
1235
+ return;
1236
+ if (!dream.preloadedThroughColumns)
1237
+ return;
1238
+ let columnNames = [];
1239
+ const columnNameToPreloadedThroughColumnNameMap = {};
1240
+ if ((0, typechecks_js_1.isObject)(association.preloadThroughColumns)) {
1241
+ const preloadMap = association.preloadThroughColumns;
1242
+ columnNames = Object.keys(preloadMap).map(columnName => {
1243
+ columnNameToPreloadedThroughColumnNameMap[columnName] = preloadMap[columnName];
1244
+ return columnName;
1245
+ });
1246
+ }
1247
+ else if (Array.isArray(association.preloadThroughColumns)) {
1248
+ columnNames = association.preloadThroughColumns.map(columnName => {
1249
+ columnNameToPreloadedThroughColumnNameMap[columnName] = columnName;
1250
+ return columnName;
1251
+ });
1252
+ }
1253
+ columnNames.forEach(columnName => (dream.preloadedThroughColumns[columnNameToPreloadedThroughColumnNameMap[columnName]] =
1254
+ singleSqlResult[columnToColumnAliasMap[columnName]]));
1255
+ }
1256
+ /**
1257
+ * Plucks the provided fields from the given dream class table
1258
+ *
1259
+ * ```ts
1260
+ * await User.order('id').pluck('id')
1261
+ * // [1, 2, 3]
1262
+ * ```
1263
+ *
1264
+ * If more than one column is requested, a multi-dimensional
1265
+ * array is returned:
1266
+ *
1267
+ * ```ts
1268
+ * await User.order('id').pluck('id', 'email')
1269
+ * // [[1, 'a@a.com'], [2, 'b@b.com']]
1270
+ * ```
1271
+ *
1272
+ * @param columnNames - The column or array of columns to pluck
1273
+ * @returns An array of pluck results
1274
+ */
1275
+ async pluck(...columnNames) {
1276
+ const vals = await this.executePluck(...columnNames);
1277
+ return (columnNames.length > 1 ? vals : vals.flat());
1278
+ }
1279
+ /**
1280
+ * Plucks the specified column names from the given dream class table
1281
+ * in batches, passing each found columns into the
1282
+ * provided callback function
1283
+ *
1284
+ * ```ts
1285
+ * await User.order('id').pluckEach('id', (id) => {
1286
+ * console.log(id)
1287
+ * })
1288
+ * // 1
1289
+ * // 2
1290
+ * // 3
1291
+ * ```
1292
+ *
1293
+ * @param args - a list of column names to pluck, followed by a callback function to call for each set of found fields
1294
+ * @returns void
1295
+ */
1296
+ async pluckEach(...args) {
1297
+ const providedCbIndex = args.findIndex(v => typeof v === 'function');
1298
+ const providedCb = args[providedCbIndex];
1299
+ const providedOpts = args[providedCbIndex + 1];
1300
+ if (!providedCb)
1301
+ throw new MissingRequiredCallbackFunctionToPluckEach_js_1.default('pluckEach', args);
1302
+ if (providedOpts !== undefined && !providedOpts?.batchSize)
1303
+ throw new CannotPassAdditionalFieldsToPluckEachAfterCallback_js_1.default('pluckEach', args);
1304
+ const onlyColumns = args.filter((_, index) => index < providedCbIndex);
1305
+ const batchSize = providedOpts?.batchSize || Query.BATCH_SIZES.PLUCK_EACH_THROUGH;
1306
+ let offset = 0;
1307
+ let records;
1308
+ do {
1309
+ const onlyIncludesPrimaryKey = onlyColumns.find(column => column === this.dreamClass.primaryKey || column === this.namespacedPrimaryKey);
1310
+ const columnsIncludingPrimaryKey = onlyIncludesPrimaryKey
1311
+ ? onlyColumns
1312
+ : [this.namespacedPrimaryKey, ...onlyColumns];
1313
+ records = await this.offset(offset)
1314
+ .order(null)
1315
+ .order(this.namespacedPrimaryKey)
1316
+ .limit(batchSize)
1317
+ .executePluck(...columnsIncludingPrimaryKey);
1318
+ // In order to batch, we need to order by primary key, so the primary key must be plucked.
1319
+ // If the developer did not include the primary key in the columns to pluck, then we prepended it above
1320
+ // and need to remove it from each group of plucked columns prior to passing them into the callback functions
1321
+ const vals = onlyIncludesPrimaryKey ? records : records.map(valueArr => valueArr.slice(1));
1322
+ for (const val of vals) {
1323
+ await providedCb(...val);
1324
+ }
1325
+ offset += batchSize;
1326
+ } while (records.length > 0 && records.length === batchSize);
1327
+ }
1328
+ /**
1329
+ * Retrieves an array containing all records matching the Query.
1330
+ * Be careful using this, since it will attempt to pull every
1331
+ * record into memory at once. When querying might return a large
1332
+ * number of records, consider using `.findEach`, which will pull
1333
+ * the records in batches.
1334
+ *
1335
+ * ```ts
1336
+ * await User.query().all()
1337
+ * ```
1338
+ *
1339
+ * @returns an array of dreams
1340
+ */
1341
+ async all(options = {}) {
1342
+ if (this.joinLoadActivated)
1343
+ return await this.executeJoinLoad(options);
1344
+ const kyselyQuery = this.buildSelect(options);
1345
+ const results = await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'execute');
1346
+ const theAll = results.map(r => (0, sqlResultToDreamInstance_js_1.default)(this.dreamClass, r));
1347
+ await this.applyPreload(this.preloadStatements, this.preloadOnStatements, theAll);
1348
+ return theAll;
1349
+ }
1350
+ /**
1351
+ * Forces use of a database connection (e.g. 'primary') during the query.
1352
+ *
1353
+ * NOTE: all queries within a transaction always use the 'primary' replica, so
1354
+ * explicitly setting connection within a transaction has no effect.
1355
+ *
1356
+ * @param connection - The connection you wish to access ('primary' or 'replica')
1357
+ * @returns A Query with the requested connection
1358
+ */
1359
+ connection(connection) {
1360
+ return this._connection(connection);
1361
+ }
1362
+ _connection(connection) {
1363
+ if (!connection)
1364
+ return this;
1365
+ return this.clone({ connection });
1366
+ }
1367
+ /**
1368
+ * Returns true if a record exists for the given
1369
+ * Query
1370
+ *
1371
+ * ```ts
1372
+ * await User.query().exists()
1373
+ * // false
1374
+ *
1375
+ * await User.create({ email: 'how@yadoin' })
1376
+ *
1377
+ * await User.query().exists()
1378
+ * // true
1379
+ * ```
1380
+ *
1381
+ * @returns boolean
1382
+ */
1383
+ async exists() {
1384
+ // Implementing via `limit(1).all()`, rather than the simpler `!!(await this.first())`
1385
+ // because it avoids the step of finding the first. Just find any, and return
1386
+ // that one.
1387
+ return (await this.limit(1).all()).length > 0;
1388
+ }
1389
+ /**
1390
+ * Returns the first record in the database
1391
+ * matching the Query. If the Query is not
1392
+ * ordered, it will automatically order
1393
+ * by primary key.
1394
+ *
1395
+ * ```ts
1396
+ * await User.query().first()
1397
+ * // User{id: 1}
1398
+ * ```
1399
+ *
1400
+ * @returns First record in the database, or null if no record exists
1401
+ */
1402
+ async first() {
1403
+ const query = this.orderStatements.length
1404
+ ? this
1405
+ : this.order({ [this.namespacedPrimaryKey]: 'asc' });
1406
+ return await query.takeOne();
1407
+ }
1408
+ /**
1409
+ * Returns the first record in the database
1410
+ * matching the Query. If the Query is not
1411
+ * ordered, it will automatically order
1412
+ * by primary key. If no record is found,
1413
+ * an exception is raised.
1414
+ *
1415
+ * ```ts
1416
+ * await User.query().first()
1417
+ * // User{id: 1}
1418
+ * ```
1419
+ *
1420
+ * @returns First record in the database, or null if no record exists
1421
+ */
1422
+ async firstOrFail() {
1423
+ const record = await this.first();
1424
+ if (!record)
1425
+ throw new RecordNotFound_js_1.default(this.dreamInstance.constructor.name);
1426
+ return record;
1427
+ }
1428
+ /**
1429
+ * Returns the last record in the database
1430
+ * matching the Query. If the Query is not
1431
+ * ordered, it will automatically order
1432
+ * by primary key.
1433
+ *
1434
+ * ```ts
1435
+ * await User.query().last()
1436
+ * // User{id: 99}
1437
+ * ```
1438
+ *
1439
+ * @returns Last record in the database, or null if no record exists
1440
+ */
1441
+ async last() {
1442
+ const query = this.orderStatements.length
1443
+ ? this.invertOrder()
1444
+ : this.order({ [this.namespacedPrimaryKey]: 'desc' });
1445
+ return await query.takeOne();
1446
+ }
1447
+ /**
1448
+ * Returns the last record in the database
1449
+ * matching the Query. If the Query is not
1450
+ * ordered, it will automatically order
1451
+ * by primary key. If no record is found,
1452
+ * it will raise an exception.
1453
+ *
1454
+ * ```ts
1455
+ * await User.where(...).lastOrFail()
1456
+ * // User{id: 99}
1457
+ * ```
1458
+ *
1459
+ * @returns Last record in the database, or null if no record exists
1460
+ */
1461
+ async lastOrFail() {
1462
+ const record = await this.last();
1463
+ if (!record)
1464
+ throw new RecordNotFound_js_1.default(this.dreamInstance.constructor.name);
1465
+ return record;
1466
+ }
1467
+ /**
1468
+ * Destroys all records matching the Query,
1469
+ * calling model hooks and cascading destroy
1470
+ * to associations with `dependent: 'destroy'`,
1471
+ * and returns the number of records that
1472
+ * were destroyed.
1473
+ *
1474
+ * To delete in a single database query,
1475
+ * ignoring model hooks and association
1476
+ * dependent-destroy declarations, use
1477
+ * {@link Query.delete | delete} instead.
1478
+ *
1479
+ * ```ts
1480
+ * await User.where({ email: ops.ilike('%burpcollaborator%') }).destroy()
1481
+ * // 12
1482
+ * ```
1483
+ *
1484
+ * @param options - Options for destroying the instance
1485
+ * @param options.skipHooks - If true, skips applying model hooks during the destroy operation. Defaults to false
1486
+ * @param options.cascade - If false, skips destroying associations marked `dependent: 'destroy'`. Defaults to true
1487
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when cascade destroying. Defaults to false
1488
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when cascade destroying. Defaults to an empty array
1489
+ * @returns The number of records that were removed
1490
+ */
1491
+ async destroy({ skipHooks, cascade, } = {}) {
1492
+ let counter = 0;
1493
+ const options = {
1494
+ bypassAllDefaultScopes: this.bypassAllDefaultScopes,
1495
+ defaultScopesToBypass: this.defaultScopesToBypass,
1496
+ skipHooks,
1497
+ cascade,
1498
+ };
1499
+ await this.findEach(async (result) => {
1500
+ const subquery = this.dreamTransaction
1501
+ ? result.txn(this.dreamTransaction)
1502
+ : result;
1503
+ if (this.shouldReallyDestroy) {
1504
+ await subquery.reallyDestroy(options);
1505
+ }
1506
+ else {
1507
+ await subquery.destroy(options);
1508
+ }
1509
+ counter++;
1510
+ });
1511
+ return counter;
1512
+ }
1513
+ /**
1514
+ * Destroys all records matching the Query,
1515
+ * ignoring the SoftDelete decorator and
1516
+ * permanently removing records from the database.
1517
+ *
1518
+ * Calls model hooks and applies cascade destroy
1519
+ * to associations with `dependent: 'destroy'`,
1520
+ * returning the number of records that
1521
+ * were destroyed.
1522
+ *
1523
+ * To destroy without bypassing the SoftDelete
1524
+ * decorator, use {@link Query.(destroy:instance) | destroy} instead.
1525
+ *
1526
+ * ```ts
1527
+ * await User.where({ email: ops.ilike('%burpcollaborator%') }).reallyDestroy()
1528
+ * // 12
1529
+ * ```
1530
+ *
1531
+ * @param options - Options for destroying the instance
1532
+ * @param options.skipHooks - If true, skips applying model hooks during the destroy operation. Defaults to false
1533
+ * @param options.cascade - If false, skips destroying associations marked `dependent: 'destroy'`. Defaults to true
1534
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when cascade destroying. Defaults to false
1535
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when cascade destroying. Defaults to an empty array
1536
+ * @returns The number of records that were removed
1537
+ */
1538
+ async reallyDestroy({ skipHooks, cascade, } = {}) {
1539
+ return await this.clone({ shouldReallyDestroy: true }).destroy({ skipHooks, cascade });
1540
+ }
1541
+ /**
1542
+ * Undestroys a SoftDelete model, unsetting
1543
+ * the `deletedAt` field in the database.
1544
+ *
1545
+ * If the model is not a SoftDelete model,
1546
+ * this will raise an exception.
1547
+ *
1548
+ * ```ts
1549
+ * await User.where({ email: ops.ilike('%burpcollaborator%') }).undestroy()
1550
+ * // 12
1551
+ * ```
1552
+ *
1553
+ * @param options - Options for undestroying the instance
1554
+ * @param options.skipHooks - If true, skips applying model hooks during the undestroy operation. Defaults to false
1555
+ * @param options.cascade - If false, skips undestroying associations marked `dependent: 'destroy'`. Defaults to true
1556
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when cascade undestroying. Defaults to false
1557
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when cascade undestroying (soft delete is always bypassed). Defaults to an empty array
1558
+ * @returns The number of records that were removed
1559
+ */
1560
+ async undestroy({ cascade, skipHooks, } = {}) {
1561
+ if (!this.dreamClass['softDelete'])
1562
+ throw new CannotCallUndestroyOnANonSoftDeleteModel_js_1.default(this.dreamClass);
1563
+ let counter = 0;
1564
+ await this.removeDefaultScope(SoftDelete_js_1.SOFT_DELETE_SCOPE_NAME).findEach(async (result) => {
1565
+ const subquery = this.dreamTransaction
1566
+ ? result.txn(this.dreamTransaction)
1567
+ : result;
1568
+ await subquery.undestroy({
1569
+ bypassAllDefaultScopes: this.bypassAllDefaultScopes,
1570
+ defaultScopesToBypass: this.defaultScopesToBypass,
1571
+ cascade,
1572
+ skipHooks,
1573
+ });
1574
+ counter++;
1575
+ });
1576
+ return counter;
1577
+ }
1578
+ /**
1579
+ * Deletes all records matching query using a single
1580
+ * database query, but does not call underlying callbacks.
1581
+ * Ignores association dependent destroy declarations,
1582
+ * though cascading may still happen at the database level.
1583
+ *
1584
+ * To apply model hooks and association dependent destroy,
1585
+ * use {@link Query.(destroy:instance) | destroy} instead.
1586
+ *
1587
+ * ```ts
1588
+ * await User.where({ email: ops.ilike('%burpcollaborator%').delete() })
1589
+ * // 12
1590
+ * ```
1591
+ *
1592
+ * @returns The number of records that were removed
1593
+ */
1594
+ async delete() {
1595
+ const deletionResult = await (0, executeDatabaseQuery_js_1.default)(this.buildDelete(), 'executeTakeFirst');
1596
+ return Number(deletionResult?.numDeletedRows || 0);
1597
+ }
1598
+ /**
1599
+ * Updates all records matching the Query
1600
+ *
1601
+ * ```ts
1602
+ * await User.where({ email: ops.ilike('%burpcollaborator%') }).updateAll({ email: null })
1603
+ * // 12
1604
+ * ```
1605
+ * @param attributes - The attributes used to update the records
1606
+ * @param options - Options for updating the instance
1607
+ * @param options.skipHooks - If true, skips applying model hooks. Defaults to false
1608
+ * @returns The number of records that were updated
1609
+ */
1610
+ async update(attributes, { skipHooks } = {}) {
1611
+ if (this.baseSelectQuery)
1612
+ throw new NoUpdateOnAssociationQuery_js_1.default();
1613
+ if (Object.keys(this.innerJoinStatements).length)
1614
+ throw new NoUpdateAllOnJoins_js_1.default();
1615
+ if (Object.keys(this.leftJoinStatements).length)
1616
+ throw new NoUpdateAllOnJoins_js_1.default();
1617
+ if (skipHooks)
1618
+ return await this.updateWithoutCallingModelHooks(attributes);
1619
+ let counter = 0;
1620
+ await this.findEach(async (result) => {
1621
+ const subquery = this.dreamTransaction
1622
+ ? result.txn(this.dreamTransaction)
1623
+ : result;
1624
+ await subquery.update(attributes);
1625
+ counter++;
1626
+ });
1627
+ return counter;
1628
+ }
1629
+ async updateWithoutCallingModelHooks(attributes) {
1630
+ const kyselyQuery = this.buildUpdate(attributes);
1631
+ const res = await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'execute');
1632
+ const resultData = Array.from(res.entries())?.[0]?.[1];
1633
+ return Number(resultData?.numUpdatedRows || 0);
1634
+ }
1635
+ /**
1636
+ * @internal
1637
+ *
1638
+ * Used for applying first and last queries
1639
+ *
1640
+ * @returns A dream instance or null
1641
+ */
1642
+ async takeOne() {
1643
+ if (this.joinLoadActivated) {
1644
+ let query;
1645
+ if (this.whereStatements.find(whereStatement => whereStatement[this.dreamClass.primaryKey] ||
1646
+ whereStatement[this.namespacedPrimaryKey])) {
1647
+ // the query already includes a primary key where statement
1648
+ query = this;
1649
+ }
1650
+ else {
1651
+ // otherwise find the primary key and apply it to the query
1652
+ const primaryKeyValue = (await this.limit(1).pluck(this.namespacedPrimaryKey))[0];
1653
+ if (primaryKeyValue === undefined)
1654
+ return null;
1655
+ query = this.where({ [this.namespacedPrimaryKey]: primaryKeyValue });
1656
+ }
1657
+ return (await query.executeJoinLoad())[0] || null;
1658
+ }
1659
+ const kyselyQuery = this.limit(1).buildSelect();
1660
+ const results = await (0, executeDatabaseQuery_js_1.default)(kyselyQuery, 'executeTakeFirst');
1661
+ if (results) {
1662
+ const theFirst = (0, sqlResultToDreamInstance_js_1.default)(this.dreamClass, results);
1663
+ if (theFirst)
1664
+ await this.applyPreload(this.preloadStatements, this.preloadOnStatements, [theFirst]);
1665
+ return theFirst;
1666
+ }
1667
+ else
1668
+ return null;
1669
+ }
1670
+ /**
1671
+ * @internal
1672
+ *
1673
+ * Used to hydrate dreams with the provided associations
1674
+ */
1675
+ hydrateAssociation(dreams, association, preloadedDreamsAndWhatTheyPointTo) {
1676
+ switch (association.type) {
1677
+ case 'HasMany':
1678
+ dreams.forEach((dream) => {
1679
+ dream[association.as] = [];
1680
+ });
1681
+ break;
1682
+ default:
1683
+ dreams.forEach((dream) => {
1684
+ dream[(0, associationToGetterSetterProp_js_1.default)(association)] = null;
1685
+ });
1686
+ }
1687
+ // dreams is a Rating
1688
+ // Rating belongs to: rateables (Posts / Compositions)
1689
+ // loadedAssociations is an array of Posts and Compositions
1690
+ // if rating.rateable_id === loadedAssociation.primaryKeyvalue
1691
+ // rating.rateable = loadedAssociation
1692
+ preloadedDreamsAndWhatTheyPointTo.forEach(preloadedDreamAndWhatItPointsTo => {
1693
+ dreams
1694
+ .filter(dream => dream.primaryKeyValue === preloadedDreamAndWhatItPointsTo.pointsToPrimaryKey)
1695
+ .forEach((dream) => {
1696
+ if (association.type === 'HasMany') {
1697
+ dream[association.as].push(preloadedDreamAndWhatItPointsTo.dream);
1698
+ }
1699
+ else {
1700
+ // in a HasOne context, order clauses will be applied in advance,
1701
+ // prior to hydration. Considering, we only want to set the first
1702
+ // result and ignore other results, so we will use ||= to set.
1703
+ dream[association.as] ||= preloadedDreamAndWhatItPointsTo.dream;
1704
+ }
1705
+ });
1706
+ });
1707
+ if (association.type === 'HasMany') {
1708
+ dreams.forEach((dream) => Object.freeze(dream[association.as]));
1709
+ }
1710
+ }
1711
+ /**
1712
+ * @internal
1713
+ *
1714
+ * Used to bridge through associations
1715
+ */
1716
+ followThroughAssociation(dreamClass, association) {
1717
+ const throughAssociation = association.through && dreamClass['getAssociationMetadata'](association.through);
1718
+ if (!throughAssociation)
1719
+ throw new MissingThroughAssociation_js_1.default({
1720
+ dreamClass,
1721
+ association,
1722
+ });
1723
+ const throughClass = throughAssociation.modelCB();
1724
+ if (Array.isArray(throughClass))
1725
+ throw new CannotAssociateThroughPolymorphic_js_1.default({
1726
+ dreamClass,
1727
+ association,
1728
+ });
1729
+ const newAssociation = getSourceAssociation(throughClass, association.source);
1730
+ if (!newAssociation)
1731
+ throw new MissingThroughAssociationSource_js_1.default({
1732
+ dreamClass,
1733
+ throughClass,
1734
+ association,
1735
+ });
1736
+ return { throughAssociation, throughClass, newAssociation };
1737
+ }
1738
+ /**
1739
+ * @internal
1740
+ *
1741
+ * Polymorphic BelongsTo. Since polymorphic associations may point to multiple tables,
1742
+ * preload by loading each target class separately.
1743
+ *
1744
+ * Used to preload polymorphic belongs to associations
1745
+ */
1746
+ async preloadPolymorphicBelongsTo(association, dreams) {
1747
+ if (!association.polymorphic)
1748
+ throw new Error(`Association ${association.as} points to an array of models but is not designated polymorphic`);
1749
+ if (association.type !== 'BelongsTo')
1750
+ throw new Error(`Polymorphic association ${association.as} points to an array of models but is ${association.type}. Only BelongsTo associations may point to an array of models.`);
1751
+ const associatedDreams = [];
1752
+ for (const associatedModel of association.modelCB()) {
1753
+ await this.preloadPolymorphicAssociationModel(dreams, association, associatedModel, associatedDreams);
1754
+ }
1755
+ return associatedDreams;
1756
+ }
1757
+ async preloadPolymorphicAssociationModel(dreams, association, associatedDreamClass, associatedDreams) {
1758
+ const relevantAssociatedModels = dreams.filter((dream) => {
1759
+ return dream[association.foreignKeyTypeField()] === associatedDreamClass['stiBaseClassOrOwnClass'].name;
1760
+ });
1761
+ if (relevantAssociatedModels.length) {
1762
+ dreams.forEach((dream) => {
1763
+ dream[(0, associationToGetterSetterProp_js_1.default)(association)] = null;
1764
+ });
1765
+ // Load all models of type associated that are associated with any of the already loaded Dream models
1766
+ const loadedAssociations = await this.dreamClassQueryWithScopeBypasses(associatedDreamClass, {
1767
+ // The association may remove specific default scopes that would otherwise preclude
1768
+ // certain instances of the associated class from being found.
1769
+ defaultScopesToBypassExceptOnAssociations: association.withoutDefaultScopes,
1770
+ })
1771
+ .where({
1772
+ [associatedDreamClass.primaryKey]: relevantAssociatedModels.map((dream) => dream[association.foreignKey()]),
1773
+ })
1774
+ .all();
1775
+ loadedAssociations.forEach((loadedAssociation) => associatedDreams.push(loadedAssociation));
1776
+ //////////////////////////////////////////////////////////////////////////////////////////////
1777
+ // Associate each loaded association with each dream based on primary key and foreign key type
1778
+ //////////////////////////////////////////////////////////////////////////////////////////////
1779
+ for (const loadedAssociation of loadedAssociations) {
1780
+ dreams
1781
+ .filter((dream) => {
1782
+ return (dream[association.foreignKeyTypeField()] === loadedAssociation['stiBaseClassOrOwnClass'].name &&
1783
+ dream[association.foreignKey()] === association.primaryKeyValue(loadedAssociation));
1784
+ })
1785
+ .forEach((dream) => {
1786
+ dream[association.as] = loadedAssociation;
1787
+ });
1788
+ }
1789
+ ///////////////////////////////////////////////////////////////////////////////////////////////////
1790
+ // end: Associate each loaded association with each dream based on primary key and foreign key type
1791
+ ///////////////////////////////////////////////////////////////////////////////////////////////////
1792
+ }
1793
+ }
1794
+ /**
1795
+ * @internal
1796
+ *
1797
+ * Applies a preload statement
1798
+ */
1799
+ async applyOnePreload(associationName, dreams, onStatement = {}) {
1800
+ if (!Array.isArray(dreams))
1801
+ dreams = [dreams];
1802
+ const dream = dreams.find(dream => dream['getAssociationMetadata'](associationName));
1803
+ if (!dream)
1804
+ return;
1805
+ const association = dream['getAssociationMetadata'](associationName);
1806
+ const dreamClass = dream.constructor;
1807
+ const dreamClassToHydrate = association.modelCB();
1808
+ if ((association.polymorphic && association.type === 'BelongsTo') || Array.isArray(dreamClassToHydrate))
1809
+ return this.preloadPolymorphicBelongsTo(association, dreams);
1810
+ const dreamClassToHydrateColumns = [...dreamClassToHydrate.columns()];
1811
+ const throughColumnsToHydrate = [];
1812
+ const columnsToPluck = dreamClassToHydrateColumns.map(column => this.namespaceColumn(column.toString(), associationName));
1813
+ const asHasAssociation = association;
1814
+ if (asHasAssociation.through && asHasAssociation.preloadThroughColumns) {
1815
+ if ((0, typechecks_js_1.isObject)(asHasAssociation.preloadThroughColumns)) {
1816
+ const preloadMap = asHasAssociation.preloadThroughColumns;
1817
+ Object.keys(preloadMap).forEach(preloadThroughColumn => {
1818
+ throughColumnsToHydrate.push(preloadMap[preloadThroughColumn]);
1819
+ columnsToPluck.push(this.namespaceColumn(preloadThroughColumn, asHasAssociation.through));
1820
+ });
1821
+ }
1822
+ else {
1823
+ const preloadArray = asHasAssociation.preloadThroughColumns;
1824
+ preloadArray.forEach(preloadThroughColumn => {
1825
+ throughColumnsToHydrate.push(preloadThroughColumn);
1826
+ columnsToPluck.push(this.namespaceColumn(preloadThroughColumn, asHasAssociation.through));
1827
+ });
1828
+ }
1829
+ }
1830
+ columnsToPluck.push(this.namespaceColumn(dreamClass.primaryKey, dreamClass.table));
1831
+ const baseClass = dreamClass['stiBaseClassOrOwnClass']['getAssociationMetadata'](associationName)
1832
+ ? dreamClass['stiBaseClassOrOwnClass']
1833
+ : dreamClass;
1834
+ const associationDataScope = this.dreamClassQueryWithScopeBypasses(baseClass, {
1835
+ // In order to stay DRY, preloading leverages the association logic built into
1836
+ // `joins` (by using `pluck`, which calls `joins`). However, baseClass may have
1837
+ // default scopes that would preclude finding that instance. We remove all
1838
+ // default scopes on baseClass, but not subsequent associations, so that the
1839
+ // single query will be able to find each row corresponding to a Dream in `dreams`,
1840
+ // regardless of default scopes on that Dream's class.
1841
+ bypassAllDefaultScopesExceptOnAssociations: true,
1842
+ }).where({
1843
+ [dreamClass.primaryKey]: dreams.map(obj => obj.primaryKeyValue),
1844
+ });
1845
+ const hydrationData = await associationDataScope
1846
+ ._connection(this.connectionOverride)
1847
+ .innerJoin(associationName, (onStatement || {}))
1848
+ .pluck(...columnsToPluck);
1849
+ const preloadedDreamsAndWhatTheyPointTo = hydrationData.map(pluckedData => {
1850
+ const attributes = {};
1851
+ dreamClassToHydrateColumns.forEach((columnName, index) => (attributes[(0, protectAgainstPollutingAssignment_js_1.default)(columnName)] = pluckedData[index]));
1852
+ const hydratedDream = (0, sqlResultToDreamInstance_js_1.default)(dreamClassToHydrate, attributes);
1853
+ throughColumnsToHydrate.forEach((throughAssociationColumn, index) => (hydratedDream.preloadedThroughColumns[throughAssociationColumn] =
1854
+ pluckedData[dreamClassToHydrateColumns.length + index]));
1855
+ return {
1856
+ dream: hydratedDream,
1857
+ pointsToPrimaryKey: pluckedData[pluckedData.length - 1],
1858
+ };
1859
+ });
1860
+ this.hydrateAssociation(dreams, association, preloadedDreamsAndWhatTheyPointTo);
1861
+ return preloadedDreamsAndWhatTheyPointTo.map(obj => obj.dream);
1862
+ }
1863
+ /**
1864
+ * @internal
1865
+ *
1866
+ * Used by loadBuider
1867
+ */
1868
+ async hydratePreload(dream) {
1869
+ await this.applyPreload(this.preloadStatements, this.preloadOnStatements, dream);
1870
+ }
1871
+ /**
1872
+ * @internal
1873
+ *
1874
+ * Applies a preload statement
1875
+ */
1876
+ async applyPreload(preloadStatement, preloadOnStatements, dream) {
1877
+ const keys = Object.keys(preloadStatement);
1878
+ for (const key of keys) {
1879
+ const nestedDreams = await this.applyOnePreload(key, dream, this.applyablePreloadOnStatements(preloadOnStatements[key]));
1880
+ if (nestedDreams) {
1881
+ await this.applyPreload(preloadStatement[key], preloadOnStatements[key], nestedDreams);
1882
+ }
1883
+ }
1884
+ }
1885
+ /**
1886
+ * @internal
1887
+ *
1888
+ * retrieves on statements that can be applied to a preload
1889
+ */
1890
+ applyablePreloadOnStatements(preloadOnStatements) {
1891
+ if (preloadOnStatements === undefined)
1892
+ return undefined;
1893
+ return Object.keys(preloadOnStatements).reduce((agg, key) => {
1894
+ const value = preloadOnStatements[key];
1895
+ // filter out plain objects, but not ops and not on/notOn/onAny statements
1896
+ // because plain objects are just the next level of nested preload
1897
+ if (key === 'on' ||
1898
+ key === 'notOn' ||
1899
+ key === 'onAny' ||
1900
+ value === null ||
1901
+ value.constructor !== Object) {
1902
+ agg[key] = value;
1903
+ }
1904
+ return agg;
1905
+ }, {});
1906
+ }
1907
+ conditionallyApplyDefaultScopes() {
1908
+ if (this.bypassAllDefaultScopes || this.bypassAllDefaultScopesExceptOnAssociations)
1909
+ return this;
1910
+ const thisScopes = this.dreamClass['scopes'].default;
1911
+ let query = this;
1912
+ for (const scope of thisScopes) {
1913
+ if (!(0, shouldBypassDefaultScope_js_1.default)(scope.method, {
1914
+ defaultScopesToBypass: [
1915
+ ...this.defaultScopesToBypass,
1916
+ ...this.defaultScopesToBypassExceptOnAssociations,
1917
+ ],
1918
+ })) {
1919
+ query = this.dreamClass[scope.method](query);
1920
+ }
1921
+ }
1922
+ return query;
1923
+ }
1924
+ // Through associations don't get written into the SQL; they
1925
+ // locate the next association we need to build into the SQL
1926
+ // AND the source to reference on the other side
1927
+ joinsBridgeThroughAssociations({ query, dreamClass, association, previousAssociationTableOrAlias, throughAssociations, joinType, }) {
1928
+ if (association.type === 'BelongsTo' || !association.through) {
1929
+ return {
1930
+ query,
1931
+ dreamClass,
1932
+ association,
1933
+ previousAssociationTableOrAlias,
1934
+ };
1935
+ }
1936
+ else {
1937
+ throughAssociations.push(association);
1938
+ // We have entered joinsBridgeThroughAssociations with the
1939
+ // CompositionAssetAudits HasOne User association, which
1940
+ // is through compositionAsset
1941
+ // We now apply the compositionAsset association (a BelongsTo)
1942
+ // to the query
1943
+ const { query: queryWithThroughAssociationApplied } = this.applyOneJoin({
1944
+ query,
1945
+ dreamClass,
1946
+ previousAssociationTableOrAlias,
1947
+ currentAssociationTableOrAlias: association.through,
1948
+ throughAssociations,
1949
+ joinType,
1950
+ });
1951
+ // The through association has both a `through` and a `source`. The `source`
1952
+ // is the association on the model that has now been joined. In our example,
1953
+ // the `source` is the `user` association on the CompositionAsset model
1954
+ const { newAssociation, throughAssociation, throughClass } = this.followThroughAssociation(dreamClass, association);
1955
+ if (newAssociation.through) {
1956
+ // This new association is itself a through association, so we recursively
1957
+ // call joinsBridgeThroughAssociations
1958
+ return this.joinsBridgeThroughAssociations({
1959
+ query: queryWithThroughAssociationApplied,
1960
+ dreamClass: throughClass,
1961
+ association: newAssociation,
1962
+ previousAssociationTableOrAlias: throughAssociation.as,
1963
+ throughAssociations,
1964
+ joinType,
1965
+ });
1966
+ }
1967
+ else {
1968
+ // This new association is not a through association, so
1969
+ // this is the target association we were looking for
1970
+ return {
1971
+ query: queryWithThroughAssociationApplied,
1972
+ dreamClass: association.modelCB(),
1973
+ association: newAssociation,
1974
+ throughClass,
1975
+ previousAssociationTableOrAlias: association.through,
1976
+ };
1977
+ }
1978
+ }
1979
+ }
1980
+ applyOneJoin({ query, dreamClass, previousAssociationTableOrAlias, currentAssociationTableOrAlias, joinOnStatements = {}, throughAssociations = [], joinType, }) {
1981
+ const { name, alias } = (0, extractAssociationMetadataFromAssociationName_js_1.default)(currentAssociationTableOrAlias);
1982
+ previousAssociationTableOrAlias = (0, extractAssociationMetadataFromAssociationName_js_1.default)(previousAssociationTableOrAlias).alias;
1983
+ currentAssociationTableOrAlias = alias;
1984
+ let association = dreamClass['getAssociationMetadata'](name);
1985
+ if (!association) {
1986
+ throw new JoinAttemptedOnMissingAssociation_js_1.default({
1987
+ dreamClass,
1988
+ associationName: currentAssociationTableOrAlias,
1989
+ });
1990
+ }
1991
+ const results = this.joinsBridgeThroughAssociations({
1992
+ query,
1993
+ dreamClass,
1994
+ association,
1995
+ previousAssociationTableOrAlias,
1996
+ throughAssociations,
1997
+ joinType,
1998
+ });
1999
+ query = results.query;
2000
+ dreamClass = results.dreamClass;
2001
+ association = results.association;
2002
+ const timeToApplyThroughAssociations = throughAssociations.length && throughAssociations[0].source === association.as;
2003
+ const originalPreviousAssociationTableOrAlias = previousAssociationTableOrAlias;
2004
+ previousAssociationTableOrAlias = results.previousAssociationTableOrAlias;
2005
+ const throughClass = results.throughClass;
2006
+ if (timeToApplyThroughAssociations) {
2007
+ ///////////////////////////////////////////////////////////////////////////////////////
2008
+ // when an association is through another association, `joinsBridgeThroughAssociations`
2009
+ // is called, which eventually calls back to this method, passing in the original
2010
+ // through association as `originalAssociation`
2011
+ ///////////////////////////////////////////////////////////////////////////////////////
2012
+ throughAssociations.forEach((throughAssociation) => {
2013
+ if (throughAssociation.type === 'HasMany') {
2014
+ if (query?.distinctOn && throughAssociation.distinct) {
2015
+ query = query.distinctOn(this.distinctColumnNameForAssociation({
2016
+ association: throughAssociation,
2017
+ tableNameOrAlias: throughAssociation.as,
2018
+ foreignKey: throughAssociation.primaryKey(),
2019
+ }));
2020
+ }
2021
+ if (throughAssociation.order) {
2022
+ query = this.applyOrderStatementForAssociation({
2023
+ query,
2024
+ tableNameOrAlias: throughAssociation.as,
2025
+ association: throughAssociation,
2026
+ });
2027
+ }
2028
+ }
2029
+ });
2030
+ }
2031
+ if (association.type === 'BelongsTo') {
2032
+ if (Array.isArray(association.modelCB()))
2033
+ throw new CannotJoinPolymorphicBelongsToError_js_1.default({
2034
+ dreamClass,
2035
+ association,
2036
+ innerJoinStatements: this.innerJoinStatements,
2037
+ leftJoinStatements: this.leftJoinStatements,
2038
+ });
2039
+ const to = association.modelCB().table;
2040
+ const joinTableExpression = currentAssociationTableOrAlias === to
2041
+ ? currentAssociationTableOrAlias
2042
+ : `${to} as ${currentAssociationTableOrAlias}`;
2043
+ query = query[(joinType === 'inner' ? 'innerJoin' : 'leftJoin')](joinTableExpression, (join) => {
2044
+ join = join.onRef(this.namespaceColumn(association.foreignKey(), previousAssociationTableOrAlias), '=', this.namespaceColumn(association.primaryKey(), currentAssociationTableOrAlias));
2045
+ if (timeToApplyThroughAssociations) {
2046
+ throughAssociations.forEach((throughAssociation) => {
2047
+ join = this.applyAssociationOnStatementsToJoinStatement({
2048
+ join,
2049
+ association: throughAssociation,
2050
+ currentAssociationTableOrAlias,
2051
+ previousAssociationTableOrAlias: originalPreviousAssociationTableOrAlias,
2052
+ joinOnStatements,
2053
+ });
2054
+ });
2055
+ }
2056
+ join = this.conditionallyApplyDefaultScopesDependentOnAssociation({
2057
+ join,
2058
+ tableNameOrAlias: currentAssociationTableOrAlias,
2059
+ association,
2060
+ });
2061
+ join = this.applyJoinOnStatements(join, joinOnStatements[currentAssociationTableOrAlias], currentAssociationTableOrAlias);
2062
+ return join;
2063
+ });
2064
+ }
2065
+ else {
2066
+ const to = association.modelCB().table;
2067
+ const joinTableExpression = currentAssociationTableOrAlias === to
2068
+ ? currentAssociationTableOrAlias
2069
+ : `${to} as ${currentAssociationTableOrAlias}`;
2070
+ query = query[(joinType === 'inner' ? 'innerJoin' : 'leftJoin')](joinTableExpression, (join) => {
2071
+ join = join.onRef(this.namespaceColumn(association.primaryKey(), previousAssociationTableOrAlias), '=', this.namespaceColumn(association.foreignKey(), currentAssociationTableOrAlias));
2072
+ if (association.polymorphic) {
2073
+ join = join.on((eb) => this.whereStatementToExpressionWrapper(eb, this.aliasWhereStatement({
2074
+ [association.foreignKeyTypeField()]: throughClass
2075
+ ? throughClass['stiBaseClassOrOwnClass'].name
2076
+ : dreamClass['stiBaseClassOrOwnClass'].name,
2077
+ }, currentAssociationTableOrAlias)));
2078
+ }
2079
+ if (timeToApplyThroughAssociations) {
2080
+ throughAssociations.forEach((throughAssociation) => {
2081
+ join = this.applyAssociationOnStatementsToJoinStatement({
2082
+ join,
2083
+ association: throughAssociation,
2084
+ currentAssociationTableOrAlias,
2085
+ previousAssociationTableOrAlias: originalPreviousAssociationTableOrAlias,
2086
+ joinOnStatements,
2087
+ });
2088
+ });
2089
+ }
2090
+ join = this.applyAssociationOnStatementsToJoinStatement({
2091
+ join,
2092
+ association,
2093
+ currentAssociationTableOrAlias,
2094
+ previousAssociationTableOrAlias,
2095
+ joinOnStatements,
2096
+ });
2097
+ join = this.conditionallyApplyDefaultScopesDependentOnAssociation({
2098
+ join,
2099
+ tableNameOrAlias: currentAssociationTableOrAlias,
2100
+ association,
2101
+ });
2102
+ join = this.applyJoinOnStatements(join, joinOnStatements[currentAssociationTableOrAlias], currentAssociationTableOrAlias);
2103
+ return join;
2104
+ });
2105
+ if (association.type === 'HasMany') {
2106
+ if (association.order) {
2107
+ query = this.applyOrderStatementForAssociation({
2108
+ query,
2109
+ tableNameOrAlias: currentAssociationTableOrAlias,
2110
+ association,
2111
+ });
2112
+ }
2113
+ if (query.distinctOn && association.distinct) {
2114
+ query = query.distinctOn(this.distinctColumnNameForAssociation({
2115
+ association,
2116
+ tableNameOrAlias: currentAssociationTableOrAlias,
2117
+ foreignKey: association.foreignKey(),
2118
+ }));
2119
+ }
2120
+ }
2121
+ }
2122
+ return {
2123
+ query,
2124
+ association,
2125
+ previousAssociationTableOrAlias,
2126
+ currentAssociationTableOrAlias,
2127
+ };
2128
+ }
2129
+ applyAssociationOnStatementsToJoinStatement({ join, currentAssociationTableOrAlias, previousAssociationTableOrAlias, association, joinOnStatements, }) {
2130
+ if (association.on) {
2131
+ this.throwUnlessAllRequiredWhereClausesProvided(association, currentAssociationTableOrAlias, joinOnStatements);
2132
+ join = join.on((eb) => this.whereStatementToExpressionWrapper(eb, this.aliasWhereStatement(association.on, currentAssociationTableOrAlias), { disallowSimilarityOperator: false }));
2133
+ }
2134
+ if (association.notOn) {
2135
+ join = join.on((eb) => this.whereStatementToExpressionWrapper(eb, this.aliasWhereStatement(association.notOn, currentAssociationTableOrAlias), { negate: true }));
2136
+ }
2137
+ if (association.onAny) {
2138
+ join = join.on((eb) => eb.or(association.onAny.map(whereAnyStatement => this.whereStatementToExpressionWrapper(eb, this.aliasWhereStatement(whereAnyStatement, currentAssociationTableOrAlias), { disallowSimilarityOperator: false }))));
2139
+ }
2140
+ if (association.selfOn) {
2141
+ join = join.on((eb) => this.whereStatementToExpressionWrapper(eb, this.rawifiedSelfOnClause({
2142
+ associationAlias: association.as,
2143
+ selfAlias: previousAssociationTableOrAlias,
2144
+ selfOnClause: association.selfOn,
2145
+ })));
2146
+ }
2147
+ if (association.selfNotOn) {
2148
+ join = join.on((eb) => this.whereStatementToExpressionWrapper(eb, this.rawifiedSelfOnClause({
2149
+ associationAlias: association.as,
2150
+ selfAlias: previousAssociationTableOrAlias,
2151
+ selfOnClause: association.selfNotOn,
2152
+ }), { negate: true }));
2153
+ }
2154
+ return join;
2155
+ }
2156
+ conditionallyApplyDefaultScopesDependentOnAssociation({ join, tableNameOrAlias, association, }) {
2157
+ let scopesQuery = new Query(this.dreamInstance);
2158
+ const associationClass = association.modelCB();
2159
+ const associationScopes = associationClass['scopes'].default;
2160
+ for (const scope of associationScopes) {
2161
+ if (!(0, shouldBypassDefaultScope_js_1.default)(scope.method, {
2162
+ bypassAllDefaultScopes: this.bypassAllDefaultScopes,
2163
+ defaultScopesToBypass: [...this.defaultScopesToBypass, ...(association.withoutDefaultScopes || [])],
2164
+ })) {
2165
+ const tempQuery = associationClass[scope.method](scopesQuery);
2166
+ // The scope method on a Dream model should return a clone of the Query it receives
2167
+ // (e.g. by returning `scope.where(...)`), but in case the function doesn't return,
2168
+ // or returns the wrong thing, we check before overriding `scopesQuery` with what the
2169
+ // method returned.
2170
+ if (tempQuery && tempQuery.constructor === scopesQuery.constructor)
2171
+ scopesQuery = tempQuery;
2172
+ }
2173
+ }
2174
+ if (scopesQuery.whereStatements.length) {
2175
+ join = join.on((eb) => eb.and(scopesQuery.whereStatements.flatMap(whereStatement => this.whereStatementToExpressionWrapper(eb, this.aliasWhereStatement(whereStatement, tableNameOrAlias), { disallowSimilarityOperator: false }))));
2176
+ }
2177
+ return join;
2178
+ }
2179
+ distinctColumnNameForAssociation({ association, tableNameOrAlias, foreignKey, }) {
2180
+ if (!association.distinct)
2181
+ return null;
2182
+ if (association.distinct === true)
2183
+ return this.namespaceColumn(foreignKey, tableNameOrAlias);
2184
+ return this.namespaceColumn(association.distinct, tableNameOrAlias);
2185
+ }
2186
+ recursivelyJoin({ query, joinsStatement, joinOnStatements, dreamClass, previousAssociationTableOrAlias, joinType, }) {
2187
+ for (const currentAssociationTableOrAlias of Object.keys(joinsStatement)) {
2188
+ const results = this.applyOneJoin({
2189
+ query,
2190
+ dreamClass,
2191
+ previousAssociationTableOrAlias,
2192
+ currentAssociationTableOrAlias,
2193
+ joinOnStatements,
2194
+ joinType,
2195
+ });
2196
+ query = results.query;
2197
+ const association = results.association;
2198
+ query = this.recursivelyJoin({
2199
+ query,
2200
+ joinsStatement: joinsStatement[currentAssociationTableOrAlias],
2201
+ joinOnStatements: joinOnStatements[currentAssociationTableOrAlias],
2202
+ dreamClass: association.modelCB(),
2203
+ previousAssociationTableOrAlias: currentAssociationTableOrAlias,
2204
+ joinType,
2205
+ });
2206
+ }
2207
+ return query;
2208
+ }
2209
+ throwUnlessAllRequiredWhereClausesProvided(association, namespace, joinOnStatements) {
2210
+ const whereStatement = association.on;
2211
+ const columnsRequiringWhereStatements = Object.keys(whereStatement).reduce((agg, column) => {
2212
+ if (whereStatement[column] === types_js_1.DreamConst.required)
2213
+ agg.push(column);
2214
+ return agg;
2215
+ }, []);
2216
+ const missingRequiredWhereStatements = columnsRequiringWhereStatements.filter(column => joinOnStatements[namespace]?.on?.[column] === undefined);
2217
+ if (missingRequiredWhereStatements.length)
2218
+ throw new MissingRequiredAssociationOnClause_js_1.default(association, missingRequiredWhereStatements[0]);
2219
+ }
2220
+ applyOrderStatementForAssociation({ query, tableNameOrAlias, association, }) {
2221
+ if (!query.orderBy)
2222
+ return query;
2223
+ let selectQuery = query;
2224
+ const orderStatement = association.order;
2225
+ if ((0, typechecks_js_1.isString)(orderStatement)) {
2226
+ selectQuery = selectQuery.orderBy(this.namespaceColumn(orderStatement, tableNameOrAlias), 'asc');
2227
+ }
2228
+ else {
2229
+ Object.keys(orderStatement).forEach(column => {
2230
+ const direction = orderStatement[column];
2231
+ selectQuery = selectQuery.orderBy(this.namespaceColumn(column, tableNameOrAlias), direction);
2232
+ });
2233
+ }
2234
+ return selectQuery;
2235
+ }
2236
+ inArrayWithNull_or_notInArrayWithoutNull_ExpressionBuilder(eb, a, b, c) {
2237
+ const isNullStatement = eb(a, 'is', null);
2238
+ const compactedC = (0, compact_js_1.default)(c);
2239
+ if (compactedC.length)
2240
+ return eb.or([eb(a, b, compactedC), isNullStatement]);
2241
+ // not in an empty array means match everything
2242
+ if (b === 'not in')
2243
+ return (0, kysely_1.sql) `TRUE`;
2244
+ return isNullStatement;
2245
+ }
2246
+ inArrayWithoutNullExpressionBuilder(eb, a, b, c) {
2247
+ const isNotNullStatement = eb(a, 'is not', null);
2248
+ const compactedC = (0, compact_js_1.default)(c);
2249
+ if (compactedC.length)
2250
+ return eb.and([eb(a, 'in', compactedC), isNotNullStatement]);
2251
+ // in an empty array means match nothing
2252
+ return (0, kysely_1.sql) `FALSE`;
2253
+ }
2254
+ notInArrayWithNullExpressionBuilder(eb, a, b, c) {
2255
+ const isNullStatement = eb(a, 'is not', null);
2256
+ const compactedC = (0, compact_js_1.default)(c);
2257
+ if (compactedC.length)
2258
+ return eb.and([eb(a, 'not in', compactedC), isNullStatement]);
2259
+ return isNullStatement;
2260
+ }
2261
+ whereStatementToExpressionWrapper(eb, whereStatement, { negate = false, disallowSimilarityOperator = true, } = {}) {
2262
+ const clauses = (0, compact_js_1.default)(Object.keys(whereStatement)
2263
+ .filter(key => whereStatement[key] !== types_js_1.DreamConst.required)
2264
+ .map(attr => {
2265
+ const val = whereStatement[attr];
2266
+ if (val?.isOpsStatement &&
2267
+ val.shouldBypassWhereStatement) {
2268
+ if (disallowSimilarityOperator)
2269
+ throw new Error('Similarity operator may not be used in whereAny');
2270
+ // some ops statements are handled specifically in the select portion of the query,
2271
+ // and should be ommited from the where clause directly
2272
+ return;
2273
+ }
2274
+ const { a, b, c, a2, b2, c2 } = this.dreamWhereStatementToExpressionBuilderParts(attr, val);
2275
+ // postgres is unable to handle WHERE IN statements with blank arrays, such as in
2276
+ // "WHERE id IN ()", meaning that:
2277
+ // 1. If we receive a blank array during an IN comparison,
2278
+ // then we need to simply regurgitate a where statement which
2279
+ // guarantees no records.
2280
+ // 2. If we receive a blank array during a NOT IN comparison,
2281
+ // then it is the same as the where statement not being present at all,
2282
+ // resulting in a noop on our end
2283
+ //
2284
+ if (Array.isArray(c)) {
2285
+ if ((b === 'in' && c.includes(null)) || (b === 'not in' && !c.includes(null))) {
2286
+ return this.inArrayWithNull_or_notInArrayWithoutNull_ExpressionBuilder(eb, a, b, c);
2287
+ }
2288
+ else if (negate && b === 'in' && !c.includes(null)) {
2289
+ return this.inArrayWithoutNullExpressionBuilder(eb, a, b, c);
2290
+ }
2291
+ else if (b === 'not in' && c.includes(null)) {
2292
+ return this.notInArrayWithNullExpressionBuilder(eb, a, b, c);
2293
+ }
2294
+ const compactedC = (0, compact_js_1.default)(c);
2295
+ if (b === 'in' && compactedC.length === 0) {
2296
+ // in an empty array means match nothing
2297
+ return (0, kysely_1.sql) `FALSE`;
2298
+ }
2299
+ else if (b === 'not in' && compactedC.length === 0) {
2300
+ // not in an empty array means match everything
2301
+ return (0, kysely_1.sql) `TRUE`;
2302
+ }
2303
+ else {
2304
+ return eb(a, b, compactedC);
2305
+ }
2306
+ //
2307
+ }
2308
+ else if (b === '=' && c === null) {
2309
+ return eb(a, 'is', null);
2310
+ //
2311
+ }
2312
+ else if (b === '!=' && c === null) {
2313
+ return eb(a, 'is not', null);
2314
+ //
2315
+ }
2316
+ else if (b === '=' && negate) {
2317
+ return eb.and([eb(a, '=', c), eb(a, 'is not', null)]);
2318
+ //
2319
+ }
2320
+ else if (b === '!=' && c !== null) {
2321
+ return eb.or([eb(a, '!=', c), eb(a, 'is', null)]);
2322
+ //
2323
+ }
2324
+ else {
2325
+ const expression = eb(a, b, c);
2326
+ if (b2)
2327
+ return expression.and(eb(a2, b2, c2));
2328
+ return expression;
2329
+ }
2330
+ }));
2331
+ return negate ? eb.not(eb.parens(eb.and(clauses))) : eb.and(clauses);
2332
+ }
2333
+ dreamWhereStatementToExpressionBuilderParts(attr, val) {
2334
+ let a;
2335
+ let b;
2336
+ let c;
2337
+ let a2 = null;
2338
+ let b2 = null;
2339
+ let c2 = null;
2340
+ if (val instanceof Function && val !== types_js_1.DreamConst.passthrough) {
2341
+ val = val();
2342
+ }
2343
+ else if (val === types_js_1.DreamConst.passthrough) {
2344
+ const column = attr.split('.').pop();
2345
+ if (this.passthroughOnStatement[column] === undefined)
2346
+ throw new MissingRequiredPassthroughForAssociationOnClause_js_1.default(column);
2347
+ val = this.passthroughOnStatement[column];
2348
+ }
2349
+ if (val === null) {
2350
+ a = attr;
2351
+ b = 'is';
2352
+ c = val;
2353
+ }
2354
+ else if (['SelectQueryBuilder', 'SelectQueryBuilderImpl'].includes(val?.constructor?.name)) {
2355
+ a = attr;
2356
+ b = 'in';
2357
+ c = val;
2358
+ }
2359
+ else if (Array.isArray(val)) {
2360
+ a = attr;
2361
+ b = 'in';
2362
+ c = val;
2363
+ }
2364
+ else if (val instanceof curried_ops_statement_js_1.default) {
2365
+ val = val.toOpsStatement(this.dreamClass, attr);
2366
+ a = attr;
2367
+ b = val.operator;
2368
+ c = val.value;
2369
+ }
2370
+ else if (val instanceof ops_statement_js_1.default) {
2371
+ a = attr;
2372
+ b = val.operator;
2373
+ c = val.value;
2374
+ }
2375
+ else if (val instanceof range_js_1.Range) {
2376
+ const rangeStart = val.begin;
2377
+ const rangeEnd = val.end;
2378
+ const excludeEnd = val.excludeEnd;
2379
+ if (rangeStart && rangeEnd) {
2380
+ a = attr;
2381
+ b = '>=';
2382
+ c = rangeStart;
2383
+ a2 = attr;
2384
+ b2 = excludeEnd ? '<' : '<=';
2385
+ c2 = rangeEnd;
2386
+ }
2387
+ else if (rangeStart) {
2388
+ a = attr;
2389
+ b = '>=';
2390
+ c = rangeStart;
2391
+ }
2392
+ else {
2393
+ a = attr;
2394
+ b = excludeEnd ? '<' : '<=';
2395
+ c = rangeEnd;
2396
+ }
2397
+ }
2398
+ else {
2399
+ a = attr;
2400
+ b = '=';
2401
+ c = val;
2402
+ }
2403
+ if (c instanceof luxon_1.DateTime || c instanceof CalendarDate_js_1.default)
2404
+ c = c.toJSDate();
2405
+ if (c2 instanceof luxon_1.DateTime || c2 instanceof CalendarDate_js_1.default)
2406
+ c2 = c2.toJSDate();
2407
+ if (a && c === undefined)
2408
+ throw new CannotPassUndefinedAsAValueToAWhereClause_js_1.default(this.dreamClass, a);
2409
+ if (a2 && c2 === undefined)
2410
+ throw new CannotPassUndefinedAsAValueToAWhereClause_js_1.default(this.dreamClass, a2);
2411
+ return { a, b, c, a2, b2, c2 };
2412
+ }
2413
+ applyJoinOnStatements(join, joinOnStatement, rootTableOrAssociationAlias) {
2414
+ if (!joinOnStatement)
2415
+ return join;
2416
+ join = this._applyJoinOnStatements(join, joinOnStatement.on, rootTableOrAssociationAlias);
2417
+ join = this._applyJoinOnStatements(join, joinOnStatement.notOn, rootTableOrAssociationAlias, {
2418
+ negate: true,
2419
+ });
2420
+ join = this._applyJoinOnAnyStatements(join, joinOnStatement.onAny, rootTableOrAssociationAlias);
2421
+ return join;
2422
+ }
2423
+ _applyJoinOnStatements(join, joinOnStatement, rootTableOrAssociationAlias, { negate = false, } = {}) {
2424
+ if (!joinOnStatement)
2425
+ return join;
2426
+ return join.on((eb) => this.joinOnStatementToExpressionWrapper(joinOnStatement, rootTableOrAssociationAlias, eb, {
2427
+ negate,
2428
+ disallowSimilarityOperator: negate,
2429
+ }));
2430
+ }
2431
+ _applyJoinOnAnyStatements(join, joinOnAnyStatement, rootTableOrAssociationAlias) {
2432
+ if (!joinOnAnyStatement)
2433
+ return join;
2434
+ if (!joinOnAnyStatement.length)
2435
+ return join;
2436
+ return join.on((eb) => {
2437
+ return eb.or(joinOnAnyStatement.map(joinOnStatement => this.joinOnStatementToExpressionWrapper(joinOnStatement, rootTableOrAssociationAlias, eb)));
2438
+ });
2439
+ }
2440
+ joinOnStatementToExpressionWrapper(joinOnStatement, rootTableOrAssociationAlias, eb, { negate = false, disallowSimilarityOperator = true, } = {}) {
2441
+ return this.whereStatementToExpressionWrapper(eb, Object.keys(joinOnStatement).reduce((agg, key) => {
2442
+ agg[this.namespaceColumn(key.toString(), rootTableOrAssociationAlias)] = joinOnStatement[key];
2443
+ return agg;
2444
+ }, {}), {
2445
+ negate,
2446
+ disallowSimilarityOperator,
2447
+ });
2448
+ }
2449
+ buildCommon(kyselyQuery) {
2450
+ this.checkForQueryViolations();
2451
+ const query = this.conditionallyApplyDefaultScopes();
2452
+ if (!(0, isEmpty_js_1.default)(query.innerJoinStatements)) {
2453
+ kyselyQuery = query.recursivelyJoin({
2454
+ query: kyselyQuery,
2455
+ joinsStatement: query.innerJoinStatements,
2456
+ joinOnStatements: query.innerJoinOnStatements,
2457
+ dreamClass: query.dreamClass,
2458
+ previousAssociationTableOrAlias: this.baseSqlAlias,
2459
+ joinType: 'inner',
2460
+ });
2461
+ }
2462
+ if (!(0, isEmpty_js_1.default)(query.leftJoinStatements)) {
2463
+ kyselyQuery = query.recursivelyJoin({
2464
+ query: kyselyQuery,
2465
+ joinsStatement: query.leftJoinStatements,
2466
+ joinOnStatements: query.leftJoinOnStatements,
2467
+ dreamClass: query.dreamClass,
2468
+ previousAssociationTableOrAlias: this.baseSqlAlias,
2469
+ joinType: 'left',
2470
+ });
2471
+ }
2472
+ if (query.whereStatements.length || query.whereNotStatements.length || query.whereAnyStatements.length) {
2473
+ kyselyQuery = kyselyQuery.where((eb) => eb.and([
2474
+ ...this.aliasWhereStatements(query.whereStatements, query.baseSqlAlias).map(whereStatement => this.whereStatementToExpressionWrapper(eb, whereStatement, {
2475
+ disallowSimilarityOperator: false,
2476
+ })),
2477
+ ...this.aliasWhereStatements(query.whereNotStatements, query.baseSqlAlias).map(whereNotStatement => this.whereStatementToExpressionWrapper(eb, whereNotStatement, { negate: true })),
2478
+ ...query.whereAnyStatements.map(whereAnyStatements => eb.or(this.aliasWhereStatements(whereAnyStatements, query.baseSqlAlias).map(whereAnyStatement => this.whereStatementToExpressionWrapper(eb, whereAnyStatement)))),
2479
+ ]));
2480
+ }
2481
+ return kyselyQuery;
2482
+ }
2483
+ checkForQueryViolations() {
2484
+ const invalidWhereNotClauses = this.similarityStatementBuilder().whereNotStatementsWithSimilarityClauses();
2485
+ if (invalidWhereNotClauses.length) {
2486
+ const { tableName, columnName, opsStatement } = invalidWhereNotClauses[0];
2487
+ throw new CannotNegateSimilarityClause_js_1.default(tableName, columnName, opsStatement.value);
2488
+ }
2489
+ }
2490
+ aliasWhereStatements(whereStatements, alias) {
2491
+ return whereStatements.map(whereStatement => this.aliasWhereStatement(whereStatement, alias));
2492
+ }
2493
+ aliasWhereStatement(whereStatement, alias) {
2494
+ return Object.keys(whereStatement).reduce((aliasedWhere, key) => {
2495
+ aliasedWhere[this.namespaceColumn(key, alias)] = whereStatement[key];
2496
+ return aliasedWhere;
2497
+ }, {});
2498
+ }
2499
+ rawifiedSelfOnClause({ associationAlias, selfAlias, selfOnClause, }) {
2500
+ const alphanumericUnderscoreRegexp = /[^a-zA-Z0-9_]/g;
2501
+ selfAlias = selfAlias.replace(alphanumericUnderscoreRegexp, '');
2502
+ return Object.keys(selfOnClause).reduce((acc, key) => {
2503
+ const selfColumn = selfOnClause[key]?.replace(alphanumericUnderscoreRegexp, '');
2504
+ if (!selfColumn)
2505
+ return acc;
2506
+ acc[this.namespaceColumn(key, associationAlias)] = kysely_1.sql.raw(`"${(0, snakeify_js_1.default)(selfAlias)}"."${(0, snakeify_js_1.default)(selfColumn)}"`);
2507
+ return acc;
2508
+ }, {});
2509
+ }
2510
+ buildDelete() {
2511
+ const kyselyQuery = this.dbFor('delete').deleteFrom(this.baseSqlAlias);
2512
+ const results = this.attachLimitAndOrderStatementsToNonSelectQuery(kyselyQuery);
2513
+ return results.clone.buildCommon(results.kyselyQuery);
2514
+ }
2515
+ buildSelect({ bypassSelectAll = false, bypassOrder = false, columns, } = {}) {
2516
+ let kyselyQuery;
2517
+ if (this.baseSelectQuery) {
2518
+ kyselyQuery = (this.connectionOverride
2519
+ ? this.baseSelectQuery.connection(this.connectionOverride)
2520
+ : this.baseSelectQuery).buildSelect({ bypassSelectAll: true });
2521
+ }
2522
+ else {
2523
+ const from = this.baseSqlAlias === this.tableName ? this.tableName : `${this.tableName} as ${this.baseSqlAlias}`;
2524
+ kyselyQuery = this.dbFor('select').selectFrom(from);
2525
+ }
2526
+ if (this.distinctColumn) {
2527
+ kyselyQuery = kyselyQuery.distinctOn(this.distinctColumn);
2528
+ }
2529
+ kyselyQuery = this.buildCommon(kyselyQuery);
2530
+ kyselyQuery = this.conditionallyAttachSimilarityColumnsToSelect(kyselyQuery, {
2531
+ bypassOrder: bypassOrder || !!this.distinctColumn,
2532
+ });
2533
+ if (this.orderStatements.length && !bypassOrder) {
2534
+ this.orderStatements.forEach(orderStatement => {
2535
+ kyselyQuery = kyselyQuery.orderBy(this.namespaceColumn(orderStatement.column), (0, orderByDirection_js_1.default)(orderStatement.direction));
2536
+ });
2537
+ }
2538
+ if (this.limitStatement)
2539
+ kyselyQuery = kyselyQuery.limit(this.limitStatement);
2540
+ if (this.offsetStatement)
2541
+ kyselyQuery = kyselyQuery.offset(this.offsetStatement);
2542
+ if (columns) {
2543
+ kyselyQuery = kyselyQuery.select(this.columnsWithRequiredLoadColumns(columns).map(column => this.namespaceColumn(column)));
2544
+ }
2545
+ else if (!bypassSelectAll) {
2546
+ kyselyQuery = kyselyQuery.selectAll(this.baseSqlAlias);
2547
+ }
2548
+ return kyselyQuery;
2549
+ }
2550
+ columnsWithRequiredLoadColumns(columns) {
2551
+ return (0, uniq_js_1.default)((0, compact_js_1.default)([this.dreamClass.primaryKey, this.dreamClass['isSTIBase'] ? 'type' : null, ...columns]));
2552
+ }
2553
+ buildUpdate(attributes) {
2554
+ let kyselyQuery = this.dbFor('update')
2555
+ .updateTable(this.tableName)
2556
+ .set(attributes);
2557
+ kyselyQuery = this.conditionallyAttachSimilarityColumnsToUpdate(kyselyQuery);
2558
+ const results = this.attachLimitAndOrderStatementsToNonSelectQuery(kyselyQuery);
2559
+ return results.clone.buildCommon(results.kyselyQuery);
2560
+ }
2561
+ attachLimitAndOrderStatementsToNonSelectQuery(kyselyQuery) {
2562
+ if (this.limitStatement || this.orderStatements.length) {
2563
+ kyselyQuery = kyselyQuery.where((eb) => {
2564
+ const subquery = this.nestedSelect(this.dreamInstance.primaryKey);
2565
+ return eb(this.dreamInstance.primaryKey, 'in', subquery);
2566
+ });
2567
+ return {
2568
+ kyselyQuery,
2569
+ clone: this.clone({ where: null, whereNot: null, order: null, limit: null }),
2570
+ };
2571
+ }
2572
+ return { kyselyQuery, clone: this };
2573
+ }
2574
+ get hasSimilarityClauses() {
2575
+ return this.similarityStatementBuilder().hasSimilarityClauses;
2576
+ }
2577
+ similarityStatementBuilder() {
2578
+ return new SimilarityBuilder_js_1.default(this.dreamInstance, {
2579
+ where: [...this.whereStatements],
2580
+ whereNot: [...this.whereNotStatements],
2581
+ joinOnStatements: this.innerJoinOnStatements,
2582
+ transaction: this.dreamTransaction,
2583
+ connection: this.connectionOverride,
2584
+ });
2585
+ }
2586
+ conditionallyAttachSimilarityColumnsToSelect(kyselyQuery, { bypassOrder = false } = {}) {
2587
+ const similarityBuilder = this.similarityStatementBuilder();
2588
+ if (similarityBuilder.hasSimilarityClauses) {
2589
+ kyselyQuery = similarityBuilder.select(kyselyQuery, { bypassOrder });
2590
+ }
2591
+ return kyselyQuery;
2592
+ }
2593
+ conditionallyAttachSimilarityColumnsToUpdate(kyselyQuery) {
2594
+ const similarityBuilder = this.similarityStatementBuilder();
2595
+ if (similarityBuilder.hasSimilarityClauses) {
2596
+ kyselyQuery = similarityBuilder.update(kyselyQuery);
2597
+ }
2598
+ return kyselyQuery;
2599
+ }
2600
+ invertOrder() {
2601
+ let query = this.clone({ order: null });
2602
+ for (const orderStatement of this.orderStatements) {
2603
+ query = query.order({
2604
+ [orderStatement.column]: orderStatement.direction === 'desc' ? 'asc' : 'desc',
2605
+ });
2606
+ }
2607
+ return query;
2608
+ }
2609
+ }
2610
+ exports.default = Query;
2611
+ function getSourceAssociation(dream, sourceName) {
2612
+ if (!dream)
2613
+ return;
2614
+ if (!sourceName)
2615
+ return;
2616
+ return (dream['getAssociationMetadata'](sourceName) ||
2617
+ dream['getAssociationMetadata'](pluralize_esm_1.default.singular(sourceName)));
2618
+ }