joist-codegen 2.3.0-next.42 → 2.3.0-next.44

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 (337) hide show
  1. package/build/EntityDbMetadata.cjs +608 -0
  2. package/build/EntityDbMetadata.cjs.map +1 -0
  3. package/build/EntityDbMetadata.d.cts +274 -0
  4. package/build/EntityDbMetadata.d.cts.map +1 -0
  5. package/build/EntityDbMetadata.d.mts +274 -0
  6. package/build/EntityDbMetadata.d.mts.map +1 -0
  7. package/build/EntityDbMetadata.js +485 -664
  8. package/build/EntityDbMetadata.js.map +1 -1
  9. package/build/_virtual/_rolldown/runtime.cjs +23 -0
  10. package/build/_virtual/_rolldown/runtime.js +5 -0
  11. package/build/assignTags.cjs +45 -0
  12. package/build/assignTags.cjs.map +1 -0
  13. package/build/{assignTags.d.ts → assignTags.d.cts} +8 -3
  14. package/build/assignTags.d.cts.map +1 -0
  15. package/build/assignTags.d.mts +16 -0
  16. package/build/assignTags.d.mts.map +1 -0
  17. package/build/assignTags.js +37 -59
  18. package/build/assignTags.js.map +1 -1
  19. package/build/codemods/Codemod.cjs +2 -0
  20. package/build/codemods/Codemod.d.cts +17 -0
  21. package/build/codemods/Codemod.d.cts.map +1 -0
  22. package/build/codemods/Codemod.d.mts +17 -0
  23. package/build/codemods/Codemod.d.mts.map +1 -0
  24. package/build/codemods/Codemod.js +2 -3
  25. package/build/codemods/JscodeshiftMod.cjs +42 -0
  26. package/build/codemods/JscodeshiftMod.cjs.map +1 -0
  27. package/build/codemods/JscodeshiftMod.d.cts +14 -0
  28. package/build/codemods/JscodeshiftMod.d.cts.map +1 -0
  29. package/build/codemods/JscodeshiftMod.d.mts +14 -0
  30. package/build/codemods/JscodeshiftMod.d.mts.map +1 -0
  31. package/build/codemods/JscodeshiftMod.js +33 -33
  32. package/build/codemods/JscodeshiftMod.js.map +1 -1
  33. package/build/codemods/codemod_0001-rename_has_async_property.cjs +30 -0
  34. package/build/codemods/codemod_0001-rename_has_async_property.cjs.map +1 -0
  35. package/build/codemods/codemod_0001-rename_has_async_property.d.cts +9 -0
  36. package/build/codemods/codemod_0001-rename_has_async_property.d.cts.map +1 -0
  37. package/build/codemods/codemod_0001-rename_has_async_property.d.mts +9 -0
  38. package/build/codemods/codemod_0001-rename_has_async_property.d.mts.map +1 -0
  39. package/build/codemods/codemod_0001-rename_has_async_property.js +21 -25
  40. package/build/codemods/codemod_0001-rename_has_async_property.js.map +1 -1
  41. package/build/codemods/codemod_0002-rename_async_query_fields.cjs +50 -0
  42. package/build/codemods/codemod_0002-rename_async_query_fields.cjs.map +1 -0
  43. package/build/codemods/codemod_0002-rename_async_query_fields.d.cts +9 -0
  44. package/build/codemods/codemod_0002-rename_async_query_fields.d.cts.map +1 -0
  45. package/build/codemods/codemod_0002-rename_async_query_fields.d.mts +9 -0
  46. package/build/codemods/codemod_0002-rename_async_query_fields.d.mts.map +1 -0
  47. package/build/codemods/codemod_0002-rename_async_query_fields.js +38 -46
  48. package/build/codemods/codemod_0002-rename_async_query_fields.js.map +1 -1
  49. package/build/codemods/codemod_0003-rename_find_paginated.cjs +25 -0
  50. package/build/codemods/codemod_0003-rename_find_paginated.cjs.map +1 -0
  51. package/build/codemods/codemod_0003-rename_find_paginated.d.cts +9 -0
  52. package/build/codemods/codemod_0003-rename_find_paginated.d.cts.map +1 -0
  53. package/build/codemods/codemod_0003-rename_find_paginated.d.mts +9 -0
  54. package/build/codemods/codemod_0003-rename_find_paginated.d.mts.map +1 -0
  55. package/build/codemods/codemod_0003-rename_find_paginated.js +17 -26
  56. package/build/codemods/codemod_0003-rename_find_paginated.js.map +1 -1
  57. package/build/codemods/index.cjs +49 -0
  58. package/build/codemods/index.cjs.map +1 -0
  59. package/build/codemods/index.d.cts +12 -0
  60. package/build/codemods/index.d.cts.map +1 -0
  61. package/build/codemods/index.d.mts +12 -0
  62. package/build/codemods/index.d.mts.map +1 -0
  63. package/build/codemods/index.js +34 -42
  64. package/build/codemods/index.js.map +1 -1
  65. package/build/config.cjs +377 -0
  66. package/build/config.cjs.map +1 -0
  67. package/build/config.d.cts +181 -0
  68. package/build/config.d.cts.map +1 -0
  69. package/build/config.d.mts +181 -0
  70. package/build/config.d.mts.map +1 -0
  71. package/build/config.js +300 -382
  72. package/build/config.js.map +1 -1
  73. package/build/docs/cache.cjs +62 -0
  74. package/build/docs/cache.cjs.map +1 -0
  75. package/build/docs/cache.d.cts +17 -0
  76. package/build/docs/cache.d.cts.map +1 -0
  77. package/build/docs/cache.d.mts +17 -0
  78. package/build/docs/cache.d.mts.map +1 -0
  79. package/build/docs/cache.js +52 -53
  80. package/build/docs/cache.js.map +1 -1
  81. package/build/docs/generate-metadata-docs.cjs +32 -0
  82. package/build/docs/generate-metadata-docs.cjs.map +1 -0
  83. package/build/docs/generate-metadata-docs.d.cts +9 -0
  84. package/build/docs/generate-metadata-docs.d.cts.map +1 -0
  85. package/build/docs/generate-metadata-docs.d.mts +9 -0
  86. package/build/docs/generate-metadata-docs.d.mts.map +1 -0
  87. package/build/docs/generate-metadata-docs.js +18 -20
  88. package/build/docs/generate-metadata-docs.js.map +1 -1
  89. package/build/docs/index.cjs +90 -0
  90. package/build/docs/index.cjs.map +1 -0
  91. package/build/docs/index.d.cts +16 -0
  92. package/build/docs/index.d.cts.map +1 -0
  93. package/build/docs/index.d.mts +16 -0
  94. package/build/docs/index.d.mts.map +1 -0
  95. package/build/docs/index.js +72 -91
  96. package/build/docs/index.js.map +1 -1
  97. package/build/docs/markdown.cjs +181 -0
  98. package/build/docs/markdown.cjs.map +1 -0
  99. package/build/docs/{markdown.d.ts → markdown.d.cts} +14 -11
  100. package/build/docs/markdown.d.cts.map +1 -0
  101. package/build/docs/markdown.d.mts +32 -0
  102. package/build/docs/markdown.d.mts.map +1 -0
  103. package/build/docs/markdown.js +152 -220
  104. package/build/docs/markdown.js.map +1 -1
  105. package/build/docs/parsing.cjs +117 -0
  106. package/build/docs/parsing.cjs.map +1 -0
  107. package/build/docs/parsing.d.cts +48 -0
  108. package/build/docs/parsing.d.cts.map +1 -0
  109. package/build/docs/parsing.d.mts +48 -0
  110. package/build/docs/parsing.d.mts.map +1 -0
  111. package/build/docs/parsing.js +86 -91
  112. package/build/docs/parsing.js.map +1 -1
  113. package/build/findEntityScopes.cjs +119 -0
  114. package/build/findEntityScopes.cjs.map +1 -0
  115. package/build/findEntityScopes.d.cts +14 -0
  116. package/build/findEntityScopes.d.cts.map +1 -0
  117. package/build/findEntityScopes.d.mts +14 -0
  118. package/build/findEntityScopes.d.mts.map +1 -0
  119. package/build/findEntityScopes.js +79 -121
  120. package/build/findEntityScopes.js.map +1 -1
  121. package/build/foreignKeyOrdering.cjs +52 -0
  122. package/build/foreignKeyOrdering.cjs.map +1 -0
  123. package/build/foreignKeyOrdering.d.cts +8 -0
  124. package/build/foreignKeyOrdering.d.cts.map +1 -0
  125. package/build/foreignKeyOrdering.d.mts +8 -0
  126. package/build/foreignKeyOrdering.d.mts.map +1 -0
  127. package/build/foreignKeyOrdering.js +46 -55
  128. package/build/foreignKeyOrdering.js.map +1 -1
  129. package/build/generate.cjs +127 -0
  130. package/build/generate.cjs.map +1 -0
  131. package/build/generate.d.cts +17 -0
  132. package/build/generate.d.cts.map +1 -0
  133. package/build/generate.d.mts +17 -0
  134. package/build/generate.d.mts.map +1 -0
  135. package/build/generate.js +109 -129
  136. package/build/generate.js.map +1 -1
  137. package/build/generateEntitiesFile.cjs +46 -0
  138. package/build/generateEntitiesFile.cjs.map +1 -0
  139. package/build/generateEntitiesFile.d.cts +11 -0
  140. package/build/generateEntitiesFile.d.cts.map +1 -0
  141. package/build/generateEntitiesFile.d.mts +11 -0
  142. package/build/generateEntitiesFile.d.mts.map +1 -0
  143. package/build/generateEntitiesFile.js +28 -25
  144. package/build/generateEntitiesFile.js.map +1 -1
  145. package/build/generateEntityCodegenFile.cjs +936 -0
  146. package/build/generateEntityCodegenFile.cjs.map +1 -0
  147. package/build/generateEntityCodegenFile.d.cts +16 -0
  148. package/build/generateEntityCodegenFile.d.cts.map +1 -0
  149. package/build/generateEntityCodegenFile.d.mts +16 -0
  150. package/build/generateEntityCodegenFile.d.mts.map +1 -0
  151. package/build/generateEntityCodegenFile.js +707 -852
  152. package/build/generateEntityCodegenFile.js.map +1 -1
  153. package/build/generateEntityFile.cjs +23 -0
  154. package/build/generateEntityFile.cjs.map +1 -0
  155. package/build/generateEntityFile.d.cts +9 -0
  156. package/build/generateEntityFile.d.cts.map +1 -0
  157. package/build/generateEntityFile.d.mts +9 -0
  158. package/build/generateEntityFile.d.mts.map +1 -0
  159. package/build/generateEntityFile.js +11 -8
  160. package/build/generateEntityFile.js.map +1 -1
  161. package/build/generateEntityTestFile.cjs +25 -0
  162. package/build/generateEntityTestFile.cjs.map +1 -0
  163. package/build/generateEntityTestFile.d.cts +9 -0
  164. package/build/generateEntityTestFile.d.cts.map +1 -0
  165. package/build/generateEntityTestFile.d.mts +9 -0
  166. package/build/generateEntityTestFile.d.mts.map +1 -0
  167. package/build/generateEntityTestFile.js +10 -7
  168. package/build/generateEntityTestFile.js.map +1 -1
  169. package/build/generateEnumFile.cjs +73 -0
  170. package/build/generateEnumFile.cjs.map +1 -0
  171. package/build/generateEnumFile.d.cts +9 -0
  172. package/build/generateEnumFile.d.cts.map +1 -0
  173. package/build/generateEnumFile.d.mts +9 -0
  174. package/build/generateEnumFile.d.mts.map +1 -0
  175. package/build/generateEnumFile.js +33 -43
  176. package/build/generateEnumFile.js.map +1 -1
  177. package/build/generateFactoriesFiles.cjs +28 -0
  178. package/build/generateFactoriesFiles.cjs.map +1 -0
  179. package/build/generateFactoriesFiles.d.cts +7 -0
  180. package/build/generateFactoriesFiles.d.cts.map +1 -0
  181. package/build/generateFactoriesFiles.d.mts +7 -0
  182. package/build/generateFactoriesFiles.d.mts.map +1 -0
  183. package/build/generateFactoriesFiles.js +21 -16
  184. package/build/generateFactoriesFiles.js.map +1 -1
  185. package/build/generateFlushFunction.cjs +61 -0
  186. package/build/generateFlushFunction.cjs.map +1 -0
  187. package/build/{generateFlushFunction.d.ts → generateFlushFunction.d.cts} +8 -4
  188. package/build/generateFlushFunction.d.cts.map +1 -0
  189. package/build/generateFlushFunction.d.mts +23 -0
  190. package/build/generateFlushFunction.d.mts.map +1 -0
  191. package/build/generateFlushFunction.js +32 -73
  192. package/build/generateFlushFunction.js.map +1 -1
  193. package/build/generateMetadataFile.cjs +290 -0
  194. package/build/generateMetadataFile.cjs.map +1 -0
  195. package/build/generateMetadataFile.d.cts +8 -0
  196. package/build/generateMetadataFile.d.cts.map +1 -0
  197. package/build/generateMetadataFile.d.mts +8 -0
  198. package/build/generateMetadataFile.d.mts.map +1 -0
  199. package/build/generateMetadataFile.js +111 -142
  200. package/build/generateMetadataFile.js.map +1 -1
  201. package/build/generatePgEnumFile.cjs +21 -0
  202. package/build/generatePgEnumFile.cjs.map +1 -0
  203. package/build/generatePgEnumFile.d.cts +9 -0
  204. package/build/generatePgEnumFile.d.cts.map +1 -0
  205. package/build/generatePgEnumFile.d.mts +9 -0
  206. package/build/generatePgEnumFile.d.mts.map +1 -0
  207. package/build/generatePgEnumFile.js +12 -9
  208. package/build/generatePgEnumFile.js.map +1 -1
  209. package/build/index.cjs +135 -0
  210. package/build/index.cjs.map +1 -0
  211. package/build/index.d.cts +12 -0
  212. package/build/index.d.cts.map +1 -0
  213. package/build/index.d.mts +12 -0
  214. package/build/index.d.mts.map +1 -0
  215. package/build/index.js +105 -147
  216. package/build/index.js.map +1 -1
  217. package/build/inheritance.cjs +213 -0
  218. package/build/inheritance.cjs.map +1 -0
  219. package/build/inheritance.d.cts +12 -0
  220. package/build/inheritance.d.cts.map +1 -0
  221. package/build/inheritance.d.mts +12 -0
  222. package/build/inheritance.d.mts.map +1 -0
  223. package/build/inheritance.js +193 -247
  224. package/build/inheritance.js.map +1 -1
  225. package/build/installSkills.cjs +68 -0
  226. package/build/installSkills.cjs.map +1 -0
  227. package/build/{installSkills.d.ts → installSkills.d.cts} +5 -1
  228. package/build/installSkills.d.cts.map +1 -0
  229. package/build/installSkills.d.mts +16 -0
  230. package/build/installSkills.d.mts.map +1 -0
  231. package/build/installSkills.js +55 -57
  232. package/build/installSkills.js.map +1 -1
  233. package/build/keywords.cjs +7 -0
  234. package/build/keywords.cjs.map +1 -0
  235. package/build/keywords.d.cts +5 -0
  236. package/build/keywords.d.cts.map +1 -0
  237. package/build/keywords.d.mts +5 -0
  238. package/build/keywords.d.mts.map +1 -0
  239. package/build/keywords.js +5 -4
  240. package/build/keywords.js.map +1 -1
  241. package/build/loadMetadata.cjs +39 -0
  242. package/build/loadMetadata.cjs.map +1 -0
  243. package/build/loadMetadata.d.cts +31 -0
  244. package/build/loadMetadata.d.cts.map +1 -0
  245. package/build/loadMetadata.d.mts +31 -0
  246. package/build/loadMetadata.d.mts.map +1 -0
  247. package/build/loadMetadata.js +32 -39
  248. package/build/loadMetadata.js.map +1 -1
  249. package/build/logger.cjs +28 -0
  250. package/build/logger.cjs.map +1 -0
  251. package/build/logger.d.cts +13 -0
  252. package/build/logger.d.cts.map +1 -0
  253. package/build/logger.d.mts +13 -0
  254. package/build/logger.d.mts.map +1 -0
  255. package/build/logger.js +17 -16
  256. package/build/logger.js.map +1 -1
  257. package/build/scanEntityFiles.cjs +46 -0
  258. package/build/scanEntityFiles.cjs.map +1 -0
  259. package/build/scanEntityFiles.d.cts +8 -0
  260. package/build/scanEntityFiles.d.cts.map +1 -0
  261. package/build/scanEntityFiles.d.mts +8 -0
  262. package/build/scanEntityFiles.d.mts.map +1 -0
  263. package/build/scanEntityFiles.js +37 -42
  264. package/build/scanEntityFiles.js.map +1 -1
  265. package/build/sortForeignKeys.cjs +99 -0
  266. package/build/sortForeignKeys.cjs.map +1 -0
  267. package/build/{sortForeignKeys.d.ts → sortForeignKeys.d.cts} +8 -4
  268. package/build/sortForeignKeys.d.cts.map +1 -0
  269. package/build/sortForeignKeys.d.mts +35 -0
  270. package/build/sortForeignKeys.d.mts.map +1 -0
  271. package/build/sortForeignKeys.js +88 -117
  272. package/build/sortForeignKeys.js.map +1 -1
  273. package/build/symbols.cjs +226 -0
  274. package/build/symbols.cjs.map +1 -0
  275. package/build/symbols.d.cts +114 -0
  276. package/build/symbols.d.cts.map +1 -0
  277. package/build/symbols.d.mts +114 -0
  278. package/build/symbols.d.mts.map +1 -0
  279. package/build/symbols.js +115 -116
  280. package/build/symbols.js.map +1 -1
  281. package/build/tsdoc.cjs +22 -0
  282. package/build/tsdoc.cjs.map +1 -0
  283. package/build/tsdoc.d.cts +15 -0
  284. package/build/tsdoc.d.cts.map +1 -0
  285. package/build/tsdoc.d.mts +15 -0
  286. package/build/tsdoc.d.mts.map +1 -0
  287. package/build/tsdoc.js +18 -15
  288. package/build/tsdoc.js.map +1 -1
  289. package/build/utils.cjs +173 -0
  290. package/build/utils.cjs.map +1 -0
  291. package/build/utils.d.cts +34 -0
  292. package/build/utils.d.cts.map +1 -0
  293. package/build/utils.d.mts +34 -0
  294. package/build/utils.d.mts.map +1 -0
  295. package/build/utils.js +112 -166
  296. package/build/utils.js.map +1 -1
  297. package/build/write-json-schema.cjs +23 -0
  298. package/build/write-json-schema.cjs.map +1 -0
  299. package/build/write-json-schema.d.cts +1 -0
  300. package/build/write-json-schema.d.mts +1 -0
  301. package/build/write-json-schema.js +19 -13
  302. package/build/write-json-schema.js.map +1 -1
  303. package/package.json +28 -5
  304. package/build/EntityDbMetadata.d.ts +0 -271
  305. package/build/codemods/Codemod.d.ts +0 -13
  306. package/build/codemods/Codemod.js.map +0 -1
  307. package/build/codemods/JscodeshiftMod.d.ts +0 -10
  308. package/build/codemods/codemod_0001-rename_has_async_property.d.ts +0 -6
  309. package/build/codemods/codemod_0002-rename_async_query_fields.d.ts +0 -6
  310. package/build/codemods/codemod_0003-rename_find_paginated.d.ts +0 -6
  311. package/build/codemods/index.d.ts +0 -8
  312. package/build/config.d.ts +0 -178
  313. package/build/docs/cache.d.ts +0 -13
  314. package/build/docs/generate-metadata-docs.d.ts +0 -5
  315. package/build/docs/index.d.ts +0 -13
  316. package/build/docs/parsing.d.ts +0 -45
  317. package/build/findEntityScopes.d.ts +0 -10
  318. package/build/foreignKeyOrdering.d.ts +0 -2
  319. package/build/generate.d.ts +0 -11
  320. package/build/generateEntitiesFile.d.ts +0 -6
  321. package/build/generateEntityCodegenFile.d.ts +0 -11
  322. package/build/generateEntityFile.d.ts +0 -5
  323. package/build/generateEntityTestFile.d.ts +0 -5
  324. package/build/generateEnumFile.d.ts +0 -4
  325. package/build/generateFactoriesFiles.d.ts +0 -3
  326. package/build/generateMetadataFile.d.ts +0 -4
  327. package/build/generatePgEnumFile.d.ts +0 -4
  328. package/build/index.d.ts +0 -11
  329. package/build/inheritance.d.ts +0 -9
  330. package/build/keywords.d.ts +0 -1
  331. package/build/loadMetadata.d.ts +0 -25
  332. package/build/logger.d.ts +0 -9
  333. package/build/scanEntityFiles.d.ts +0 -4
  334. package/build/symbols.d.ts +0 -110
  335. package/build/tsdoc.d.ts +0 -11
  336. package/build/utils.d.ts +0 -30
  337. package/build/write-json-schema.d.ts +0 -1
