relations.cjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc2) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var relations_exports = {};
  20. __export(relations_exports, {
  21. Many: () => Many,
  22. One: () => One,
  23. Relation: () => Relation,
  24. Relations: () => Relations,
  25. createMany: () => createMany,
  26. createOne: () => createOne,
  27. createTableRelationsHelpers: () => createTableRelationsHelpers,
  28. extractTablesRelationalConfig: () => extractTablesRelationalConfig,
  29. getOperators: () => getOperators,
  30. getOrderByOperators: () => getOrderByOperators,
  31. mapRelationalRow: () => mapRelationalRow,
  32. normalizeRelation: () => normalizeRelation,
  33. relations: () => relations
  34. });
  35. module.exports = __toCommonJS(relations_exports);
  36. var import_table = require("./table.cjs");
  37. var import_column = require("./column.cjs");
  38. var import_entity = require("./entity.cjs");
  39. var import_primary_keys = require("./pg-core/primary-keys.cjs");
  40. var import_expressions = require("./sql/expressions/index.cjs");
  41. var import_sql = require("./sql/sql.cjs");
  42. class Relation {
  43. constructor(sourceTable, referencedTable, relationName) {
  44. this.sourceTable = sourceTable;
  45. this.referencedTable = referencedTable;
  46. this.relationName = relationName;
  47. this.referencedTableName = referencedTable[import_table.Table.Symbol.Name];
  48. }
  49. static [import_entity.entityKind] = "Relation";
  50. referencedTableName;
  51. fieldName;
  52. }
  53. class Relations {
  54. constructor(table, config) {
  55. this.table = table;
  56. this.config = config;
  57. }
  58. static [import_entity.entityKind] = "Relations";
  59. }
  60. class One extends Relation {
  61. constructor(sourceTable, referencedTable, config, isNullable) {
  62. super(sourceTable, referencedTable, config?.relationName);
  63. this.config = config;
  64. this.isNullable = isNullable;
  65. }
  66. static [import_entity.entityKind] = "One";
  67. withFieldName(fieldName) {
  68. const relation = new One(
  69. this.sourceTable,
  70. this.referencedTable,
  71. this.config,
  72. this.isNullable
  73. );
  74. relation.fieldName = fieldName;
  75. return relation;
  76. }
  77. }
  78. class Many extends Relation {
  79. constructor(sourceTable, referencedTable, config) {
  80. super(sourceTable, referencedTable, config?.relationName);
  81. this.config = config;
  82. }
  83. static [import_entity.entityKind] = "Many";
  84. withFieldName(fieldName) {
  85. const relation = new Many(
  86. this.sourceTable,
  87. this.referencedTable,
  88. this.config
  89. );
  90. relation.fieldName = fieldName;
  91. return relation;
  92. }
  93. }
  94. function getOperators() {
  95. return {
  96. and: import_expressions.and,
  97. between: import_expressions.between,
  98. eq: import_expressions.eq,
  99. exists: import_expressions.exists,
  100. gt: import_expressions.gt,
  101. gte: import_expressions.gte,
  102. ilike: import_expressions.ilike,
  103. inArray: import_expressions.inArray,
  104. isNull: import_expressions.isNull,
  105. isNotNull: import_expressions.isNotNull,
  106. like: import_expressions.like,
  107. lt: import_expressions.lt,
  108. lte: import_expressions.lte,
  109. ne: import_expressions.ne,
  110. not: import_expressions.not,
  111. notBetween: import_expressions.notBetween,
  112. notExists: import_expressions.notExists,
  113. notLike: import_expressions.notLike,
  114. notIlike: import_expressions.notIlike,
  115. notInArray: import_expressions.notInArray,
  116. or: import_expressions.or,
  117. sql: import_sql.sql
  118. };
  119. }
  120. function getOrderByOperators() {
  121. return {
  122. sql: import_sql.sql,
  123. asc: import_expressions.asc,
  124. desc: import_expressions.desc
  125. };
  126. }
  127. function extractTablesRelationalConfig(schema, configHelpers) {
  128. if (Object.keys(schema).length === 1 && "default" in schema && !(0, import_entity.is)(schema["default"], import_table.Table)) {
  129. schema = schema["default"];
  130. }
  131. const tableNamesMap = {};
  132. const relationsBuffer = {};
  133. const tablesConfig = {};
  134. for (const [key, value] of Object.entries(schema)) {
  135. if ((0, import_entity.is)(value, import_table.Table)) {
  136. const dbName = (0, import_table.getTableUniqueName)(value);
  137. const bufferedRelations = relationsBuffer[dbName];
  138. tableNamesMap[dbName] = key;
  139. tablesConfig[key] = {
  140. tsName: key,
  141. dbName: value[import_table.Table.Symbol.Name],
  142. schema: value[import_table.Table.Symbol.Schema],
  143. columns: value[import_table.Table.Symbol.Columns],
  144. relations: bufferedRelations?.relations ?? {},
  145. primaryKey: bufferedRelations?.primaryKey ?? []
  146. };
  147. for (const column of Object.values(
  148. value[import_table.Table.Symbol.Columns]
  149. )) {
  150. if (column.primary) {
  151. tablesConfig[key].primaryKey.push(column);
  152. }
  153. }
  154. const extraConfig = value[import_table.Table.Symbol.ExtraConfigBuilder]?.(value[import_table.Table.Symbol.ExtraConfigColumns]);
  155. if (extraConfig) {
  156. for (const configEntry of Object.values(extraConfig)) {
  157. if ((0, import_entity.is)(configEntry, import_primary_keys.PrimaryKeyBuilder)) {
  158. tablesConfig[key].primaryKey.push(...configEntry.columns);
  159. }
  160. }
  161. }
  162. } else if ((0, import_entity.is)(value, Relations)) {
  163. const dbName = (0, import_table.getTableUniqueName)(value.table);
  164. const tableName = tableNamesMap[dbName];
  165. const relations2 = value.config(
  166. configHelpers(value.table)
  167. );
  168. let primaryKey;
  169. for (const [relationName, relation] of Object.entries(relations2)) {
  170. if (tableName) {
  171. const tableConfig = tablesConfig[tableName];
  172. tableConfig.relations[relationName] = relation;
  173. if (primaryKey) {
  174. tableConfig.primaryKey.push(...primaryKey);
  175. }
  176. } else {
  177. if (!(dbName in relationsBuffer)) {
  178. relationsBuffer[dbName] = {
  179. relations: {},
  180. primaryKey
  181. };
  182. }
  183. relationsBuffer[dbName].relations[relationName] = relation;
  184. }
  185. }
  186. }
  187. }
  188. return { tables: tablesConfig, tableNamesMap };
  189. }
  190. function relations(table, relations2) {
  191. return new Relations(
  192. table,
  193. (helpers) => Object.fromEntries(
  194. Object.entries(relations2(helpers)).map(([key, value]) => [
  195. key,
  196. value.withFieldName(key)
  197. ])
  198. )
  199. );
  200. }
  201. function createOne(sourceTable) {
  202. return function one(table, config) {
  203. return new One(
  204. sourceTable,
  205. table,
  206. config,
  207. config?.fields.reduce((res, f) => res && f.notNull, true) ?? false
  208. );
  209. };
  210. }
  211. function createMany(sourceTable) {
  212. return function many(referencedTable, config) {
  213. return new Many(sourceTable, referencedTable, config);
  214. };
  215. }
  216. function normalizeRelation(schema, tableNamesMap, relation) {
  217. if ((0, import_entity.is)(relation, One) && relation.config) {
  218. return {
  219. fields: relation.config.fields,
  220. references: relation.config.references
  221. };
  222. }
  223. const referencedTableTsName = tableNamesMap[(0, import_table.getTableUniqueName)(relation.referencedTable)];
  224. if (!referencedTableTsName) {
  225. throw new Error(
  226. `Table "${relation.referencedTable[import_table.Table.Symbol.Name]}" not found in schema`
  227. );
  228. }
  229. const referencedTableConfig = schema[referencedTableTsName];
  230. if (!referencedTableConfig) {
  231. throw new Error(`Table "${referencedTableTsName}" not found in schema`);
  232. }
  233. const sourceTable = relation.sourceTable;
  234. const sourceTableTsName = tableNamesMap[(0, import_table.getTableUniqueName)(sourceTable)];
  235. if (!sourceTableTsName) {
  236. throw new Error(
  237. `Table "${sourceTable[import_table.Table.Symbol.Name]}" not found in schema`
  238. );
  239. }
  240. const reverseRelations = [];
  241. for (const referencedTableRelation of Object.values(
  242. referencedTableConfig.relations
  243. )) {
  244. if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
  245. reverseRelations.push(referencedTableRelation);
  246. }
  247. }
  248. if (reverseRelations.length > 1) {
  249. throw relation.relationName ? new Error(
  250. `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`
  251. ) : new Error(
  252. `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[import_table.Table.Symbol.Name]}". Please specify relation name`
  253. );
  254. }
  255. if (reverseRelations[0] && (0, import_entity.is)(reverseRelations[0], One) && reverseRelations[0].config) {
  256. return {
  257. fields: reverseRelations[0].config.references,
  258. references: reverseRelations[0].config.fields
  259. };
  260. }
  261. throw new Error(
  262. `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`
  263. );
  264. }
  265. function createTableRelationsHelpers(sourceTable) {
  266. return {
  267. one: createOne(sourceTable),
  268. many: createMany(sourceTable)
  269. };
  270. }
  271. function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
  272. const result = {};
  273. for (const [
  274. selectionItemIndex,
  275. selectionItem
  276. ] of buildQueryResultSelection.entries()) {
  277. if (selectionItem.isJson) {
  278. const relation = tableConfig.relations[selectionItem.tsKey];
  279. const rawSubRows = row[selectionItemIndex];
  280. const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
  281. result[selectionItem.tsKey] = (0, import_entity.is)(relation, One) ? subRows && mapRelationalRow(
  282. tablesConfig,
  283. tablesConfig[selectionItem.relationTableTsKey],
  284. subRows,
  285. selectionItem.selection,
  286. mapColumnValue
  287. ) : subRows.map(
  288. (subRow) => mapRelationalRow(
  289. tablesConfig,
  290. tablesConfig[selectionItem.relationTableTsKey],
  291. subRow,
  292. selectionItem.selection,
  293. mapColumnValue
  294. )
  295. );
  296. } else {
  297. const value = mapColumnValue(row[selectionItemIndex]);
  298. const field = selectionItem.field;
  299. let decoder;
  300. if ((0, import_entity.is)(field, import_column.Column)) {
  301. decoder = field;
  302. } else if ((0, import_entity.is)(field, import_sql.SQL)) {
  303. decoder = field.decoder;
  304. } else {
  305. decoder = field.sql.decoder;
  306. }
  307. result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
  308. }
  309. }
  310. return result;
  311. }
  312. // Annotate the CommonJS export names for ESM import in node:
  313. 0 && (module.exports = {
  314. Many,
  315. One,
  316. Relation,
  317. Relations,
  318. createMany,
  319. createOne,
  320. createTableRelationsHelpers,
  321. extractTablesRelationalConfig,
  322. getOperators,
  323. getOrderByOperators,
  324. mapRelationalRow,
  325. normalizeRelation,
  326. relations
  327. });
  328. //# sourceMappingURL=relations.cjs.map