@casekit/orm 0.0.1-alpha.11 → 0.0.1-alpha.13

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 (229) hide show
  1. package/lib/queries/find/types/FindManyResult.d.ts +2 -1
  2. package/lib/queries/find/types/FindManyResult.d.ts.map +1 -1
  3. package/package.json +13 -3
  4. package/.env +0 -2
  5. package/.eslintrc.cjs +0 -69
  6. package/.github/actions/ci-setup/action.yml +0 -19
  7. package/.github/dependabot.yml +0 -12
  8. package/.github/workflows/ci.yml +0 -119
  9. package/.github/workflows/dependabot.yml +0 -26
  10. package/.github/workflows/semgrep.yml +0 -24
  11. package/.prettierrc.cjs +0 -11
  12. package/.vscode/tasks.json +0 -28
  13. package/codecov.yml +0 -7
  14. package/lib/orm.query.test.d.ts +0 -2
  15. package/lib/orm.query.test.d.ts.map +0 -1
  16. package/lib/orm.query.test.js +0 -22
  17. package/lib/orm.query.test.js.map +0 -1
  18. package/src/Connection.ts +0 -65
  19. package/src/errors.ts +0 -18
  20. package/src/index.ts +0 -16
  21. package/src/logger.ts +0 -3
  22. package/src/migrate/commands/implode.ts +0 -46
  23. package/src/migrate/index.ts +0 -1
  24. package/src/migrate/migrator.ts +0 -24
  25. package/src/migrate/sql/createExtensionsSql.test.ts +0 -26
  26. package/src/migrate/sql/createExtensionsSql.ts +0 -16
  27. package/src/migrate/sql/createForeignKeyConstraintSql.test.ts +0 -50
  28. package/src/migrate/sql/createForeignKeyConstraintSql.ts +0 -44
  29. package/src/migrate/sql/createSchemasSql.test.ts +0 -81
  30. package/src/migrate/sql/createSchemasSql.ts +0 -15
  31. package/src/migrate/sql/createTableSql.properties.ts +0 -38
  32. package/src/migrate/sql/createTableSql.test.ts +0 -74
  33. package/src/migrate/sql/createTableSql.ts +0 -53
  34. package/src/migrate/sql/createUniqueConstraintSql.ts +0 -27
  35. package/src/migrate/sql/dropSchemasSql.ts +0 -15
  36. package/src/migrate/sql/dropTableSql.ts +0 -13
  37. package/src/orm.query.test.ts +0 -28
  38. package/src/orm.ts +0 -370
  39. package/src/pull/index.ts +0 -1
  40. package/src/pull/introspect/getForeignKeys.ts +0 -64
  41. package/src/pull/introspect/getPrimaryKeys.ts +0 -26
  42. package/src/pull/introspect/getTables.ts +0 -51
  43. package/src/pull/introspect/getUniqueConstraints.ts +0 -39
  44. package/src/pull/parse/parseCreateUniqueIndexStatement.test.ts +0 -14
  45. package/src/pull/parse/parseCreateUniqueIndexStatement.ts +0 -19
  46. package/src/pull/pull.ts +0 -78
  47. package/src/pull/render/renderModel.test.ts +0 -144
  48. package/src/pull/render/renderModel.ts +0 -141
  49. package/src/pull/render/renderModelsIndex.ts +0 -24
  50. package/src/pull/render/renderRelations.ts +0 -77
  51. package/src/pull/render/renderRelationsIndex.ts +0 -24
  52. package/src/pull/types/ColumnMeta.ts +0 -10
  53. package/src/pull/types/ForeignKey.ts +0 -6
  54. package/src/pull/types/PrimaryKey.ts +0 -6
  55. package/src/pull/types/UniqueConstraint.ts +0 -8
  56. package/src/pull/util/format.ts +0 -17
  57. package/src/pull/util/quote.ts +0 -7
  58. package/src/pull/util/unquote.ts +0 -9
  59. package/src/queries/clauses/IncludeClause.ts +0 -39
  60. package/src/queries/clauses/LateralByClause.ts +0 -4
  61. package/src/queries/clauses/ReturningClause.ts +0 -7
  62. package/src/queries/clauses/SelectClause.ts +0 -7
  63. package/src/queries/clauses/WhereClause.ts +0 -16
  64. package/src/queries/clauses/helpers/OptionalColumn.ts +0 -18
  65. package/src/queries/clauses/helpers/OptionalParams.ts +0 -14
  66. package/src/queries/clauses/helpers/RequiredColumn.ts +0 -8
  67. package/src/queries/clauses/helpers/RequiredParams.ts +0 -14
  68. package/src/queries/clauses/include/IncludedRelationModel.ts +0 -13
  69. package/src/queries/clauses/include/IncludedRelationName.ts +0 -11
  70. package/src/queries/clauses/include/IncludedRelationQuery.ts +0 -20
  71. package/src/queries/clauses/where/buildWhereClause.ts +0 -121
  72. package/src/queries/clauses/where/buildWhereClauses.test.ts +0 -145
  73. package/src/queries/clauses/where/buildWhereClauses.ts +0 -45
  74. package/src/queries/clauses/where/operators.ts +0 -13
  75. package/src/queries/clauses/where/types/WhereClauseValue.ts +0 -39
  76. package/src/queries/count/buildCount.ts +0 -77
  77. package/src/queries/count/countToSql.ts +0 -66
  78. package/src/queries/count/tests/count.test.ts +0 -35
  79. package/src/queries/count/types/BaseCountParams.ts +0 -11
  80. package/src/queries/count/types/CountBuilder.ts +0 -45
  81. package/src/queries/count/types/CountParams.ts +0 -27
  82. package/src/queries/count.ts +0 -33
  83. package/src/queries/create/buildCreate.ts +0 -67
  84. package/src/queries/create/createResultSchema.ts +0 -24
  85. package/src/queries/create/createToSql.ts +0 -44
  86. package/src/queries/create/tests/createMany.varied-keys.test.ts +0 -28
  87. package/src/queries/create/tests/createOne.test-d.ts +0 -116
  88. package/src/queries/create/tests/createOne.test.ts +0 -197
  89. package/src/queries/create/types/BaseCreateManyParams.ts +0 -7
  90. package/src/queries/create/types/BaseCreateOneParams.ts +0 -7
  91. package/src/queries/create/types/CreateManyParams.ts +0 -15
  92. package/src/queries/create/types/CreateManyResult.ts +0 -17
  93. package/src/queries/create/types/CreateOneParams.ts +0 -22
  94. package/src/queries/create/types/CreateOneResult.ts +0 -17
  95. package/src/queries/createMany.ts +0 -38
  96. package/src/queries/createOne.ts +0 -27
  97. package/src/queries/delete/buildDelete.ts +0 -56
  98. package/src/queries/delete/deleteResultSchema.ts +0 -23
  99. package/src/queries/delete/deleteToSql.ts +0 -48
  100. package/src/queries/delete/tests/deleteOne.test.ts +0 -108
  101. package/src/queries/delete/types/BaseDeleteParams.ts +0 -9
  102. package/src/queries/delete/types/DeleteManyResult.ts +0 -16
  103. package/src/queries/delete/types/DeleteOneResult.ts +0 -16
  104. package/src/queries/delete/types/DeleteParams.ts +0 -12
  105. package/src/queries/deleteMany.ts +0 -33
  106. package/src/queries/deleteOne.ts +0 -32
  107. package/src/queries/find/buildFind.ts +0 -138
  108. package/src/queries/find/findResultSchema.ts +0 -32
  109. package/src/queries/find/findToSql.test.ts +0 -123
  110. package/src/queries/find/findToSql.ts +0 -141
  111. package/src/queries/find/getIncludedManyToManyRelations.ts +0 -49
  112. package/src/queries/find/getIncludedOneToManyRelations.ts +0 -44
  113. package/src/queries/find/tests/findMany.include.test.ts +0 -107
  114. package/src/queries/find/tests/findMany.limit.test-d.ts +0 -75
  115. package/src/queries/find/tests/findMany.limit.test.ts +0 -176
  116. package/src/queries/find/tests/findMany.nullable-relations.test.ts +0 -127
  117. package/src/queries/find/tests/findMany.orderBy.test-d.ts +0 -84
  118. package/src/queries/find/tests/findMany.orderBy.test.ts +0 -184
  119. package/src/queries/find/tests/findMany.select.test-d.ts +0 -117
  120. package/src/queries/find/tests/findMany.select.test.ts +0 -188
  121. package/src/queries/find/tests/findMany.too-deep.test-d.ts +0 -154
  122. package/src/queries/find/tests/findMany.where.test-d.ts +0 -85
  123. package/src/queries/find/tests/findMany.where.test.ts +0 -76
  124. package/src/queries/find/tests/middleware.find.where.test.ts +0 -467
  125. package/src/queries/find/types/BaseFindParams.ts +0 -18
  126. package/src/queries/find/types/FindBuilder.ts +0 -73
  127. package/src/queries/find/types/FindManyParams.ts +0 -24
  128. package/src/queries/find/types/FindManyResult.ts +0 -12
  129. package/src/queries/find/types/FindOneParams.ts +0 -17
  130. package/src/queries/find/types/FindOneResult.ts +0 -50
  131. package/src/queries/findMany.ts +0 -134
  132. package/src/queries/findOne.ts +0 -30
  133. package/src/queries/middleware/Middleware.ts +0 -53
  134. package/src/queries/middleware/ValuesMiddleware.ts +0 -9
  135. package/src/queries/middleware/WhereMiddleware.ts +0 -16
  136. package/src/queries/update/buildUpdate.ts +0 -76
  137. package/src/queries/update/tests/updateOne.test.ts +0 -118
  138. package/src/queries/update/types/BaseUpdateParams.ts +0 -10
  139. package/src/queries/update/types/UpdateManyResult.ts +0 -16
  140. package/src/queries/update/types/UpdateOneResult.ts +0 -16
  141. package/src/queries/update/types/UpdateParams.ts +0 -14
  142. package/src/queries/update/types/UpdateValues.ts +0 -12
  143. package/src/queries/update/updateResultSchema.ts +0 -23
  144. package/src/queries/update/updateToSql.ts +0 -43
  145. package/src/queries/updateMany.ts +0 -33
  146. package/src/queries/updateOne.ts +0 -33
  147. package/src/queries/util/hasConditions.test.ts +0 -36
  148. package/src/queries/util/hasConditions.ts +0 -14
  149. package/src/queries/util/rowToObject.test.ts +0 -76
  150. package/src/queries/util/rowToObject.ts +0 -13
  151. package/src/queries/util/tableAlias.test.ts +0 -20
  152. package/src/queries/util/tableAlias.ts +0 -10
  153. package/src/schema/populate/composeMiddleware.ts +0 -51
  154. package/src/schema/populate/populateConfiguration.ts +0 -48
  155. package/src/schema/populate/populateModel.ts +0 -98
  156. package/src/schema/populate/suggestedColumnSchema.ts +0 -62
  157. package/src/schema/types/base/BaseColumn.ts +0 -10
  158. package/src/schema/types/base/BaseConfiguration.ts +0 -14
  159. package/src/schema/types/base/BaseModel.ts +0 -12
  160. package/src/schema/types/base/BaseModels.ts +0 -3
  161. package/src/schema/types/base/BaseOrm.ts +0 -8
  162. package/src/schema/types/base/BaseRelation.ts +0 -19
  163. package/src/schema/types/base/BaseRelations.ts +0 -3
  164. package/src/schema/types/constraints/ForeignKey.ts +0 -13
  165. package/src/schema/types/constraints/UniqueConstraint.ts +0 -9
  166. package/src/schema/types/helpers/ColumnName.ts +0 -6
  167. package/src/schema/types/helpers/ColumnType.ts +0 -23
  168. package/src/schema/types/helpers/Columns.ts +0 -3
  169. package/src/schema/types/helpers/HasDefault.ts +0 -11
  170. package/src/schema/types/helpers/IsNullable.ts +0 -7
  171. package/src/schema/types/helpers/IsProvided.ts +0 -8
  172. package/src/schema/types/helpers/IsSerial.ts +0 -10
  173. package/src/schema/types/helpers/ModelName.ts +0 -6
  174. package/src/schema/types/loose/LooseColumnDefinition.ts +0 -80
  175. package/src/schema/types/loose/LooseModelDefinition.ts +0 -47
  176. package/src/schema/types/loose/LooseModelDefinitions.ts +0 -3
  177. package/src/schema/types/loose/LooseRelationDefinition.ts +0 -10
  178. package/src/schema/types/loose/LooseRelationsDefinition.ts +0 -8
  179. package/src/schema/types/loose/LooseRelationsDefinitions.ts +0 -7
  180. package/src/schema/types/postgres/DataType.ts +0 -65
  181. package/src/schema/types/relations/ManyToManyRelation.ts +0 -15
  182. package/src/schema/types/relations/ManyToOneRelation.ts +0 -14
  183. package/src/schema/types/relations/OneToManyRelation.ts +0 -12
  184. package/src/schema/types/strict/ColumnDefinition.ts +0 -81
  185. package/src/schema/types/strict/ModelDefinition.ts +0 -47
  186. package/src/schema/types/strict/ModelDefinitions.ts +0 -3
  187. package/src/schema/types/strict/RelationDefinition.ts +0 -13
  188. package/src/schema/types/strict/RelationsDefinition.ts +0 -8
  189. package/src/schema/types/strict/RelationsDefinitions.ts +0 -7
  190. package/src/schema/validate/validateConfiguration.ts +0 -9
  191. package/src/schema/validate/validateModel.ts +0 -32
  192. package/src/sql/SQLStatement.test.ts +0 -112
  193. package/src/sql/SQLStatement.ts +0 -86
  194. package/src/sql/index.ts +0 -2
  195. package/src/sql/sql.ts +0 -47
  196. package/src/test/db/index.ts +0 -27
  197. package/src/test/db/models/foo.model.ts +0 -24
  198. package/src/test/db/models/foo.relations.ts +0 -4
  199. package/src/test/db/models/post.model.ts +0 -34
  200. package/src/test/db/models/post.relations.ts +0 -21
  201. package/src/test/db/models/tenant.model.ts +0 -14
  202. package/src/test/db/models/tenant.relations.ts +0 -22
  203. package/src/test/db/models/tenantUser.model.ts +0 -23
  204. package/src/test/db/models/tenantUser.relations.ts +0 -15
  205. package/src/test/db/models/user.model.ts +0 -29
  206. package/src/test/db/models/user.relations.ts +0 -38
  207. package/src/test/db/models.ts +0 -15
  208. package/src/test/db/relations.ts +0 -13
  209. package/src/test/gen/column.ts +0 -39
  210. package/src/test/gen/index.ts +0 -2
  211. package/src/test/gen/model.ts +0 -58
  212. package/src/test/gen/sqldate.ts +0 -8
  213. package/src/test/globalSetup.ts +0 -6
  214. package/src/test/seed/index.ts +0 -75
  215. package/src/test/util/withRollback.ts +0 -18
  216. package/src/test/util/withTransaction.ts +0 -19
  217. package/src/types/ColumnName.ts +0 -6
  218. package/src/types/ColumnType.ts +0 -20
  219. package/src/types/Configuration.ts +0 -21
  220. package/src/types/ModelType.ts +0 -20
  221. package/src/types/util/DeepRequired.ts +0 -7
  222. package/src/types/util/DisallowExtraKeys.ts +0 -5
  223. package/src/types/util/NonEmptyArray.ts +0 -1
  224. package/src/types/util/Simplify.ts +0 -8
  225. package/src/util/ensureArray.ts +0 -4
  226. package/src/util/interleave.test.ts +0 -35
  227. package/src/util/interleave.ts +0 -8
  228. package/tsconfig.json +0 -18
  229. package/vitest.config.ts +0 -15
