@casekit/orm2 0.0.0-20250331181319 → 0.0.0

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 (94) hide show
  1. package/build/builders/buildCount.d.ts +2 -1
  2. package/build/builders/buildCount.js +5 -8
  3. package/build/builders/buildCount.test.js +5 -5
  4. package/build/builders/buildCreate.d.ts +2 -1
  5. package/build/builders/buildCreate.js +6 -3
  6. package/build/builders/buildCreate.test.js +4 -4
  7. package/build/builders/buildDelete.d.ts +2 -1
  8. package/build/builders/buildDelete.js +2 -2
  9. package/build/builders/buildDelete.test.js +8 -8
  10. package/build/builders/buildFind.d.ts +2 -1
  11. package/build/builders/buildFind.js +5 -8
  12. package/build/builders/buildFind.test.js +4 -4
  13. package/build/builders/buildUpdate.d.ts +2 -1
  14. package/build/builders/buildUpdate.js +6 -3
  15. package/build/builders/buildUpdate.test.js +8 -8
  16. package/build/builders/buildWhere.d.ts +2 -1
  17. package/build/builders/buildWhere.js +30 -8
  18. package/build/builders/buildWhere.test.js +39 -24
  19. package/build/connection.d.ts +2 -2
  20. package/build/index.d.ts +1 -1
  21. package/build/index.js +1 -1
  22. package/build/orm.count.d.ts +2 -10
  23. package/build/orm.count.js +2 -11
  24. package/build/orm.createMany.d.ts +2 -1
  25. package/build/orm.createMany.js +2 -2
  26. package/build/orm.createOne.d.ts +2 -1
  27. package/build/orm.createOne.js +2 -2
  28. package/build/orm.d.ts +2 -2
  29. package/build/orm.deleteMany.d.ts +2 -1
  30. package/build/orm.deleteMany.js +2 -2
  31. package/build/orm.deleteOne.d.ts +2 -1
  32. package/build/orm.deleteOne.js +2 -2
  33. package/build/orm.findMany.d.ts +2 -1
  34. package/build/orm.findMany.js +3 -3
  35. package/build/orm.findOne.d.ts +2 -1
  36. package/build/orm.findOne.js +11 -19
  37. package/build/orm.js +13 -13
  38. package/build/orm.restrict.d.ts +2 -1
  39. package/build/orm.restrict.js +2 -2
  40. package/build/orm.updateMany.d.ts +2 -1
  41. package/build/orm.updateMany.js +3 -3
  42. package/build/orm.updateOne.d.ts +2 -1
  43. package/build/orm.updateOne.js +2 -2
  44. package/build/tests/orm.findMany.includeManyToOne.test.js +21 -5
  45. package/build/tests/orm.findOne.includeManyToMany.test.js +270 -0
  46. package/build/tests/orm.findOne.includeManyToOne.test.js +280 -0
  47. package/build/tests/orm.findOne.includeOneToMany.test.js +454 -0
  48. package/build/tests/orm.findOne.select.test.js +205 -0
  49. package/build/tests/orm.findOne.where.test.js +471 -0
  50. package/build/tests/orm.middleware.findOne.test.d.ts +1 -0
  51. package/build/tests/orm.middleware.set.test.d.ts +1 -0
  52. package/build/tests/orm.middleware.set.test.js +100 -0
  53. package/build/tests/orm.middleware.updateMany.test.d.ts +1 -0
  54. package/build/tests/orm.middleware.updateOne.test.d.ts +1 -0
  55. package/build/tests/orm.middleware.values.test.d.ts +1 -0
  56. package/build/tests/orm.middleware.values.test.js +126 -0
  57. package/build/tests/orm.middleware.where.test.d.ts +1 -0
  58. package/build/tests/orm.middleware.where.test.js +1054 -0
  59. package/build/tests/util/db.d.ts +52 -70
  60. package/build/types/CreateOneResult.d.ts +6 -2
  61. package/build/types/CreateOneResult.test-d.js +3 -0
  62. package/build/types/Middleware.d.ts +14 -0
  63. package/build/types/Middleware.js +37 -1
  64. package/build/types/WhereClause.d.ts +8 -8
  65. package/build/util/applySetMiddleware.d.ts +5 -0
  66. package/build/util/applySetMiddleware.js +7 -0
  67. package/build/util/applyValuesMiddleware.d.ts +5 -0
  68. package/build/util/applyValuesMiddleware.js +7 -0
  69. package/build/util/applyWhereMiddleware.d.ts +5 -0
  70. package/build/util/applyWhereMiddleware.js +7 -0
  71. package/build/util/applyWhereMiddleware.test.d.ts +1 -0
  72. package/build/util/applyWhereMiddleware.test.js +88 -0
  73. package/build/util/resultSchema.d.ts +6 -6
  74. package/package.json +23 -24
  75. /package/build/tests/{orm.count.middleware.test.d.ts → orm.findOne.includeManyToMany.test.d.ts} +0 -0
  76. /package/build/tests/{orm.createMany.middleware.test.d.ts → orm.findOne.includeManyToOne.test.d.ts} +0 -0
  77. /package/build/tests/{orm.createOne.middleware.test.d.ts → orm.findOne.includeOneToMany.test.d.ts} +0 -0
  78. /package/build/tests/{orm.deleteMany.middleware.test.d.ts → orm.findOne.select.test.d.ts} +0 -0
  79. /package/build/tests/{orm.deleteOne.middleware.test.d.ts → orm.findOne.where.test.d.ts} +0 -0
  80. /package/build/tests/{orm.findMany.middleware.test.d.ts → orm.middleware.count.test.d.ts} +0 -0
  81. /package/build/tests/{orm.count.middleware.test.js → orm.middleware.count.test.js} +0 -0
  82. /package/build/tests/{orm.findOne.middleware.test.d.ts → orm.middleware.createMany.test.d.ts} +0 -0
  83. /package/build/tests/{orm.createMany.middleware.test.js → orm.middleware.createMany.test.js} +0 -0
  84. /package/build/tests/{orm.updateMany.middleware.test.d.ts → orm.middleware.createOne.test.d.ts} +0 -0
  85. /package/build/tests/{orm.createOne.middleware.test.js → orm.middleware.createOne.test.js} +0 -0
  86. /package/build/tests/{orm.updateOne.middleware.test.d.ts → orm.middleware.deleteMany.test.d.ts} +0 -0
  87. /package/build/tests/{orm.deleteMany.middleware.test.js → orm.middleware.deleteMany.test.js} +0 -0
  88. /package/build/{types/BaseFindParams.d.ts → tests/orm.middleware.deleteOne.test.d.ts} +0 -0
  89. /package/build/tests/{orm.deleteOne.middleware.test.js → orm.middleware.deleteOne.test.js} +0 -0
  90. /package/build/{types/BaseFindParams.js → tests/orm.middleware.findMany.test.d.ts} +0 -0
  91. /package/build/tests/{orm.findMany.middleware.test.js → orm.middleware.findMany.test.js} +0 -0
  92. /package/build/tests/{orm.findOne.middleware.test.js → orm.middleware.findOne.test.js} +0 -0
  93. /package/build/tests/{orm.updateMany.middleware.test.js → orm.middleware.updateMany.test.js} +0 -0
  94. /package/build/tests/{orm.updateOne.middleware.test.js → orm.middleware.updateOne.test.js} +0 -0