@@ -1,776 +1,597 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EntityDbMetadata = void 0;
4
- exports.oneToOneName = oneToOneName;
5
- exports.referenceName = referenceName;
6
- exports.manyToManyName = manyToManyName;
7
- exports.collectionName = collectionName;
8
- exports.failIfOverlappingFieldNames = failIfOverlappingFieldNames;
9
- exports.makeEntity = makeEntity;
10
- exports.canonicalizeOtherEntities = canonicalizeOtherEntities;
11
- exports.resolveNameConflicts = resolveNameConflicts;
12
- const change_case_1 = require("change-case");
13
- const joist_utils_1 = require("joist-utils");
14
- const pg_structure_1 = require("pg-structure");
15
- const pluralize_1 = require("pluralize");
16
- const ts_poet_1 = require("ts-poet");
17
- const config_1 = require("./config");
18
- const symbols_1 = require("./symbols");
19
- const utils_1 = require("./utils");
1
+ import { fail, isEnumTable, isJoinTable, isSubClassTable, joinTableHasId, mapSimpleDbTypeToTypescriptType, parseOrder, tableToEntityName } from "./utils.js";
2
+ import { fieldTypeConfig, getTimestampConfig, isFieldHasDefault, isFieldIgnored, isGetterField, isLargeCollection, isLazyField, isProtected, isReactiveField, isReactiveManyToMany, isReactiveReference, ormMaintainedFields, serdeConfig, softDeletesConfig, superstructConfig, zodSchemaConfig } from "./config.js";
3
+ import { Zod } from "./symbols.js";
4
+ import "./loadMetadata.js";
5
+ import { camelCase, pascalCase, snakeCase } from "change-case";
6
+ import { groupBy } from "joist-utils";
7
+ import { EnumType, M2ORelation } from "pg-structure";
8
+ import pluralize from "pluralize";
9
+ import { Import, code, imp } from "ts-poet";
10
+ //#region src/EntityDbMetadata.ts
11
+ const { plural, singular } = pluralize;
20
12
  /** Adapts the generally-great pg-structure metadata into our specific ORM types. */
