@casekit/orm 0.0.1-alpha.12 → 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 (227) hide show
  1. package/package.json +13 -3
  2. package/.env +0 -2
  3. package/.eslintrc.cjs +0 -69
  4. package/.github/actions/ci-setup/action.yml +0 -19
  5. package/.github/dependabot.yml +0 -12
  6. package/.github/workflows/ci.yml +0 -119
  7. package/.github/workflows/dependabot.yml +0 -26
  8. package/.github/workflows/semgrep.yml +0 -24
  9. package/.prettierrc.cjs +0 -11
  10. package/.vscode/tasks.json +0 -28
  11. package/codecov.yml +0 -7
  12. package/lib/orm.query.test.d.ts +0 -2
  13. package/lib/orm.query.test.d.ts.map +0 -1
  14. package/lib/orm.query.test.js +0 -22
  15. package/lib/orm.query.test.js.map +0 -1
  16. package/src/Connection.ts +0 -65
  17. package/src/errors.ts +0 -18
  18. package/src/index.ts +0 -16
  19. package/src/logger.ts +0 -3
  20. package/src/migrate/commands/implode.ts +0 -46
  21. package/src/migrate/index.ts +0 -1
  22. package/src/migrate/migrator.ts +0 -24
  23. package/src/migrate/sql/createExtensionsSql.test.ts +0 -26
  24. package/src/migrate/sql/createExtensionsSql.ts +0 -16
  25. package/src/migrate/sql/createForeignKeyConstraintSql.test.ts +0 -50
  26. package/src/migrate/sql/createForeignKeyConstraintSql.ts +0 -44
  27. package/src/migrate/sql/createSchemasSql.test.ts +0 -81
  28. package/src/migrate/sql/createSchemasSql.ts +0 -15
  29. package/src/migrate/sql/createTableSql.properties.ts +0 -38
  30. package/src/migrate/sql/createTableSql.test.ts +0 -74
  31. package/src/migrate/sql/createTableSql.ts +0 -53
  32. package/src/migrate/sql/createUniqueConstraintSql.ts +0 -27
  33. package/src/migrate/sql/dropSchemasSql.ts +0 -15
  34. package/src/migrate/sql/dropTableSql.ts +0 -13
  35. package/src/orm.query.test.ts +0 -28
  36. package/src/orm.ts +0 -370
  37. package/src/pull/index.ts +0 -1
  38. package/src/pull/introspect/getForeignKeys.ts +0 -64
  39. package/src/pull/introspect/getPrimaryKeys.ts +0 -26
  40. package/src/pull/introspect/getTables.ts +0 -51
  41. package/src/pull/introspect/getUniqueConstraints.ts +0 -39
  42. package/src/pull/parse/parseCreateUniqueIndexStatement.test.ts +0 -14
  43. package/src/pull/parse/parseCreateUniqueIndexStatement.ts +0 -19
  44. package/src/pull/pull.ts +0 -78
  45. package/src/pull/render/renderModel.test.ts +0 -144
  46. package/src/pull/render/renderModel.ts +0 -141
  47. package/src/pull/render/renderModelsIndex.ts +0 -24
  48. package/src/pull/render/renderRelations.ts +0 -77
  49. package/src/pull/render/renderRelationsIndex.ts +0 -24
  50. package/src/pull/types/ColumnMeta.ts +0 -10
  51. package/src/pull/types/ForeignKey.ts +0 -6
  52. package/src/pull/types/PrimaryKey.ts +0 -6
  53. package/src/pull/types/UniqueConstraint.ts +0 -8
  54. package/src/pull/util/format.ts +0 -17
  55. package/src/pull/util/quote.ts +0 -7
  56. package/src/pull/util/unquote.ts +0 -9
  57. package/src/queries/clauses/IncludeClause.ts +0 -39
  58. package/src/queries/clauses/LateralByClause.ts +0 -4
  59. package/src/queries/clauses/ReturningClause.ts +0 -7
  60. package/src/queries/clauses/SelectClause.ts +0 -7
  61. package/src/queries/clauses/WhereClause.ts +0 -16
  62. package/src/queries/clauses/helpers/OptionalColumn.ts +0 -18
  63. package/src/queries/clauses/helpers/OptionalParams.ts +0 -14
  64. package/src/queries/clauses/helpers/RequiredColumn.ts +0 -8
  65. package/src/queries/clauses/helpers/RequiredParams.ts +0 -14
  66. package/src/queries/clauses/include/IncludedRelationModel.ts +0 -13
  67. package/src/queries/clauses/include/IncludedRelationName.ts +0 -11
  68. package/src/queries/clauses/include/IncludedRelationQuery.ts +0 -20
  69. package/src/queries/clauses/where/buildWhereClause.ts +0 -121
  70. package/src/queries/clauses/where/buildWhereClauses.test.ts +0 -145
  71. package/src/queries/clauses/where/buildWhereClauses.ts +0 -45
  72. package/src/queries/clauses/where/operators.ts +0 -13
  73. package/src/queries/clauses/where/types/WhereClauseValue.ts +0 -39
  74. package/src/queries/count/buildCount.ts +0 -77
  75. package/src/queries/count/countToSql.ts +0 -66
  76. package/src/queries/count/tests/count.test.ts +0 -35
  77. package/src/queries/count/types/BaseCountParams.ts +0 -11
  78. package/src/queries/count/types/CountBuilder.ts +0 -45
  79. package/src/queries/count/types/CountParams.ts +0 -27
  80. package/src/queries/count.ts +0 -33
  81. package/src/queries/create/buildCreate.ts +0 -67
  82. package/src/queries/create/createResultSchema.ts +0 -24
  83. package/src/queries/create/createToSql.ts +0 -44
  84. package/src/queries/create/tests/createMany.varied-keys.test.ts +0 -28
  85. package/src/queries/create/tests/createOne.test-d.ts +0 -116
  86. package/src/queries/create/tests/createOne.test.ts +0 -197
  87. package/src/queries/create/types/BaseCreateManyParams.ts +0 -7
  88. package/src/queries/create/types/BaseCreateOneParams.ts +0 -7
  89. package/src/queries/create/types/CreateManyParams.ts +0 -15
  90. package/src/queries/create/types/CreateManyResult.ts +0 -17
  91. package/src/queries/create/types/CreateOneParams.ts +0 -22
  92. package/src/queries/create/types/CreateOneResult.ts +0 -17
  93. package/src/queries/createMany.ts +0 -38
  94. package/src/queries/createOne.ts +0 -27
  95. package/src/queries/delete/buildDelete.ts +0 -56
  96. package/src/queries/delete/deleteResultSchema.ts +0 -23
  97. package/src/queries/delete/deleteToSql.ts +0 -48
  98. package/src/queries/delete/tests/deleteOne.test.ts +0 -108
  99. package/src/queries/delete/types/BaseDeleteParams.ts +0 -9
  100. package/src/queries/delete/types/DeleteManyResult.ts +0 -16
  101. package/src/queries/delete/types/DeleteOneResult.ts +0 -16
  102. package/src/queries/delete/types/DeleteParams.ts +0 -12
  103. package/src/queries/deleteMany.ts +0 -33
  104. package/src/queries/deleteOne.ts +0 -32
  105. package/src/queries/find/buildFind.ts +0 -138
  106. package/src/queries/find/findResultSchema.ts +0 -32
  107. package/src/queries/find/findToSql.test.ts +0 -123
  108. package/src/queries/find/findToSql.ts +0 -141
  109. package/src/queries/find/getIncludedManyToManyRelations.ts +0 -49
  110. package/src/queries/find/getIncludedOneToManyRelations.ts +0 -44
  111. package/src/queries/find/tests/findMany.include.test.ts +0 -107
  112. package/src/queries/find/tests/findMany.limit.test-d.ts +0 -75
  113. package/src/queries/find/tests/findMany.limit.test.ts +0 -176
  114. package/src/queries/find/tests/findMany.nullable-relations.test.ts +0 -127
  115. package/src/queries/find/tests/findMany.orderBy.test-d.ts +0 -84
  116. package/src/queries/find/tests/findMany.orderBy.test.ts +0 -184
  117. package/src/queries/find/tests/findMany.select.test-d.ts +0 -117
  118. package/src/queries/find/tests/findMany.select.test.ts +0 -188
  119. package/src/queries/find/tests/findMany.too-deep.test-d.ts +0 -154
  120. package/src/queries/find/tests/findMany.where.test-d.ts +0 -85
  121. package/src/queries/find/tests/findMany.where.test.ts +0 -76
  122. package/src/queries/find/tests/middleware.find.where.test.ts +0 -467
  123. package/src/queries/find/types/BaseFindParams.ts +0 -18
  124. package/src/queries/find/types/FindBuilder.ts +0 -73
  125. package/src/queries/find/types/FindManyParams.ts +0 -24
  126. package/src/queries/find/types/FindManyResult.ts +0 -13
  127. package/src/queries/find/types/FindOneParams.ts +0 -17
  128. package/src/queries/find/types/FindOneResult.ts +0 -50
  129. package/src/queries/findMany.ts +0 -134
  130. package/src/queries/findOne.ts +0 -30
  131. package/src/queries/middleware/Middleware.ts +0 -53
  132. package/src/queries/middleware/ValuesMiddleware.ts +0 -9
  133. package/src/queries/middleware/WhereMiddleware.ts +0 -16
  134. package/src/queries/update/buildUpdate.ts +0 -76
  135. package/src/queries/update/tests/updateOne.test.ts +0 -118
  136. package/src/queries/update/types/BaseUpdateParams.ts +0 -10
  137. package/src/queries/update/types/UpdateManyResult.ts +0 -16
  138. package/src/queries/update/types/UpdateOneResult.ts +0 -16
  139. package/src/queries/update/types/UpdateParams.ts +0 -14
  140. package/src/queries/update/types/UpdateValues.ts +0 -12
  141. package/src/queries/update/updateResultSchema.ts +0 -23
  142. package/src/queries/update/updateToSql.ts +0 -43
  143. package/src/queries/updateMany.ts +0 -33
  144. package/src/queries/updateOne.ts +0 -33
  145. package/src/queries/util/hasConditions.test.ts +0 -36
  146. package/src/queries/util/hasConditions.ts +0 -14
  147. package/src/queries/util/rowToObject.test.ts +0 -76
  148. package/src/queries/util/rowToObject.ts +0 -13
  149. package/src/queries/util/tableAlias.test.ts +0 -20
  150. package/src/queries/util/tableAlias.ts +0 -10
  151. package/src/schema/populate/composeMiddleware.ts +0 -51
  152. package/src/schema/populate/populateConfiguration.ts +0 -48
  153. package/src/schema/populate/populateModel.ts +0 -98
  154. package/src/schema/populate/suggestedColumnSchema.ts +0 -62
  155. package/src/schema/types/base/BaseColumn.ts +0 -10
  156. package/src/schema/types/base/BaseConfiguration.ts +0 -14
  157. package/src/schema/types/base/BaseModel.ts +0 -12
  158. package/src/schema/types/base/BaseModels.ts +0 -3
  159. package/src/schema/types/base/BaseOrm.ts +0 -8
  160. package/src/schema/types/base/BaseRelation.ts +0 -19
  161. package/src/schema/types/base/BaseRelations.ts +0 -3
  162. package/src/schema/types/constraints/ForeignKey.ts +0 -13
  163. package/src/schema/types/constraints/UniqueConstraint.ts +0 -9
  164. package/src/schema/types/helpers/ColumnName.ts +0 -6
  165. package/src/schema/types/helpers/ColumnType.ts +0 -23
  166. package/src/schema/types/helpers/Columns.ts +0 -3
  167. package/src/schema/types/helpers/HasDefault.ts +0 -11
  168. package/src/schema/types/helpers/IsNullable.ts +0 -7
  169. package/src/schema/types/helpers/IsProvided.ts +0 -8
  170. package/src/schema/types/helpers/IsSerial.ts +0 -10
  171. package/src/schema/types/helpers/ModelName.ts +0 -6
  172. package/src/schema/types/loose/LooseColumnDefinition.ts +0 -80
  173. package/src/schema/types/loose/LooseModelDefinition.ts +0 -47
  174. package/src/schema/types/loose/LooseModelDefinitions.ts +0 -3
  175. package/src/schema/types/loose/LooseRelationDefinition.ts +0 -10
  176. package/src/schema/types/loose/LooseRelationsDefinition.ts +0 -8
  177. package/src/schema/types/loose/LooseRelationsDefinitions.ts +0 -7
  178. package/src/schema/types/postgres/DataType.ts +0 -65
  179. package/src/schema/types/relations/ManyToManyRelation.ts +0 -15
  180. package/src/schema/types/relations/ManyToOneRelation.ts +0 -14
  181. package/src/schema/types/relations/OneToManyRelation.ts +0 -12
  182. package/src/schema/types/strict/ColumnDefinition.ts +0 -81
  183. package/src/schema/types/strict/ModelDefinition.ts +0 -47
  184. package/src/schema/types/strict/ModelDefinitions.ts +0 -3
  185. package/src/schema/types/strict/RelationDefinition.ts +0 -13
  186. package/src/schema/types/strict/RelationsDefinition.ts +0 -8
  187. package/src/schema/types/strict/RelationsDefinitions.ts +0 -7
  188. package/src/schema/validate/validateConfiguration.ts +0 -9
  189. package/src/schema/validate/validateModel.ts +0 -32
  190. package/src/sql/SQLStatement.test.ts +0 -112
  191. package/src/sql/SQLStatement.ts +0 -86
  192. package/src/sql/index.ts +0 -2
  193. package/src/sql/sql.ts +0 -47
  194. package/src/test/db/index.ts +0 -27
  195. package/src/test/db/models/foo.model.ts +0 -24
  196. package/src/test/db/models/foo.relations.ts +0 -4
  197. package/src/test/db/models/post.model.ts +0 -34
  198. package/src/test/db/models/post.relations.ts +0 -21
  199. package/src/test/db/models/tenant.model.ts +0 -14
  200. package/src/test/db/models/tenant.relations.ts +0 -22
  201. package/src/test/db/models/tenantUser.model.ts +0 -23
  202. package/src/test/db/models/tenantUser.relations.ts +0 -15
  203. package/src/test/db/models/user.model.ts +0 -29
  204. package/src/test/db/models/user.relations.ts +0 -38
  205. package/src/test/db/models.ts +0 -15
  206. package/src/test/db/relations.ts +0 -13
  207. package/src/test/gen/column.ts +0 -39
  208. package/src/test/gen/index.ts +0 -2
  209. package/src/test/gen/model.ts +0 -58
  210. package/src/test/gen/sqldate.ts +0 -8
  211. package/src/test/globalSetup.ts +0 -6
  212. package/src/test/seed/index.ts +0 -75
  213. package/src/test/util/withRollback.ts +0 -18
  214. package/src/test/util/withTransaction.ts +0 -19
  215. package/src/types/ColumnName.ts +0 -6
  216. package/src/types/ColumnType.ts +0 -20
  217. package/src/types/Configuration.ts +0 -21
  218. package/src/types/ModelType.ts +0 -20
  219. package/src/types/util/DeepRequired.ts +0 -7
  220. package/src/types/util/DisallowExtraKeys.ts +0 -5
  221. package/src/types/util/NonEmptyArray.ts +0 -1
  222. package/src/types/util/Simplify.ts +0 -8
  223. package/src/util/ensureArray.ts +0 -4
  224. package/src/util/interleave.test.ts +0 -35
  225. package/src/util/interleave.ts +0 -8
  226. package/tsconfig.json +0 -18
  227. 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
- };