@@ -24,131 +24,146 @@ describe("buildWhere", () => {
24
24
  };
25
25
  test("builds simple equality clause", () => {
26
26
  const where = { id: 1 };
27
- const result = buildWhere(db.config, table, where);
27
+ const result = buildWhere(db.config, [], table, where);
28
28
  expect(result.text).toBe('"u"."id" = $1');
29
29
  expect(result.values).toEqual([1]);
30
30
  });
31
31
  test("builds IS NULL clause", () => {
32
32
  const where = { name: null };
33
- const result = buildWhere(db.config, table, where);
33
+ const result = buildWhere(db.config, [], table, where);
34
34
  expect(result.text).toBe('"u"."name" IS NULL');
35
35
  });
36
36
  test("builds boolean clauses", () => {
37
37
  const whereTrue = { active: true };
38
38
  const whereFalse = { active: false };
39
- expect(buildWhere(db.config, table, whereTrue).text).toBe('"u"."active" IS TRUE');
40
- expect(buildWhere(db.config, table, whereFalse).text).toBe('"u"."active" IS FALSE');
39
+ expect(buildWhere(db.config, [], table, whereTrue).text).toBe('"u"."active" IS TRUE');
40
+ expect(buildWhere(db.config, [], table, whereFalse).text).toBe('"u"."active" IS FALSE');
41
41
  });
42
42
  test("builds AND clause", () => {
43
43
  const where = { [$and]: [{ id: 1 }, { name: "test" }] };
44
- const result = buildWhere(db.config, table, where);
44
+ const result = buildWhere(db.config, [], table, where);
45
45
  expect(result.text).toBe('("u"."id" = $1 AND "u"."name" = $2)');
46
46
  expect(result.values).toEqual([1, "test"]);
47
47
  });
48
48
  test("builds OR clause", () => {
49
49
  const where = { [$or]: [{ id: 1 }, { name: "test" }] };
50
- const result = buildWhere(db.config, table, where);
50
+ const result = buildWhere(db.config, [], table, where);
51
51
  expect(result.text).toBe('("u"."id" = $1 OR "u"."name" = $2)');
52
52
  expect(result.values).toEqual([1, "test"]);
53
53
  });
54
54
  test("builds NOT clause", () => {
55
55
  const where = { [$not]: { active: true } };
56
- const result = buildWhere(db.config, table, where);
56
+ const result = buildWhere(db.config, [], table, where);
57
57
  expect(result.text).toBe('NOT "u"."active" IS TRUE');
58
58
  });
59
59
  test("throws error for unrecognized field", () => {
60
60
  const where = { unknownField: 1 };
61
- expect(() => buildWhere(db.config, table, where)).toThrow("Unrecognised field");
61
+ expect(() => buildWhere(db.config, [], table, where)).toThrow("Unrecognised field");
62
62
  });
63
63
  test("handles Date objects", () => {
64
64
  const date = new Date("2023-01-01");
65
65
  const where = { createdAt: date };
66
- const result = buildWhere(db.config, table, where);
66
+ const result = buildWhere(db.config, [], table, where);
67
67
  expect(result.text).toBe('"u"."created_at" = $1');
68
68
  expect(result.values).toEqual([date]);
69
69
  });
70
70
  test("builds $eq operator clause", () => {
71
71
  const where = { id: { [$eq]: 1 } };
72
- const result = buildWhere(db.config, table, where);
72
+ const result = buildWhere(db.config, [], table, where);
73
73
  expect(result.text).toBe('"u"."id" = $1');
74
74
  expect(result.values).toEqual([1]);
75
75
  });
76
76
  test("builds $gt operator clause", () => {
77
77
  const where = { id: { [$gt]: 1 } };
78
- const result = buildWhere(db.config, table, where);
78
+ const result = buildWhere(db.config, [], table, where);
79
79
  expect(result.text).toBe('"u"."id" > $1');
80
80
  expect(result.values).toEqual([1]);
81
81
  });
82
82
  test("builds $gte operator clause", () => {
83
83
  const where = { id: { [$gte]: 1 } };
84
- const result = buildWhere(db.config, table, where);
84
+ const result = buildWhere(db.config, [], table, where);
85
85
  expect(result.text).toBe('"u"."id" >= $1');
86
86
  expect(result.values).toEqual([1]);
87
87
  });
88
88
  test("builds $ilike operator clause", () => {
89
89
  const where = { name: { [$ilike]: "%test%" } };
90
- const result = buildWhere(db.config, table, where);
90
+ const result = buildWhere(db.config, [], table, where);
91
91
  expect(result.text).toBe('"u"."name" ILIKE $1');
92
92
  expect(result.values).toEqual(["%test%"]);
93
93
  });
94
94
  test("builds $is operator clause", () => {
95
95
  const where = { name: { [$is]: null } };
96
- const result = buildWhere(db.config, table, where);
96
+ const result = buildWhere(db.config, [], table, where);
97
97
  expect(result.text).toBe('"u"."name" IS NULL');
98
98
  expect(result.values).toEqual([]);
99
99
  });
100
100
  test("builds $not operator clause", () => {
101
101
  const where = { name: { [$not]: null } };
102
- const result = buildWhere(db.config, table, where);
102
+ const result = buildWhere(db.config, [], table, where);
103
103
  expect(result.text).toBe('"u"."name" IS NOT NULL');
104
104
  expect(result.values).toEqual([]);
105
105
  });
106
106
  test("builds $like operator clause", () => {
107
107
  const where = { name: { [$like]: "%test%" } };
108
- const result = buildWhere(db.config, table, where);
108
+ const result = buildWhere(db.config, [], table, where);
109
109
  expect(result.text).toBe('"u"."name" LIKE $1');
110
110
  expect(result.values).toEqual(["%test%"]);
111
111
  });
112
112
  test("builds $lt operator clause", () => {
113
113
  const where = { id: { [$lt]: 1 } };
114
- const result = buildWhere(db.config, table, where);
114
+ const result = buildWhere(db.config, [], table, where);
115
115
  expect(result.text).toBe('"u"."id" < $1');
116
116
  expect(result.values).toEqual([1]);
117
117
  });
118
118
  test("builds $lte operator clause", () => {
119
119
  const where = { id: { [$lte]: 1 } };
120
- const result = buildWhere(db.config, table, where);
120
+ const result = buildWhere(db.config, [], table, where);
121
121
  expect(result.text).toBe('"u"."id" <= $1');
122
122
  expect(result.values).toEqual([1]);
123
123
  });
124
124
  test("builds $ne operator clause", () => {
125
125
  const where = { id: { [$ne]: 1 } };
126
- const result = buildWhere(db.config, table, where);
126
+ const result = buildWhere(db.config, [], table, where);
127
127
  expect(result.text).toBe('"u"."id" != $1');
128
128
  expect(result.values).toEqual([1]);
129
129
  });
130
130
  test("builds $not operator clause with null", () => {
131
131
  const where = { name: { [$not]: null } };
132
- const result = buildWhere(db.config, table, where);
132
+ const result = buildWhere(db.config, [], table, where);
133
133
  expect(result.text).toBe('"u"."name" IS NOT NULL');
134
134
  });
135
135
  test("throws error when $not operator receives non-null or boolean value", () => {
136
136
  const where = { name: { [$not]: "test" } };
137
- expect(() => buildWhere(db.config, table, where)).toThrow("Invalid value passed to $not operator");
137
+ expect(() => buildWhere(db.config, [], table, where)).toThrow("Invalid value passed to $not operator");
138
138
  });
139
139
  test("builds $in operator clause", () => {
140
140
  const where = { id: { [$in]: [1, 2, 3] } };
141
- const result = buildWhere(db.config, table, where);
141
+ const result = buildWhere(db.config, [], table, where);
142
142
  expect(result.text).toBe('"u"."id" IN ($1, $2, $3)');
143
143
  expect(result.values).toEqual([1, 2, 3]);
144
144
  });
145
145
  test("throws error when $in operator receives non-array value", () => {
146
146
  const where = { id: { [$in]: 1 } };
147
- expect(() => buildWhere(db.config, table, where)).toThrow("Non-array passed to IN clause");
147
+ expect(() => buildWhere(db.config, [], table, where)).toThrow("Non-array passed to IN clause");
148
148
  });
149
149
  test("throws error for unrecognised operator", () => {
150
150
  const unknownSymbol = Symbol("unknown");
151
151
  const where = { id: { [unknownSymbol]: 1 } };
152
- expect(() => buildWhere(db.config, table, where)).toThrow("Unrecognised query operator or value");
152
+ expect(() => buildWhere(db.config, [], table, where)).toThrow("Unrecognised query operator or value");
153
+ });
154
+ test("applies where middleware", () => {
155
+ const middleware = [
156
+ {
157
+ where: (_config, _modelName, where) => {
158
+ // Add a soft delete filter
159
+ return { active: true, ...where };
160
+ },
161
+ },
162
+ ];
163
+ const where = { id: 1 };
164
+ const result = buildWhere(db.config, middleware, table, where);
165
+ // Should include both the original where clause and the middleware-added clause
166
+ expect(result.text).toBe('"u"."active" IS TRUE AND "u"."id" = $1');
167
+ expect(result.values).toEqual([1]);
153
168
  });
154
169
  });