21
- class EntityDbMetadata {
22
- entity;
23
- primaryKey;
24
- primitives;
25
- enums;
26
- pgEnums;
27
- manyToOnes;
28
- oneToManys;
29
- largeOneToManys;
30
- oneToOnes;
31
- manyToManys;
32
- largeManyToManys;
33
- manyToManyEnums;
34
- polymorphics;
35
- tableName;
36
- tagName;
37
- createdAt;
38
- updatedAt;
39
- deletedAt;
40
- baseClassName;
41
- baseType;
42
- subTypes = [];
43
- inheritanceType;
44
- /** This will only be set on the base meta. */
45
- stiDiscriminatorField;
46
- /** This will only be set on the sub metas. */
47
- stiDiscriminatorValue;
48
- abstract;
49
- nonDeferredFkOrder = -1;
50
- uniqueConstraints;
51
- constructor(config, table, enums = {}) {
52
- this.entity = makeEntity((0, utils_1.tableToEntityName)(config, table));
53
- if ((0, utils_1.isSubClassTable)(table)) {
54
- this.baseClassName = (0, utils_1.tableToEntityName)(config, table.columns.get("id").foreignKeys[0].referencedTable);
55
- this.inheritanceType = "cti";
56
- }
57
- this.primaryKey =
58
- table.columns
59
- .filter((c) => c.isPrimaryKey)
60
- .map((column) => newPrimitive(config, this.entity, column, table))[0] ||
61
- (0, utils_1.fail)(`No primary key found for ${table.name}`);
62
- this.primitives = table.columns
63
- .filter((c) => !c.isPrimaryKey && !c.isForeignKey)
64
- .filter((c) => !isEnumArray(c) && !isPgEnum(c))
65
- .map((column) => newPrimitive(config, this.entity, column, table))
66
- .filter((f) => !f.ignore);
67
- this.enums = [
68
- ...table.m2oRelations
69
- .filter((r) => (0, utils_1.isEnumTable)(config, r.targetTable))
70
- .map((r) => newEnumField(config, this.entity, r, enums))
71
- .filter((f) => !f.ignore),
72
- ...table.columns
73
- .filter((c) => isEnumArray(c))
74
- .map((column) => newEnumArrayField(config, this.entity, column, enums))
75
- .filter((f) => !f.ignore),
76
- ];
77
- this.pgEnums = [
78
- ...table.columns
79
- .filter((c) => isPgEnum(c))
80
- .map((column) => newPgEnumField(config, this.entity, column))
81
- .filter((f) => !f.ignore),
82
- ];
83
- this.manyToOnes = table.m2oRelations
84
- .filter((r) => !(0, utils_1.isEnumTable)(config, r.targetTable))
85
- .filter((r) => !isMultiColumnForeignKey(r))
86
- .filter((r) => !isComponentOfPolymorphicRelation(config, r))
87
- .filter((r) => !isBaseClassForeignKey(r))
88
- .map((r) => newManyToOneField(config, this.entity, r))
89
- .filter((f) => !f.ignore);
90
- // We split these into regular/large...
91
- const allOneToManys = table.o2mRelations
92
- // ManyToMany join tables also show up as OneToMany tables in pg-structure
93
- .filter((r) => !(0, utils_1.isJoinTable)(config, r.targetTable))
94
- .filter((r) => !isMultiColumnForeignKey(r))
95
- .filter((r) => !isOneToOneRelation(r))
96
- .map((r) => newOneToMany(config, this.entity, r))
97
- // Do not generate o2m for ReactiveReferences
98
- .filter((f) => !(0, config_1.isReactiveReference)(config, f.otherEntity, f.otherFieldName))
99
- .filter((f) => !f.ignore);
100
- this.oneToManys = allOneToManys.filter((f) => !f.isLargeCollection);
101
- this.largeOneToManys = allOneToManys.filter((f) => f.isLargeCollection);
102
- this.oneToOnes = table.o2mRelations
103
- // ManyToMany join tables also show up as OneToMany tables in pg-structure
104
- .filter((r) => !(0, utils_1.isJoinTable)(config, r.targetTable))
105
- .filter((r) => !isMultiColumnForeignKey(r))
106
- .filter((r) => !isBaseClassForeignKey(r))
107
- .filter((r) => isOneToOneRelation(r))
108
- .map((r) => newOneToOne(config, this.entity, r))
109
- .filter((f) => !f.ignore);
110
- // We split these into regular/large
111
- const allManyToManys = table.m2mRelations
112
- // pg-structure is really loose on what it considers a m2m relationship, i.e. any entity
113
- // that has a foreign key to us, and a foreign key to something else, is automatically
114
- // considered as a join table/m2m between "us" and "something else". Filter these out
115
- // by looking for only true join tables, i.e. tables with only id, fk1, and fk2.
116
- .filter((r) => (0, utils_1.isJoinTable)(config, r.joinTable))
117
- .filter((r) => !isMultiColumnForeignKey(r))
118
- // Join tables whose "other" side is an enum table become EnumCollections instead.
119
- .filter((r) => !(0, utils_1.isEnumTable)(config, r.targetTable))
120
- .map((r) => newManyToManyField(config, this.entity, r))
121
- .filter((f) => !f.ignore);
122
- this.manyToManys = allManyToManys.filter((f) => !f.isLargeCollection);
123
- this.largeManyToManys = allManyToManys.filter((f) => f.isLargeCollection);
124
- // A join table between us and an enum table, i.e. `Publisher.logoColors`.
125
- this.manyToManyEnums = table.m2mRelations
126
- .filter((r) => (0, utils_1.isJoinTable)(config, r.joinTable))
127
- .filter((r) => !isMultiColumnForeignKey(r))
128
- .filter((r) => (0, utils_1.isEnumTable)(config, r.targetTable))
129
- .map((r) => newManyToManyEnumField(config, this.entity, r, enums))
130
- .filter((f) => !f.ignore);
131
- this.polymorphics = polymorphicRelations(config, table).map((rc) => newPolymorphicField(config, table, this.entity, rc));
132
- this.tableName = table.name;
133
- this.tagName = config.entities[this.entity.name]?.tag;
134
- this.abstract = config.entities[this.entity.name]?.abstract || false;
135
- const { createdAtConf, updatedAtConf, deletedAtConf } = (0, config_1.getTimestampConfig)(config);
136
- this.createdAt = this.primitives.find((f) => createdAtConf.names.includes(f.columnName));
137
- this.updatedAt = this.primitives.find((f) => updatedAtConf.names.includes(f.columnName));
138
- this.deletedAt = this.primitives.find((f) => deletedAtConf.names.includes(f.columnName));
139
- this.uniqueConstraints = inferUniqueConstraints(this, table);
140
- }
141
- get name() {
142
- return this.entity.name;
143
- }
144
- get nonDeferredFks() {
145
- return [
146
- ...this.manyToOnes.filter((r) => !r.isDeferredAndDeferrable),
147
- ...this.polymorphics.flatMap((p) => p.components).filter((c) => !c.isDeferredAndDeferrable),
148
- ];
149
- }
150
- get nonDeferredManyToManyFks() {
151
- return this.manyToManys.filter((r) => !r.isDeferredAndDeferrable);
152
- }
153
- }
154
- exports.EntityDbMetadata = EntityDbMetadata;
13
+ var EntityDbMetadata = class {
14
+ entity;
15
+ primaryKey;
16
+ primitives;
17
+ enums;
18
+ pgEnums;
19
+ manyToOnes;
20
+ oneToManys;
21
+ largeOneToManys;
22
+ oneToOnes;
23
+ manyToManys;
24
+ largeManyToManys;
25
+ manyToManyEnums;
26
+ polymorphics;
27
+ tableName;
28
+ tagName;
29
+ createdAt;
30
+ updatedAt;
31
+ deletedAt;
32
+ baseClassName;
33
+ baseType;
34
+ subTypes = [];
35
+ inheritanceType;
36
+ /** This will only be set on the base meta. */
37
+ stiDiscriminatorField;
38
+ /** This will only be set on the sub metas. */
39
+ stiDiscriminatorValue;
40
+ abstract;
41
+ nonDeferredFkOrder = -1;
42
+ uniqueConstraints;
43
+ constructor(config, table, enums = {}) {
44
+ this.entity = makeEntity(tableToEntityName(config, table));
45
+ if (isSubClassTable(table)) {
46
+ this.baseClassName = tableToEntityName(config, table.columns.get("id").foreignKeys[0].referencedTable);
47
+ this.inheritanceType = "cti";
48
+ }
49
+ this.primaryKey = table.columns.filter((c) => c.isPrimaryKey).map((column) => newPrimitive(config, this.entity, column, table))[0] || fail(`No primary key found for ${table.name}`);
50
+ this.primitives = table.columns.filter((c) => !c.isPrimaryKey && !c.isForeignKey).filter((c) => !isEnumArray(c) && !isPgEnum(c)).map((column) => newPrimitive(config, this.entity, column, table)).filter((f) => !f.ignore);
51
+ this.enums = [...table.m2oRelations.filter((r) => isEnumTable(config, r.targetTable)).map((r) => newEnumField(config, this.entity, r, enums)).filter((f) => !f.ignore), ...table.columns.filter((c) => isEnumArray(c)).map((column) => newEnumArrayField(config, this.entity, column, enums)).filter((f) => !f.ignore)];
52
+ this.pgEnums = table.columns.filter((c) => isPgEnum(c)).map((column) => newPgEnumField(config, this.entity, column)).filter((f) => !f.ignore);
53
+ this.manyToOnes = table.m2oRelations.filter((r) => !isEnumTable(config, r.targetTable)).filter((r) => !isMultiColumnForeignKey(r)).filter((r) => !isComponentOfPolymorphicRelation(config, r)).filter((r) => !isBaseClassForeignKey(r)).map((r) => newManyToOneField(config, this.entity, r)).filter((f) => !f.ignore);
54
+ const allOneToManys = table.o2mRelations.filter((r) => !isJoinTable(config, r.targetTable)).filter((r) => !isMultiColumnForeignKey(r)).filter((r) => !isOneToOneRelation(r)).map((r) => newOneToMany(config, this.entity, r)).filter((f) => !isReactiveReference(config, f.otherEntity, f.otherFieldName)).filter((f) => !f.ignore);
55
+ this.oneToManys = allOneToManys.filter((f) => !f.isLargeCollection);
56
+ this.largeOneToManys = allOneToManys.filter((f) => f.isLargeCollection);
57
+ this.oneToOnes = table.o2mRelations.filter((r) => !isJoinTable(config, r.targetTable)).filter((r) => !isMultiColumnForeignKey(r)).filter((r) => !isBaseClassForeignKey(r)).filter((r) => isOneToOneRelation(r)).map((r) => newOneToOne(config, this.entity, r)).filter((f) => !f.ignore);
58
+ const allManyToManys = table.m2mRelations.filter((r) => isJoinTable(config, r.joinTable)).filter((r) => !isMultiColumnForeignKey(r)).filter((r) => !isEnumTable(config, r.targetTable)).map((r) => newManyToManyField(config, this.entity, r)).filter((f) => !f.ignore);
59
+ this.manyToManys = allManyToManys.filter((f) => !f.isLargeCollection);
60
+ this.largeManyToManys = allManyToManys.filter((f) => f.isLargeCollection);
61
+ this.manyToManyEnums = table.m2mRelations.filter((r) => isJoinTable(config, r.joinTable)).filter((r) => !isMultiColumnForeignKey(r)).filter((r) => isEnumTable(config, r.targetTable)).map((r) => newManyToManyEnumField(config, this.entity, r, enums)).filter((f) => !f.ignore);
62
+ this.polymorphics = polymorphicRelations(config, table).map((rc) => newPolymorphicField(config, table, this.entity, rc));
63
+ this.tableName = table.name;
64
+ this.tagName = config.entities[this.entity.name]?.tag;
65
+ this.abstract = config.entities[this.entity.name]?.abstract || false;
66
+ const { createdAtConf, updatedAtConf, deletedAtConf } = getTimestampConfig(config);
67
+ this.createdAt = this.primitives.find((f) => createdAtConf.names.includes(f.columnName));
68
+ this.updatedAt = this.primitives.find((f) => updatedAtConf.names.includes(f.columnName));
69
+ this.deletedAt = this.primitives.find((f) => deletedAtConf.names.includes(f.columnName));
70
+ this.uniqueConstraints = inferUniqueConstraints(this, table);
71
+ }
72
+ get name() {
73
+ return this.entity.name;
74
+ }
75
+ get nonDeferredFks() {
76
+ return [...this.manyToOnes.filter((r) => !r.isDeferredAndDeferrable), ...this.polymorphics.flatMap((p) => p.components).filter((c) => !c.isDeferredAndDeferrable)];
77
+ }
78
+ get nonDeferredManyToManyFks() {
79
+ return this.manyToManys.filter((r) => !r.isDeferredAndDeferrable);
80
+ }
81
+ };
155
82
  function isMultiColumnForeignKey(r) {
156
- return r.foreignKey.columns.length > 1;
83
+ return r.foreignKey.columns.length > 1;
157
84
  }