@@ -1,86 +0,0 @@
1
- /**
2
- * This file is heavily inspired by felixfbecker/node-sql-template-strings,
3
- * which has the following licence:
4
- *
5
- * ISC License
6
- * Copyright (c) 2016, Felix Frederick Becker
7
- *
8
- * Permission to use, copy, modify, and/or distribute this software for any
9
- * purpose with or without fee is hereby granted, provided that the above
10
- * copyright notice and this permission notice appear in all copies.
11
- *
12
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
- */
20
- import pgfmt from "pg-format";
21
-
22
- export class SQLStatement {
23
- public fragments: string[];
24
- public values: unknown[];
25
-
26
- constructor(
27
- sql: readonly string[] | string = [],
28
- values: readonly unknown[] = [],
29
- ) {
30
- this.fragments = typeof sql === "string" ? [sql] : [...sql];
31
- this.values = [...values];
32
- }
33
-
34
- get text() {
35
- return this.fragments.reduce((prev, curr, i) => prev + "$" + i + curr);
36
- }
37
-
38
- public push(...args: (SQLStatement | string | null)[]): SQLStatement {
39
- for (const arg of args) {
40
- if (arg === null) {
41
- // do nothing - this case is here as a convenience
42
- // for when using functions that might not have any
43
- // SQL to return
44
- } else if (typeof arg === "string") {
45
- if (this.fragments.length === 0) {
46
- this.fragments.push(arg);
47
- } else {
48
- this.fragments[this.fragments.length - 1] += arg;
49
- }
50
- } else {
51
- if (arg.fragments.length === 0) {
52
- // do nothing - statement is empty
53
- } else if (this.fragments.length === 0) {
54
- this.fragments.push(...arg.fragments);
55
- this.values.push(...arg.values);
56
- } else {
57
- this.fragments[this.fragments.length - 1] +=
58
- arg.fragments[0];
59
- this.fragments.push(...arg.fragments.slice(1));
60
- this.values.push(...arg.values);
61
- }
62
- }
63
- }
64
- return this;
65
- }
66
-
67
- public withIdentifiers(...identifiers: string[]) {
68
- const remainingIdentifiers = [...identifiers];
69
- for (const index of this.fragments.keys()) {
70
- const countPlaceholders =
71
- this.fragments[index].match(/%I/g)?.length ?? 0;
72
- if (countPlaceholders > 0) {
73
- const interpolated = pgfmt(
74
- this.fragments[index],
75
- ...remainingIdentifiers.splice(0, countPlaceholders),
76
- );
77
- this.fragments[index] = interpolated;
78
- if (remainingIdentifiers.length === 0) {
79
- break;
80
- }
81
- }
82
- }
83
-
84
- return this;
85
- }
86
- }
package/src/sql/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export { sql } from "./sql";
2
- export { SQLStatement } from "./SQLStatement";
package/src/sql/sql.ts DELETED
@@ -1,47 +0,0 @@
1
- import { interleave } from "../util/interleave";
2
- import { SQLStatement } from "./SQLStatement";
3
-
4
- export const sql = (
5
- fragments: TemplateStringsArray,
6
- ...variables: readonly unknown[]
7
- ) => {
8
- /**
9
- * This complicated mess allows us to interpolate a SQLStatement
10
- * inside a SQLStatement, which is v helpful in eloquently
11
- * building up complex statements.
12
- */
13
- const expandedFragments: string[] = [];
14
- const expandedVariables: unknown[] = [];
15
- const remainingFragments = [...fragments];
16
- const remainingVariables = [...variables];
17
- let index = 0;
18
-
19
- while (remainingFragments.length > 0) {
20
- const fragment = remainingFragments.shift();
21
- const variable = remainingVariables.shift();
22
- expandedFragments[index] = (expandedFragments[index] ?? "") + fragment;
23
- if (remainingFragments.length > 0) {
24
- if (variable instanceof SQLStatement) {
25
- if (variable.fragments.length > 0) {
26
- expandedFragments[index] += variable.fragments[0];
27
- expandedFragments.push(...variable.fragments.slice(1));
28
- expandedVariables.push(...variable.values);
29
- index += variable.fragments.length - 1;
30
- }
31
- } else {
32
- expandedVariables.push(variable);
33
- index += 1;
34
- }
35
- }
36
- }
37
-
38
- return new SQLStatement(expandedFragments, expandedVariables);
39
- };
40
-
41
- sql.splat = <T>(values: T[], separator = `, `) =>
42
- new SQLStatement().push(
43
- ...interleave(
44
- values.map((v) => sql`${v}`),
45
- separator,
46
- ),
47
- );
@@ -1,27 +0,0 @@
1
- import { snakeCase } from "lodash-es";
2
- import pg from "pg";
3
-
4
- import { orm } from "../..";
5
- import { FindManyParams } from "../../queries/find/types/FindManyParams";
6
- import { ModelName } from "../../schema/types/helpers/ModelName";
7
- import { Models, models } from "./models";
8
- import { Relations, relations } from "./relations";
9
-
10
- export const db = orm({
11
- models,
12
- relations,
13
- extensions: ["uuid-ossp"],
14
- naming: { column: snakeCase },
15
- schema: "casekit",
16
- pool: new pg.Pool(),
17
- });
18
-
19
- export type FindMany<M extends ModelName<Models>> = FindManyParams<
20
- Models,
21
- Relations,
22
- M
23
- >;
24
-
25
- export { models, relations };
26
- export type { Models, Relations };
27
- export type DB = typeof db;
@@ -1,24 +0,0 @@
1
- import { ModelDefinition } from "../../..";
2
- import { sql } from "../../../sql";
3
-
4
- export const foo = {
5
- columns: {
6
- id: {
7
- type: "uuid",
8
- default: sql`uuid_generate_v4()`,
9
- primaryKey: true,
10
- },
11
- bigint: { type: "bigint" },
12
- text: { type: "text" },
13
- timestamp: { type: "timestamp" },
14
- renamedColumn: { name: "original_name", type: "timestamp" },
15
- a: { type: "bigint" },
16
- b: { type: "bigint" },
17
- c: { type: "bigint" },
18
- d: { type: "bigint" },
19
- e: { type: "bigint" },
20
- f: { type: "bigint" },
21
- g: { type: "bigint" },
22
- h: { type: "bigint" },
23
- },
24
- } as const satisfies ModelDefinition;
@@ -1,4 +0,0 @@
1
- import { RelationsDefinition } from "../../..";
2
- import { Models } from "../models";
3
-
4
- export const foo = {} as const satisfies RelationsDefinition<Models, "foo">;
@@ -1,34 +0,0 @@
1
- import { ModelDefinition } from "../../..";
2
- import { sql } from "../../../sql";
3
-
4
- export const post = {
5
- columns: {
6
- id: {
7
- type: "uuid",
8
- default: sql`uuid_generate_v4()`,
9
- primaryKey: true,
10
- },
11
- title: { type: "text" },
12
- content: { type: "text" },
13
- authorId: {
14
- name: "created_by_id",
15
- type: "uuid",
16
- references: { table: "user", column: "id" },
17
- },
18
- reviewedById: {
19
- name: "reviewed_by_id",
20
- type: "uuid",
21
- nullable: true,
22
- references: { table: "user", column: "id" },
23
- },
24
- publishedAt: { type: "timestamp", nullable: true },
25
- tags: { type: "text[][][][]", nullable: true },
26
- tenantId: {
27
- type: "uuid",
28
- references: { table: "tenant", column: "id" },
29
- default: "00000000-0000-0000-0000-000000000000",
30
- },
31
- updatedAt: { type: "timestamp", nullable: true },
32
- deletedAt: { type: "timestamp", nullable: true },
33
- },
34
- } as const satisfies ModelDefinition;
@@ -1,21 +0,0 @@
1
- import { RelationsDefinition } from "../../..";
2
- import { Models } from "../models";
3
-
4
- export const post = {
5
- author: {
6
- model: "user",
7
- type: "N:1",
8
- foreignKey: "authorId",
9
- },
10
- reviewedBy: {
11
- model: "user",
12
- type: "N:1",
13
- foreignKey: "reviewedById",
14
- optional: true,
15
- },
16
- tenant: {
17
- model: "tenant",
18
- type: "N:1",
19
- foreignKey: "tenantId",
20
- },
21
- } as const satisfies RelationsDefinition<Models, "post">;
@@ -1,14 +0,0 @@
1
- import { ModelDefinition } from "../../..";
2
- import { sql } from "../../../sql";
3
-
4
- export const tenant = {
5
- columns: {
6
- id: {
7
- type: "uuid",
8
- default: sql`uuid_generate_v4()`,
9
- primaryKey: true,
10
- },
11
- name: { type: "text" },
12
- createdAt: { type: "timestamp", default: sql`now()` },
13
- },
14
- } as const satisfies ModelDefinition;
@@ -1,22 +0,0 @@
1
- import { RelationsDefinition } from "../../..";
2
- import { Models } from "../models";
3
-
4
- export const tenant = {
5
- users: {
6
- model: "user",
7
- through: "tenantUser",
8
- type: "N:N",
9
- foreignKey: "tenantId",
10
- otherKey: "userId",
11
- },
12
- tenancies: {
13
- model: "tenantUser",
14
- type: "1:N",
15
- foreignKey: "tenantId",
16
- },
17
- posts: {
18
- model: "post",
19
- type: "1:N",
20
- foreignKey: "tenantId",
21
- },
22
- } as const satisfies RelationsDefinition<Models, "tenant">;
@@ -1,23 +0,0 @@
1
- import { ModelDefinition } from "../../..";
2
- import { sql } from "../../../sql";
3
-
4
- export const tenantUser = {
5
- table: "tenant_user",
6
- columns: {
7
- id: {
8
- type: "uuid",
9
- default: sql`uuid_generate_v4()`,
10
- primaryKey: true,
11
- },
12
- tenantId: {
13
- type: "uuid",
14
- references: { table: "tenant", column: "id" },
15
- },
16
- userId: { type: "uuid", references: { table: "user", column: "id" } },
17
- createdAt: { type: "timestamp with time zone", default: sql`now()` },
18
- deletedAt: {
19
- type: "timestamp with time zone",
20
- nullable: true,
21
- },
22
- },
23
- } as const satisfies ModelDefinition;
@@ -1,15 +0,0 @@
1
- import { RelationsDefinition } from "../../..";
2
- import { Models } from "../models";
3
-
4
- export const tenantUser = {
5
- user: {
6
- model: "user",
7
- type: "N:1",
8
- foreignKey: "userId",
9
- },
10
- tenant: {
11
- model: "tenant",
12
- type: "N:1",
13
- foreignKey: "tenantId",
14
- },
15
- } as const satisfies RelationsDefinition<Models, "tenantUser">;
@@ -1,29 +0,0 @@
1
- import { z } from "zod";
2
-
3
- import { ModelDefinition } from "../../..";
4
- import { sql } from "../../../sql";
5
-
6
- export const user = {
7
- columns: {
8
- id: { type: "uuid", default: sql`uuid_generate_v4()` },
9
- username: { zodSchema: z.string(), type: "text" },
10
- invitedById: {
11
- name: "invited_by_id",
12
- type: "uuid",
13
- nullable: true,
14
- references: { table: "user", column: "id" },
15
- },
16
- joinedAt: {
17
- name: "created_at",
18
- zodSchema: z.date(),
19
- type: "timestamp",
20
- nullable: true,
21
- },
22
- updatedAt: { type: "timestamp", nullable: true },
23
- deletedAt: { zodSchema: z.date(), type: "timestamp", nullable: true },
24
- },
25
- primaryKey: ["id"],
26
- uniqueConstraints: [
27
- { columns: ["username"], where: sql`deleted_at IS NULL` },
28
- ],
29
- } as const satisfies ModelDefinition;
@@ -1,38 +0,0 @@
1
- import { RelationsDefinition } from "../../..";
2
- import { Models } from "../models";
3
-
4
- export const user = {
5
- posts: {
6
- type: "1:N",
7
- model: "post",
8
- foreignKey: "authorId",
9
- },
10
- reviewedPosts: {
11
- type: "1:N",
12
- model: "post",
13
- foreignKey: "reviewedById",
14
- },
15
- invitedBy: {
16
- type: "N:1",
17
- model: "user",
18
- foreignKey: "invitedById",
19
- optional: true,
20
- },
21
- invitedUsers: {
22
- type: "1:N",
23
- model: "user",
24
- foreignKey: "invitedById",
25
- },
26
- tenancies: {
27
- type: "1:N",
28
- model: "tenantUser",
29
- foreignKey: "userId",
30
- },
31
- tenants: {
32
- type: "N:N",
33
- model: "tenant",
34
- through: "tenantUser",
35
- foreignKey: "userId",
36
- otherKey: "tenantId",
37
- },
38
- } as const satisfies RelationsDefinition<Models, "user">;
@@ -1,15 +0,0 @@
1
- import { foo } from "./models/foo.model";
2
- import { post } from "./models/post.model";
3
- import { tenant } from "./models/tenant.model";
4
- import { tenantUser } from "./models/tenantUser.model";
5
- import { user } from "./models/user.model";
6
-
7
- export const models = {
8
- foo,
9
- post,
10
- user,
11
- tenant,
12
- tenantUser,
13
- };
14
-
15
- export type Models = typeof models;
@@ -1,13 +0,0 @@
1
- import { post } from "./models/post.relations";
2
- import { tenant } from "./models/tenant.relations";
3
- import { tenantUser } from "./models/tenantUser.relations";
4
- import { user } from "./models/user.relations";
5
-
6
- export const relations = {
7
- post,
8
- user,
9
- tenant,
10
- tenantUser,
11
- };
12
-
13
- export type Relations = typeof relations;
@@ -1,39 +0,0 @@
1
- import { fc } from "@fast-check/vitest";
2
- import { z } from "zod";
3
-
4
- import { LooseColumnDefinition } from "../../schema/types/loose/LooseColumnDefinition";
5
- import { DataType } from "../../schema/types/postgres/DataType";
6
- import { sqldate } from "./sqldate";
7
-
8
- export const column = () => {
9
- return fc.oneof(
10
- fc.record<LooseColumnDefinition>({
11
- name: fc.string({ minLength: 1, maxLength: 80 }),
12
- nullable: fc.boolean(),
13
- zodSchema: fc.constant(z.string()),
14
- type: fc.constant<DataType>("text"),
15
- default: fc.oneof(fc.string(), fc.constant(null)),
16
- }),
17
- fc.record<LooseColumnDefinition>({
18
- name: fc.string({ minLength: 1, maxLength: 80 }),
19
- nullable: fc.boolean(),
20
- zodSchema: fc.constant(z.string().uuid()),
21
- type: fc.constant<DataType>("uuid"),
22
- default: fc.oneof(fc.uuid(), fc.constant(null)),
23
- }),
24
- fc.record<LooseColumnDefinition>({
25
- name: fc.string({ minLength: 1, maxLength: 80 }),
26
- nullable: fc.boolean(),
27
- zodSchema: fc.constant(z.number()),
28
- type: fc.constant<DataType>("bigint"),
29
- default: fc.oneof(fc.integer(), fc.constant(null)),
30
- }),
31
- fc.record<LooseColumnDefinition>({
32
- name: fc.string({ minLength: 1, maxLength: 80 }),
33
- nullable: fc.boolean(),
34
- zodSchema: fc.constant(z.date()),
35
- type: fc.constant<DataType>("timestamp"),
36
- default: fc.oneof(sqldate(), fc.constant(null)),
37
- }),
38
- );
39
- };
@@ -1,2 +0,0 @@
1
- export { column } from "./column";
2
- export { model } from "./model";
@@ -1,58 +0,0 @@
1
- import { fc } from "@fast-check/vitest";
2
- import { drop, take, uniqBy } from "lodash-es";
3
-
4
- import { UniqueConstraint } from "../../schema/types/constraints/UniqueConstraint";
5
- import { LooseModelDefinition } from "../../schema/types/loose/LooseModelDefinition";
6
- import { column } from "./column";
7
-
8
- export const model = () => {
9
- return fc
10
- .tuple(
11
- fc.record<LooseModelDefinition>({
12
- table: fc.string({ minLength: 1, maxLength: 80 }),
13
- schema: fc.string({ minLength: 1, maxLength: 80 }),
14
- columns: fc.dictionary(fc.string({ minLength: 1 }), column(), {
15
- minKeys: 1,
16
- maxKeys: 65,
17
- }),
18
- primaryKey: fc.constant([]),
19
- uniqueConstraints: fc.constant([]),
20
- foreignKeys: fc.constant([]),
21
- }),
22
- fc.integer({ min: 1, max: 2 }), // no of primary keys
23
- fc.integer({ min: 0, max: 2 }), // no of unique constraints
24
- )
25
- .map<LooseModelDefinition>(
26
- ([model, numPrimaryKeyColumns, numUniqueColumns]) => {
27
- // remove any duplicate column names
28
- const columns = uniqBy(
29
- Object.entries(model.columns),
30
- ([, c]) => c.name,
31
- );
32
-
33
- // take the first n columns as the primary key, if one has been specified
34
- const primaryKeyColumns = take(columns, numPrimaryKeyColumns);
35
-
36
- // and columns after it as the unique columns, if they have been specified
37
- const uniqueKeyColumns = take(
38
- drop(columns, numPrimaryKeyColumns),
39
- numUniqueColumns,
40
- );
41
-
42
- const primaryKey = primaryKeyColumns.map(
43
- ([, c]) => c.name as string,
44
- );
45
-
46
- const uniqueConstraints = uniqueKeyColumns.map(([, c]) => ({
47
- columns: [c.name as string],
48
- })) as UniqueConstraint[];
49
-
50
- return {
51
- ...model,
52
- columns: Object.fromEntries(columns),
53
- primaryKey,
54
- uniqueConstraints,
55
- };
56
- },
57
- );
58
- };
@@ -1,8 +0,0 @@
1
- import { fc } from "@fast-check/vitest";
2
-
3
- export const sqldate = () =>
4
- fc.date({
5
- min: new Date("1970-01-01T00:00:00.000Z"),
6
- max: new Date("9999-01-01T00:00:00.000Z"),
7
- noInvalidDate: true,
8
- });
@@ -1,6 +0,0 @@
1
- import { migrator } from "..";
2
- import { db } from "./db";
3
-
4
- export default async function setup() {
5
- await migrator(db).implode({ dryRun: false, output: true });
6
- }
@@ -1,75 +0,0 @@
1
- import { keyBy, times, uniq } from "lodash-es";
2
-
3
- import { DB } from "../db";
4
-
5
- export type SeedParams = {
6
- users: {
7
- username: string;
8
- tenants: {
9
- name: string;
10
- posts: number;
11
- }[];
12
- }[];
13
- };
14
-
15
- export const seed = async (
16
- db: DB,
17
- params: SeedParams,
18
- ): Promise<{
19
- users: Record<string, { id: string; username: string }>;
20
- tenants: Record<string, { id: string; name: string }>;
21
- tenantUsers: { userId: string; tenantId: string }[];
22
- posts: { id: string; title: string; content: string; authorId: string }[];
23
- }> => {
24
- const tenants = keyBy(
25
- await db.createMany("tenant", {
26
- values: uniq(params.users.flatMap((u) => u.tenants)).map(
27
- (tenant) => ({ name: tenant.name }),
28
- ),
29
- returning: ["id", "name", "createdAt"],
30
- }),
31
- "name",
32
- );
33
-
34
- const users = keyBy(
35
- await db.createMany("user", {
36
- values: uniq(
37
- params.users.map((user) => ({ username: user.username })),
38
- ),
39
- returning: ["id", "username"],
40
- }),
41
- "username",
42
- );
43
-
44
- const tenantUsers = await db.createMany("tenantUser", {
45
- values: params.users.flatMap((user) => {
46
- return user.tenants.map((tenant) => ({
47
- userId: users[user.username].id,
48
- tenantId: tenants[tenant.name].id,
49
- }));
50
- }),
51
- returning: ["id", "userId", "tenantId"],
52
- });
53
-
54
- let postIndex = 0;
55
- const posts = await db.createMany("post", {
56
- values: params.users.flatMap((user) =>
57
- user.tenants.flatMap((tenant) =>
58
- times(tenant.posts, () => {
59
- const letter = String.fromCharCode(
60
- "a".charCodeAt(0) + postIndex++,
61
- );
62
- return {
63
- title: `Post ${letter}`,
64
- content: `This is the content of post ${letter}`,
65
- authorId: users[user.username].id,
66
- tenantId: tenants[tenant.name].id,
67
- };
68
- }),
69
- ),
70
- ),
71
- returning: ["id", "title", "content", "authorId"],
72
- });
73
-
74
- return { users, tenants, tenantUsers, posts };
75
- };
@@ -1,18 +0,0 @@
1
- import pg from "pg";
2
-
3
- export const withRollback = async <T>(
4
- cb: (client: pg.Client) => Promise<T>,
5
- ): Promise<T> => {
6
- const client = new pg.Client();
7
- try {
8
- await client.connect();
9
- await client.query("BEGIN");
10
- return await cb(client);
11
- } finally {
12
- try {
13
- await client.query("ROLLBACK");
14
- } finally {
15
- await client.end();
16
- }
17
- }
18
- };
@@ -1,19 +0,0 @@
1
- import pg from "pg";
2
-
3
- export const withTransaction = async <T>(
4
- cb: (client: pg.Client) => Promise<T>,
5
- ): Promise<T> => {
6
- const client = new pg.Client();
7
- try {
8
- await client.connect();
9
- await client.query("BEGIN");
10
- const result = await cb(client);
11
- await client.query("COMMIT");
12
- return result;
13
- } catch (e) {
14
- await client.query("ROLLBACK");
15
- throw e;
16
- } finally {
17
- await client.end();
18
- }
19
- };