@@ -11,7 +11,7 @@ export declare class Connection {
11
11
  constructor(config: NormalizedConfig);
12
12
  connect(): Promise<void>;
13
13
  close(): Promise<void>;
14
- query<T extends QueryResultRow>(sql: SQLStatement): Promise<pg.QueryResult<T>>;
14
+ query<T extends QueryResultRow>(sql: SQLStatement): Promise<import("pg").QueryResult<T>>;
15
15
  startTransaction(): Promise<Transaction>;
16
16
  isTransaction(): boolean;
17
17
  }
@@ -22,7 +22,7 @@ export declare class Transaction extends Connection {
22
22
  constructor(config: NormalizedConfig, client?: pg.Client | null, pool?: pg.Pool | null, poolClient?: pg.PoolClient | null, nested?: boolean);
23
23
  connect(): Promise<void>;
24
24
  close(): Promise<void>;
25
- query<T extends QueryResultRow>(sql: SQLStatement): Promise<pg.QueryResult<T>>;
25
+ query<T extends QueryResultRow>(sql: SQLStatement): Promise<import("pg").QueryResult<T>>;
26
26
  startTransaction(): Promise<Transaction>;
27
27
  begin(): Promise<void>;
28
28
  rollback(): Promise<void>;
package/build/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export * as op from "./operators.js";
1
+ export * from "./operators.js";
2
2
  export { orm, type Orm } from "./orm.js";
3
3
  export type { Config, FieldDefinition, ForeignKeyDefinition, ModelDefinition, ModelDefinitions, ModelType, PostgresDataTypes, RelationDefinition, UniqueConstraintDefinition, } from "@casekit/orm2-schema";
4
4
  export type { FindParams } from "./types/FindParams.js";
package/build/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /* v8 ignore start */
2
- export * as op from "./operators.js";
2
+ export * from "./operators.js";
3
3
  export { orm } from "./orm.js";
4
4
  export { sql, SQLStatement } from "@casekit/sql";
5
5
  /* v8 ignore stop */
@@ -2,13 +2,5 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinition, OperatorDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { CountParams } from "./types/CountParams.js";
5
- /**
6
- * Executes a count query against the database.
7
- *
8
- * @param config The normalized ORM configuration
9
- * @param conn The database connection
10
- * @param modelName The name of the model to count records for
11
- * @param query Parameters for the count query, including where and include clauses
12
- * @returns The number of matching records
13
- */
14
- export declare const count: (config: NormalizedConfig, conn: Connection, modelName: string, query: CountParams<Record<string, Required<ModelDefinition>>, OperatorDefinitions, string>) => Promise<number>;
5
+ import { Middleware } from "./types/Middleware.js";
6
+ export declare const count: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: CountParams<Record<string, Required<ModelDefinition>>, OperatorDefinitions, string>) => Promise<number>;
@@ -1,17 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { buildCount } from "./builders/buildCount.js";
3
3
  import { countToSql } from "./sql/countToSql.js";