158
85
  function isBaseClassForeignKey(r) {
159
- return r.foreignKey.columns.length === 1 && r.foreignKey.columns[0].name === "id";
86
+ return r.foreignKey.columns.length === 1 && r.foreignKey.columns[0].name === "id";
160
87
  }
161
88
  function isOneToOneRelation(r) {
162
- // otherColumn will be the images.book_id in the other table
163
- const otherColumn = r.foreignKey.columns[0];
164
- // r.foreignKey.index is the index on _us_ (i.e. our Book primary key), so look up indexes in the target table
165
- const indexes = r.targetTable.columns.find((c) => c.name == otherColumn.name)?.uniqueIndexes || [];
166
- return indexes.find(isOneToOneIndex) !== undefined;
89
+ const otherColumn = r.foreignKey.columns[0];
90
+ return (r.targetTable.columns.find((c) => c.name == otherColumn.name)?.uniqueIndexes || []).find(isOneToOneIndex) !== void 0;
167
91
  }
168
- // If the unique index has only one column and is NOT a partial index, it's a one-to-one
169
92
  function isOneToOneIndex(i) {
170
- return i.columns.length === 1 && !i.isPartial;
93
+ return i.columns.length === 1 && !i.isPartial;
171
94
  }
172
95
  /** Infers field names from unique constraints, i.e. `(author_id, title)` becomes `author, title`. */
173
96
  function inferUniqueConstraints(meta, table) {
174
- return table.uniqueConstraints.flatMap((constraint) => {
175
- if (constraint.index.isPartial)
176
- return [];
177
- const fields = Array.from(constraint.columns).map((column) => fieldNameForColumn(meta, column.name));
178
- if (fields.some((field) => field === undefined))
179
- return [];
180
- return [fields];
181
- });
97
+ return table.uniqueConstraints.flatMap((constraint) => {
98
+ if (constraint.index.isPartial) return [];
99
+ const fields = Array.from(constraint.columns).map((column) => fieldNameForColumn(meta, column.name));
100
+ if (fields.some((field) => field === void 0)) return [];
101
+ return [fields];
102
+ });
182
103
  }
183
104
  /** Returns the queryable field name for a unique constraint column. */
184
105
  function fieldNameForColumn(meta, columnName) {
185
- const primitive = meta.primitives.find((field) => field.columnName === columnName);
186
- if (primitive && !primitive.derived && !primitive.isArray && !primitive.customSerde)
187
- return primitive.fieldName;
188
- const enumField = meta.enums.find((field) => field.columnName === columnName);
189
- if (enumField && !enumField.derived && !enumField.isArray)
190
- return enumField.fieldName;
191
- const pgEnum = meta.pgEnums.find((field) => field.columnName === columnName);
192
- if (pgEnum)
193
- return pgEnum.fieldName;
194
- const manyToOne = meta.manyToOnes.find((field) => field.columnName === columnName);
195
- if (manyToOne && !manyToOne.derived)
196
- return manyToOne.fieldName;
197
- return undefined;
106
+ const primitive = meta.primitives.find((field) => field.columnName === columnName);
107
+ if (primitive && !primitive.derived && !primitive.isArray && !primitive.customSerde) return primitive.fieldName;
108
+ const enumField = meta.enums.find((field) => field.columnName === columnName);
109
+ if (enumField && !enumField.derived && !enumField.isArray) return enumField.fieldName;
110
+ const pgEnum = meta.pgEnums.find((field) => field.columnName === columnName);
111
+ if (pgEnum) return pgEnum.fieldName;
112
+ const manyToOne = meta.manyToOnes.find((field) => field.columnName === columnName);
113
+ if (manyToOne && !manyToOne.derived) return manyToOne.fieldName;
198
114
  }
199
115
  function polymorphicRelations(config, table) {
200
- const entity = config.entities[(0, utils_1.tableToEntityName)(config, table)];
201
- return Object.entries(entity?.relations ?? {})
202
- .filter(([, r]) => r.polymorphic)
203
- .map(([fieldName, { polymorphic }]) => ({ fieldName, notNull: polymorphic === "notNull" }));
116
+ const entity = config.entities[tableToEntityName(config, table)];
117
+ return Object.entries(entity?.relations ?? {}).filter(([, r]) => r.polymorphic).map(([fieldName, { polymorphic }]) => ({
118
+ fieldName,
119
+ notNull: polymorphic === "notNull"
120
+ }));
204
121
  }
205
122
  function polymorphicFieldName(config, r) {
206
- const { name } = r.foreignKey.columns[0];
207
- const table = r.type === "m2o" ? r.sourceTable : r.targetTable;
208
- return polymorphicRelations(config, table).find((pr) => name.startsWith(`${(0, change_case_1.snakeCase)(pr.fieldName)}_`))?.fieldName;
123
+ const { name } = r.foreignKey.columns[0];
124
+ return polymorphicRelations(config, r.type === "m2o" ? r.sourceTable : r.targetTable).find((pr) => name.startsWith(`${snakeCase(pr.fieldName)}_`))?.fieldName;
209
125
  }
210
126
  function isComponentOfPolymorphicRelation(config, r) {
211
- return polymorphicFieldName(config, r) !== undefined;
127
+ return polymorphicFieldName(config, r) !== void 0;
212
128
  }
213
129
  function determineUserType(fieldType, superstruct, zodSchema, userFieldType) {
214
- if (fieldType === "Object" && superstruct) {
215
- return superstructType(superstruct);
216
- }
217
- if (fieldType === "Object" && zodSchema) {
218
- return zodSchemaType(zodSchema);
219
- }
220
- if (userFieldType) {
221
- return userFieldTypeType(userFieldType);
222
- }
223
- return fieldType;
130
+ if (fieldType === "Object" && superstruct) return superstructType(superstruct);
131
+ if (fieldType === "Object" && zodSchema) return zodSchemaType(zodSchema);
132
+ if (userFieldType) return userFieldTypeType(userFieldType);
133
+ return fieldType;
224
134
  }
225
135
  function newPrimitive(config, entity, column, table) {
226
- const fieldName = primitiveFieldName(column.name);
227
- const columnName = column.name;
228
- const columnType = (column.type.shortName || column.type.name);
229
- const array = isArray(column);
230
- const fieldType = mapType(config, table.name, columnName, columnType);
231
- const customSerde = (0, config_1.serdeConfig)(config, entity, fieldName);
232
- const superstruct = (0, config_1.superstructConfig)(config, entity, fieldName);
233
- const zodSchema = (0, config_1.zodSchemaConfig)(config, entity, fieldName);
234
- const userFieldType = (0, config_1.fieldTypeConfig)(config, entity, fieldName);
235
- const maybeUserType = determineUserType(fieldType, superstruct, zodSchema, userFieldType);
236
- const unique = column.uniqueIndexes.find(isOneToOneIndex) !== undefined;
237
- const hasConfigDefault = (0, config_1.isFieldHasDefault)(config, entity, fieldName);
238
- return {
239
- kind: "primitive",
240
- fieldName,
241
- columnName,
242
- columnType,
243
- fieldType: array ? (0, ts_poet_1.code) `${fieldType}[]` : maybeUserType,
244
- rawFieldType: fieldType,
245
- notNull: column.notNull,
246
- columnDefault: column.default,
247
- derived: fieldDerived(config, entity, fieldName),
248
- protected: (0, config_1.isProtected)(config, entity, fieldName),
249
- unique,
250
- ignore: (0, config_1.isFieldIgnored)(config, entity, fieldName, column.notNull, column.default !== null),
251
- superstruct: fieldType === "Object" && superstruct ? ts_poet_1.Import.from(superstruct) : undefined,
252
- zodSchema: fieldType === "Object" && zodSchema ? ts_poet_1.Import.from(zodSchema) : undefined,
253
- customSerde: customSerde ? serdeType(customSerde) : undefined,
254
- isArray: array,
255
- hasConfigDefault, // can be set to true by scanEntityFiles
256
- lazy: (0, config_1.isLazyField)(config, entity, fieldName),
257
- };
136
+ const fieldName = primitiveFieldName(column.name);
137
+ const columnName = column.name;
138
+ const columnType = column.type.shortName || column.type.name;
139
+ const array = isArray(column);
140
+ const fieldType = mapType(config, table.name, columnName, columnType);
141
+ const customSerde = serdeConfig(config, entity, fieldName);
142
+ const superstruct = superstructConfig(config, entity, fieldName);
143
+ const zodSchema = zodSchemaConfig(config, entity, fieldName);
144
+ const maybeUserType = determineUserType(fieldType, superstruct, zodSchema, fieldTypeConfig(config, entity, fieldName));
145
+ const unique = column.uniqueIndexes.find(isOneToOneIndex) !== void 0;
146
+ const hasConfigDefault = isFieldHasDefault(config, entity, fieldName);
147
+ return {
148
+ kind: "primitive",
149
+ fieldName,
150
+ columnName,
151
+ columnType,
152
+ fieldType: array ? code`${fieldType}[]` : maybeUserType,
153
+ rawFieldType: fieldType,
154
+ notNull: column.notNull,
155
+ columnDefault: column.default,
156
+ derived: fieldDerived(config, entity, fieldName),
157
+ protected: isProtected(config, entity, fieldName),
158
+ unique,
159
+ ignore: isFieldIgnored(config, entity, fieldName, column.notNull, column.default !== null),
160
+ superstruct: fieldType === "Object" && superstruct ? Import.from(superstruct) : void 0,
161
+ zodSchema: fieldType === "Object" && zodSchema ? Import.from(zodSchema) : void 0,
162
+ customSerde: customSerde ? serdeType(customSerde) : void 0,
163
+ isArray: array,
164
+ hasConfigDefault,
165
+ lazy: isLazyField(config, entity, fieldName)
166
+ };
258
167
  }
259
168
  function fieldDerived(config, entity, fieldName) {
260
- if (config_1.ormMaintainedFields.includes(fieldName)) {
261
- return "orm";
262
- }
263
- else if ((0, config_1.isGetterField)(config, entity, fieldName)) {
264
- return "sync";
265
- }
266
- else if ((0, config_1.isReactiveField)(config, entity, fieldName)) {
267
- return "async";
268
- }
269
- else {
270
- return false;
271
- }
169
+ if (ormMaintainedFields.includes(fieldName)) return "orm";
170
+ else if (isGetterField(config, entity, fieldName)) return "sync";
171
+ else if (isReactiveField(config, entity, fieldName)) return "async";
172
+ else return false;
272
173
  }
