@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,2981 @@
1
+ import { DateTime } from 'luxon';
2
+ import { pgErrorType } from './db/errors.js';
3
+ import db from './db/index.js';
4
+ import associationToGetterSetterProp from './decorators/associations/associationToGetterSetterProp.js';
5
+ import { blankAssociationsFactory, } from './decorators/associations/shared.js';
6
+ import { blankHooksFactory } from './decorators/hooks/shared.js';
7
+ import resortAllRecords from './decorators/sortable/helpers/resortAllRecords.js';
8
+ import DreamClassTransactionBuilder from './dream/DreamClassTransactionBuilder.js';
9
+ import DreamInstanceTransactionBuilder from './dream/DreamInstanceTransactionBuilder.js';
10
+ import DreamTransaction from './dream/DreamTransaction.js';
11
+ import associationQuery from './dream/internal/associations/associationQuery.js';
12
+ import associationUpdateQuery from './dream/internal/associations/associationUpdateQuery.js';
13
+ import createAssociation from './dream/internal/associations/createAssociation.js';
14
+ import destroyAssociation from './dream/internal/associations/destroyAssociation.js';
15
+ import undestroyAssociation from './dream/internal/associations/undestroyAssociation.js';
16
+ import destroyDream from './dream/internal/destroyDream.js';
17
+ import { destroyOptions, reallyDestroyOptions, undestroyOptions, } from './dream/internal/destroyOptions.js';
18
+ import ensureSTITypeFieldIsSet from './dream/internal/ensureSTITypeFieldIsSet.js';
19
+ import extractAssociationMetadataFromAssociationName from './dream/internal/extractAssociationMetadataFromAssociationName.js';
20
+ import reload from './dream/internal/reload.js';
21
+ import runValidations from './dream/internal/runValidations.js';
22
+ import saveDream from './dream/internal/saveDream.js';
23
+ import { DEFAULT_BYPASS_ALL_DEFAULT_SCOPES, DEFAULT_DEFAULT_SCOPES_TO_BYPASS, DEFAULT_SKIP_HOOKS, } from './dream/internal/scopeHelpers.js';
24
+ import undestroyDream from './dream/internal/undestroyDream.js';
25
+ import LeftJoinLoadBuilder from './dream/LeftJoinLoadBuilder.js';
26
+ import LoadBuilder from './dream/LoadBuilder.js';
27
+ import Query from './dream/Query.js';
28
+ import CannotPassNullOrUndefinedToRequiredBelongsTo from './errors/associations/CannotPassNullOrUndefinedToRequiredBelongsTo.js';
29
+ import CanOnlyPassBelongsToModelParam from './errors/associations/CanOnlyPassBelongsToModelParam.js';
30
+ import NonLoadedAssociation from './errors/associations/NonLoadedAssociation.js';
31
+ import CannotCallUndestroyOnANonSoftDeleteModel from './errors/CannotCallUndestroyOnANonSoftDeleteModel.js';
32
+ import ConstructorOnlyForInternalUse from './errors/ConstructorOnlyForInternalUse.js';
33
+ import CreateOrFindByFailedToCreateAndFind from './errors/CreateOrFindByFailedToCreateAndFind.js';
34
+ import GlobalNameNotSet from './errors/dream-application/GlobalNameNotSet.js';
35
+ import MissingSerializer from './errors/MissingSerializersDefinition.js';
36
+ import MissingTable from './errors/MissingTable.js';
37
+ import NonExistentScopeProvidedToResort from './errors/NonExistentScopeProvidedToResort.js';
38
+ import CalendarDate from './helpers/CalendarDate.js';
39
+ import cloneDeepSafe from './helpers/cloneDeepSafe.js';
40
+ import cachedTypeForAttribute from './helpers/db/cachedTypeForAttribute.js';
41
+ import isJsonColumn from './helpers/db/types/isJsonColumn.js';
42
+ import inferSerializerFromDreamOrViewModel from './helpers/inferSerializerFromDreamOrViewModel.js';
43
+ import { isString } from './helpers/typechecks.js';
44
+ export default class Dream {
45
+ DB;
46
+ /**
47
+ * @internal
48
+ *
49
+ * This getter will throw an error when developers use .toEqual instead of
50
+ * useToMatchDreamModels or useToMatchDreamModel in a jest spec. This
51
+ * must be the first getter in the class in order for this to work, so don't move it.
52
+ *
53
+ */
54
+ get _useToMatchDreamModels() {
55
+ throw new Error(`
56
+ Hi there! It looks like you're trying to compare a Dream model in
57
+ a Jest expectation using \`toEqual\`. That won't work.
58
+ Instead, use \`toMatchDreamModel\` or \`toMatchDreamModels\`.
59
+
60
+ For example, instead of:
61
+
62
+ expect(balloons).toEqual([balloon])
63
+
64
+ write:
65
+
66
+ expect(balloons).toMatchDreamModels([balloon])
67
+ `);
68
+ }
69
+ /**
70
+ * @internal
71
+ *
72
+ * Modern Javascript sets all properties that do not have an explicit
73
+ * assignment within the constructor to undefined in an implicit constructor.
74
+ * Since the Dream constructor sets the value of properties of instances of
75
+ * classes that extend Dream (e.g. when passing attributes to #new or #create
76
+ * or when loading a model via one of the #find methods or #all), we need to
77
+ * prevent those properties from being set back to undefined. Since all
78
+ * properties corresponding to a database column get a setter, we achieve this
79
+ * protection by including a guard in the setters that returns if this
80
+ * property is set.
81
+ *
82
+ */
83
+ columnSetterGuardActivated = false;
84
+ /**
85
+ * @internal
86
+ *
87
+ * Certain features (e.g. passing a Dream instance to `create` so that it automatically destructures polymorphic type and primary key)
88
+ * need static access to things set up by decorators (e.g. associations). Stage 3 Decorators change the context that is available
89
+ * at decoration time such that the class of a property being decorated is only avilable during instance instantiation. In order
90
+ * to only apply static values once, on boot, `globallyInitializingDecorators` is set to true on Dream, and all Dream models are instantiated.
91
+ *
92
+ */
93
+ static globallyInitializingDecorators = false;
94
+ get schema() {
95
+ throw new Error('Must define schema getter in ApplicationModel');
96
+ }
97
+ get globalSchema() {
98
+ throw new Error('Must define schema getter in ApplicationModel');
99
+ }
100
+ /**
101
+ * Shadows #primaryKey, a getter which can be overwritten to customize the id field
102
+ * for a given model.
103
+ *
104
+ * @returns string
105
+ */
106
+ static get primaryKey() {
107
+ return this.prototype.primaryKey;
108
+ }
109
+ /**
110
+ * Shadows #table, a getter which can be overwritten to customize the table field
111
+ * for a given model.
112
+ *
113
+ * @returns string
114
+ */
115
+ static get table() {
116
+ return this.prototype.table;
117
+ }
118
+ /**
119
+ * A getter which can be overwritten to customize the automatic createdAt timestamp field
120
+ * for a given model.
121
+ *
122
+ * ```ts
123
+ * class User extends ApplicationModel {
124
+ * public get createdAtField() {
125
+ * return 'createdAtTimestamp' as const
126
+ * }
127
+ * }
128
+ *
129
+ * const user = await User.first()
130
+ * user.createdAtTimestamp // returns the DateTime that this user was created
131
+ *
132
+ * @returns string
133
+ */
134
+ get createdAtField() {
135
+ return 'createdAt';
136
+ }
137
+ /**
138
+ * A getter which can be overwritten to customize the automatic updatedAt timestamp field
139
+ * for a given model.
140
+ *
141
+ * ```ts
142
+ * class User extends ApplicationModel {
143
+ * public get updatedAtField() {
144
+ * return 'updatedAtTimestamp' as const
145
+ * }
146
+ * }
147
+ *
148
+ * const user = await User.first()
149
+ * user.updatedAtTimestamp // returns the DateTime that this user was updated
150
+ * ```
151
+ *
152
+ * @returns string
153
+ */
154
+ get updatedAtField() {
155
+ return 'updatedAt';
156
+ }
157
+ get deletedAtField() {
158
+ return 'deletedAt';
159
+ }
160
+ /**
161
+ * @internal
162
+ *
163
+ * Model storage for association metadata, set when using the association decorators like:
164
+ * @Deco.HasOne
165
+ * @Deco.HasMany
166
+ * @Deco.BelongsTo
167
+ */
168
+ static associationMetadataByType = blankAssociationsFactory(this, {
169
+ freeze: true,
170
+ });
171
+ /**
172
+ * @internal
173
+ *
174
+ * Model storage for scope metadata, set when using the Scope decorator
175
+ * (this default assignment simply ensures that it is
176
+ * always an array rather than undefined,
177
+ * freezing ensures that we never modify the static array on the inherited Dream class)
178
+ */
179
+ static scopes = Object.freeze({
180
+ default: Object.freeze([]),
181
+ named: Object.freeze([]),
182
+ });
183
+ /**
184
+ * @internal
185
+ *
186
+ * Model storage for virtual attribute metadata, set on the inheriting class when
187
+ * using the Virtual decorator (this default assignment simply ensures that it is
188
+ * always an array rather than undefined,
189
+ * freezing ensures that we never modify the static array on the inherited Dream class)
190
+ */
191
+ static virtualAttributes = Object.freeze([]);
192
+ /**
193
+ * @internal
194
+ *
195
+ * Model storage for additional columns that may not be set via the new/create/update
196
+ * methods. Set on the inheriting class when using the Virtual decorator (this default
197
+ * assignment simply ensures that it is always an array rather than undefined)
198
+ */
199
+ static explicitUnsafeParamColumns = Object.freeze([]);
200
+ /**
201
+ * @internal
202
+ *
203
+ * Model storage for sortable metadata, set when using the Sortable decorator
204
+ * (this default assignment simply ensures that it is always an array rather than undefined,
205
+ * freezing ensures that we never modify the static array on the inherited Dream class)
206
+ *
207
+ */
208
+ static sortableFields = Object.freeze([]);
209
+ /**
210
+ * @internal
211
+ *
212
+ * Model storage for STI metadata, set when using the STI decorator
213
+ */
214
+ static extendedBy = null;
215
+ /**
216
+ * @internal
217
+ *
218
+ * Model storage for STI metadata, set when using the STI decorator
219
+ * (this default assignment simply ensures that it is always a valid object rather than undefined,
220
+ * freezing ensures that we never modify the static array on the inherited Dream class)
221
+ */
222
+ static sti = Object.freeze({
223
+ active: false,
224
+ baseClass: null,
225
+ value: null,
226
+ });
227
+ /**
228
+ * @internal
229
+ *
230
+ * Model storage for model hook metadata, set when using the following decorators:
231
+ * BeforeCreate
232
+ * BeforeUpdate
233
+ * BeforeSave
234
+ * BeforeDestroy
235
+ * AfterCreate
236
+ * AfterCreateCommit
237
+ * AfterUpdate
238
+ * AfterUpdateCommit
239
+ * AfterSave
240
+ * AfterSaveCommit
241
+ * AfterDestroy
242
+ * AfterDestroyCommit
243
+ */
244
+ static hooks = blankHooksFactory(this, { freeze: true });
245
+ /**
246
+ * @internal
247
+ *
248
+ * Model storage for validation metadata, set when using the Validates decorator
249
+ * (this default assignment simply ensures that it is always an array rather than undefined,
250
+ * freezing ensures that we never modify the static array on the inherited Dream class)
251
+ */
252
+ static validations = Object.freeze([]);
253
+ /**
254
+ * @internal
255
+ *
256
+ * Model storage for custom validation metadata, set when using the Validate decorator
257
+ * (this default assignment simply ensures that it is always an array rather than undefined,
258
+ * freezing ensures that we never modify the static array on the inherited Dream class)
259
+ *
260
+ */
261
+ static customValidations = Object.freeze([]);
262
+ /**
263
+ * @internal
264
+ *
265
+ * Model storage for replica-safe metadata, set when using the ReplicaSafe decorator
266
+ */
267
+ static replicaSafe = false;
268
+ /**
269
+ * @internal
270
+ *
271
+ * Model storage for soft-delete metadata, set when using the SoftDelete decorator
272
+ */
273
+ static softDelete = false;
274
+ /**
275
+ * @internal
276
+ *
277
+ * Provided to distinguish between Dream and other classes
278
+ *
279
+ * @returns true
280
+ */
281
+ static get isDream() {
282
+ return true;
283
+ }
284
+ /**
285
+ * @internal
286
+ *
287
+ * Returns true if this model class is the base class of other STI models
288
+ *
289
+ * @returns boolean
290
+ */
291
+ static get isSTIBase() {
292
+ return !!this.extendedBy?.length && !this.isSTIChild;
293
+ }
294
+ /**
295
+ * @internal
296
+ *
297
+ * Returns true if this model class a child class of a base STI model
298
+ *
299
+ * @returns boolean
300
+ */
301
+ static get isSTIChild() {
302
+ return !!this.sti?.active;
303
+ }
304
+ /**
305
+ * @internal
306
+ *
307
+ * Returns either the base STI class, or else this class
308
+ *
309
+ * @returns A dream class
310
+ */
311
+ static get stiBaseClassOrOwnClass() {
312
+ return this.sti.baseClass || this;
313
+ }
314
+ /**
315
+ * @internal
316
+ *
317
+ * Shadows .stiBaseClassOrOwnClass. Returns either the base STI class, or else this class
318
+ *
319
+ * @returns A dream class
320
+ */
321
+ get stiBaseClassOrOwnClass() {
322
+ return this.constructor.stiBaseClassOrOwnClass;
323
+ }
324
+ /**
325
+ * @internal
326
+ *
327
+ * Used by model hook decorators to apply a hook to a specific model.
328
+ *
329
+ * @param hookType - the type of hook you want to attach the provided statement to
330
+ * @param statement - the statement to couple to the provided hookType
331
+ * @returns void
332
+ */
333
+ static addHook(hookType, statement) {
334
+ const existingHook = this.hooks[hookType].find(hook => hook.method === statement.method);
335
+ if (existingHook)
336
+ return;
337
+ this.hooks[hookType] = [...this.hooks[hookType], statement];
338
+ }
339
+ /**
340
+ * @internal
341
+ *
342
+ * Returns a unique global name for the given model.
343
+ *
344
+ * @returns A string representing a unique key for this model
345
+ */
346
+ static get globalName() {
347
+ if (!this._globalName)
348
+ throw new GlobalNameNotSet(this);
349
+ return this._globalName;
350
+ }
351
+ static _globalName;
352
+ /**
353
+ * @internal
354
+ *
355
+ * Used by DreamApplication during the load process
356
+ * for models, services, and controllers to assign
357
+ * unique global names to each model based on the file
358
+ * name of that model.
359
+ */
360
+ static setGlobalName(globalName) {
361
+ this._globalName = globalName;
362
+ }
363
+ /**
364
+ * Returns the column names for the given model
365
+ *
366
+ * @returns The column names for the given model
367
+ */
368
+ static columns() {
369
+ if (this._columns)
370
+ return this._columns;
371
+ const columns = this.prototype.schema[this.table]?.columns;
372
+ this._columns = new Set(columns ? Object.keys(columns) : []);
373
+ return this._columns;
374
+ }
375
+ static _columns;
376
+ /**
377
+ * Returns the list of column names that are safe for
378
+ * casting automatically using `.paramsFor` within a
379
+ * psychic controller. It will return a subset of the
380
+ * `.columns` getter, but which filters out the following:
381
+ * * createdAt
382
+ * * updatedAt
383
+ * * deletedAt
384
+ * * type fields for STI models
385
+ * * foreign key fields for belongs to associations (these should usually be verified before being set)
386
+ * * type fields corresponding to polymorphic associations
387
+ *
388
+ * @returns A subset of columns for the given dream class
389
+ */
390
+ static paramSafeColumnsOrFallback() {
391
+ const defaultParams = this.defaultParamSafeColumns();
392
+ const userDefinedParams = this.prototype.paramSafeColumns;
393
+ if (Array.isArray(userDefinedParams)) {
394
+ return userDefinedParams.filter(param => defaultParams.includes(param));
395
+ }
396
+ return defaultParams;
397
+ }
398
+ static defaultParamSafeColumns() {
399
+ const columns = [...this.columns()].filter(column => {
400
+ if (this.prototype.primaryKey === column)
401
+ return false;
402
+ if (this.prototype.createdAtField === column)
403
+ return false;
404
+ if (this.prototype.updatedAtField === column)
405
+ return false;
406
+ if (this.prototype.deletedAtField === column)
407
+ return false;
408
+ if (this.explicitUnsafeParamColumns.includes(column))
409
+ return false;
410
+ if (this.isBelongsToAssociationForeignKey(column))
411
+ return false;
412
+ if (this.isBelongsToAssociationPolymorphicTypeField(column))
413
+ return false;
414
+ if (this.sti.active && column === 'type')
415
+ return false;
416
+ return true;
417
+ });
418
+ return [
419
+ ...new Set([...columns, ...this.virtualAttributes.map(attr => attr.property)]),
420
+ ];
421
+ }
422
+ /**
423
+ * @internal
424
+ *
425
+ * Returns true if the column is virtual (set using the Virtual decorator)
426
+ *
427
+ * @param columnName - the name of the property you are checking for
428
+ * @returns boolean
429
+ */
430
+ static isVirtualColumn(columnName) {
431
+ return this.prototype.isVirtualColumn(columnName);
432
+ }
433
+ /**
434
+ * @internal
435
+ *
436
+ * Locates an association's metadata by key
437
+ *
438
+ * ```ts
439
+ * Post.getAssociationMetadata('user')
440
+ * // {
441
+ * // modelCB: [Function (anonymous)],
442
+ * // type: 'BelongsTo',
443
+ * // as: 'user',
444
+ * // optional: false,
445
+ * // polymorphic: false,
446
+ * // primaryKeyOverride: null,
447
+ * // primaryKey: [Function: primaryKey],
448
+ * // primaryKeyValue: [Function: primaryKeyValue],
449
+ * // foreignKey: [Function: foreignKey],
450
+ * // foreignKeyTypeField: [Function: foreignKeyTypeField]
451
+ * // }
452
+ * ```
453
+ *
454
+ * @param associationName - the name of the association you wish to retrieve metadata for
455
+ * @returns Association metadata for the requested association
456
+ */
457
+ static getAssociationMetadata(associationName) {
458
+ return this.associationMetadataMap()[extractAssociationMetadataFromAssociationName(associationName).name];
459
+ }
460
+ /**
461
+ * @internal
462
+ *
463
+ * Returns an array containing all of the associations for this dream class
464
+ *
465
+ * @returns An array containing all of the associations for this dream class
466
+ */
467
+ static associationMetadataMap() {
468
+ const allAssociations = [
469
+ ...this.associationMetadataByType.belongsTo,
470
+ ...this.associationMetadataByType.hasOne,
471
+ ...this.associationMetadataByType.hasMany,
472
+ ];
473
+ const map = {};
474
+ for (const association of allAssociations) {
475
+ map[association.as] = association;
476
+ }
477
+ return map;
478
+ }
479
+ /**
480
+ * @internal
481
+ *
482
+ * Returns all of the association names for this dream class
483
+ *
484
+ * @returns All of the association names for this dream class
485
+ */
486
+ static get associationNames() {
487
+ const allAssociations = [
488
+ ...this.associationMetadataByType.belongsTo,
489
+ ...this.associationMetadataByType.hasOne,
490
+ ...this.associationMetadataByType.hasMany,
491
+ ];
492
+ return allAssociations.map(association => {
493
+ return association.as;
494
+ });
495
+ }
496
+ /**
497
+ * Returns a query for this model which disregards default scopes
498
+ *
499
+ * @returns A query for this model which disregards default scopes
500
+ */
501
+ static removeAllDefaultScopes() {
502
+ return this.query().removeAllDefaultScopes();
503
+ }
504
+ /**
505
+ * Prevents a specific default scope from applying when
506
+ * the Query is executed
507
+ *
508
+ * @returns A new Query which will prevent a specific default scope from applying
509
+ */
510
+ static removeDefaultScope(scopeName) {
511
+ return this.query().removeDefaultScope(scopeName);
512
+ }
513
+ /**
514
+ * Retrieves an array containing all records corresponding to
515
+ * this model. Be careful using this, since it will attempt to
516
+ * pull every record into memory at once. For a large number
517
+ * of records, consider using `.findEach`, which will pull
518
+ * the records in batches.
519
+ *
520
+ * ```ts
521
+ * await User.all()
522
+ * ```
523
+ *
524
+ * @returns an array of dreams
525
+ */
526
+ static async all(options = {}) {
527
+ return await this.query().all(options);
528
+ }
529
+ /**
530
+ * Forces use of a database connection (e.g. 'primary') during the query.
531
+ *
532
+ * NOTE: all queries within a transaction always use the 'primary' replica, so
533
+ * explicitly setting connection within a transaction has no effect.
534
+ *
535
+ * @param connection - The connection you wish to access ('primary' or 'replica')
536
+ * @returns A Query with the requested connection
537
+ */
538
+ static connection(connection) {
539
+ return new Query(this.prototype, {
540
+ connection,
541
+ });
542
+ }
543
+ /**
544
+ * Retrieves the number of records corresponding
545
+ * to this model.
546
+ *
547
+ * @returns The number of records corresponding to this model
548
+ */
549
+ static async count() {
550
+ return await this.query().count();
551
+ }
552
+ /**
553
+ * Retrieves the max value of the specified column
554
+ * for this model's records.
555
+ *
556
+ * ```ts
557
+ * await User.max('id')
558
+ * // 99
559
+ * ```
560
+ *
561
+ * @param columnName - a column name on the model
562
+ * @returns the max value of the specified column for this model's records
563
+ */
564
+ static async max(columnName) {
565
+ return await this.query().max(columnName);
566
+ }
567
+ /**
568
+ * Retrieves the min value of the specified column
569
+ * for this model's records.
570
+ *
571
+ *
572
+ * ```ts
573
+ * await User.min('id')
574
+ * // 1
575
+ * ```
576
+ *
577
+ * @param columnName - a column name on the model
578
+ * @returns the min value of the specified column for this model's records
579
+ */
580
+ static async min(columnName) {
581
+ return await this.query().min(columnName);
582
+ }
583
+ /**
584
+ * Persists a new record, setting the provided attributes
585
+ *
586
+ * ```ts
587
+ * const user = await User.create({ email: 'how@yadoin' })
588
+ * await Post.create({ body: 'howdy', user })
589
+ * ```
590
+ *
591
+ * @param attributes - attributes or belongs to associations you wish to set on this model before persisting
592
+ * @returns A newly persisted dream instance
593
+ */
594
+ static async create(attributes) {
595
+ const dreamModel = this.new(attributes);
596
+ await dreamModel.save();
597
+ return dreamModel;
598
+ }
599
+ /**
600
+ * Attempt to create the model. If creation fails
601
+ * due to uniqueness constraint, then find the existing
602
+ * model.
603
+ *
604
+ * This is useful in situations where we want to avoid
605
+ * a race condition creating duplicate records.
606
+ *
607
+ * IMPORTANT: A unique index/uniqueness constraint must exist on
608
+ * at least one of the provided attributes
609
+ *
610
+ * ```ts
611
+ * const logEntry = await LogEntry.createOrFindBy({ externalId }, { createWith: params })
612
+ * ```
613
+ *
614
+ * @param attributes - The base attributes to persist, but also the attributes to use to find when create fails
615
+ * @param extraOpts.createWith - additional attributes to persist when creating, but not used for finding
616
+ * @returns A dream instance
617
+ */
618
+ static async createOrFindBy(attributes, extraOpts = {}) {
619
+ try {
620
+ const dreamModel = this.new({
621
+ ...attributes,
622
+ ...(extraOpts?.createWith || {}),
623
+ });
624
+ await dreamModel.save();
625
+ return dreamModel;
626
+ }
627
+ catch (err) {
628
+ if (pgErrorType(err) === 'UNIQUE_CONSTRAINT_VIOLATION') {
629
+ const dreamModel = await this.findBy(this.extractAttributesFromUpdateableProperties(attributes));
630
+ if (!dreamModel)
631
+ throw new CreateOrFindByFailedToCreateAndFind(this);
632
+ return dreamModel;
633
+ }
634
+ throw err;
635
+ }
636
+ }
637
+ /**
638
+ * Returns a new query instance with the distinct query applied.
639
+ * If no columnName is provided, then distinct will apply to the
640
+ * primary key by default.
641
+ *
642
+ * ```ts
643
+ * await User.distinct('name').pluck('name')
644
+ * ```
645
+ *
646
+ * @param columnName - The column name you wish to apply the distinct clause to
647
+ * @returns A Query scoped to this Dream model with the distinct clause applied
648
+ */
649
+ static distinct(columnName) {
650
+ return this.query().distinct(columnName);
651
+ }
652
+ /**
653
+ * Finds a record for the corresponding model with the
654
+ * specified primary key. If not found, null
655
+ * is returned
656
+ *
657
+ * ```ts
658
+ * await User.query().find(123)
659
+ * // User{id: 123}
660
+ * ```
661
+ *
662
+ * @param primaryKey - The primaryKey of the record to look up
663
+ * @returns Either the found record, or else null
664
+ */
665
+ static async find(primaryKey) {
666
+ return await this.query().find(primaryKey);
667
+ }
668
+ /**
669
+ * Finds a record for the corresponding model with the
670
+ * specified primary key. If not found, an exception is raised.
671
+ *
672
+ * ```ts
673
+ * await User.query().findOrFail(123)
674
+ * // User{id: 123}
675
+ * ```
676
+ *
677
+ * @param primaryKey - The primaryKey of the record to look up
678
+ * @returns Either the found record, or else null
679
+ */
680
+ static async findOrFail(primaryKey) {
681
+ return await this.query().findOrFail(primaryKey);
682
+ }
683
+ /**
684
+ * Finds all records for the corresponding model in batches,
685
+ * and then calls the provided callback
686
+ * for each found record. Once all records
687
+ * have been passed for a given batch, the next set of
688
+ * records will be fetched and passed to your callback, until all
689
+ * records matching the corresponding model have been fetched.
690
+ *
691
+ * ```ts
692
+ * await User.findEach(user => {
693
+ * console.log(user)
694
+ * })
695
+ * // User{email: 'hello@world'}
696
+ * // User{email: 'goodbye@world'}
697
+ * ```
698
+ *
699
+ * @param cb - The callback to call for each found record
700
+ * @param opts.batchSize - the batch size you wish to collect records in. If not provided, it will default to 1000
701
+ * @returns void
702
+ */
703
+ static async findEach(cb, opts) {
704
+ await this.query().findEach(cb, opts);
705
+ }
706
+ /**
707
+ * Returns a new instance of Query scoped to the given
708
+ * model class
709
+ *
710
+ * ```ts
711
+ * await User.query().all()
712
+ * // [User{id: 1}, User{id: 2}, ...]
713
+ * ```
714
+ *
715
+ * @returns A new Query instance scoped to this Dream class
716
+ *
717
+ */
718
+ static query() {
719
+ return new Query(this.prototype);
720
+ }
721
+ /**
722
+ * @internal
723
+ *
724
+ * Returns a new instance of Query scoped to the given
725
+ * Dream instance
726
+ *
727
+ * ```ts
728
+ * await user = User.first()
729
+ * await user.query()
730
+ * ```
731
+ *
732
+ * @returns A new Query instance scoped to this Dream instance
733
+ *
734
+ */
735
+ query() {
736
+ const dreamClass = this.constructor;
737
+ return dreamClass.where({ [this.primaryKey]: this.primaryKeyValue });
738
+ }
739
+ /**
740
+ * Finds the first record—ordered by primary key—matching
741
+ * the corresponding model and the specified where statement.
742
+ * If not found, null is returned.
743
+ *
744
+ * ```ts
745
+ * await User.findBy({ email: 'how@yadoin' })
746
+ * // User{email: 'how@yadoin'}
747
+ * ```
748
+ *
749
+ * @param whereStatement - The where statement used to locate the record
750
+ * @returns The first model found matching the whereStatement
751
+ */
752
+ static async findBy(whereStatement) {
753
+ return await this.query().findBy(whereStatement);
754
+ }
755
+ /**
756
+ * Finds the first record—ordered by primary key—matching
757
+ * the corresponding model and the specified where statement.
758
+ * If not found, an exception is raised.
759
+ *
760
+ * ```ts
761
+ * await User.findOrFailBy({ email: 'how@yadoin' })
762
+ * // User{email: 'how@yadoin'}
763
+ * ```
764
+ *
765
+ * @param whereStatement - The where statement used to locate the record
766
+ * @returns The first model found matching the whereStatement
767
+ */
768
+ static async findOrFailBy(whereStatement) {
769
+ return await this.query().findOrFailBy(whereStatement);
770
+ }
771
+ /**
772
+ * Attempt to find the model with the given attributes.
773
+ * If no record is found, then a new record is created.
774
+ *
775
+ * ```ts
776
+ * const user = await User.findOrCreateBy({ email }, { createWith: params })
777
+ * ```
778
+ *
779
+ * @param attributes - The base attributes for finding, but also the attributes to use when creating
780
+ * @param extraOpts.createWith - additional attributes to persist when creating, but not used for finding
781
+ * @returns A dream instance
782
+ */
783
+ static async findOrCreateBy(attributes, extraOpts = {}) {
784
+ const existingRecord = await this.findBy(this.extractAttributesFromUpdateableProperties(attributes));
785
+ if (existingRecord)
786
+ return existingRecord;
787
+ const dreamModel = this.new({
788
+ ...attributes,
789
+ ...(extraOpts?.createWith || {}),
790
+ });
791
+ await dreamModel.save();
792
+ return dreamModel;
793
+ }
794
+ /**
795
+ * Returns true if a record exists for the given
796
+ * model class
797
+ *
798
+ * ```ts
799
+ * await User.exists()
800
+ * // false
801
+ *
802
+ * await User.create({ email: 'how@yadoin' })
803
+ *
804
+ * await User.exists()
805
+ * // true
806
+ * ```
807
+ *
808
+ * @returns boolean
809
+ */
810
+ static async exists() {
811
+ return await this.query().exists();
812
+ }
813
+ /**
814
+ * Load each specified association using a single SQL query.
815
+ * See {@link #preload} for preloading in separate queries.
816
+ *
817
+ * Note: since leftJoinPreload loads via single query, it has
818
+ * some downsides and that may be avoided using {@link #preload}:
819
+ * 1. `limit` and `offset` will be automatically removed
820
+ * 2. `through` associations will bring additional namespaces into the query that can conflict with through associations from other associations, creating an invalid query
821
+ * 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.
822
+ * 4. the individual query becomes more complex the more associations are included
823
+ * 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
824
+ *
825
+ * ```ts
826
+ * const user = await User.leftJoinPreload('posts', 'comments', { visibilty: 'public' }, 'replies').first()
827
+ * console.log(user.posts[0].comments[0].replies)
828
+ * // [Reply{id: 1}, Reply{id: 2}]
829
+ * ```
830
+ *
831
+ * @param args - A chain of association names and where clauses
832
+ * @returns A query for this model with the include statement applied
833
+ */
834
+ static leftJoinPreload(...args) {
835
+ return this.query().leftJoinPreload(...args);
836
+ }
837
+ /**
838
+ * Applies preload statement to a Query scoped to this model.
839
+ * Upon instantiating records of this model type,
840
+ * specified associations will be preloaded.
841
+ *
842
+ * Preloading/loading/including is necessary prior to accessing associations
843
+ * on a Dream instance.
844
+ *
845
+ * Preload is useful for avoiding the N+1 query problem
846
+ *
847
+ * ```ts
848
+ * const user = await User.preload('posts', 'comments', { visibilty: 'public' }, 'replies').first()
849
+ * console.log(user.posts[0].comments[0].replies)
850
+ * // [Reply{id: 1}, Reply{id: 2}]
851
+ * ```
852
+ *
853
+ * @param args - A chain of association names and where clauses
854
+ * @returns A query for this model with the preload statement applied
855
+ */
856
+ static preload(...args) {
857
+ return this.query().preload(...args);
858
+ }
859
+ /**
860
+ * Returns a new Query instance with the provided
861
+ * inner join statement attached
862
+ *
863
+ * ```ts
864
+ * await User.innerJoin('posts').first()
865
+ * ```
866
+ *
867
+ * @param args - A chain of association names and where clauses
868
+ * @returns A Query for this model with the inner join clause applied
869
+ */
870
+ static innerJoin(...args) {
871
+ return this.query().innerJoin(...args);
872
+ }
873
+ /**
874
+ * Returns a new Query instance with the provided
875
+ * inner join statement attached
876
+ *
877
+ * ```ts
878
+ * await user.innerJoin('posts').first()
879
+ * ```
880
+ *
881
+ * @param args - A chain of association names and where clauses
882
+ * @returns A Query for this model with the inner join clause applied
883
+ */
884
+ innerJoin(...args) {
885
+ return this.query().innerJoin(...args);
886
+ }
887
+ /**
888
+ * Returns a new Query instance with the provided
889
+ * left join statement attached
890
+ *
891
+ * ```ts
892
+ * await User.leftJoin('posts').first()
893
+ * ```
894
+ *
895
+ * @param args - A chain of association names and where clauses
896
+ * @returns A Query for this model with the left join clause applied
897
+ */
898
+ static leftJoin(...args) {
899
+ return this.query().leftJoin(...args);
900
+ }
901
+ /**
902
+ * Returns a new Query instance with the provided
903
+ * left join statement attached
904
+ *
905
+ * ```ts
906
+ * await user.leftJoin('posts').first()
907
+ * ```
908
+ *
909
+ * @param args - A chain of association names and where clauses
910
+ * @returns A Query for this model with the left join clause applied
911
+ */
912
+ leftJoin(...args) {
913
+ return this.query().leftJoin(...args);
914
+ }
915
+ /**
916
+ * Returns the first record corresponding to the
917
+ * model, ordered by primary key.
918
+ *
919
+ * ```ts
920
+ * await User.first()
921
+ * // User{id: 1}
922
+ * ```
923
+ *
924
+ * @returns First record, or null if no record exists
925
+ */
926
+ static async first() {
927
+ return await this.query().first();
928
+ }
929
+ /**
930
+ * Returns the first record corresponding to the
931
+ * model, ordered by primary key. If no record is
932
+ * found, an exception is raised.
933
+ *
934
+ * ```ts
935
+ * await User.firstOrFail()
936
+ * // User{id: 1}
937
+ * ```
938
+ *
939
+ * @returns First record
940
+ */
941
+ static async firstOrFail() {
942
+ return await this.query().firstOrFail();
943
+ }
944
+ /**
945
+ * Returns the last record corresponding to the
946
+ * model, ordered by primary key.
947
+ *
948
+ * ```ts
949
+ * await User.last()
950
+ * // User{id: 99}
951
+ * ```
952
+ *
953
+ * @returns Last record, or null if no record exists
954
+ */
955
+ static async last() {
956
+ return await this.query().last();
957
+ }
958
+ /**
959
+ * Returns the last record corresponding to the
960
+ * model, ordered by primary key. If no record
961
+ * is found, an exception is raised.
962
+ *
963
+ * ```ts
964
+ * await User.lastOrFail()
965
+ * // User{id: 99}
966
+ * ```
967
+ *
968
+ * @returns Last record
969
+ */
970
+ static async lastOrFail() {
971
+ return await this.query().lastOrFail();
972
+ }
973
+ /**
974
+ * Returns a new Query instance, specifying a limit
975
+ *
976
+ * ```ts
977
+ * await User.limit(2).all()
978
+ * // [User{}, User{}]
979
+ * ```
980
+ *
981
+ * @returns A Query for this model with the limit clause applied
982
+ */
983
+ static limit(count) {
984
+ return this.query().limit(count);
985
+ }
986
+ /**
987
+ * Returns a new Query instance, specifying an offset
988
+ *
989
+ * ```ts
990
+ * await User.offset(2).order('id').limit(2).all()
991
+ * // [User{id: 3}, User{id: 4}]
992
+ * ```
993
+ *
994
+ * @returns A Query for this model with the offset clause applied
995
+ */
996
+ static offset(offset) {
997
+ return this.query().offset(offset);
998
+ }
999
+ /**
1000
+ * Returns a new Query instance, attaching the provided
1001
+ * order statement
1002
+ *
1003
+ * ```ts
1004
+ * await User.order('id').all()
1005
+ * // [User{id: 1}, User{id: 2}, ...]
1006
+ * ```
1007
+ *
1008
+ * ```ts
1009
+ * await User.order({ name: 'asc', id: 'desc' }).all()
1010
+ * // [User{name: 'a', id: 99}, User{name: 'a', id: 97}, User{ name: 'b', id: 98 } ...]
1011
+ * ```
1012
+ *
1013
+ * @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
1014
+ * @returns A query for this model with the order clause applied
1015
+ */
1016
+ static order(orderStatement) {
1017
+ return this.query().order(orderStatement);
1018
+ }
1019
+ /**
1020
+ * Plucks the provided fields from the corresponding model
1021
+ *
1022
+ * ```ts
1023
+ * await User.pluck('id')
1024
+ * // [1, 3, 2]
1025
+ * ```
1026
+ *
1027
+ * If more than one column is requested, a multi-dimensional
1028
+ * array is returned:
1029
+ *
1030
+ * ```ts
1031
+ * await User.order('id').pluck('id', 'email')
1032
+ * // [[1, 'a@a.com'], [2, 'b@b.com']]
1033
+ * ```
1034
+ *
1035
+ * @param columnNames - The column or array of columns to pluck
1036
+ * @returns An array of pluck results
1037
+ */
1038
+ static async pluck(...columnNames) {
1039
+ return (await this.query().pluck(...columnNames));
1040
+ }
1041
+ /**
1042
+ * Plucks the specified fields from the given dream class table
1043
+ * in batches, passing each found columns into the
1044
+ * provided callback function
1045
+ *
1046
+ * ```ts
1047
+ * await User.order('id').pluckEach('id', (id) => {
1048
+ * console.log(id)
1049
+ * })
1050
+ * // 1
1051
+ * // 2
1052
+ * // 3
1053
+ * ```
1054
+ *
1055
+ * @param fields - a list of fields to pluck, followed by a callback function to call for each set of found fields
1056
+ * @returns void
1057
+ */
1058
+ static async pluckEach(...args) {
1059
+ return await this.query().pluckEach(...args);
1060
+ }
1061
+ /**
1062
+ * Used in conjunction with the Sortable decorator, `resort`
1063
+ * takes a list of sortable fields, and for each one, finds and
1064
+ * sorts each record in the DB matching the field based on the
1065
+ * scope provided for each Sortable decorator found.
1066
+ *
1067
+ * Calling this method shouldn't be necessary, but if
1068
+ * the contents of the database have shifted without firing the
1069
+ * correct callback mechanisms at the application layer, calling
1070
+ * `resort` will ensure that all sortable fields are set from 1..n
1071
+ * with no gaps, accounting for the scopes specified in the
1072
+ * corresponding Sortable decorator.
1073
+ *
1074
+ * ```ts
1075
+ * class Post extends ApplicationModel {
1076
+ * @Sortable({ scope: ['user']})
1077
+ * public position: DreamColumn<User, 'position'>
1078
+ * }
1079
+ *
1080
+ * await Post.all()
1081
+ * // [Post{position: 1}, Post{position: 3}, Post{position: 5}]
1082
+ *
1083
+ * await Post.resort('position')
1084
+ * await Post.all()
1085
+ * // [Post{position: 1}, Post{position: 2}, Post{position: 3}]
1086
+ * ```
1087
+ *
1088
+ * @param fields - A list of sortable fields to resort
1089
+ * @returns void
1090
+ *
1091
+ */
1092
+ static async resort(...fields) {
1093
+ for (const field of fields) {
1094
+ const sortableMetadata = this.sortableFields.find(conf => conf.positionField === field);
1095
+ if (!sortableMetadata)
1096
+ throw new NonExistentScopeProvidedToResort(fields, this);
1097
+ await resortAllRecords(this, field, sortableMetadata.scope);
1098
+ }
1099
+ }
1100
+ /**
1101
+ * Returns a Query scoped to this model with
1102
+ * the specified scope applied.
1103
+ *
1104
+ * ```ts
1105
+ * class User extends ApplicationModel {
1106
+ * @Scope()
1107
+ * public visible(query: Query<User>) {
1108
+ * return query.where({ hidden: false })
1109
+ * }
1110
+ * }
1111
+ *
1112
+ * await User.scope('visible').all()
1113
+ * // [User{hidden: false}, User{hidden: false}]
1114
+ * ```
1115
+ *
1116
+ * @param scopeName - The name of the scope
1117
+ * @returns a Query scoped to this model with the specified scope applied
1118
+ */
1119
+ static scope(scopeName) {
1120
+ return this[scopeName](this.query());
1121
+ }
1122
+ /**
1123
+ * Returns the sql that would be executed by a Query
1124
+ * scoped to this model.
1125
+ *
1126
+ * ```ts
1127
+ * User.sql()
1128
+ * // {
1129
+ * // query: {
1130
+ * // kind: 'SelectQueryNode',
1131
+ * // from: { kind: 'FromNode', froms: [Array] },
1132
+ * // selections: [ [Object] ],
1133
+ * // distinctOn: undefined,
1134
+ * // joins: undefined,
1135
+ * // groupBy: undefined,
1136
+ * // orderBy: undefined,
1137
+ * // where: { kind: 'WhereNode', where: [Object] },
1138
+ * // frontModifiers: undefined,
1139
+ * // endModifiers: undefined,
1140
+ * // limit: undefined,
1141
+ * // offset: undefined,
1142
+ * // with: undefined,
1143
+ * // having: undefined,
1144
+ * // explain: undefined,
1145
+ * // setOperations: undefined
1146
+ * // },
1147
+ * // sql: 'select "users".* from "users" where "users"."deleted_at" is null',
1148
+ * // parameters: []
1149
+ * //}
1150
+ * ```
1151
+ *
1152
+ * @returns An object representing the underlying sql statement
1153
+ *
1154
+ */
1155
+ static sql() {
1156
+ return this.query().sql();
1157
+ }
1158
+ /**
1159
+ * Converts the given Dream class into a Kysely query, enabling
1160
+ * you to build custom queries using the Kysely API
1161
+ *
1162
+ * ```ts
1163
+ * await User.toKysely('select').where('email', '=', 'how@yadoin').execute()
1164
+ * ```
1165
+ *
1166
+ * @param type - The type of Kysely query builder instance you would like to obtain
1167
+ * @returns A Kysely query. Depending on the type passed, it will return either a SelectQueryBuilder, DeleteQueryBuilder, UpdateQueryBuilder, or an InsertQueryBuilder
1168
+ */
1169
+ static toKysely(type) {
1170
+ switch (type) {
1171
+ case 'select':
1172
+ return this.query().dbFor('select').selectFrom(this.table);
1173
+ case 'delete':
1174
+ return this.query().dbFor('delete').deleteFrom(this.table);
1175
+ case 'update':
1176
+ return this.query().dbFor('update').updateTable(this.table);
1177
+ case 'insert':
1178
+ return this.query().dbFor('insert').insertInto(this.table);
1179
+ default:
1180
+ throw new Error('never');
1181
+ }
1182
+ }
1183
+ /**
1184
+ * Applies transaction to a new Query scoped
1185
+ * to this model
1186
+ *
1187
+ * ```ts
1188
+ * await ApplicationModel.transaction(async txn => {
1189
+ * await User.txn(txn).create({ email: 'how@yadoin' })
1190
+ * })
1191
+ * ```
1192
+ *
1193
+ * @param txn - A DreamTransaction instance (usually collected by calling `ApplicationModel.transaction`)
1194
+ * @returns A Query scoped to this model with the transaction applied
1195
+ */
1196
+ static txn(txn) {
1197
+ return new DreamClassTransactionBuilder(this.prototype, txn);
1198
+ }
1199
+ /**
1200
+ * Builds a new DreamTransaction instance, provides
1201
+ * the instance to the provided callback.
1202
+ *
1203
+ * ```ts
1204
+ * await ApplicationModel.transaction(async txn => {
1205
+ * const user = await User.txn(txn).create({ email: 'how@yadoin' })
1206
+ * await Pet.txn(txn).create({ user })
1207
+ * })
1208
+ * ```
1209
+ *
1210
+ * @param callback - A callback function to call. The transaction provided to the callback can be passed to subsequent database calls within the transaction callback
1211
+ * @returns void
1212
+ */
1213
+ static async transaction(callback) {
1214
+ const dreamTransaction = new DreamTransaction();
1215
+ let callbackResponse = undefined;
1216
+ await db('primary')
1217
+ .transaction()
1218
+ .execute(async (kyselyTransaction) => {
1219
+ dreamTransaction.kyselyTransaction = kyselyTransaction;
1220
+ callbackResponse = (await callback(dreamTransaction));
1221
+ });
1222
+ await dreamTransaction.runAfterCommitHooks(dreamTransaction);
1223
+ return callbackResponse;
1224
+ }
1225
+ /**
1226
+ * Sends data through for use as passthrough data
1227
+ * for the associations that require it.
1228
+ *
1229
+ * ```ts
1230
+ * class Post {
1231
+ * @Deco.HasMany('LocalizedText')
1232
+ * public localizedTexts: LocalizedText[]
1233
+ *
1234
+ * @Deco.HasOne('LocalizedText', {
1235
+ * where: { locale: DreamConst.passthrough },
1236
+ * })
1237
+ * public currentLocalizedText: LocalizedText
1238
+ * }
1239
+ *
1240
+ * await User.passthrough({ locale: 'es-ES' })
1241
+ * .preload('posts', 'currentLocalizedText')
1242
+ * .first()
1243
+ * ```
1244
+ *
1245
+ * @param passthroughWhereStatement - Where statement used for associations that require passthrough data
1246
+ * @returns A Query for this model with the passthrough data
1247
+ */
1248
+ static passthrough(passthroughWhereStatement) {
1249
+ return this.query().passthrough(passthroughWhereStatement);
1250
+ }
1251
+ /**
1252
+ * Applies a where statement to a new Query instance
1253
+ * scoped to this model
1254
+ *
1255
+ * ```ts
1256
+ * await User.where({ email: 'how@yadoin' }).first()
1257
+ * // User{email: 'how@yadoin'}
1258
+ * ```
1259
+ *
1260
+ * @param whereStatement - Where statement to apply to the Query
1261
+ * @returns A Query for this model with the where clause applied
1262
+ */
1263
+ static where(whereStatement) {
1264
+ return this.query().where(whereStatement);
1265
+ }
1266
+ /**
1267
+ * Applies "OR"'d where statements to a Query scoped
1268
+ * to this model.
1269
+ *
1270
+ * ```ts
1271
+ * await User.whereAny([{ email: 'how@yadoin' }, { name: 'fred' }]).first()
1272
+ * // [User{email: 'how@yadoin'}, User{name: 'fred'}, User{name: 'fred'}]
1273
+ * ```
1274
+ *
1275
+ * @param whereStatements - a list of where statements to `OR` together
1276
+ * @returns A Query for this model with the whereAny clause applied
1277
+ */
1278
+ static whereAny(statements) {
1279
+ return this.query().whereAny(statements);
1280
+ }
1281
+ /**
1282
+ * Applies a whereNot statement to a new Query instance
1283
+ * scoped to this model.
1284
+ *
1285
+ * ```ts
1286
+ * await User.whereNot({ email: 'how@yadoin' }).first()
1287
+ * // User{email: 'hello@world'}
1288
+ * ```
1289
+ *
1290
+ * @param whereStatement - A where statement to negate and apply to the Query
1291
+ * @returns A Query for this model with the whereNot clause applied
1292
+ */
1293
+ static whereNot(attributes) {
1294
+ return this.query().whereNot(attributes);
1295
+ }
1296
+ /**
1297
+ * @internal
1298
+ *
1299
+ * Given a column, checks to see if it is a foreign key
1300
+ * belonging to a BelongsTo association
1301
+ *
1302
+ * ```ts
1303
+ * Post.isBelongsToAssociationForeignKey('id')
1304
+ * // false
1305
+ * Post.isBelongsToAssociationForeignKey('userId')
1306
+ * // true
1307
+ * ```
1308
+ *
1309
+ * @param column - A column on this Dream class
1310
+ * @returns A boolean
1311
+ */
1312
+ static isBelongsToAssociationForeignKey(column) {
1313
+ return this.belongsToAssociationForeignKeys().includes(column);
1314
+ }
1315
+ /**
1316
+ * @internal
1317
+ *
1318
+ * Given a column, checks to see if it is a belongs to
1319
+ * polymorphic type field
1320
+ *
1321
+ * ```ts
1322
+ * LocalizedText.isBelongsToAssociationPolymorphicTypeField('localizableId')
1323
+ * // false
1324
+ * LocalizedText.isBelongsToAssociationPolymorphicTypeField('localizableType')
1325
+ * // true
1326
+ * ```
1327
+ *
1328
+ * @param column - a column on this dream class
1329
+ * @returns A boolean
1330
+ */
1331
+ static isBelongsToAssociationPolymorphicTypeField(column) {
1332
+ return this.polymorphicTypeColumns().includes(column);
1333
+ }
1334
+ /**
1335
+ * @internal
1336
+ *
1337
+ * Returns an array of column names that are belongs
1338
+ * to foreign keys on this dream class
1339
+ *
1340
+ * ```ts
1341
+ * Post.belongsToAssociationForeignKeys()
1342
+ * // ['userId']
1343
+ * ```
1344
+ *
1345
+ * @returns An array of column names that are belongs to foreign keys on this dream class
1346
+ */
1347
+ static belongsToAssociationForeignKeys() {
1348
+ const associationMap = this.associationMetadataMap();
1349
+ return this.belongsToAssociationNames().map(belongsToKey => associationMap[belongsToKey].foreignKey());
1350
+ }
1351
+ /**
1352
+ * @internal
1353
+ *
1354
+ * Returns all polymorphic type columns
1355
+ *
1356
+ * ```ts
1357
+ * LocalizedText.polymorphicTypeColumns()
1358
+ * // ['localizableType']
1359
+ * ```
1360
+ *
1361
+ * @returns An array of column names that are polymorphic type fields on the given dream class
1362
+ */
1363
+ static polymorphicTypeColumns() {
1364
+ const associationMap = this.associationMetadataMap();
1365
+ return this.belongsToAssociationNames()
1366
+ .filter(key => associationMap[key].polymorphic)
1367
+ .map(belongsToKey => associationMap[belongsToKey].foreignKeyTypeField());
1368
+ }
1369
+ /**
1370
+ * @internal
1371
+ *
1372
+ * Returns a list of association names which
1373
+ * correspond to belongs to associations
1374
+ * on this model class.
1375
+ *
1376
+ * ```ts
1377
+ * Post.belongsToAssociationNames()
1378
+ * // ['user']
1379
+ * ```
1380
+ *
1381
+ * @returns An array of belongs to association names
1382
+ */
1383
+ static belongsToAssociationNames() {
1384
+ const associationMap = this.associationMetadataMap();
1385
+ return Object.keys(associationMap).filter(key => associationMap[key].type === 'BelongsTo');
1386
+ }
1387
+ /**
1388
+ * @internal
1389
+ *
1390
+ * Returns a list of association names which
1391
+ * have `dependent: destroy` set
1392
+ *
1393
+ * ```ts
1394
+ * Post.dependentDestroyAssociationNames()
1395
+ * // ['user']
1396
+ * ```
1397
+ *
1398
+ * @returns An array of HasOne/HasMany association names with `dependent: 'destroy'` defined
1399
+ */
1400
+ static dependentDestroyAssociationNames() {
1401
+ const associationMap = this.associationMetadataMap();
1402
+ return Object.keys(associationMap).filter(key => associationMap[key]
1403
+ .dependent === 'destroy');
1404
+ }
1405
+ /**
1406
+ * @internal
1407
+ *
1408
+ * Returns the metadata for the provided association
1409
+ *
1410
+ * ```ts
1411
+ * new Post()['getAssociationMetadata']('user')
1412
+ * // {
1413
+ * // modelCB: [Function (anonymous)],
1414
+ * // type: 'BelongsTo',
1415
+ * // as: 'user',
1416
+ * // optional: false,
1417
+ * // polymorphic: false,
1418
+ * // primaryKeyOverride: null,
1419
+ * // primaryKey: [Function: primaryKey],
1420
+ * // primaryKeyValue: [Function: primaryKeyValue],
1421
+ * // foreignKey: [Function: foreignKey],
1422
+ * // foreignKeyTypeField: [Function: foreignKeyTypeField]
1423
+ * // }
1424
+ * ```
1425
+ *
1426
+ * @returns Association metadata
1427
+ *
1428
+ */
1429
+ getAssociationMetadata(associationName) {
1430
+ return this.constructor.getAssociationMetadata(associationName);
1431
+ }
1432
+ /**
1433
+ * @internal
1434
+ *
1435
+ * Returns all association metadata for the given dream class
1436
+ *
1437
+ * ```ts
1438
+ * new Post()['associationMetadataMap']()
1439
+ * // {
1440
+ * // user: {
1441
+ * // modelCB: [Function (anonymous)],
1442
+ * // type: 'BelongsTo',
1443
+ * // as: 'user',
1444
+ * // optional: false,
1445
+ * // polymorphic: false,
1446
+ * // primaryKeyOverride: null,
1447
+ * // primaryKey: [Function: primaryKey],
1448
+ * // primaryKeyValue: [Function: primaryKeyValue],
1449
+ * // foreignKey: [Function: foreignKey],
1450
+ * // foreignKeyTypeField: [Function: foreignKeyTypeField]
1451
+ * // },
1452
+ * // ratings: {
1453
+ * // modelCB: [Function (anonymous)],
1454
+ * // type: 'HasMany',
1455
+ * // as: 'ratings',
1456
+ * // polymorphic: true,
1457
+ * // source: 'ratings',
1458
+ * // preloadThroughColumns: undefined,
1459
+ * // where: undefined,
1460
+ * // whereNot: undefined,
1461
+ * // selfWhere: undefined,
1462
+ * // selfWhereNot: undefined,
1463
+ * // primaryKeyOverride: null,
1464
+ * // primaryKey: [Function: primaryKey],
1465
+ * // primaryKeyValue: [Function: primaryKeyValue],
1466
+ * // through: undefined,
1467
+ * // distinct: undefined,
1468
+ * // order: undefined,
1469
+ * // foreignKey: [Function: foreignKey],
1470
+ * // foreignKeyTypeField: [Function: foreignKeyTypeField]
1471
+ * // },
1472
+ * // ...
1473
+ * // }
1474
+ * ```
1475
+ *
1476
+ * @returns association metadata
1477
+ */
1478
+ associationMetadataMap() {
1479
+ return this.constructor.associationMetadataMap();
1480
+ }
1481
+ /**
1482
+ * @internal
1483
+ *
1484
+ * returns all association data for the given dream class,
1485
+ * organized by the type of association
1486
+ *
1487
+ * ```ts
1488
+ * new Post().associationMetadataByType
1489
+ * // {
1490
+ * // belongsTo: [
1491
+ * // {
1492
+ * // modelCB: [Function (anonymous)],
1493
+ * // type: 'BelongsTo',
1494
+ * // as: 'user',
1495
+ * // optional: false,
1496
+ * // polymorphic: false,
1497
+ * // primaryKeyOverride: null,
1498
+ * // primaryKey: [Function: primaryKey],
1499
+ * // primaryKeyValue: [Function: primaryKeyValue],
1500
+ * // foreignKey: [Function: foreignKey],
1501
+ * // foreignKeyTypeField: [Function: foreignKeyTypeField]
1502
+ * // },
1503
+ * // ],
1504
+ * // hasMany: [
1505
+ * // ],
1506
+ * // hasOne: []
1507
+ * // }
1508
+ * // }
1509
+ * ```
1510
+ *
1511
+ * @returns association metadata by type
1512
+ *
1513
+ */
1514
+ get associationMetadataByType() {
1515
+ return this.constructor.associationMetadataByType;
1516
+ }
1517
+ /**
1518
+ * @internal
1519
+ *
1520
+ * Returns an array of association names for the
1521
+ * given dream class
1522
+ *
1523
+ * ```ts
1524
+ * new Post().associationNames
1525
+ * // [ 'user', 'postVisibility', 'ratings', 'heartRatings' ]
1526
+ * ```
1527
+ *
1528
+ * @returns association names array
1529
+ */
1530
+ get associationNames() {
1531
+ return this.constructor.associationNames;
1532
+ }
1533
+ /**
1534
+ * Returns true if any of the attributes on the instance
1535
+ * have changed since it was last pulled from the database.
1536
+ * It will also return true if the instance is not yet
1537
+ * persisted.
1538
+ *
1539
+ * ```ts
1540
+ * const post = Post.new({ body: 'howyadoin' })
1541
+ * post.isDirty
1542
+ * // true
1543
+ *
1544
+ * await post.save()
1545
+ * post.isDirty
1546
+ * // false
1547
+ *
1548
+ * post.body = 'groiyyyt'
1549
+ * post.isDirty
1550
+ * // true
1551
+ * ```
1552
+ *
1553
+ * @returns A boolean
1554
+ */
1555
+ get isDirty() {
1556
+ return !!Object.keys(this.dirtyAttributes()).length;
1557
+ }
1558
+ /**
1559
+ * Returns true. This is useful for identifying
1560
+ * dream instances from other objects
1561
+ *
1562
+ * @returns true
1563
+ */
1564
+ get isDreamInstance() {
1565
+ return true;
1566
+ }
1567
+ /**
1568
+ * Runs validation checks against all validations
1569
+ * declared using the Validate and Validates decorators,
1570
+ * and returns true if any of them fail.
1571
+ *
1572
+ * ```ts
1573
+ * class User extends ApplicationModel {
1574
+ * @Validates('presence')
1575
+ * public email: DreamColumn<User, 'email'>
1576
+ * }
1577
+ * const user = User.new()
1578
+ * user.isInvalid
1579
+ * // true
1580
+ *
1581
+ * user.email = 'how@yadoin'
1582
+ * user.isInvalid
1583
+ * // false
1584
+ * ```
1585
+ *
1586
+ * @returns A boolean
1587
+ */
1588
+ get isInvalid() {
1589
+ return !this.isValid;
1590
+ }
1591
+ /**
1592
+ * Returns true if the model has not been persisted
1593
+ * to the database.
1594
+ *
1595
+ * ```ts
1596
+ * const user = User.new({ email: 'howyadoin' })
1597
+ * user.isNewRecord
1598
+ * // true
1599
+ *
1600
+ * await user.save()
1601
+ * user.isNewRecord
1602
+ * // false
1603
+ * ```
1604
+ *
1605
+ * @returns A boolean
1606
+ */
1607
+ get isNewRecord() {
1608
+ return !this.isPersisted;
1609
+ }
1610
+ /**
1611
+ * Runs validation checks against all validations
1612
+ * declared using the Validate and Validates decorators.
1613
+ * Returns true if none of the validations fail.
1614
+ *
1615
+ * NOTE: Any validations that fail will leave the errors
1616
+ * field populated on your model instance.
1617
+ *
1618
+ * ```ts
1619
+ * class User extends ApplicationModel {
1620
+ * @Validates('presence')
1621
+ * public email: DreamColumn<User, 'email'>
1622
+ * }
1623
+ *
1624
+ * const user = User.new()
1625
+ * user.isValid
1626
+ * // false
1627
+ *
1628
+ * user.email = 'how@yadoin'
1629
+ * user.isValid
1630
+ * // true
1631
+ * ```
1632
+ *
1633
+ * @returns A boolean
1634
+ */
1635
+ get isValid() {
1636
+ this._errors = {};
1637
+ runValidations(this);
1638
+ return !Object.keys(this.errors).filter(key => !!this.errors[key].length).length;
1639
+ }
1640
+ /**
1641
+ * The name of the primary key column on this model.
1642
+ * NOTE: Must specify `as const` when defining a custom
1643
+ * primary key.
1644
+ *
1645
+ * ```ts
1646
+ * class User extends ApplicationModel {
1647
+ * public customIdField: DreamColumn<User, 'customIdField'>
1648
+ *
1649
+ * public get primaryKey() {
1650
+ * return 'customIdField' as const
1651
+ * }
1652
+ * }
1653
+ * ```
1654
+ *
1655
+ * @returns The primary key column name
1656
+ */
1657
+ get primaryKey() {
1658
+ return 'id';
1659
+ }
1660
+ /**
1661
+ * Returns the value of the primary key
1662
+ *
1663
+ * @returns The value of the primary key field for this Dream instance
1664
+ */
1665
+ get primaryKeyValue() {
1666
+ return this[this.primaryKey] || null;
1667
+ }
1668
+ /**
1669
+ * This must be defined on every model, and it must point
1670
+ * to a table in your database. In addition, you must
1671
+ * return the value using the `as const` suffix, like so:
1672
+ *
1673
+ * ```ts
1674
+ * class User extends ApplicationModel {
1675
+ * public get table() {
1676
+ * return 'users' as const
1677
+ * }
1678
+ * }
1679
+ * ```
1680
+ *
1681
+ * @returns The table name for this model
1682
+ */
1683
+ get table() {
1684
+ throw new MissingTable(this.constructor);
1685
+ }
1686
+ /**
1687
+ * @internal
1688
+ *
1689
+ * _errors is used to inform validation errors,
1690
+ * and is built whenever validations are run on
1691
+ * a dream instance.
1692
+ */
1693
+ _errors = {};
1694
+ /**
1695
+ * @internal
1696
+ *
1697
+ * Used for the changes api
1698
+ */
1699
+ frozenAttributes = {};
1700
+ /**
1701
+ * @internal
1702
+ *
1703
+ * Used for the changes api
1704
+ */
1705
+ originalAttributes = {};
1706
+ /**
1707
+ * @internal
1708
+ *
1709
+ * Used for the changes api
1710
+ */
1711
+ currentAttributes = {};
1712
+ /**
1713
+ * @internal
1714
+ *
1715
+ * Used for the changes api
1716
+ */
1717
+ attributesFromBeforeLastSave = {};
1718
+ /**
1719
+ * @internal
1720
+ *
1721
+ * Stores whether the record has been persisted or not
1722
+ */
1723
+ _isPersisted;
1724
+ /**
1725
+ * Returns true if the model has been persisted
1726
+ * to the database.
1727
+ *
1728
+ * ```ts
1729
+ * const user = User.new({ email: 'howyadoin' })
1730
+ * user.isPersisted
1731
+ * // false
1732
+ *
1733
+ * await user.save()
1734
+ * user.isPersisted
1735
+ * // true
1736
+ * ```
1737
+ *
1738
+ * @returns A boolean
1739
+ */
1740
+ get isPersisted() {
1741
+ return this._isPersisted || false;
1742
+ }
1743
+ set isPersisted(val) {
1744
+ this._isPersisted = val;
1745
+ }
1746
+ /**
1747
+ * Since typescript prevents constructor functions
1748
+ * from absorbing type generics, we provide the `new`
1749
+ * method to instantiate with type protection
1750
+ *
1751
+ * ```ts
1752
+ * const user = User.new({ email: 'how@yadoin' })
1753
+ * ```
1754
+ *
1755
+ * @returns A new (unpersisted) instance of the provided dream class
1756
+ */
1757
+ static new(opts, additionalOpts = {}) {
1758
+ const dreamModel = new this(opts, {
1759
+ ...additionalOpts,
1760
+ _internalUseOnly: true,
1761
+ });
1762
+ dreamModel.finalizeConstruction();
1763
+ return dreamModel;
1764
+ }
1765
+ /**
1766
+ * @internal
1767
+ *
1768
+ * NOTE: avoid using the constructor function directly.
1769
+ * Use the static `.new` or `.create` methods instead, which
1770
+ * will provide type guarding for your attributes.
1771
+ *
1772
+ * Since typescript prevents constructor functions
1773
+ * from absorbing type generics, we provide the `new`
1774
+ * method to instantiate with type protection.
1775
+ *
1776
+ * ```ts
1777
+ * const user = User.new({ email: 'how@yadoin' })
1778
+ * ```
1779
+ *
1780
+ * @returns A new (unpersisted) instance of the provided dream class
1781
+ */
1782
+ constructor(opts, additionalOpts) {
1783
+ if (!additionalOpts._internalUseOnly)
1784
+ throw new ConstructorOnlyForInternalUse();
1785
+ this.isPersisted = additionalOpts?.isPersisted || false;
1786
+ this.defineAttributeAccessors();
1787
+ if (opts) {
1788
+ const marshalledOpts = this._setAttributes(opts, additionalOpts);
1789
+ // if id is set, then we freeze attributes after setting them, so that
1790
+ // any modifications afterwards will indicate updates.
1791
+ if (this.isPersisted) {
1792
+ this.freezeAttributes();
1793
+ this.originalAttributes = { ...marshalledOpts };
1794
+ this.attributesFromBeforeLastSave = { ...marshalledOpts };
1795
+ }
1796
+ else {
1797
+ const columns = this.constructor.columns();
1798
+ columns.forEach(column => {
1799
+ this.originalAttributes[column] = undefined;
1800
+ this.attributesFromBeforeLastSave[column] = undefined;
1801
+ });
1802
+ }
1803
+ }
1804
+ /**
1805
+ *
1806
+ * Modern Javascript sets all properties that do not have an explicit
1807
+ * assignment within the constructor to undefined in an implicit constructor.
1808
+ * Since the Dream constructor sets the value of properties of instances of
1809
+ * classes that extend Dream (e.g. when passing attributes to #new or #create
1810
+ * or when loading a model via one of the #find methods or #all), we need to
1811
+ * prevent those properties from being set back to undefined. Since all
1812
+ * properties corresponding to a database column get a setter, we achieve this
1813
+ * protection by including a guard in the setters that returns if this
1814
+ * property is set.
1815
+ *
1816
+ */
1817
+ this.columnSetterGuardActivated = true;
1818
+ }
1819
+ /**
1820
+ * @internal
1821
+ *
1822
+ * Used for determining which attributes to update
1823
+ */
1824
+ static extractAttributesFromUpdateableProperties(attributes, dreamInstance, { bypassUserDefinedSetters = false } = {}) {
1825
+ const returnValues = {};
1826
+ const setAttributeOnDreamInstance = (attr, value) => {
1827
+ if (!dreamInstance)
1828
+ return;
1829
+ if (bypassUserDefinedSetters) {
1830
+ dreamInstance.setAttribute(attr, value);
1831
+ }
1832
+ else {
1833
+ dreamInstance.assignAttribute(attr, value);
1834
+ }
1835
+ };
1836
+ Object.keys(attributes).forEach(attr => {
1837
+ const associationMetaData = this.associationMetadataMap()[attr];
1838
+ if (associationMetaData && associationMetaData.type !== 'BelongsTo') {
1839
+ throw new CanOnlyPassBelongsToModelParam(this, associationMetaData);
1840
+ }
1841
+ else if (associationMetaData) {
1842
+ const belongsToAssociationMetaData = associationMetaData;
1843
+ const associatedObject = attributes[attr];
1844
+ // if dream instance is passed, set the loaded association
1845
+ if (dreamInstance && associatedObject !== undefined)
1846
+ dreamInstance[attr] = associatedObject;
1847
+ if (!associationMetaData.optional && !associatedObject)
1848
+ throw new CannotPassNullOrUndefinedToRequiredBelongsTo(this, associationMetaData);
1849
+ const foreignKey = belongsToAssociationMetaData.foreignKey();
1850
+ const foreignKeyValue = belongsToAssociationMetaData.primaryKeyValue(associatedObject);
1851
+ if (foreignKeyValue !== undefined) {
1852
+ returnValues[foreignKey] = foreignKeyValue;
1853
+ setAttributeOnDreamInstance(foreignKey, returnValues[foreignKey]);
1854
+ // Set the belongs-to association
1855
+ setAttributeOnDreamInstance(attr, attributes[attr]);
1856
+ }
1857
+ if (belongsToAssociationMetaData.polymorphic) {
1858
+ const foreignKeyTypeField = belongsToAssociationMetaData.foreignKeyTypeField();
1859
+ returnValues[foreignKeyTypeField] = associatedObject?.stiBaseClassOrOwnClass?.name;
1860
+ setAttributeOnDreamInstance(foreignKeyTypeField, returnValues[foreignKeyTypeField]);
1861
+ }
1862
+ }
1863
+ else {
1864
+ returnValues[attr] = attributes[attr];
1865
+ setAttributeOnDreamInstance(attr, returnValues[attr]);
1866
+ }
1867
+ });
1868
+ return returnValues;
1869
+ }
1870
+ /**
1871
+ * @internal
1872
+ *
1873
+ * defines attribute setters and getters for every column
1874
+ * set within your types/dream.ts file
1875
+ */
1876
+ defineAttributeAccessors() {
1877
+ const dreamClass = this.constructor;
1878
+ const columns = dreamClass.columns();
1879
+ const dreamPrototype = Object.getPrototypeOf(this);
1880
+ columns.forEach(column => {
1881
+ // this ensures that the currentAttributes object will contain keys
1882
+ // for each of the properties
1883
+ if (this.currentAttributes[column] === undefined)
1884
+ this.currentAttributes[column] = undefined;
1885
+ if (!Object.getOwnPropertyDescriptor(dreamPrototype, column)?.set) {
1886
+ if (isJsonColumn(this.constructor, column)) {
1887
+ // handle JSON columns
1888
+ Object.defineProperty(dreamPrototype, column, {
1889
+ get() {
1890
+ if ([undefined, null].includes(this.currentAttributes[column]))
1891
+ return this.currentAttributes[column];
1892
+ return JSON.parse(this.currentAttributes[column]);
1893
+ },
1894
+ set(val) {
1895
+ /**
1896
+ *
1897
+ * Modern Javascript sets all properties that do not have an explicit
1898
+ * assignment within the constructor to undefined in an implicit constructor.
1899
+ * Since the Dream constructor sets the value of properties of instances of
1900
+ * classes that extend Dream (e.g. when passing attributes to #new or #create
1901
+ * or when loading a model via one of the #find methods or #all), we need to
1902
+ * prevent those properties from being set back to undefined. Since all
1903
+ * properties corresponding to a database column get a setter, we achieve this
1904
+ * protection by including a guard in the setters that returns if this
1905
+ * property is set.
1906
+ *
1907
+ */
1908
+ if (this.columnSetterGuardActivated)
1909
+ return;
1910
+ this.currentAttributes[column] = isString(val) ? val : JSON.stringify(val);
1911
+ },
1912
+ configurable: true,
1913
+ });
1914
+ }
1915
+ else {
1916
+ // handle all other columns
1917
+ Object.defineProperty(dreamPrototype, column, {
1918
+ get() {
1919
+ return this.currentAttributes[column];
1920
+ },
1921
+ set(val) {
1922
+ /**
1923
+ *
1924
+ * Modern Javascript sets all properties that do not have an explicit
1925
+ * assignment within the constructor to undefined in an implicit constructor.
1926
+ * Since the Dream constructor sets the value of properties of instances of
1927
+ * classes that extend Dream (e.g. when passing attributes to #new or #create
1928
+ * or when loading a model via one of the #find methods or #all), we need to
1929
+ * prevent those properties from being set back to undefined. Since all
1930
+ * properties corresponding to a database column get a setter, we achieve this
1931
+ * protection by including a guard in the setters that returns if this
1932
+ * property is set.
1933
+ *
1934
+ */
1935
+ if (this.columnSetterGuardActivated)
1936
+ return;
1937
+ this.currentAttributes[column] = val;
1938
+ },
1939
+ configurable: true,
1940
+ });
1941
+ }
1942
+ }
1943
+ });
1944
+ ensureSTITypeFieldIsSet(this);
1945
+ }
1946
+ /**
1947
+ * @internal
1948
+ *
1949
+ * Modern Javascript applies implicit accessors to instance properties that
1950
+ * shadow prototype accessors applied by Dream. This method is called after
1951
+ * every Dream model is initialized to delete the instance accessors so that
1952
+ * the prototype accessors can be reached.
1953
+ */
1954
+ unshadowColumnPropertyPrototypeAccessors() {
1955
+ ;
1956
+ this.constructor.columns().forEach(column => delete this[column]);
1957
+ }
1958
+ finalizeConstruction() {
1959
+ /**
1960
+ *
1961
+ * Modern Javascript sets all properties that do not have an explicit
1962
+ * assignment within the constructor to undefined in an implicit constructor.
1963
+ * Since the Dream constructor sets the value of properties of instances of
1964
+ * classes that extend Dream (e.g. when passing attributes to #new or #create
1965
+ * or when loading a model via one of the #find methods or #all), we need to
1966
+ * prevent those properties from being set back to undefined. Since all
1967
+ * properties corresponding to a database column get a setter, we achieve this
1968
+ * protection by including a guard in the setters that returns if this
1969
+ * property is set.
1970
+ *
1971
+ */
1972
+ this.columnSetterGuardActivated = false;
1973
+ /**
1974
+ * Modern Javascript applies implicit accessors to instance properties
1975
+ * that don't have an accessor explicitly defined in the class definition.
1976
+ * The instance accessors shadow prototype accessors applied by Dream.
1977
+ * This method is called after every Dream model is initialized to delete the
1978
+ * instance accessors so that the prototype accessors can be reached.
1979
+ */
1980
+ this.unshadowColumnPropertyPrototypeAccessors();
1981
+ }
1982
+ /**
1983
+ * Returns true if the columnName passed is marked by a
1984
+ * Virtual attribute decorator
1985
+ *
1986
+ * @param columnName - A property on this model to check
1987
+ * @returns A boolean
1988
+ */
1989
+ isVirtualColumn(columnName) {
1990
+ return this.constructor.virtualAttributes
1991
+ .map(attr => attr.property)
1992
+ .includes(columnName);
1993
+ }
1994
+ /**
1995
+ * Returns an object with column names for keys, and an
1996
+ * array of strings representing validation errors for values.
1997
+ *
1998
+ * @returns An error object
1999
+ */
2000
+ get errors() {
2001
+ return { ...this._errors };
2002
+ }
2003
+ /**
2004
+ * Adds an error to the model. Any errors added to the model
2005
+ * will cause the model to be invalid, and will prevent the
2006
+ * model from saving.
2007
+ *
2008
+ * ```ts
2009
+ * class User extends ApplicationModel {
2010
+ * ...
2011
+ * @Validate()
2012
+ * public async validateName() {
2013
+ * if (typeof this.name === 'number')
2014
+ * this.addError('name', 'name cannot be a number')
2015
+ * }
2016
+ * }
2017
+ * ```
2018
+ *
2019
+ * @returns void
2020
+ */
2021
+ addError(column, error) {
2022
+ this._errors[column] ||= [];
2023
+ this._errors[column].push(error);
2024
+ }
2025
+ /**
2026
+ * Changes the attribute value for a single attribute,
2027
+ * leveraging any custom-defined setters. If you would like to
2028
+ * bypass custom-defined setters, use #setAttribute instead
2029
+ *
2030
+ * ```ts
2031
+ * const user = new User()
2032
+ * user.assignAttribute('email', 'sally@gmail.com')
2033
+ * ```
2034
+ */
2035
+ assignAttribute(attr, val) {
2036
+ const self = this;
2037
+ self[attr] = val;
2038
+ }
2039
+ /**
2040
+ * Changes the attribute value for a single attribute internally,
2041
+ * bypassing any custom-defined setters. If you would like to set attributes
2042
+ * without bypassing custom-defined setters, use #assignAttribute instead
2043
+ *
2044
+ * ```ts
2045
+ * const user = new User()
2046
+ * user.setAttribute('email', 'sally@gmail.com')
2047
+ * ```
2048
+ */
2049
+ setAttribute(attr, val) {
2050
+ const columns = this.constructor.columns();
2051
+ const self = this;
2052
+ if (columns.has(attr)) {
2053
+ self.currentAttributes[attr] = isJsonColumn(this.constructor, attr)
2054
+ ? isString(val)
2055
+ ? val
2056
+ : JSON.stringify(val)
2057
+ : val;
2058
+ }
2059
+ else {
2060
+ self.currentAttributes[attr] = val;
2061
+ }
2062
+ }
2063
+ /**
2064
+ * Returns the value for a columnName provided,
2065
+ * bypassing the getters.
2066
+ *
2067
+ * ```ts
2068
+ * const user = User.new({ email: 'how@yadoin' })
2069
+ * user.getAttribute('email') // 'how@yadoin'
2070
+ * ```
2071
+ */
2072
+ getAttribute(columnName) {
2073
+ const columns = this.constructor.columns();
2074
+ const self = this;
2075
+ if (columns.has(columnName)) {
2076
+ return self.currentAttributes[columnName];
2077
+ }
2078
+ else {
2079
+ return self[columnName];
2080
+ }
2081
+ }
2082
+ /**
2083
+ * Returns an object containing all the columns
2084
+ * on this dream class, as well as their values,
2085
+ * bypassing getters.
2086
+ *
2087
+ * ```ts
2088
+ * const user = User.new({ email: 'how@yadoin' })
2089
+ * user.attributes()
2090
+ * // {
2091
+ * // email: 'how@yadoin',
2092
+ * // ...
2093
+ * // }
2094
+ * ```
2095
+ */
2096
+ getAttributes() {
2097
+ return { ...this.currentAttributes };
2098
+ }
2099
+ /**
2100
+ * @internal
2101
+ *
2102
+ * Returns the db type stored within the database
2103
+ */
2104
+ static cachedTypeFor(attribute) {
2105
+ return cachedTypeForAttribute(this, attribute);
2106
+ }
2107
+ /**
2108
+ * Returns the attributes that have changed since
2109
+ * being persisted to the database, with the values
2110
+ * that were last persisted to the database.
2111
+ *
2112
+ * ```ts
2113
+ * const user = User.new({ email: 'original@email', password: 'howyadoin' })
2114
+ * await user.save()
2115
+ *
2116
+ * user.email = 'new@email'
2117
+ * user.changedAttributes()
2118
+ * // { email: 'original@email' }
2119
+ *
2120
+ * user.email = 'original@email'
2121
+ * user.changedAttributes()
2122
+ * // {}
2123
+ * ```
2124
+ *
2125
+ * @returns An object containing changed attributes and their original values
2126
+ */
2127
+ changedAttributes() {
2128
+ const obj = {};
2129
+ Object.keys(this.dirtyAttributes()).forEach(column => {
2130
+ ;
2131
+ obj[column] = this.frozenAttributes[column];
2132
+ });
2133
+ return obj;
2134
+ }
2135
+ /**
2136
+ * Returns an object containing the attributes that have
2137
+ * changed since last persisting, along with their current
2138
+ * and previously persisted values.
2139
+ *
2140
+ * ```ts
2141
+ * const pet = Pet.new({ species: 'dog' })
2142
+ * pet.changes()
2143
+ * // {
2144
+ * // species: {
2145
+ * // was: undefined,
2146
+ * // now: 'dog',
2147
+ * // }
2148
+ * // }
2149
+ *
2150
+ * await pet.save()
2151
+ * pet.changes()
2152
+ * // {
2153
+ * // species: {
2154
+ * // was: undefined,
2155
+ * // now: 'dog',
2156
+ * // }
2157
+ * // }
2158
+ *
2159
+ * pet.species = 'cat'
2160
+ * pet.species = 'frog'
2161
+ * pet.changes()
2162
+ * // {
2163
+ * // species: {
2164
+ * // was: 'dog',
2165
+ * // now: 'frog',
2166
+ * // }
2167
+ * // }
2168
+ *
2169
+ * await pet.save()
2170
+ * pet.changes()
2171
+ * // {
2172
+ * // species: {
2173
+ * // was: 'dog',
2174
+ * // now: 'frog',
2175
+ * // }
2176
+ * // }
2177
+ * ```
2178
+ *
2179
+ * @returns An object containing changed attributes
2180
+ */
2181
+ changes() {
2182
+ const obj = {};
2183
+ this.constructor.columns().forEach(column => {
2184
+ const was = this.previousValueForAttribute(column);
2185
+ const now = this[column];
2186
+ if (was !== now) {
2187
+ ;
2188
+ obj[column] = {
2189
+ was,
2190
+ now,
2191
+ };
2192
+ }
2193
+ });
2194
+ return obj;
2195
+ }
2196
+ /**
2197
+ * Returns the value most recently persisted
2198
+ * to the database.
2199
+ *
2200
+ * ```ts
2201
+ * const pet = Pet.new({ species: 'cat' })
2202
+ * pet.previousValueForAttribute('species')
2203
+ * // undefined
2204
+ *
2205
+ * await pet.save()
2206
+ * pet.previousValueForAttribute('species')
2207
+ * // undefined
2208
+ *
2209
+ * pet.species = 'dog'
2210
+ * pet.previousValueForAttribute('species')
2211
+ * // 'cat'
2212
+ *
2213
+ * await pet.save()
2214
+ * pet.previousValueForAttribute('species')
2215
+ * // 'cat'
2216
+ *
2217
+ * await pet.update({ species: 'cat' })
2218
+ * pet.previousValueForAttribute('species')
2219
+ * // 'dog'
2220
+ * ```
2221
+ *
2222
+ * @param columName - The column name you want the previous value for
2223
+ * @returns Returns the previous value for an attribute
2224
+ */
2225
+ previousValueForAttribute(columnName) {
2226
+ if (this.frozenAttributes[columnName] !== this[columnName])
2227
+ return this.frozenAttributes[columnName];
2228
+ return this.attributesFromBeforeLastSave[columnName];
2229
+ }
2230
+ /**
2231
+ * Returns true if the columnName provided has
2232
+ * changes that were persisted during the most
2233
+ * recent save.
2234
+ *
2235
+ * @param columnName - the column name to check
2236
+ * @returns A boolean
2237
+ */
2238
+ savedChangeToAttribute(columnName) {
2239
+ const changes = this.changes();
2240
+ const now = changes?.[columnName]?.now;
2241
+ const was = changes?.[columnName]?.was;
2242
+ return this.isPersisted && now !== was;
2243
+ }
2244
+ /**
2245
+ * Returns true if the columnName provided has
2246
+ * changes that have not yet been persisted.
2247
+ *
2248
+ * @param columnName - the column name to check
2249
+ * @returns A boolean
2250
+ */
2251
+ willSaveChangeToAttribute(attribute) {
2252
+ return this.attributeIsDirty(attribute);
2253
+ }
2254
+ /**
2255
+ * Returns the column names for the given model
2256
+ *
2257
+ * @returns The column names for the given model
2258
+ */
2259
+ columns() {
2260
+ return this.constructor.columns();
2261
+ }
2262
+ /**
2263
+ * Returns an object containing the column names
2264
+ * of columns that have changed since last persist,
2265
+ * and their current values.
2266
+ *
2267
+ * ```ts
2268
+ * const user = User.new({ email: 'hello@world' })
2269
+ * user.dirtyAttributes()
2270
+ * // { email: 'hello@world' }
2271
+ *
2272
+ * await user.save()
2273
+ *
2274
+ * user.email = 'hello@world'
2275
+ * user.dirtyAttributes()
2276
+ * // {}
2277
+ *
2278
+ * user.email = 'goodbye@world'
2279
+ * user.dirtyAttributes()
2280
+ * // { email: 'goodbye@world' }
2281
+ *
2282
+ * user.email = 'hello@world'
2283
+ * user.dirtyAttributes()
2284
+ * // {}
2285
+ * ```
2286
+ *
2287
+ * @returns An object containing the changed attributes
2288
+ */
2289
+ dirtyAttributes() {
2290
+ const obj = {};
2291
+ this.columns().forEach(column => {
2292
+ // TODO: clean up types
2293
+ if (this.attributeIsDirty(column))
2294
+ obj[column] = this.getAttributes()[column];
2295
+ });
2296
+ return obj;
2297
+ }
2298
+ /**
2299
+ * Returns true if an attribute has changes since last persist
2300
+ *
2301
+ * @returns A boolean
2302
+ */
2303
+ attributeIsDirty(attribute) {
2304
+ const frozenValue = this.frozenAttributes[attribute];
2305
+ const currentValue = this.getAttributes()[attribute];
2306
+ if (this.isNewRecord)
2307
+ return true;
2308
+ if (frozenValue instanceof DateTime) {
2309
+ return frozenValue.toMillis() !== this.unknownValueToMillis(currentValue);
2310
+ }
2311
+ else if (frozenValue instanceof CalendarDate) {
2312
+ return frozenValue.toISO() !== this.unknownValueToDateString(currentValue);
2313
+ }
2314
+ else {
2315
+ return frozenValue !== currentValue;
2316
+ }
2317
+ }
2318
+ /**
2319
+ * @internal
2320
+ */
2321
+ unknownValueToMillis(currentValue) {
2322
+ if (!currentValue)
2323
+ return;
2324
+ if (isString(currentValue))
2325
+ currentValue = DateTime.fromISO(currentValue);
2326
+ if (currentValue instanceof CalendarDate)
2327
+ currentValue = currentValue.toDateTime();
2328
+ if (currentValue instanceof DateTime && currentValue.isValid)
2329
+ return currentValue.toMillis();
2330
+ }
2331
+ /**
2332
+ * @internal
2333
+ */
2334
+ unknownValueToDateString(currentValue) {
2335
+ if (!currentValue)
2336
+ return;
2337
+ if (isString(currentValue))
2338
+ currentValue = CalendarDate.fromISO(currentValue);
2339
+ if (currentValue instanceof DateTime)
2340
+ currentValue = CalendarDate.fromDateTime(currentValue);
2341
+ if (currentValue instanceof CalendarDate && currentValue.isValid)
2342
+ return currentValue.toISO();
2343
+ }
2344
+ /**
2345
+ * Deletes the record represented by this instance
2346
+ * from the database, calling any destroy
2347
+ * hooks on this model.
2348
+ *
2349
+ * ```ts
2350
+ * const user = await User.last()
2351
+ * await user.destroy()
2352
+ * ```
2353
+ *
2354
+ * @param options - Options for destroying the instance
2355
+ * @param options.skipHooks - If true, skips applying model hooks during the destroy operation. Defaults to false
2356
+ * @param options.cascade - If false, skips destroying associations marked `dependent: 'destroy'`. Defaults to true
2357
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when cascade destroying. Defaults to false
2358
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when cascade destroying. Defaults to an empty array
2359
+ * @returns The instance that was destroyed
2360
+ */
2361
+ async destroy(options = {}) {
2362
+ return await destroyDream(this, null, destroyOptions(options));
2363
+ }
2364
+ /**
2365
+ * Deletes the record represented by this instance
2366
+ * from the database, calling any destroy
2367
+ * hooks on this model.
2368
+ *
2369
+ * If the record being destroyed is using
2370
+ * a SoftDelete decorator, the soft delete
2371
+ * will be bypassed, causing the record
2372
+ * to be permanently removed from the database.
2373
+ *
2374
+ * ```ts
2375
+ * const user = await User.last()
2376
+ * await user.reallyDestroy()
2377
+ * ```
2378
+ *
2379
+ * @param options - Options for destroying the instance
2380
+ * @param options.skipHooks - If true, skips applying model hooks during the destroy operation. Defaults to false
2381
+ * @param options.cascade - If false, skips destroying associations marked `dependent: 'destroy'`. Defaults to true
2382
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when cascade destroying. Defaults to false
2383
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when cascade destroying. Defaults to an empty array
2384
+ * @returns The instance that was destroyed
2385
+ */
2386
+ async reallyDestroy(options = {}) {
2387
+ return await destroyDream(this, null, reallyDestroyOptions(options));
2388
+ }
2389
+ /**
2390
+ * Undestroys a SoftDelete model, unsetting
2391
+ * the `deletedAt` field in the database.
2392
+ *
2393
+ * If the model is not a SoftDelete model,
2394
+ * this will raise an exception.
2395
+ *
2396
+ * ```ts
2397
+ * const user = await User.removeAllDefaultScopes().last()
2398
+ * await user.undestroy()
2399
+ * ```
2400
+ *
2401
+ * @param options - Options for undestroying the instance
2402
+ * @param options.skipHooks - If true, skips applying model hooks during the undestroy operation. Defaults to false
2403
+ * @param options.cascade - If false, skips undestroying associations marked `dependent: 'destroy'`. Defaults to true
2404
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when cascade undestroying. Defaults to false
2405
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when cascade undestroying (soft delete is always bypassed). Defaults to an empty array
2406
+ * @returns The undestroyed record
2407
+ */
2408
+ async undestroy(options = {}) {
2409
+ const dreamClass = this.constructor;
2410
+ if (!dreamClass['softDelete'])
2411
+ throw new CannotCallUndestroyOnANonSoftDeleteModel(dreamClass);
2412
+ await undestroyDream(this, null, undestroyOptions(options));
2413
+ return this;
2414
+ }
2415
+ /**
2416
+ * Returns true if the argument is the same Dream class
2417
+ * with the same primary key value.
2418
+ *
2419
+ * NOTE: This does not compare attribute values other than
2420
+ * the primary key.
2421
+ *
2422
+ * @returns A boolean
2423
+ */
2424
+ equals(other) {
2425
+ return other?.constructor === this.constructor && other.primaryKeyValue === this.primaryKeyValue;
2426
+ }
2427
+ /**
2428
+ * @internal
2429
+ *
2430
+ * Used for changes API
2431
+ */
2432
+ freezeAttributes() {
2433
+ this.frozenAttributes = { ...this.getAttributes() };
2434
+ }
2435
+ /**
2436
+ * Deep clones the model and its non-association attributes.
2437
+ * Unsets primaryKey, created and updated fields.
2438
+ *
2439
+ * @returns Non-persisted, cloned Dream instance
2440
+ */
2441
+ dup() {
2442
+ const clone = this.clone({ includeAssociations: false });
2443
+ clone.isPersisted = false;
2444
+ clone[clone.primaryKey] = undefined;
2445
+ clone[clone.createdAtField] = undefined;
2446
+ clone[clone.updatedAtField] = undefined;
2447
+ const dreamClass = this.constructor;
2448
+ dreamClass.sortableFields.forEach(data => {
2449
+ ;
2450
+ clone[data.positionField] = undefined;
2451
+ });
2452
+ clone.freezeAttributes();
2453
+ clone.originalAttributes = { ...clone.getAttributes() };
2454
+ clone.attributesFromBeforeLastSave = { ...clone.getAttributes() };
2455
+ return clone;
2456
+ }
2457
+ /**
2458
+ * Deep clones the model and it's attributes, but maintains references to
2459
+ * loaded associations
2460
+ */
2461
+ clone({ includeAssociations = true } = {}) {
2462
+ const self = this;
2463
+ const clone = self.constructor.new({});
2464
+ const associationDataKeys = Object.values(this.constructor.associationMetadataMap()).map(association => associationToGetterSetterProp(association));
2465
+ Object.keys(this).forEach(property => {
2466
+ if (!associationDataKeys.includes(property))
2467
+ clone[property] = cloneDeepSafe(self[property]);
2468
+ });
2469
+ if (includeAssociations) {
2470
+ associationDataKeys.forEach(associationDataKey => (clone[associationDataKey] = self[associationDataKey]));
2471
+ }
2472
+ return clone;
2473
+ }
2474
+ /**
2475
+ * Creates an association for an instance. Automatically
2476
+ * handles setting foreign key and, in the case of polymorphism,
2477
+ * foreign key type.
2478
+ *
2479
+ * ```ts
2480
+ * await user.createAssociation('posts', { body: 'hello world' })
2481
+ * ```
2482
+ *
2483
+ * @param associationName - the name of the association to create
2484
+ * @param attributes - the attributes with which to create the associated model
2485
+ * @returns The created association
2486
+ */
2487
+ async createAssociation(associationName, attributes = {}) {
2488
+ return createAssociation(this, null, associationName, attributes);
2489
+ }
2490
+ /**
2491
+ * Destroys models associated with the current instance,
2492
+ * deleting their corresponding records within the database.
2493
+ *
2494
+ * ```ts
2495
+ * await user.destroyAssociation('posts', { body: 'hello world' })
2496
+ * ```
2497
+ *
2498
+ * @param associationName - The name of the association to destroy
2499
+ * @param options - Options for destroying the association
2500
+ * @param options.on - Optional where statement to apply to query before destroying
2501
+ * @param options.skipHooks - If true, skips applying model hooks during the destroy operation. Defaults to false
2502
+ * @param options.cascade - If false, skips destroying associations marked `dependent: 'destroy'`. Defaults to true
2503
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when destroying the association. Defaults to false
2504
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when destroying the association. Defaults to an empty array
2505
+ * @returns The number of records deleted
2506
+ */
2507
+ async destroyAssociation(associationName, options) {
2508
+ return await destroyAssociation(this, null, associationName, {
2509
+ ...destroyOptions(options),
2510
+ joinOnStatements: {
2511
+ on: options?.on,
2512
+ notOn: options?.notOn,
2513
+ onAny: options?.onAny,
2514
+ },
2515
+ });
2516
+ }
2517
+ /**
2518
+ * Destroys models associated with the current instance,
2519
+ * deleting their corresponding records within the database.
2520
+ *
2521
+ * If the record, or else any of its associations
2522
+ * which are marked cascade: "destroy", are using
2523
+ * the SoftDelete decorator, it will be bypassed,
2524
+ * causing those records to be deleted from the database.
2525
+ *
2526
+ * ```ts
2527
+ * await user.reallyDestroyAssociation('posts', { body: 'hello world' })
2528
+ * ```
2529
+ *
2530
+ * @param associationName - The name of the association to destroy
2531
+ * @param options - Options for destroying the association
2532
+ * @param options.on - Optional where statement to apply to query before destroying
2533
+ * @param options.skipHooks - If true, skips applying model hooks during the destroy operation. Defaults to false
2534
+ * @param options.cascade - If true, cascades the destroy operation to associations marked with `dependent: 'destroy'`. Defaults to true
2535
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when destroying the association. Defaults to false
2536
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when destroying the association. Defaults to an empty array
2537
+ * @returns The number of records deleted
2538
+ */
2539
+ async reallyDestroyAssociation(associationName, options) {
2540
+ return await destroyAssociation(this, null, associationName, {
2541
+ ...reallyDestroyOptions(options),
2542
+ joinOnStatements: {
2543
+ on: options?.on,
2544
+ notOn: options?.notOn,
2545
+ onAny: options?.onAny,
2546
+ },
2547
+ });
2548
+ }
2549
+ /**
2550
+ * Undestroys a SoftDelete association.
2551
+ * If cascade: true is passed, any child
2552
+ * associations that have been soft deleted
2553
+ * will also be undeleted.
2554
+ *
2555
+ * ```ts
2556
+ * await user.undestroyAssociation('posts', { body: 'hello world' })
2557
+ * ```
2558
+ *
2559
+ * @param associationName - The name of the association to undestroy
2560
+ * @param options - Options for undestroying the association
2561
+ * @param options.on - Optional where statement to apply to query before undestroying
2562
+ * @param options.skipHooks - If true, skips applying model hooks during the undestroy operation. Defaults to false
2563
+ * @param options.cascade - If false, skips undestroying associations marked `dependent: 'destroy'`. Defaults to true
2564
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when undestroying the association. Defaults to false
2565
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when undestroying the association. Defaults to an empty array
2566
+ * @returns The number of records undestroyed
2567
+ */
2568
+ async undestroyAssociation(associationName, options) {
2569
+ return await undestroyAssociation(this, null, associationName, {
2570
+ ...undestroyOptions(options),
2571
+ joinOnStatements: {
2572
+ on: options?.on,
2573
+ notOn: options?.notOn,
2574
+ onAny: options?.onAny,
2575
+ },
2576
+ });
2577
+ }
2578
+ /**
2579
+ * Returns a Query instance for the specified
2580
+ * association on the current instance.
2581
+ *
2582
+ * ```ts
2583
+ * await user.associationQuery('posts').all()
2584
+ * // only user posts returned
2585
+ * ```
2586
+ *
2587
+ * @returns A Query scoped to the specified association on the current instance
2588
+ *
2589
+ */
2590
+ associationQuery(associationName, joinOnStatements) {
2591
+ return associationQuery(this, null, associationName, {
2592
+ joinOnStatements: joinOnStatements,
2593
+ bypassAllDefaultScopes: DEFAULT_BYPASS_ALL_DEFAULT_SCOPES,
2594
+ defaultScopesToBypass: DEFAULT_DEFAULT_SCOPES_TO_BYPASS,
2595
+ });
2596
+ }
2597
+ /**
2598
+ * Updates all records matching the association with
2599
+ * the provided attributes. If a where statement is passed,
2600
+ * The on statement will be applied to the query
2601
+ * before updating.
2602
+ *
2603
+ * ```ts
2604
+ * await user.createAssociation('posts', { body: 'hello world' })
2605
+ * await user.createAssociation('posts', { body: 'howyadoin' })
2606
+ * await user.updateAssociation('posts', { body: 'goodbye world' }, { on: { body: 'hello world' }})
2607
+ * // 1
2608
+ * ```
2609
+ *
2610
+ * @param associationName - The name of the association to update
2611
+ * @param attributes - The attributes to update on the association
2612
+ * @param options - Options for updating the association
2613
+ * @param options.on - Optional on statement to apply to query before updating
2614
+ * @param options.skipHooks - If true, skips applying model hooks during the update operation. Defaults to false
2615
+ * @param options.bypassAllDefaultScopes - If true, bypasses all default scopes when updating the association. Defaults to false
2616
+ * @param options.defaultScopesToBypass - An array of default scope names to bypass when updating the association. Defaults to an empty array
2617
+ * @returns The number of updated records
2618
+ */
2619
+ async updateAssociation(associationName, attributes, updateAssociationOptions) {
2620
+ return associationUpdateQuery(this, null, associationName, {
2621
+ joinOnStatements: {
2622
+ on: updateAssociationOptions?.on,
2623
+ notOn: updateAssociationOptions?.notOn,
2624
+ onAny: updateAssociationOptions?.onAny,
2625
+ },
2626
+ bypassAllDefaultScopes: updateAssociationOptions?.bypassAllDefaultScopes ?? DEFAULT_BYPASS_ALL_DEFAULT_SCOPES,
2627
+ defaultScopesToBypass: updateAssociationOptions?.defaultScopesToBypass ?? DEFAULT_DEFAULT_SCOPES_TO_BYPASS,
2628
+ }).update(attributes, { skipHooks: updateAssociationOptions?.skipHooks ?? DEFAULT_SKIP_HOOKS });
2629
+ }
2630
+ ///////////////////
2631
+ // end: updateAssociation
2632
+ ///////////////////
2633
+ /**
2634
+ * Sends data through for use as passthrough data
2635
+ * for the associations that require it.
2636
+ *
2637
+ * ```ts
2638
+ * class Post {
2639
+ * @Deco.HasMany('LocalizedText')
2640
+ * public localizedTexts: LocalizedText[]
2641
+ *
2642
+ * @Deco.HasOne('LocalizedText', {
2643
+ * where: { locale: DreamConst.passthrough },
2644
+ * })
2645
+ * public currentLocalizedText: LocalizedText
2646
+ * }
2647
+ *
2648
+ * await User.passthrough({ locale: 'es-ES' })
2649
+ * .preload('posts', 'currentLocalizedText')
2650
+ * .first()
2651
+ * ```
2652
+ *
2653
+ * @param passthroughWhereStatement - where statement used for associations that require passthrough data
2654
+ * @returns A cloned Query with the passthrough data
2655
+ */
2656
+ passthrough(passthroughWhereStatement) {
2657
+ return new LoadBuilder(this).passthrough(passthroughWhereStatement);
2658
+ }
2659
+ /**
2660
+ * Loads the requested associations upon execution
2661
+ *
2662
+ * NOTE: {@link #preload} is often a preferrable way of achieving the
2663
+ * same goal.
2664
+ *
2665
+ * ```ts
2666
+ * await user
2667
+ * .load('posts', { body: ops.ilike('%hello world%') }, 'comments', 'replies')
2668
+ * .load('images')
2669
+ * .execute()
2670
+ *
2671
+ * user.posts[0].comments[0].replies[0]
2672
+ * // Reply{}
2673
+ *
2674
+ * user.images[0]
2675
+ * // Image{}
2676
+ * ```
2677
+ *
2678
+ * @param args - A list of associations (and optional where clauses) to load
2679
+ * @returns A chainable LoadBuilder instance
2680
+ */
2681
+ load(...args) {
2682
+ return new LoadBuilder(this).load(...args);
2683
+ }
2684
+ /**
2685
+ * Load each specified association using a single SQL query.
2686
+ * See {@link #load} for loading in separate queries.
2687
+ *
2688
+ * Note: since leftJoinPreload loads via single query, it has
2689
+ * some downsides and that may be avoided using {@link #load}:
2690
+ * 1. `limit` and `offset` will be automatically removed
2691
+ * 2. `through` associations will bring additional namespaces into the query that can conflict with through associations from other associations, creating an invalid query
2692
+ * 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`. `.load('a', 'b', 'c')` would perform three separate SQL queries, but the data for a single `a` would only be returned once.
2693
+ * 4. the individual query becomes more complex the more associations are included
2694
+ * 5. associations loading associations loading associations could result in exponential amounts of data; in those cases, `.load(...).findEach(...)` avoids instantiating massive amounts of data at once
2695
+ * Loads the requested associations upon execution
2696
+ *
2697
+ * NOTE: {@link #leftJoinPreload} is often a preferrable way of achieving the
2698
+ * same goal.
2699
+ *
2700
+ * ```ts
2701
+ * await user
2702
+ * .leftJoinLoad('posts', { body: ops.ilike('%hello world%') }, 'comments', 'replies')
2703
+ * .leftJoinLoad('images')
2704
+ * .execute()
2705
+ *
2706
+ * user.posts[0].comments[0].replies[0]
2707
+ * // Reply{}
2708
+ *
2709
+ * user.images[0]
2710
+ * // Image{}
2711
+ * ```
2712
+ *
2713
+ * @param args - A list of associations (and optional where clauses) to load
2714
+ * @returns A chainable LeftJoinLoadBuilder instance
2715
+ */
2716
+ leftJoinLoad(...args) {
2717
+ return new LeftJoinLoadBuilder(this).leftJoinLoad(...args);
2718
+ }
2719
+ /**
2720
+ * Returns true if the association specified has
2721
+ * been loaded on this instance
2722
+ *
2723
+ * Since accessing associations that haven't been
2724
+ * loaded/preloaded will raise an exception, `loaded`
2725
+ * is useful for conditionally loading from the database
2726
+ * in contexts where an association may not yet be loaded.
2727
+ *
2728
+ * ```ts
2729
+ * user.loaded('posts')
2730
+ * // false
2731
+ *
2732
+ * user = await user.load('posts').execute()
2733
+ * user.loaded('posts')
2734
+ * // true
2735
+ * ```
2736
+ *
2737
+ * @param associationName - the association name you wish to check the loading of
2738
+ * @returns A boolean
2739
+ */
2740
+ loaded(associationName) {
2741
+ try {
2742
+ ;
2743
+ this[associationName];
2744
+ return true;
2745
+ }
2746
+ catch (error) {
2747
+ if (error.constructor !== NonLoadedAssociation)
2748
+ throw error;
2749
+ return false;
2750
+ }
2751
+ }
2752
+ /**
2753
+ * Reloads an instance, refreshing all it's attribute values
2754
+ * to those in the database.
2755
+ *
2756
+ * NOTE: this does not refresh associations
2757
+ *
2758
+ * ```ts
2759
+ * await user.reload()
2760
+ * ```
2761
+ *
2762
+ * @returns void
2763
+ */
2764
+ async reload() {
2765
+ await reload(this);
2766
+ }
2767
+ /**
2768
+ * Serializes an instance. You can specify a serializer key,
2769
+ * or else the default will be used
2770
+ *
2771
+ * ```ts
2772
+ * // uses the default serializer provided in the model's `serializers` getter
2773
+ * await user.serialize()
2774
+ *
2775
+ * // uses the summary serializer provided in the model's `serializers` getter
2776
+ * await user.serialize({ serializerKey: 'summary' })
2777
+ * ```
2778
+ *
2779
+ * @param args.casing - Which casing to use when serializing (camel or snake, default camel)
2780
+ * @param args.serializerKey - The key to use when referencing the object returned by the `serializers` getter on the given model instance (defaults to "default")
2781
+ * @returns A serialized representation of the model
2782
+ */
2783
+ serialize({ casing = null, serializerKey } = {}) {
2784
+ const serializerClass = inferSerializerFromDreamOrViewModel(this, serializerKey?.toString());
2785
+ if (!serializerClass)
2786
+ throw new MissingSerializer(this.constructor);
2787
+ const serializer = new serializerClass(this);
2788
+ if (casing)
2789
+ serializer.casing(casing);
2790
+ return serializer.render();
2791
+ }
2792
+ /**
2793
+ * Takes the attributes passed in and sets their values,
2794
+ * leveraging any custom setters defined for these attributes.
2795
+ *
2796
+ * NOTE:
2797
+ * To bypass custom-defined setters, use `#setAttributes` instead.
2798
+ *
2799
+ * ```ts
2800
+ * const user = new User()
2801
+ * user.assignAttributes({ email: 'my@email', password: 'my password' })
2802
+ * ```
2803
+ */
2804
+ assignAttributes(attributes) {
2805
+ return this._setAttributes(attributes, { bypassUserDefinedSetters: false });
2806
+ }
2807
+ /**
2808
+ * Takes the attributes passed in and sets their values internally,
2809
+ * bypassing any custom setters defined for these attributes.
2810
+ *
2811
+ * NOTE:
2812
+ * To leverage custom-defined setters, use `#assignAttributes` instead.
2813
+ *
2814
+ * ```ts
2815
+ * const user = new User()
2816
+ * user.setAttributes({ email: 'my@email', password: 'my password' })
2817
+ * ```
2818
+ */
2819
+ setAttributes(attributes) {
2820
+ return this._setAttributes(attributes, { bypassUserDefinedSetters: true });
2821
+ }
2822
+ _setAttributes(attributes, additionalOpts = {}) {
2823
+ const dreamClass = this.constructor;
2824
+ const marshalledOpts = dreamClass.extractAttributesFromUpdateableProperties(attributes, this, additionalOpts);
2825
+ return marshalledOpts;
2826
+ }
2827
+ /**
2828
+ * Saves the state of the current instance to the
2829
+ * database. For new instances (that have not been
2830
+ * persisted), `save` and `create` model hooks will be called.
2831
+ * For instances that have already been persisted,
2832
+ * the `save` and `update` model hooks will be called.
2833
+ *
2834
+ * Upon saving a new instance, the primary key, timestamp
2835
+ * fields (if defined), and `type` (if STI) will be set on
2836
+ * the model.
2837
+ *
2838
+ * Upon updating an instance, the update timestamp (if defined)
2839
+ * will be updated on the model.
2840
+ *
2841
+ * ```ts
2842
+ * const user = User.new({ email: 'how@yadoin' })
2843
+ * user.name = 'fred'
2844
+ * await user.save()
2845
+ *
2846
+ * user.email // 'how@yadoin'
2847
+ * user.name // 'fred'
2848
+ * user.id // 1
2849
+ * user.createdAt // A DateTime object
2850
+ * user.updatedAt // A DateTime object
2851
+ *
2852
+ * // If User were STI:
2853
+ * user.type // 'User'
2854
+ * ```
2855
+ *
2856
+ * @param opts.skipHooks - if true, will skip applying model hooks. Defaults to false
2857
+ * @returns void
2858
+ */
2859
+ async save({ skipHooks } = {}) {
2860
+ await saveDream(this, null, { skipHooks });
2861
+ }
2862
+ /**
2863
+ * Applies transaction to a new Query instance
2864
+ *
2865
+ * ```ts
2866
+ * await ApplicationModel.transaction(async txn => {
2867
+ * const user = await User.txn(txn).create({ email: 'how@yadoin' })
2868
+ * await Pet.txn(txn).create({ user })
2869
+ * })
2870
+ * ```
2871
+ *
2872
+ * @param txn - A DreamTransaction instance (collected by calling `ApplicationModel.transaction`)
2873
+ * @returns A Query scoped to this model with the transaction applied
2874
+ */
2875
+ txn(txn) {
2876
+ return new DreamInstanceTransactionBuilder(this, txn);
2877
+ }
2878
+ /**
2879
+ * Applies all attribute changes passed to the Dream
2880
+ * instance, leveraging any custom-defined setters,
2881
+ * and then saves the Dream instance. Can be called
2882
+ * on an unpersisted Dream instance.
2883
+ *
2884
+ * See {@link Dream.save | save} for details on
2885
+ * the side effects of saving.
2886
+ *
2887
+ * NOTE:
2888
+ * To bypass custom-defined setters, use {@link Dream.updateAttributes | updateAttributes} instead.
2889
+ *
2890
+ * ```ts
2891
+ * const user = await User.create({ email: 'saly@gmail.com' })
2892
+ * await user.update({ email: 'sally@gmail.com' })
2893
+ * ```
2894
+ *
2895
+ * @param attributes - the attributes to set on the model
2896
+ * @param opts.skipHooks - if true, will skip applying model hooks. Defaults to false
2897
+ * @returns void
2898
+ */
2899
+ async update(attributes, { skipHooks } = {}) {
2900
+ // use #assignAttributes to leverage any custom-defined setters
2901
+ this.assignAttributes(attributes);
2902
+ await this.save({ skipHooks });
2903
+ }
2904
+ /**
2905
+ * Applies all attribute changes passed to the dream,
2906
+ * bypassing any custom-defined setters,
2907
+ * and then saves the dream instance. Does not bypass
2908
+ * model hooks.
2909
+ *
2910
+ * See {@link Dream.save | save} for details on
2911
+ * the side effects of saving.
2912
+ *
2913
+ * NOTE:
2914
+ * To update the values without bypassing any custom-defined
2915
+ * setters, use {@link Dream.update | update} instead.
2916
+ *
2917
+ * ```ts
2918
+ * const user = await User.create({ email: 'saly@gmail.com' })
2919
+ * await user.updateAttributes({ email: 'sally@gmail.com' })
2920
+ * ```
2921
+ *
2922
+ * @param attributes - The attributes to update on this instance
2923
+ * @param opts.skipHooks - if true, will skip applying model hooks. Defaults to false
2924
+ * @returns - void
2925
+ */
2926
+ async updateAttributes(attributes, { skipHooks } = {}) {
2927
+ // use #setAttributes to bypass any custom-defined setters
2928
+ this.setAttributes(attributes);
2929
+ await this.save({ skipHooks });
2930
+ }
2931
+ /**
2932
+ * Flags a dream model so that it does not
2933
+ * actually destroy when in a destroy phase.
2934
+ * This is usually used for a soft-delete
2935
+ * pattern
2936
+ *
2937
+ * ```ts
2938
+ * class User extends ApplicationModel {
2939
+ * @Deco.BeforeDestroy()
2940
+ * public softDelete() {
2941
+ * await this.update({ deletedAt: DateTime.now() })
2942
+ * this.preventDeletion()
2943
+ * }
2944
+ * }
2945
+ * ```
2946
+ *
2947
+ * @returns void
2948
+ */
2949
+ preventDeletion() {
2950
+ this._preventDeletion = true;
2951
+ }
2952
+ /**
2953
+ * Flags a dream model so that it allows
2954
+ * deletion once again.
2955
+ *
2956
+ * Undoes {@link Dream.(preventDeletion:instance) | preventDeletion}
2957
+ *
2958
+ * ```ts
2959
+ * class User extends ApplicationModel {
2960
+ * @Deco.BeforeDestroy()
2961
+ * public async softDelete() {
2962
+ * await this.update({ deletedAt: DateTime.now() })
2963
+ * this.preventDeletion()
2964
+ * }
2965
+ *
2966
+ * @Deco.BeforeDestroy()
2967
+ * public async undoSoftDelete() {
2968
+ * await this.update({ deletedAt: null })
2969
+ * this.unpreventDeletion()
2970
+ * }
2971
+ * }
2972
+ * ```
2973
+ *
2974
+ * @returns void
2975
+ */
2976
+ unpreventDeletion() {
2977
+ this._preventDeletion = false;
2978
+ return this;
2979
+ }
2980
+ _preventDeletion = false;
2981
+ }