4
- /**
5
- * Executes a count query against the database.
6
- *
7
- * @param config The normalized ORM configuration
8
- * @param conn The database connection
9
- * @param modelName The name of the model to count records for
10
- * @param query Parameters for the count query, including where and include clauses
11
- * @returns The number of matching records
12
- */
13
- export const count = async (config, conn, modelName, query) => {
14
- const builder = buildCount(config, modelName, query);
4
+ export const count = async (config, conn, middleware, modelName, query) => {
5
+ const builder = buildCount(config, middleware, modelName, query);
15
6
  const statement = countToSql(builder);
16
7
  config.logger.info("Executing count", {
17
8
  sql: statement.pretty,
@@ -2,4 +2,5 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { CreateManyParams } from "./types/CreateManyParams.js";
5
- export declare const createMany: (config: NormalizedConfig, conn: Connection, modelName: string, query: CreateManyParams<ModelDefinitions, string>) => Promise<Record<string, unknown>[] | number>;
5
+ import { Middleware } from "./types/Middleware.js";
6
+ export declare const createMany: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: CreateManyParams<ModelDefinitions, string>) => Promise<Record<string, unknown>[] | number>;
@@ -1,11 +1,11 @@
1
1
  import { buildCreate } from "./builders/buildCreate.js";
2
2
  import { createToSql } from "./sql/createToSql.js";
3
3
  import { rowToObject } from "./util/rowToObject.js";
4
- export const createMany = async (config, conn, modelName, query) => {
4
+ export const createMany = async (config, conn, middleware, modelName, query) => {
5
5
  if (query.values.length === 0) {
6
6
  return query.returning ? [] : 0;
7
7
  }
8
- const builder = buildCreate(config, modelName, query);
8
+ const builder = buildCreate(config, middleware, modelName, query);
9
9
  const statement = createToSql(builder);
10
10
  config.logger.info("Executing createMany", {
11
11
  sql: statement.pretty,
@@ -2,4 +2,5 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { CreateOneParams } from "./types/CreateOneParams.js";
5
- export declare const createOne: (config: NormalizedConfig, conn: Connection, modelName: string, { values, ...query }: CreateOneParams<ModelDefinitions, string>) => Promise<Record<string, unknown> | number | null>;
5
+ import { Middleware } from "./types/Middleware.js";
6
+ export declare const createOne: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, { values, ...query }: CreateOneParams<ModelDefinitions, string>) => Promise<Record<string, unknown> | number | null>;
@@ -1,8 +1,8 @@
1
1
  import { buildCreate } from "./builders/buildCreate.js";
2
2
  import { createToSql } from "./sql/createToSql.js";
3
3
  import { rowToObject } from "./util/rowToObject.js";
4
- export const createOne = async (config, conn, modelName, { values, ...query }) => {
5
- const builder = buildCreate(config, modelName, {
4
+ export const createOne = async (config, conn, middleware, modelName, { values, ...query }) => {
5
+ const builder = buildCreate(config, middleware, modelName, {
6
6
  ...query,
7
7
  values: [values],
8
8
  });
package/build/orm.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { QueryResultRow } from "pg";
2
2
  import { DeepReadonly } from "ts-essentials";
3
- import { ZodSchema } from "zod";
3
+ import { ZodType } from "zod";
4
4
  import { NormalizedConfig } from "@casekit/orm2-config";
5
5
  import { Config, ModelDefinitions, ModelName, OperatorDefinitions } from "@casekit/orm2-schema";
6
6
  import { SQLStatement } from "@casekit/sql";
@@ -65,7 +65,7 @@ export declare class Orm<const C extends Config = Config, const Models extends M
65
65
  * SELECT foo FROM table WHERE foo = ${value}
66
66
  * `;
67
67
  */
68
- query<const ResultType extends QueryResultRow = QueryResultRow>(schema: ZodSchema<ResultType>): (fragments: TemplateStringsArray, ...values: unknown[]) => Promise<ResultType[]>;
68
+ query<const ResultType extends QueryResultRow = QueryResultRow>(schema: ZodType<ResultType>): (fragments: TemplateStringsArray, ...values: unknown[]) => Promise<ResultType[]>;
69
69
  /**
70
70
  * const statement = sql<{ one: number }>`SELECT 1 as one`;
71
71
  * await db.query(statement);
@@ -2,4 +2,5 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinitions, OperatorDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { DeleteParams } from "./types/DeleteParams.js";
5
- export declare const deleteMany: (config: NormalizedConfig, conn: Connection, modelName: string, query: DeleteParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown>[] | number>;
5
+ import { Middleware } from "./types/Middleware.js";
6
+ export declare const deleteMany: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: DeleteParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown>[] | number>;
@@ -1,8 +1,8 @@
1
1
  import { buildDelete } from "./builders/buildDelete.js";
2
2
  import { deleteToSql } from "./sql/deleteToSql.js";
3
3
  import { rowToObject } from "./util/rowToObject.js";
4
- export const deleteMany = async (config, conn, modelName, query) => {
5
- const builder = buildDelete(config, modelName, query);
4
+ export const deleteMany = async (config, conn, middleware, modelName, query) => {
5
+ const builder = buildDelete(config, middleware, modelName, query);
6
6
  const statement = deleteToSql(builder);
7
7
  config.logger.info("Executing deleteMany", {
8
8
  sql: statement.pretty,
@@ -2,4 +2,5 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinitions, OperatorDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { DeleteParams } from "./types/DeleteParams.js";
5
- export declare const deleteOne: (config: NormalizedConfig, conn: Connection, modelName: string, query: DeleteParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown> | number | null>;
5
+ import { Middleware } from "./types/Middleware.js";
6
+ export declare const deleteOne: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: DeleteParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown> | number | null>;
@@ -1,8 +1,8 @@
1
1
  import { buildDelete } from "./builders/buildDelete.js";
2
2
  import { deleteToSql } from "./sql/deleteToSql.js";
3
3
  import { rowToObject } from "./util/rowToObject.js";
4
- export const deleteOne = async (config, conn, modelName, query) => {
5
- const builder = buildDelete(config, modelName, query);
4
+ export const deleteOne = async (config, conn, middleware, modelName, query) => {
5
+ const builder = buildDelete(config, middleware, modelName, query);
6
6
  const statement = deleteToSql(builder);
7
7
  config.logger.info("Executing deleteOne", {
8
8
  sql: statement.pretty,
@@ -2,7 +2,8 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinition, OperatorDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { FindParams } from "./types/FindParams.js";
5
- export declare const findMany: (config: NormalizedConfig, conn: Connection, modelName: string, query: FindParams<Record<string, Required<ModelDefinition>>, OperatorDefinitions, string>, lateralBy?: {
5
+ import { Middleware } from "./types/Middleware.js";
6
+ export declare const findMany: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: FindParams<Record<string, Required<ModelDefinition>>, OperatorDefinitions, string>, lateralBy?: {
6
7
  field: string;
7
8
  values: unknown[];
8
9
  }[]) => Promise<Record<string, unknown>[]>;
@@ -6,8 +6,8 @@ import { findToSql } from "./sql/findToSql.js";
6
6
  import { getIncludedToManySubqueries } from "./util/getIncludedToManySubqueries.js";
7
7
  import { getLateralJoinValues } from "./util/getLateralJoinValues.js";
8
8
  import { rowToObject } from "./util/rowToObject.js";
9
- export const findMany = async (config, conn, modelName, query, lateralBy = []) => {
10
- const builder = buildFind(config, modelName, query, lateralBy);
9
+ export const findMany = async (config, conn, middleware, modelName, query, lateralBy = []) => {
10
+ const builder = buildFind(config, middleware, modelName, query, lateralBy);
11
11
  const statement = findToSql(builder);
12
12
  config.logger.info("Executing findMany", {
13
13
  sql: statement.pretty,
@@ -26,7 +26,7 @@ export const findMany = async (config, conn, modelName, query, lateralBy = []) =
26
26
  const lateralBy = getLateralJoinValues(results, dropRight(path, 1), from, to);
27
27
  // rather than awaiting the findMany query here, we'll push a promise
28
28
  // into an array that we can await in parallel later.
29
- const promise = findMany(config, conn, modelName, query, lateralBy).then((relationResults) => {
29
+ const promise = findMany(config, conn, middleware, modelName, query, lateralBy).then((relationResults) => {
30
30
  // we group the results by the hash of the 'to' columns so
31
31
  // we can find the right list of values for each result
32
32
  const lookup = groupBy(relationResults, (result) => hash(to.map((f) => result[f])));
@@ -2,4 +2,5 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinitions, OperatorDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { FindParams } from "./types/FindParams.js";
5
- export declare const findOne: (config: NormalizedConfig, conn: Connection, model: string, query: FindParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown>>;
5
+ import { Middleware } from "./types/Middleware.js";
6
+ export declare const findOne: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: FindParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown>>;
@@ -1,20 +1,12 @@
1
- import { buildFind } from "./builders/buildFind.js";
2
- import { findToSql } from "./sql/findToSql.js";
3
- import { rowToObject } from "./util/rowToObject.js";
4
- export const findOne = async (config, conn, model, query) => {
5
- const builder = buildFind(config, model, { ...query, limit: 2 });
6
- const statement = findToSql(builder);
7
- config.logger.info("Executing findOne", {
8
- sql: statement.pretty,
9
- values: statement.values,
10
- });
11
- return await conn.query(statement).then((res) => {
12
- if (res.rows.length === 0) {
13
- throw new Error("Expected one row, but found none");
14
- }
15
- if (res.rows.length > 1) {
16
- throw new Error("Expected one row, but found more");
17
- }
18
- return res.rows.map((row) => rowToObject(row, builder.columns))[0];
19
- });
1
+ import { findMany } from "./orm.findMany.js";
2
+ export const findOne = async (config, conn, middleware, modelName, query) => {
3
+ config.logger.info("Delegating findOne to findMany");
4
+ const results = await findMany(config, conn, middleware, modelName, query);
5
+ if (results.length === 0) {
6
+ throw new Error("Expected one row, but found none");
7
+ }
8
+ if (results.length > 1) {
9
+ throw new Error("Expected one row, but found more");
10
+ }
11
+ return results[0];
20
12
  };
package/build/orm.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * the general - and nowhere else in the project should be doing this.
9
9
  */
10
10
  import { mapValues, pick, pickBy } from "es-toolkit";
11
- import { ZodSchema, z } from "zod";
11
+ import { ZodType, z } from "zod";
12
12
  import { getModel, normalizeConfig, } from "@casekit/orm2-config";
13
13
  import { SQLStatement, sql } from "@casekit/sql";
14
14
  import { Connection } from "./connection.js";
@@ -43,7 +43,7 @@ export class Orm {
43
43
  async transact(fn, options = { rollback: false }) {
44
44
  const tx = await this._connection.startTransaction();
45
45
  try {
46
- const result = await fn(new Orm(this.config, tx));
46
+ const result = await fn(new Orm(this.config, tx, this._middleware));
47
47
  if (options.rollback) {
48
48
  await tx.rollback();
49
49
  }
@@ -78,7 +78,7 @@ export class Orm {
78
78
  // otherwise typescript goes absolutely haywire causing an OOM error
79
79
  return (await mw(db, modelName, query));
80
80
  }
81
- const result = await findOne(this.config, this._connection, modelName, query);
81
+ const result = await findOne(this.config, this._connection, this._middleware, modelName, query);
82
82
  const schema = findOneResultSchema(this.config, modelName, query);
83
83
  return schema.parse(result);
84
84
  }
@@ -90,7 +90,7 @@ export class Orm {
90
90
  // otherwise typescript goes absolutely haywire causing an OOM error
91
91
  return (await mw(db, modelName, query));
92
92
  }
93
- const result = await findMany(this.config, this._connection, modelName, query);
93
+ const result = await findMany(this.config, this._connection, this._middleware, modelName, query);
94
94
  const schema = findManyResultSchema(this.config, modelName, query);
95
95
  return schema.parse(result);
96
96
  }
@@ -102,7 +102,7 @@ export class Orm {
102
102
  // otherwise typescript goes absolutely haywire causing an OOM error
103
103
  return (await mw(db, modelName, query));
104
104
  }
105
- return await count(this.config, this._connection, modelName, query);
105
+ return await count(this.config, this._connection, this._middleware, modelName, query);
106
106
  }
107
107
  async createOne(modelName, query) {
108
108
  const [mw, next] = this.getNextMiddleware("createOne");
@@ -112,7 +112,7 @@ export class Orm {
112
112
  // otherwise typescript goes absolutely haywire causing an OOM error
113
113
  return (await mw(db, modelName, query));
114
114
  }
115
- const result = await createOne(this.config, this._connection, modelName, query);
115
+ const result = await createOne(this.config, this._connection, this._middleware, modelName, query);
116
116
  const schema = returningOneResultSchema(getModel(this.config.models, modelName), query.returning);
117
117
  return schema.parse(result);
118
118
  }
@@ -124,7 +124,7 @@ export class Orm {
124
124
  // otherwise typescript goes absolutely haywire causing an OOM error
125
125
  return (await mw(db, modelName, query));
126
126
  }
127
- const result = await createMany(this.config, this._connection, modelName, query);
127
+ const result = await createMany(this.config, this._connection, this._middleware, modelName, query);
128
128
  const schema = returningManyResultSchema(getModel(this.config.models, modelName), query.returning);
129
129
  return schema.parse(result);
130
130
  }
@@ -136,7 +136,7 @@ export class Orm {
136
136
  // otherwise typescript goes absolutely haywire causing an OOM error
137
137
  return (await mw(db, modelName, query));
138
138
  }
139
- const result = await updateOne(this.config, this._connection, modelName, query);
139
+ const result = await updateOne(this.config, this._connection, this._middleware, modelName, query);
140
140
  const schema = returningOneResultSchema(getModel(this.config.models, modelName), query.returning);
141
141
  return schema.parse(result);
142
142
  }
@@ -148,7 +148,7 @@ export class Orm {
148
148
  // otherwise typescript goes absolutely haywire causing an OOM error
149
149
  return (await mw(db, modelName, query));
150
150
  }
151
- const result = await updateMany(this.config, this._connection, modelName, query);
151
+ const result = await updateMany(this.config, this._connection, this._middleware, modelName, query);
152
152
  const schema = returningManyResultSchema(getModel(this.config.models, modelName), query.returning);
153
153
  return schema.parse(result);
154
154
  }
@@ -160,7 +160,7 @@ export class Orm {
160
160
  // otherwise typescript goes absolutely haywire causing an OOM error
161
161
  return (await mw(db, modelName, query));
162
162
  }
163
- const result = await deleteOne(this.config, this._connection, modelName, query);
163
+ const result = await deleteOne(this.config, this._connection, this._middleware, modelName, query);
164
164
  const schema = returningOneResultSchema(getModel(this.config.models, modelName), query.returning);
165
165
  return schema.parse(result);
166
166
  }
@@ -172,7 +172,7 @@ export class Orm {
172
172
  // otherwise typescript goes absolutely haywire causing an OOM error
173
173
  return (await mw(db, modelName, query));
174
174
  }
175
- const result = await deleteMany(this.config, this._connection, modelName, query);
175
+ const result = await deleteMany(this.config, this._connection, this._middleware, modelName, query);
176
176
  const schema = returningManyResultSchema(getModel(this.config.models, modelName), query.returning);
177
177
  return schema.parse(result);
178
178
  }
@@ -198,7 +198,7 @@ export class Orm {
198
198
  allowed.includes(r.model)),
199
199
  })),
200
200
  };
201
- return new Orm(config, this._connection);
201
+ return new Orm(config, this._connection, this._middleware);
202
202
  }
203
203
  /** Returns a new ORM instance with middleware applied.
204
204
  * The new ORM instance shares the same connection as
@@ -211,7 +211,7 @@ export class Orm {
211
211
  return new Orm(this.config, this._connection, middleware);
212
212
  }
213
213
  query(schemaOrStatementOrFragments, ...values) {
214
- if (schemaOrStatementOrFragments instanceof ZodSchema) {
214
+ if (schemaOrStatementOrFragments instanceof ZodType) {
215
215
  return this.queryWithSchema(schemaOrStatementOrFragments);
216
216
  }
217
217
  if (schemaOrStatementOrFragments instanceof SQLStatement) {
@@ -2,5 +2,6 @@ import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { Config, ModelName } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
4
  import { Orm } from "./orm.js";
5
+ import { Middleware } from "./types/Middleware.js";
5
6
  import { RestrictModels } from "./types/RestrictModels.js";
6
- export declare const restrict: <const C extends Config, const Allowed extends [...ModelName<C["models"]>[]]>(config: NormalizedConfig, allowed: string[], connection: Connection) => Orm<RestrictModels<C, Allowed[number]>>;
7
+ export declare const restrict: <const C extends Config, const Allowed extends [...ModelName<C["models"]>[]]>(config: NormalizedConfig, allowed: string[], connection: Connection, middleware: Middleware[]) => Orm<RestrictModels<C, Allowed[number]>>;
@@ -1,5 +1,5 @@
1
1
  import { Orm } from "./orm.js";
2
- export const restrict = (config, allowed, connection) => {
2
+ export const restrict = (config, allowed, connection, middleware) => {
3
3
  if (connection.isTransaction()) {
4
4
  throw new Error("Cannot create restricted ORM in a transaction");
5
5
  }
@@ -48,5 +48,5 @@ export const restrict = (config, allowed, connection) => {
48
48
  };
49
49
  }
50
50
  }, {});
51
- return new Orm({ ...config, models }, connection);
51
+ return new Orm({ ...config, models }, connection, middleware);
52
52
  };
@@ -1,5 +1,6 @@
1
1
  import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinitions, OperatorDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
+ import { Middleware } from "./types/Middleware.js";
4
5
  import { UpdateParams } from "./types/UpdateParams.js";
5
- export declare const updateMany: (config: NormalizedConfig, conn: Connection, modelName: string, query: UpdateParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown>[] | number>;
6
+ export declare const updateMany: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: UpdateParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown>[] | number>;
@@ -1,13 +1,13 @@
1
1
  import { buildUpdate } from "./builders/buildUpdate.js";
2
2
  import { updateToSql } from "./sql/updateToSql.js";
3
3
  import { rowToObject } from "./util/rowToObject.js";
4
- export const updateMany = async (config, conn, modelName, query) => {
4
+ export const updateMany = async (config, conn, middleware, modelName, query) => {
5
5
  if (Object.keys(query.set).length === 0) {
6
6
  throw new Error("Update requires at least one value to set");
7
7
  }
8
- const builder = buildUpdate(config, modelName, query);
8
+ const builder = buildUpdate(config, middleware, modelName, query);
9
9
  const statement = updateToSql(builder);
10
- config.logger.info("Executing updateOne", {
10
+ config.logger.info("Executing updateMany", {
11
11
  sql: statement.pretty,
12
12
  values: statement.values,
13
13
  });
@@ -1,5 +1,6 @@
1
1
  import { NormalizedConfig } from "@casekit/orm2-config";
2
2
  import { ModelDefinitions, OperatorDefinitions } from "@casekit/orm2-schema";
3
3
  import { Connection } from "./connection.js";
4
+ import { Middleware } from "./types/Middleware.js";
4
5
  import { UpdateParams } from "./types/UpdateParams.js";
5
- export declare const updateOne: (config: NormalizedConfig, conn: Connection, modelName: string, query: UpdateParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown> | number | null>;
6
+ export declare const updateOne: (config: NormalizedConfig, conn: Connection, middleware: Middleware[], modelName: string, query: UpdateParams<ModelDefinitions, OperatorDefinitions, string>) => Promise<Record<string, unknown> | number | null>;
@@ -1,11 +1,11 @@
1
1
  import { buildUpdate } from "./builders/buildUpdate.js";
2
2
  import { updateToSql } from "./sql/updateToSql.js";
3
3
  import { rowToObject } from "./util/rowToObject.js";
4
- export const updateOne = async (config, conn, modelName, query) => {
4
+ export const updateOne = async (config, conn, middleware, modelName, query) => {
5
5
  if (Object.keys(query.set).length === 0) {
6
6
  throw new Error("Update requires at least one value to set");
7
7
  }
8
- const builder = buildUpdate(config, modelName, query);
8
+ const builder = buildUpdate(config, middleware, modelName, query);
9
9
  const statement = updateToSql(builder);
10
10
  config.logger.info("Executing updateOne", {
11
11
  sql: statement.pretty,