273
174
  function fkFieldDerived(config, entity, fieldName) {
274
- if ((0, config_1.isReactiveReference)(config, entity, fieldName)) {
275
- return "async";
276
- }
277
- else {
278
- return false;
279
- }
175
+ if (isReactiveReference(config, entity, fieldName)) return "async";
176
+ else return false;
280
177
  }
281
178
  function newEnumField(config, entity, r, enums) {
282
- const column = r.foreignKey.columns[0];
283
- const columnName = column.name;
284
- const columnType = (column.type.shortName || column.type.name);
285
- const fieldName = enumFieldName(column.name);
286
- const enumName = (0, utils_1.tableToEntityName)(config, r.targetTable);
287
- const enumType = (0, ts_poet_1.imp)(`${enumName}@./entities.ts`);
288
- const enumDetailType = (0, ts_poet_1.imp)(`${(0, pluralize_1.plural)(enumName)}@./entities.ts`);
289
- const enumDetailsType = (0, ts_poet_1.imp)(`${enumName}Details@./entities.ts`);
290
- const notNull = column.notNull;
291
- const ignore = (0, config_1.isFieldIgnored)(config, entity, fieldName, notNull, column.default !== null);
292
- const hasConfigDefault = (0, config_1.isFieldHasDefault)(config, entity, fieldName);
293
- return {
294
- kind: "enum",
295
- fieldName,
296
- columnName,
297
- columnType,
298
- columnDefault: column.default,
299
- derived: fieldDerived(config, entity, fieldName),
300
- enumName,
301
- enumType,
302
- enumDetailType,
303
- enumDetailsType,
304
- notNull,
305
- ignore,
306
- enumRows: enums[r.targetTable.name].rows,
307
- isArray: false,
308
- hasConfigDefault, // can be set to true by scanEntityFiles
309
- };
179
+ const column = r.foreignKey.columns[0];
180
+ const columnName = column.name;
181
+ const columnType = column.type.shortName || column.type.name;
182
+ const fieldName = enumFieldName(column.name);
183
+ const enumName = tableToEntityName(config, r.targetTable);
184
+ const enumType = imp(`${enumName}@./entities.ts`);
185
+ const enumDetailType = imp(`${plural(enumName)}@./entities.ts`);
186
+ const enumDetailsType = imp(`${enumName}Details@./entities.ts`);
187
+ const notNull = column.notNull;
188
+ const ignore = isFieldIgnored(config, entity, fieldName, notNull, column.default !== null);
189
+ const hasConfigDefault = isFieldHasDefault(config, entity, fieldName);
190
+ return {
191
+ kind: "enum",
192
+ fieldName,
193
+ columnName,
194
+ columnType,
195
+ columnDefault: column.default,
196
+ derived: fieldDerived(config, entity, fieldName),
197
+ enumName,
198
+ enumType,
199
+ enumDetailType,
200
+ enumDetailsType,
201
+ notNull,
202
+ ignore,
203
+ enumRows: enums[r.targetTable.name].rows,
204
+ isArray: false,
205
+ hasConfigDefault
206
+ };
310
207
  }
311
208
  function newEnumArrayField(config, entity, column, enums) {
312
- const columnName = column.name;
313
- const columnType = (column.type.shortName || column.type.name);
314
- const fieldName = enumFieldName(column.name);
315
- // Find the enum table name via the comment hint (instead of a FK constraint), and strip the enum= prefix
316
- const enumTable = column.comment.replace("enum=", "");
317
- const enumName = (enums[enumTable] || (0, utils_1.fail)(`Could not find enum ${enumTable}`)).name;
318
- const enumType = (0, ts_poet_1.imp)(`${enumName}@./entities.ts`);
319
- const enumDetailType = (0, ts_poet_1.imp)(`${(0, pluralize_1.plural)(enumName)}@./entities.ts`);
320
- const enumDetailsType = (0, ts_poet_1.imp)(`${enumName}Details@./entities.ts`);
321
- const notNull = column.notNull;
322
- const ignore = (0, config_1.isFieldIgnored)(config, entity, fieldName, notNull, column.default !== null);
323
- const hasConfigDefault = (0, config_1.isFieldHasDefault)(config, entity, fieldName);
324
- return {
325
- kind: "enum",
326
- fieldName,
327
- columnName,
328
- columnType,
329
- columnDefault: column.default,
330
- derived: fieldDerived(config, entity, fieldName),
331
- enumName,
332
- enumType,
333
- enumDetailType,
334
- enumDetailsType,
335
- notNull,
336
- ignore,
337
- enumRows: enums[enumTable].rows,
338
- isArray: true,
339
- hasConfigDefault, // can be set to true by scanEntityFiles
340
- };
209
+ const columnName = column.name;
210
+ const columnType = column.type.shortName || column.type.name;
211
+ const fieldName = enumFieldName(column.name);
212
+ const enumTable = column.comment.replace("enum=", "");
213
+ const enumName = (enums[enumTable] || fail(`Could not find enum ${enumTable}`)).name;
214
+ const enumType = imp(`${enumName}@./entities.ts`);
215
+ const enumDetailType = imp(`${plural(enumName)}@./entities.ts`);
216
+ const enumDetailsType = imp(`${enumName}Details@./entities.ts`);
217
+ const notNull = column.notNull;
218
+ const ignore = isFieldIgnored(config, entity, fieldName, notNull, column.default !== null);
219
+ const hasConfigDefault = isFieldHasDefault(config, entity, fieldName);
220
+ return {
221
+ kind: "enum",
222
+ fieldName,
223
+ columnName,
224
+ columnType,
225
+ columnDefault: column.default,
226
+ derived: fieldDerived(config, entity, fieldName),
227
+ enumName,
228
+ enumType,
229
+ enumDetailType,
230
+ enumDetailsType,
231
+ notNull,
232
+ ignore,
233
+ enumRows: enums[enumTable].rows,
234
+ isArray: true,
235
+ hasConfigDefault
236
+ };
341
237
  }
342
238
  function newPgEnumField(config, entity, column) {
343
- const fieldName = primitiveFieldName(column.name);
344
- const columnName = column.name;
345
- const enumName = (0, change_case_1.pascalCase)(column.type.name);
346
- const enumType = (0, ts_poet_1.imp)(`${enumName}@./entities.ts`);
347
- const hasConfigDefault = (0, config_1.isFieldHasDefault)(config, entity, fieldName);
348
- return {
349
- kind: "pg-enum",
350
- fieldName,
351
- columnName,
352
- dbType: column.type.name,
353
- enumType,
354
- enumName,
355
- enumValues: column.type.values,
356
- notNull: column.notNull,
357
- columnDefault: column.default,
358
- ignore: (0, config_1.isFieldIgnored)(config, entity, fieldName, column.notNull, column.default !== null),
359
- hasConfigDefault, // can be set to true by scanEntityFiles
360
- };
239
+ const fieldName = primitiveFieldName(column.name);
240
+ const columnName = column.name;
241
+ const enumName = pascalCase(column.type.name);
242
+ const enumType = imp(`${enumName}@./entities.ts`);
243
+ const hasConfigDefault = isFieldHasDefault(config, entity, fieldName);
244
+ return {
245
+ kind: "pg-enum",
246
+ fieldName,
247
+ columnName,
248
+ dbType: column.type.name,
249
+ enumType,
250
+ enumName,
251
+ enumValues: column.type.values,
252
+ notNull: column.notNull,
253
+ columnDefault: column.default,
254
+ ignore: isFieldIgnored(config, entity, fieldName, column.notNull, column.default !== null),
255
+ hasConfigDefault
256
+ };
361
257
  }
362
258
  function newManyToOneField(config, entity, r) {
363
- const column = r.foreignKey.columns[0];
364
- const columnName = column.name;
365
- const dbType = r.foreignKey.columns[0].type.shortName;
366
- const fieldName = referenceName(config, entity, r);
367
- const otherEntity = makeEntity((0, utils_1.tableToEntityName)(config, r.targetTable));
368
- const isOneToOne = column.uniqueIndexes.find(isOneToOneIndex) !== undefined;
369
- const otherFieldName = isOneToOne
370
- ? oneToOneName(config, otherEntity, entity, r)
371
- : collectionName(config, otherEntity, entity, r).fieldName;
372
- const notNull = column.notNull;
373
- const ignore = (0, config_1.isFieldIgnored)(config, entity, fieldName, notNull, column.default !== null);
374
- const isDeferredAndDeferrable = r.foreignKey.isDeferred && r.foreignKey.isDeferrable;
375
- const derived = fkFieldDerived(config, entity, fieldName);
376
- const hasConfigDefault = (0, config_1.isFieldHasDefault)(config, entity, fieldName);
377
- return {
378
- kind: "m2o",
379
- fieldName,
380
- columnName,
381
- otherEntity,
382
- otherFieldName,
383
- notNull,
384
- ignore,
385
- derived,
386
- dbType,
387
- isDeferredAndDeferrable,
388
- constraintName: r.foreignKey.name,
389
- hasConfigDefault, // can be set to true by scanEntityFiles
390
- onDelete: r.foreignKey.onDelete,
391
- };
259
+ const column = r.foreignKey.columns[0];
260
+ const columnName = column.name;
261
+ const dbType = r.foreignKey.columns[0].type.shortName;
262
+ const fieldName = referenceName(config, entity, r);
263
+ const otherEntity = makeEntity(tableToEntityName(config, r.targetTable));
264
+ const otherFieldName = column.uniqueIndexes.find(isOneToOneIndex) !== void 0 ? oneToOneName(config, otherEntity, entity, r) : collectionName(config, otherEntity, entity, r).fieldName;
265
+ const notNull = column.notNull;
266
+ const ignore = isFieldIgnored(config, entity, fieldName, notNull, column.default !== null);
267
+ const isDeferredAndDeferrable = r.foreignKey.isDeferred && r.foreignKey.isDeferrable;
268
+ const derived = fkFieldDerived(config, entity, fieldName);
269
+ const hasConfigDefault = isFieldHasDefault(config, entity, fieldName);
270
+ return {
271
+ kind: "m2o",
272
+ fieldName,
273
+ columnName,
274
+ otherEntity,
275
+ otherFieldName,
276
+ notNull,
277
+ ignore,
278
+ derived,
279
+ dbType,
280
+ isDeferredAndDeferrable,
281
+ constraintName: r.foreignKey.name,
282
+ hasConfigDefault,
283
+ onDelete: r.foreignKey.onDelete
284
+ };
392
285
  }
393
286
  function newOneToMany(config, entity, r) {
394
- const column = r.foreignKey.columns[0];
395
- // source == parent i.e. the reference of the foreign key column
396
- // target == child i.e. the table with the foreign key column in it
397
- const otherEntity = makeEntity((0, utils_1.tableToEntityName)(config, r.targetTable));
398
- const { singularName, fieldName } = collectionName(config, entity, otherEntity, r);
399
- const otherFieldName = referenceName(config, otherEntity, r);
400
- const orderBy = config.entities[entity.name]?.relations?.[fieldName]?.orderBy ?? config.entities[otherEntity.name]?.orderBy;
401
- return {
402
- kind: "o2m",
403
- fieldName,
404
- singularName,
405
- otherEntity,
406
- otherFieldName,
407
- otherColumnName: column.name,
408
- otherColumnNotNull: column.notNull,
409
- ignore: (0, config_1.isFieldIgnored)(config, entity, fieldName) || (0, config_1.isFieldIgnored)(config, otherEntity, otherFieldName),
410
- isLargeCollection: (0, config_1.isLargeCollection)(config, entity, fieldName),
411
- orderBy: (0, utils_1.parseOrder)(orderBy),
412
- softDeletes: (0, config_1.softDeletesConfig)(config, entity, fieldName),
413
- };
287
+ const column = r.foreignKey.columns[0];
288
+ const otherEntity = makeEntity(tableToEntityName(config, r.targetTable));
289
+ const { singularName, fieldName } = collectionName(config, entity, otherEntity, r);
290
+ const otherFieldName = referenceName(config, otherEntity, r);
291
+ const orderBy = config.entities[entity.name]?.relations?.[fieldName]?.orderBy ?? config.entities[otherEntity.name]?.orderBy;
292
+ return {
293
+ kind: "o2m",
294
+ fieldName,
295
+ singularName,
296
+ otherEntity,
297
+ otherFieldName,
298
+ otherColumnName: column.name,
299
+ otherColumnNotNull: column.notNull,
300
+ ignore: isFieldIgnored(config, entity, fieldName) || isFieldIgnored(config, otherEntity, otherFieldName),
301
+ isLargeCollection: isLargeCollection(config, entity, fieldName),
302
+ orderBy: parseOrder(orderBy),
303
+ softDeletes: softDeletesConfig(config, entity, fieldName)
304
+ };
414
305
  }
415
306
  function newOneToOne(config, entity, r) {
416
- const column = r.foreignKey.columns[0];
417
- // source == parent i.e. the reference of the foreign key column
418
- // target == child i.e. the table with the foreign key column in it
419
- const otherEntity = makeEntity((0, utils_1.tableToEntityName)(config, r.targetTable));
420
- const fieldName = oneToOneName(config, entity, otherEntity, r);
421
- const otherFieldName = referenceName(config, otherEntity, r);
422
- const otherColumnName = column.name;
423
- const otherColumnNotNull = column.notNull;
424
- const ignore = (0, config_1.isFieldIgnored)(config, entity, fieldName) || (0, config_1.isFieldIgnored)(config, otherEntity, otherFieldName);
425
- return { kind: "o2o", fieldName, otherEntity, otherFieldName, otherColumnName, otherColumnNotNull, ignore };
307
+ const column = r.foreignKey.columns[0];
308
+ const otherEntity = makeEntity(tableToEntityName(config, r.targetTable));
309
+ const fieldName = oneToOneName(config, entity, otherEntity, r);
310
+ const otherFieldName = referenceName(config, otherEntity, r);
311
+ return {
312
+ kind: "o2o",
313
+ fieldName,
314
+ otherEntity,
315
+ otherFieldName,
316
+ otherColumnName: column.name,
317
+ otherColumnNotNull: column.notNull,
318
+ ignore: isFieldIgnored(config, entity, fieldName) || isFieldIgnored(config, otherEntity, otherFieldName)
319
+ };
426
320
  }
427
321
  function newManyToManyField(config, entity, r) {
428
- const { foreignKey, targetForeignKey, targetTable } = r;
429
- const otherEntity = makeEntity((0, utils_1.tableToEntityName)(config, targetTable));
430
- // For foo_to_bar.some_foo_id use the `some_foo_id` column i.e. `someFoos`
431
- const fieldName = manyToManyName(targetForeignKey.columns[0]);
432
- const otherFieldName = manyToManyName(foreignKey.columns[0]);
433
- const isDeferredAndDeferrable = targetForeignKey.isDeferred && targetForeignKey.isDeferrable;
434
- // Determine if this m2m is derived:
435
- // - "async" if this side is explicitly marked as a ReactiveManyToMany
436
- // - "otherSide" if the OTHER side is marked as a ReactiveManyToMany (making this the read-only other side)
437
- // - false otherwise (regular m2m)
438
- const isThisSideDerived = (0, config_1.isReactiveManyToMany)(config, entity, fieldName);
439
- const isOtherSideDerived = (0, config_1.isReactiveManyToMany)(config, otherEntity, otherFieldName);
440
- const derived = isThisSideDerived ? "async" : isOtherSideDerived ? "otherSide" : false;
441
- return {
442
- kind: "m2m",
443
- joinTableName: r.joinTable.name,
444
- fieldName,
445
- singularName: (0, pluralize_1.singular)(fieldName),
446
- columnName: foreignKey.columns[0].name,
447
- otherEntity,
448
- otherFieldName,
449
- otherColumnName: targetForeignKey.columns[0].name,
450
- ignore: (0, config_1.isFieldIgnored)(config, entity, fieldName) || (0, config_1.isFieldIgnored)(config, otherEntity, otherFieldName),
451
- isLargeCollection: (0, config_1.isLargeCollection)(config, entity, fieldName),
452
- isDeferredAndDeferrable,
453
- derived,
454
- softDeletes: (0, config_1.softDeletesConfig)(config, entity, fieldName),
455
- hasJoinTableId: (0, utils_1.joinTableHasId)(r.joinTable),
456
- };
322
+ const { foreignKey, targetForeignKey, targetTable } = r;
323
+ const otherEntity = makeEntity(tableToEntityName(config, targetTable));
324
+ const fieldName = manyToManyName(targetForeignKey.columns[0]);
325
+ const otherFieldName = manyToManyName(foreignKey.columns[0]);
326
+ const isDeferredAndDeferrable = targetForeignKey.isDeferred && targetForeignKey.isDeferrable;
327
+ const isThisSideDerived = isReactiveManyToMany(config, entity, fieldName);
328
+ const isOtherSideDerived = isReactiveManyToMany(config, otherEntity, otherFieldName);
329
+ const derived = isThisSideDerived ? "async" : isOtherSideDerived ? "otherSide" : false;
330
+ return {
331
+ kind: "m2m",
332
+ joinTableName: r.joinTable.name,
333
+ fieldName,
334
+ singularName: singular(fieldName),
335
+ columnName: foreignKey.columns[0].name,
336
+ otherEntity,
337
+ otherFieldName,
338
+ otherColumnName: targetForeignKey.columns[0].name,
339
+ ignore: isFieldIgnored(config, entity, fieldName) || isFieldIgnored(config, otherEntity, otherFieldName),
340
+ isLargeCollection: isLargeCollection(config, entity, fieldName),
341
+ isDeferredAndDeferrable,
342
+ derived,
343
+ softDeletes: softDeletesConfig(config, entity, fieldName),
344
+ hasJoinTableId: joinTableHasId(r.joinTable)
345
+ };
457
346
  }
458
347
  function newManyToManyEnumField(config, entity, r, enums) {
459
- const { foreignKey, targetForeignKey, targetTable } = r;
460
- // For publisher_logo_colors.logo_color_id use the `logo_color_id` column i.e. `logoColors`
461
- const fieldName = manyToManyName(targetForeignKey.columns[0]);
462
- const enumName = (0, utils_1.tableToEntityName)(config, targetTable);
463
- return {
464
- kind: "m2mEnum",
465
- joinTableName: r.joinTable.name,
466
- fieldName,
467
- columnName: foreignKey.columns[0].name,
468
- otherColumnName: targetForeignKey.columns[0].name,
469
- enumName,
470
- enumType: (0, ts_poet_1.imp)(`${enumName}@./entities.ts`),
471
- enumDetailType: (0, ts_poet_1.imp)(`${(0, pluralize_1.plural)(enumName)}@./entities.ts`),
472
- enumDetailsType: (0, ts_poet_1.imp)(`${enumName}Details@./entities.ts`),
473
- enumRows: enums[targetTable.name].rows,
474
- ignore: (0, config_1.isFieldIgnored)(config, entity, fieldName),
475
- hasJoinTableId: (0, utils_1.joinTableHasId)(r.joinTable),
476
- };
348
+ const { foreignKey, targetForeignKey, targetTable } = r;
349
+ const fieldName = manyToManyName(targetForeignKey.columns[0]);
350
+ const enumName = tableToEntityName(config, targetTable);
351
+ return {
352
+ kind: "m2mEnum",
353
+ joinTableName: r.joinTable.name,
354
+ fieldName,
355
+ columnName: foreignKey.columns[0].name,
356
+ otherColumnName: targetForeignKey.columns[0].name,
357
+ enumName,
358
+ enumType: imp(`${enumName}@./entities.ts`),
359
+ enumDetailType: imp(`${plural(enumName)}@./entities.ts`),
360
+ enumDetailsType: imp(`${enumName}Details@./entities.ts`),
361
+ enumRows: enums[targetTable.name].rows,
362
+ ignore: isFieldIgnored(config, entity, fieldName),
363
+ hasJoinTableId: joinTableHasId(r.joinTable)
364
+ };
477
365
  }
478
366
  function newPolymorphicField(config, table, entity, pr) {
479
- const { fieldName, notNull } = pr;
480
- const components = table.m2oRelations
481
- .filter((r) => !(0, utils_1.isEnumTable)(config, r.targetTable))
482
- .filter((r) => !isMultiColumnForeignKey(r))
483
- .filter((r) => polymorphicFieldName(config, r) === fieldName)
484
- .map((r) => newPolymorphicFieldComponent(config, entity, r));
485
- const fieldType = `${entity.name}${(0, change_case_1.pascalCase)(fieldName)}`;
486
- const hasConfigDefault = (0, config_1.isFieldHasDefault)(config, entity, fieldName);
487
- return {
488
- kind: "poly",
489
- fieldName,
490
- fieldType,
491
- notNull,
492
- components,
493
- hasConfigDefault, // can be set to true by scanEntityFiles
494
- };
367
+ const { fieldName, notNull } = pr;
368
+ const components = table.m2oRelations.filter((r) => !isEnumTable(config, r.targetTable)).filter((r) => !isMultiColumnForeignKey(r)).filter((r) => polymorphicFieldName(config, r) === fieldName).map((r) => newPolymorphicFieldComponent(config, entity, r));
369
+ return {
370
+ kind: "poly",
371
+ fieldName,
372
+ fieldType: `${entity.name}${pascalCase(fieldName)}`,
373
+ notNull,
374
+ components,
375
+ hasConfigDefault: isFieldHasDefault(config, entity, fieldName)
376
+ };
495
377
  }
496
378
  function newPolymorphicFieldComponent(config, entity, r) {
497
- const column = r.foreignKey.columns[0];
498
- const columnName = column.name;
499
- const otherEntity = makeEntity((0, utils_1.tableToEntityName)(config, r.targetTable));
500
- const isOneToOne = column.uniqueIndexes.find(isOneToOneIndex) !== undefined;
501
- const otherFieldName = isOneToOne
502
- ? oneToOneName(config, otherEntity, entity, r)
503
- : collectionName(config, otherEntity, entity, r).fieldName;
504
- const isDeferredAndDeferrable = r.foreignKey.isDeferred && r.foreignKey.isDeferrable;
505
- return {
506
- columnName,
507
- otherEntity,
508
- otherFieldName,
509
- isDeferredAndDeferrable,
510
- constraintName: r.foreignKey.name,
511
- notNull: false,
512
- };
379
+ const column = r.foreignKey.columns[0];
380
+ const columnName = column.name;
381
+ const otherEntity = makeEntity(tableToEntityName(config, r.targetTable));
382
+ return {
383
+ columnName,
384
+ otherEntity,
385
+ otherFieldName: column.uniqueIndexes.find(isOneToOneIndex) !== void 0 ? oneToOneName(config, otherEntity, entity, r) : collectionName(config, otherEntity, entity, r).fieldName,
386
+ isDeferredAndDeferrable: r.foreignKey.isDeferred && r.foreignKey.isDeferrable,
387
+ constraintName: r.foreignKey.name,
388
+ notNull: false
389
+ };
513
390
  }
514
391
  function isFieldNameOverrides(maybeOverride) {
515
- return (maybeOverride !== null &&
516
- !Array.isArray(maybeOverride) &&
517
- typeof maybeOverride === "object" &&
518
- Object.keys(maybeOverride).some((k) => k === "fieldName" || k === "otherFieldName"));
392
+ return maybeOverride !== null && !Array.isArray(maybeOverride) && typeof maybeOverride === "object" && Object.keys(maybeOverride).some((k) => k === "fieldName" || k === "otherFieldName");
519
393
  }
520
394
  /** Finds the field name for o2o side of a o2o/m2o. */
521
- function oneToOneName(config,
522
- // I.e. the Book for o2o Book.image <-- `images.book_id`
523
- refEntity,
524
- // I.e. the Image for o2o Book.image <-- `images.book_id`
525
- keyEntity, r) {
526
- // If the name is overridden then use that
527
- const overrides = r.foreignKey.columns[0].commentData;
528
- if (isFieldNameOverrides(overrides) && overrides.otherFieldName) {
529
- return overrides.otherFieldName;
530
- }
531
- // For `comments.parent_book_review_id`, we would just use `BookReview.comment` as the name
532
- // For `authors.draft_current_book_id`, we would just use `Book.author` as the name
533
- // For `project_items.current_selection_id`, we would use `HomeownerSelection.currentProjectItem`
534
- const refTable = r instanceof pg_structure_1.M2ORelation ? r.targetTable : r.sourceTable;
535
- // Does the ref table have any m2o pointing table at the key table?
536
- const found = refTable.m2oRelations.find((s) => (0, utils_1.tableToEntityName)(config, s.targetTable) === keyEntity.name);
537
- // console.log({refTable: refTable.name, keyTable: keyTable.name, found: found?.name, fieldName});
538
- if (!found) {
539
- // If there aren't any m2os, just use the raw type name like `.image` or `.comment`
540
- return (0, change_case_1.camelCase)(keyEntity.name);
541
- }
542
- else {
543
- // If there is a m2o, assume we might conflict, and use the column name to at least be unique
544
- // Start with `book` from `images.book_id` or `current_draft_book` from `authors.current_draft_book_id`
545
- let fieldName = r.foreignKey.columns[0].name.replace(idSuffix, "");
546
- // Suffix the new type that we're pointing to, to `current_draft_book_author`
547
- fieldName = `${fieldName}_${keyEntity.name}`;
548
- // And drop the `book`, to `current_draft__author`
549
- fieldName = fieldName.replace(refEntity.name.toLowerCase(), "");
550
- // Then camel case, to `currentDraftAuthor`
551
- return (0, change_case_1.camelCase)(fieldName);
552
- }
395
+ function oneToOneName(config, refEntity, keyEntity, r) {
396
+ const overrides = r.foreignKey.columns[0].commentData;
397
+ if (isFieldNameOverrides(overrides) && overrides.otherFieldName) return overrides.otherFieldName;
398
+ if (!(r instanceof M2ORelation ? r.targetTable : r.sourceTable).m2oRelations.find((s) => tableToEntityName(config, s.targetTable) === keyEntity.name)) return camelCase(keyEntity.name);
399
+ else {
400
+ let fieldName = r.foreignKey.columns[0].name.replace(idSuffix, "");
401
+ fieldName = `${fieldName}_${keyEntity.name}`;
402
+ fieldName = fieldName.replace(refEntity.name.toLowerCase(), "");
403
+ return camelCase(fieldName);
404
+ }
553
405
  }
554
406
  const idSuffix = /_id$|Id$/;
555
407
  function referenceName(config, entity, r) {
556
- const [column] = r.foreignKey.columns;
557
- const overrides = column.commentData;
558
- return (polymorphicFieldName(config, r) ??
559
- // If the name is overridden then use that
560
- (isFieldNameOverrides(overrides) ? overrides.fieldName : undefined) ??
561
- (0, change_case_1.camelCase)(column.name.replace(idSuffix, "")));
408
+ const [column] = r.foreignKey.columns;
409
+ const overrides = column.commentData;
410
+ return polymorphicFieldName(config, r) ?? (isFieldNameOverrides(overrides) ? overrides.fieldName : void 0) ?? camelCase(column.name.replace(idSuffix, ""));
562
411
  }
563
412
  function enumFieldName(columnName) {
564
- return (0, change_case_1.camelCase)(columnName.replace(idSuffix, ""));
413
+ return camelCase(columnName.replace(idSuffix, ""));
565
414
  }
566
415
  function primitiveFieldName(columnName) {
567
- return (0, change_case_1.camelCase)(columnName);
416
+ return camelCase(columnName);
568
417
  }
569
418
  function manyToManyName(column) {
570
- const overrides = column.commentData;
571
- // If the name is overridden then use that
572
- if (isFieldNameOverrides(overrides) && overrides.otherFieldName) {
573
- return overrides.otherFieldName;
574
- }
575
- return (0, change_case_1.camelCase)((0, pluralize_1.plural)(column.name.replace(idSuffix, "")));
419
+ const overrides = column.commentData;
420
+ if (isFieldNameOverrides(overrides) && overrides.otherFieldName) return overrides.otherFieldName;
421
+ return camelCase(plural(column.name.replace(idSuffix, "")));
576
422
  }
577
423
  /** Returns the collection name to use on `entity` when referring to `otherEntity`s. */
578
- function collectionName(config,
579
- // I.e. the Author for o2m Author.books --> books.author_id
580
- singleEntity,
581
- // I.e. the Book for o2m Author.books --> books.author_id
582
- collectionEntity, r) {
583
- const [column] = r.foreignKey.columns;
584
- const overrides = column.commentData;
585
- // If the name is overridden then use that, but also singularize it
586
- if (isFieldNameOverrides(overrides) && overrides.otherFieldName) {
587
- const fieldName = overrides.otherFieldName;
588
- return { fieldName, singularName: (0, pluralize_1.singular)(fieldName) };
589
- }
590
- // I.e. if the m2o is `books.author_id`, use `Author.books` as the collection name (we pluralize at the end).
591
- let singularName = collectionEntity.name;
592
- // Check if we have multiple FKs from collectionEntity --> singleEntity and prefix with FK name if so
593
- const sourceTable = r.type === "m2o" ? r.sourceTable : r.targetTable;
594
- const targetTable = r.type === "m2o" ? r.targetTable : r.sourceTable;
595
- // If `books.foo_author_id` and `books.bar_author_id` both exist
596
- if (r.type !== "m2m" && sourceTable.m2oRelations.filter((r) => r.targetTable === targetTable).length > 1) {
597
- // Use `fooAuthorBooks`, `barAuthorBooks`
598
- singularName = `${column.name.replace(idSuffix, "")}_${singularName}`;
599
- }
600
- // If we've guessed `Book.bookReviews` based on `book_reviews.book_id` --> `bookReviews`, strip the `Book` prefix
601
- if (singularName.length > singleEntity.name.length && singularName.startsWith(singleEntity.name)) {
602
- singularName = singularName.substring(singleEntity.name.length);
603
- }
604
- // camelize the name
605
- singularName = (0, change_case_1.camelCase)(singularName);
606
- // and pluralize for fieldName
607
- return { fieldName: (0, pluralize_1.plural)(singularName), singularName };
424
+ function collectionName(config, singleEntity, collectionEntity, r) {
425
+ const [column] = r.foreignKey.columns;
426
+ const overrides = column.commentData;
427
+ if (isFieldNameOverrides(overrides) && overrides.otherFieldName) {
428
+ const fieldName = overrides.otherFieldName;
429
+ return {
430
+ fieldName,
431
+ singularName: singular(fieldName)
432
+ };
433
+ }
434
+ let singularName = collectionEntity.name;
435
+ const sourceTable = r.type === "m2o" ? r.sourceTable : r.targetTable;
436
+ const targetTable = r.type === "m2o" ? r.targetTable : r.sourceTable;
437
+ if (r.type !== "m2m" && sourceTable.m2oRelations.filter((r) => r.targetTable === targetTable).length > 1) singularName = `${column.name.replace(idSuffix, "")}_${singularName}`;
438
+ if (singularName.length > singleEntity.name.length && singularName.startsWith(singleEntity.name)) singularName = singularName.substring(singleEntity.name.length);
439
+ singularName = camelCase(singularName);
440
+ return {
441
+ fieldName: plural(singularName),
442
+ singularName
443
+ };
608
444
  }
609
445
  function failIfOverlappingFieldNames(entity) {
610
- const allFields = [
611
- entity.primaryKey,
612
- ...entity.primitives,
613
- ...entity.enums,
614
- ...entity.pgEnums,
615
- ...entity.manyToOnes,
616
- ...entity.oneToManys,
617
- ...entity.largeOneToManys,
618
- ...entity.oneToOnes,
619
- ...entity.manyToManys,
620
- ...entity.largeManyToManys,
621
- ...entity.manyToManyEnums,
622
- ...entity.polymorphics,
623
- ];
624
- Object.entries((0, joist_utils_1.groupBy)(allFields, (f) => f.fieldName)).forEach(([fieldName, fields]) => {
625
- if (fields.length > 1) {
626
- throw new Error(`In ${entity.name}, found multiple fields named '${fieldName}': ${fields.map((f) => f.kind).join(" ")}`);
627
- }
628
- });
446
+ const allFields = [
447
+ entity.primaryKey,
448
+ ...entity.primitives,
449
+ ...entity.enums,
450
+ ...entity.pgEnums,
451
+ ...entity.manyToOnes,
452
+ ...entity.oneToManys,
453
+ ...entity.largeOneToManys,
454
+ ...entity.oneToOnes,
455
+ ...entity.manyToManys,
456
+ ...entity.largeManyToManys,
457
+ ...entity.manyToManyEnums,
458
+ ...entity.polymorphics
459
+ ];
460
+ Object.entries(groupBy(allFields, (f) => f.fieldName)).forEach(([fieldName, fields]) => {
461
+ if (fields.length > 1) throw new Error(`In ${entity.name}, found multiple fields named '${fieldName}': ${fields.map((f) => f.kind).join(" ")}`);
462
+ });
629
463
  }
630
464
  function makeEntity(entityName) {
631
- // Default to the conventional names; `resolveNameConflicts` rewrites them if they collide.
632
- const names = entitySymbolNames(entityName);
633
- return {
634
- name: entityName,
635
- type: entityType(entityName),
636
- typeSymbol: entityTypeSymbol(entityName),
637
- typeForMetadataFile: entityTypeForMetadataFile(entityName),
638
- metaName: metaName(entityName),
639
- metaType: metaType(entityName),
640
- idType: entityTypeImport(entityName, names.idName),
641
- orderType: entityTypeImport(entityName, names.orderName),
642
- optsType: entityTypeImport(entityName, names.optsName),
643
- configConst: (0, ts_poet_1.imp)(`${(0, change_case_1.camelCase)(entityName)}Config@./entities.ts`, {
644
- definedIn: `./codegen/${entityName}Codegen.ts`,
645
- }),
646
- ...names,
647
- };
465
+ const names = entitySymbolNames(entityName);
466
+ return {
467
+ name: entityName,
468
+ type: entityType(entityName),
469
+ typeSymbol: entityTypeSymbol(entityName),
470
+ typeForMetadataFile: entityTypeForMetadataFile(entityName),
471
+ metaName: metaName(entityName),
472
+ metaType: metaType(entityName),
473
+ idType: entityTypeImport(entityName, names.idName),
474
+ orderType: entityTypeImport(entityName, names.orderName),
475
+ optsType: entityTypeImport(entityName, names.optsName),
476
+ configConst: imp(`${camelCase(entityName)}Config@./entities.ts`, { definedIn: `./codegen/${entityName}Codegen.ts` }),
477
+ ...names
478
+ };
648
479
  }
649
480
  /**
650
- * Collapses the per-relation `otherEntity` copies down to the one primary `Entity` per name.
651
- *
652
- * `makeEntity` mints a fresh `Entity` for every relation's `otherEntity`, so each entity ends up with
653
- * many duplicate objects floating around. Pointing them all at the single `entitiesByName[name].entity`
654
- * instance means later passes (i.e. `resolveNameConflicts`) only have to update one object per name.
655
- *
656
- * Must run after inheritance, since STI/CTI specialization both adds and re-points `otherEntity`s.
657
- */
481
+ * Collapses the per-relation `otherEntity` copies down to the one primary `Entity` per name.
482
+ *
483
+ * `makeEntity` mints a fresh `Entity` for every relation's `otherEntity`, so each entity ends up with
484
+ * many duplicate objects floating around. Pointing them all at the single `entitiesByName[name].entity`
485
+ * instance means later passes (i.e. `resolveNameConflicts`) only have to update one object per name.
486
+ *
487
+ * Must run after inheritance, since STI/CTI specialization both adds and re-points `otherEntity`s.
488
+ */
658
489
  function canonicalizeOtherEntities(db) {
659
- const canonical = (other) => db.entitiesByName[other.name]?.entity ?? other;
660
- for (const meta of db.entities) {
661
- for (const field of [
662
- ...meta.manyToOnes,
663
- ...meta.oneToManys,
664
- ...meta.largeOneToManys,
665
- ...meta.oneToOnes,
666
- ...meta.manyToManys,
667
- ...meta.largeManyToManys,
668
- ]) {
669
- field.otherEntity = canonical(field.otherEntity);
670
- }
671
- for (const poly of meta.polymorphics) {
672
- for (const comp of poly.components)
673
- comp.otherEntity = canonical(comp.otherEntity);
674
- }
675
- }
490
+ const canonical = (other) => db.entitiesByName[other.name]?.entity ?? other;
491
+ for (const meta of db.entities) {
492
+ for (const field of [
493
+ ...meta.manyToOnes,
494
+ ...meta.oneToManys,
495
+ ...meta.largeOneToManys,
496
+ ...meta.oneToOnes,
497
+ ...meta.manyToManys,
498
+ ...meta.largeManyToManys
499
+ ]) field.otherEntity = canonical(field.otherEntity);
500
+ for (const poly of meta.polymorphics) for (const comp of poly.components) comp.otherEntity = canonical(comp.otherEntity);
501
+ }
676
502
  }
677
503
  /**
678
- * Rewrites codegen'd type names that collide with another exported type name.
679
- *
680
- * `makeEntity` defaults each name to the conventional `${name}<Suffix>`, but if a separate entity or
681
- * enum is literally named e.g. `AuthorScope` or `AuthorOrder`, our generated type of the same name
682
- * would collide with it, so we fall back to `Author_Scope` / `Author_Order`.
683
- *
684
- * Relies on `canonicalizeOtherEntities` having run, so mutating each primary `meta.entity` also updates
685
- * the `otherEntity` references that point at it (e.g. `Book.author: AuthorId` follows `Author`'s rename).
686
- */
504
+ * Rewrites codegen'd type names that collide with another exported type name.
505
+ *
506
+ * `makeEntity` defaults each name to the conventional `${name}<Suffix>`, but if a separate entity or
507
+ * enum is literally named e.g. `AuthorScope` or `AuthorOrder`, our generated type of the same name
508
+ * would collide with it, so we fall back to `Author_Scope` / `Author_Order`.
509
+ *
510
+ * Relies on `canonicalizeOtherEntities` having run, so mutating each primary `meta.entity` also updates
511
+ * the `otherEntity` references that point at it (e.g. `Book.author: AuthorId` follows `Author`'s rename).
512
+ */
687
513
  function resolveNameConflicts(config, db) {
688
- // The names exported into `entities.ts` that a codegen'd type could shadow.
689
- const reserved = new Set(db.entities.map((meta) => meta.name));
690
- for (const enumData of Object.values(db.enums)) {
691
- // An enum table exports its (singularized) type, its `Details` type/const, and its pluralized const,
692
- // i.e. `ChangeRequestAssetScope`, `ChangeRequestAssetScopeDetails`, and `ChangeRequestAssetScopes`.
693
- const enumName = (0, utils_1.tableToEntityName)(config, enumData.table);
694
- reserved.add(enumName).add(`${enumName}Details`).add((0, pluralize_1.plural)(enumName));
695
- }
696
- for (const pgEnum of Object.values(db.pgEnums))
697
- reserved.add(pgEnum.name);
698
- for (const meta of db.entities) {
699
- if (hasNameConflict(meta.name, reserved))
700
- applyEntityNames(meta.entity, reserved);
701
- }
514
+ const reserved = new Set(db.entities.map((meta) => meta.name));
515
+ for (const enumData of Object.values(db.enums)) {
516
+ const enumName = tableToEntityName(config, enumData.table);
517
+ reserved.add(enumName).add(`${enumName}Details`).add(plural(enumName));
518
+ }
519
+ for (const pgEnum of Object.values(db.pgEnums)) reserved.add(pgEnum.name);
520
+ for (const meta of db.entities) if (hasNameConflict(meta.name, reserved)) applyEntityNames(meta.entity, reserved);
702
521
  }
703
522
  /** Computes the codegen'd type names for an entity, underscoring any that `reserved` already contains. */
704
523
  function entitySymbolNames(name, reserved) {
705
- const pick = (suffix) => (reserved?.has(`${name}${suffix}`) ? `${name}_${suffix}` : `${name}${suffix}`);
706
- return {
707
- idName: pick("Id"),
708
- fieldsName: pick("Fields"),
709
- optsName: pick("Opts"),
710
- idsOptsName: pick("IdsOpts"),
711
- filterName: pick("Filter"),
712
- graphqlFilterName: pick("GraphQLFilter"),
713
- orderName: pick("Order"),
714
- factoryExtrasName: pick("FactoryExtras"),
715
- scopeName: pick("Scope"),
716
- scopesName: pick("Scopes"),
717
- };
524
+ const pick = (suffix) => reserved?.has(`${name}${suffix}`) ? `${name}_${suffix}` : `${name}${suffix}`;
525
+ return {
526
+ idName: pick("Id"),
527
+ fieldsName: pick("Fields"),
528
+ optsName: pick("Opts"),
529
+ idsOptsName: pick("IdsOpts"),
530
+ filterName: pick("Filter"),
531
+ graphqlFilterName: pick("GraphQLFilter"),
532
+ orderName: pick("Order"),
533
+ factoryExtrasName: pick("FactoryExtras"),
534
+ scopeName: pick("Scope"),
535
+ scopesName: pick("Scopes")
536
+ };
718
537
  }
719
538
  /** Returns true if any of the entity's conventional type names is already taken. */
720
539
  function hasNameConflict(name, reserved) {
721
- return Object.values(entitySymbolNames(name)).some((conventional) => reserved.has(conventional));
540
+ return Object.values(entitySymbolNames(name)).some((conventional) => reserved.has(conventional));
722
541
  }
723
542
  /** Rewrites an entity's type names (and the `Import`s built from them) to their de-conflicted form. */
724
543
  function applyEntityNames(entity, reserved) {
725
- const names = entitySymbolNames(entity.name, reserved);
726
- Object.assign(entity, names);
727
- entity.idType = entityTypeImport(entity.name, names.idName);
728
- entity.orderType = entityTypeImport(entity.name, names.orderName);
729
- entity.optsType = entityTypeImport(entity.name, names.optsName);
544
+ const names = entitySymbolNames(entity.name, reserved);
545
+ Object.assign(entity, names);
546
+ entity.idType = entityTypeImport(entity.name, names.idName);
547
+ entity.orderType = entityTypeImport(entity.name, names.orderName);
548
+ entity.optsType = entityTypeImport(entity.name, names.optsName);
730
549
  }
731
550
  function entityTypeImport(entityName, symbolName) {
732
- return (0, ts_poet_1.imp)(`t:${symbolName}@./entities.ts`, { definedIn: `./codegen/${entityName}Codegen.ts` });
551
+ return imp(`t:${symbolName}@./entities.ts`, { definedIn: `./codegen/${entityName}Codegen.ts` });
733
552
  }
734
553
  function metaName(entityName) {
735
- return `${(0, change_case_1.camelCase)(entityName)}Meta`;
554
+ return `${camelCase(entityName)}Meta`;
736
555
  }
737
556
  function metaType(entityName) {
738
- return (0, ts_poet_1.imp)(`${metaName(entityName)}@./entities.ts`);
557
+ return imp(`${metaName(entityName)}@./entities.ts`);
739
558
  }
740
559
  function entityType(entityName) {
741
- return (0, ts_poet_1.imp)(`t:${entityName}@./entities.ts`);
560
+ return imp(`t:${entityName}@./entities.ts`);
742
561
  }
743
562
  function entityTypeSymbol(entityName) {
744
- return (0, ts_poet_1.imp)(`${entityName}@./entities.ts`);
563
+ return imp(`${entityName}@./entities.ts`);
745
564
  }
746
565
  function entityTypeForMetadataFile(entityName) {
747
- return (0, ts_poet_1.imp)(`${entityName}@./${entityName}.ts`);
566
+ return imp(`${entityName}@./${entityName}.ts`);
748
567
  }
749
568
  function mapType(config, tableName, columnName, dbColumnType) {
750
- return (0, utils_1.mapSimpleDbTypeToTypescriptType)(config, dbColumnType);
569
+ return mapSimpleDbTypeToTypescriptType(config, dbColumnType);
751
570
  }
752
571
  function isEnumArray(c) {
753
- return c.arrayDimension === 1 && !!c.comment && c.comment.startsWith("enum=");
572
+ return c.arrayDimension === 1 && !!c.comment && c.comment.startsWith("enum=");
754
573
  }
755
574
  function isArray(c) {
756
- return c.arrayDimension === 1;
575
+ return c.arrayDimension === 1;
757
576
  }
758
577
  function isPgEnum(c) {
759
- return c.type instanceof pg_structure_1.EnumType;
578
+ return c.type instanceof EnumType;
760
579
  }
761
580
  function superstructType(s) {
762
- // Assume it's `foo@...`, turn it into `Foo@...`
763
- const [symbol, ...path] = s.split("@");
764
- return ts_poet_1.Import.from(`${(0, change_case_1.pascalCase)(symbol)}@${path.join("@")}`);
581
+ const [symbol, ...path] = s.split("@");
582
+ return Import.from(`${pascalCase(symbol)}@${path.join("@")}`);
765
583
  }
766
584
  function zodSchemaType(s) {
767
- const schema = ts_poet_1.Import.from(s);
768
- return (0, ts_poet_1.code) `${symbols_1.Zod}.input<typeof ${schema}>`;
585
+ const schema = Import.from(s);
586
+ return code`${Zod}.input<typeof ${schema}>`;
769
587
  }
770
588
  function userFieldTypeType(s) {
771
- return ts_poet_1.Import.from(`t:${s}`);
589
+ return Import.from(`t:${s}`);
772
590
  }
773
591
  function serdeType(s) {
774
- return ts_poet_1.Import.from(s);
592
+ return Import.from(s);
775
593
  }
594
+ //#endregion
595
+ export { EntityDbMetadata, canonicalizeOtherEntities, collectionName, failIfOverlappingFieldNames, makeEntity, manyToManyName, oneToOneName, referenceName, resolveNameConflicts };
596
+
776
597
  //# sourceMappingURL=EntityDbMetadata.js.map