@wardql/drizzle 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ wardql
2
+ Copyright 2026 Saembit LLC and contributors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,165 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @wardql/drizzle
4
+
5
+ **Run wardql's policy-scoped plans through Drizzle and Postgres.**
6
+
7
+ </div>
8
+
9
+ <!--TODO: badges once published-->
10
+
11
+ ## 📖 About
12
+
13
+ So this package is the Postgres execution side of wardql. Give it a plan from `@wardql/core` and your Drizzle database plus tables, and `execute` resolves to `[error, { rows } | { count }]`, then that raw output goes into `ward.shape(plan, raw)` to produce the result you return.
14
+
15
+ The planner decides what a principal may ask for, this adapter only turns that already policy-scoped plan into parameterized Drizzle SQL. It does not authenticate anybody, and it does not expose driver errors to callers.
16
+
17
+ ## ✨ Features
18
+
19
+ - **Postgres through Drizzle**: accepts a Drizzle Postgres database or transaction and `pgTable` definitions.
20
+ - **Startup mapping checks**: pass `catalog: ward.catalog` and catch missing entity or field mappings before the first query.
21
+ - **Finds and counts**: returns raw rows for `find` plans and a raw count for `count` plans, ready for `ward.shape`.
22
+ - **Safe failures**: mapping and malformed-plan failures are wardql errors, while raw database failures go only to `onError`.
23
+ - **Spec-aligned values**: parameterized filters, SQL NULL behavior, literal case-sensitive text matching, and UTC handling for offset-less datetimes.
24
+
25
+ ## ⚙️ Installation
26
+
27
+ ```sh
28
+ pnpm add @wardql/drizzle @wardql/core drizzle-orm
29
+ ```
30
+
31
+ <!--TODO: not published yet-->
32
+
33
+ ## 🚀 Usage
34
+
35
+ ```ts
36
+ import { createWard } from "@wardql/core";
37
+ import { createDrizzleExecutor } from "@wardql/drizzle";
38
+ import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
39
+
40
+ const customers = pgTable("customers", {
41
+ id: text("id").primaryKey(),
42
+ tenantId: text("tenant_id").notNull(),
43
+ name: text("name").notNull(),
44
+ });
45
+
46
+ const orders = pgTable("orders", {
47
+ id: text("id").primaryKey(),
48
+ tenantId: text("tenant_id").notNull(),
49
+ customerId: text("customer_id"),
50
+ status: text("status").notNull(),
51
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
52
+ });
53
+
54
+ const tables = { customers, orders };
55
+
56
+ const ward = createWard({
57
+ catalog: {
58
+ entities: {
59
+ customers: {
60
+ fields: {
61
+ id: { type: "string" },
62
+ tenantId: { type: "string", exposed: false },
63
+ name: { type: "string" },
64
+ },
65
+ },
66
+ orders: {
67
+ fields: {
68
+ id: { type: "string" },
69
+ tenantId: { type: "string", exposed: false },
70
+ customerId: { type: "string" },
71
+ status: { type: "string" },
72
+ createdAt: { type: "datetime" },
73
+ },
74
+ relations: {
75
+ customer: { kind: "one", entity: "customers", from: "customerId", to: "id" },
76
+ },
77
+ },
78
+ },
79
+ },
80
+ policy: {
81
+ rules: [{
82
+ id: "orders-staff",
83
+ entity: "orders",
84
+ actions: ["find", "count"],
85
+ when: { field: "claims.roles", op: "contains", value: "staff" },
86
+ rowFilter: { field: "tenantId", op: "eq", value: { $principal: "claims.tenantId" } },
87
+ }],
88
+ },
89
+ });
90
+
91
+ // `db` is your initialized Drizzle Postgres database or transaction
92
+ const executor = createDrizzleExecutor({
93
+ db,
94
+ tables,
95
+ catalog: ward.catalog,
96
+ onError: (error, plan) => console.error("wardql query failed", { error, plan }),
97
+ });
98
+
99
+ const principal = { sub: "u_alice", claims: { tenantId: "t1", roles: ["staff"] } };
100
+ const [planError, plan] = ward.plan(principal, {
101
+ op: "find",
102
+ entity: "orders",
103
+ fields: ["id", "status", "createdAt"],
104
+ limit: 20,
105
+ });
106
+ if (planError) {
107
+ throw new Error(planError.message);
108
+ }
109
+
110
+ const [executeError, raw] = await executor.execute(plan);
111
+ if (executeError) {
112
+ throw new Error(executeError.message);
113
+ }
114
+
115
+ const [shapeError, result] = ward.shape(plan, raw);
116
+ if (shapeError) {
117
+ throw new Error(shapeError.message);
118
+ }
119
+
120
+ console.log(result);
121
+ ```
122
+
123
+ Now `raw` is deliberately not the final response. `ward.shape` validates and applies the last result-side rules, so keep the three stages together: `ward.plan`, `executor.execute`, `ward.shape`.
124
+
125
+ ## 🗺️ Mapping tables to the catalog
126
+
127
+ So `tables` maps a catalog entity name to its `pgTable`, for example `{ customers, orders }`. Catalog field names must be the table's JavaScript property names, not the SQL column names, so `tenantId` maps to `text("tenant_id")`, not a catalog field named `tenant_id`.
128
+
129
+ Hidden fields still need columns. A field with `exposed: false` is commonly what a policy uses for a tenant filter, and the executor must resolve it even though it never returns it to the caller.
130
+
131
+ Pass `catalog: ward.catalog` to `createDrizzleExecutor` to check every catalog entity and field once at creation. A missing table or column throws `WardConfigError`, since that is a startup configuration bug. If you need the same check as a value, call `checkDrizzleMapping(catalog, tables)`, which returns `[error, value]`.
132
+
133
+ Now date/time columns get one more check, and it runs both ways. A `timestamp`, `timestamptz`, or `date` column, in string or date mode, must back a `datetime` field, and a `datetime` field must be backed by one of those three. So a `datetime` field over a `text`, `varchar`, or any other column is refused with `ADAPTER_MISCONFIGURED`, otherwise its values would be bound raw and compared as strings while the planner compares instants. `time`, `time with time zone`, and `interval` columns are refused too, since a datetime cannot be compared with them without leaning on the session `TimeZone`; keep them out of the catalog or expose them some other way.
134
+
135
+ Treat passing `catalog` as required. A plan names fields but carries no field types, so at query time the adapter cannot tell a `datetime` field over a `text` column from an ordinary `string` field, and without `catalog` that mistake goes undetected. The check at creation is the only thing that guarantees every `datetime` field sits on a real date/time column.
136
+
137
+ ## 🔗 Relations and joins
138
+
139
+ Now a one-level many-to-one relation in a plan becomes a left join. The adapter applies the related entity's policy filter from the plan in the join's `ON` condition, so a related row that is not allowed becomes `null` without removing its parent row. To-many relations and nested relation joins are outside this adapter's scope.
140
+
141
+ ## 🧩 Query semantics
142
+
143
+ So Postgres does the comparison work, which means SQL's three-valued NULL logic applies: comparisons against NULL, including `ne`, `nin`, and `not` over an unknown comparison, do not match rows. Use `isNull` when NULL rows are what you want.
144
+
145
+ - Offset-less datetime strings are read as UTC, and that holds whatever the Postgres session `TimeZone` is and whatever Drizzle `mode` the column uses. Every value compared with a date/time column is parsed by wardql and bound with an explicit cast: a `timestamptz` column gets the UTC instant, a `timestamp` column (without time zone) is treated as UTC wall clock time, and a `date` column counts as midnight UTC of its day, so `gte "2026-06-01T10:00:00Z"` does not match `2026-06-01`.
146
+ - Selected date/time columns, root and joined, come back as ISO 8601 UTC strings whatever the Drizzle `mode` and whatever the session `TimeZone` and `DateStyle`: `timestamptz` and `timestamp` as `YYYY-MM-DDTHH:mm:ss.sssZ` (a `timestamp` is UTC wall clock, so it gets the `Z`), `date` as `YYYY-MM-DD`. The formatting happens in the select list with `to_char`, which never reads `DateStyle`, after an explicit `AT TIME ZONE 'UTC'`, so no session setting can move it. Postgres stores microseconds but wardql returns milliseconds, so the extra digits are truncated, never rounded, and `23:59:59.999999` stays on its own day. NULL stays `null`. Filters and `orderBy` still use the real column, not the text.
147
+ - A stored value with no ISO 8601 form, such as `infinity`, a BC date, or a year past 9999, fails the find with `EXECUTION_FAILED` instead of being returned as `null` or as the wrong year.
148
+ - `contains` and `startsWith` use literal, case-sensitive Postgres `LIKE`; `%`, `_`, and backslashes are escaped with `escapeLikePattern` before the pattern is bound.
149
+ - No implicit tiebreak is added to `orderBy`, so a page sorted on non-unique values is only as stable as Postgres makes it.
150
+
151
+ ## ⚠️ Errors
152
+
153
+ | Code | Meaning |
154
+ |---|---|
155
+ | `ADAPTER_MISCONFIGURED` | An entity or field has no table or column mapping, a date/time column is of an unsupported type or backs a field that is not a `datetime`, a `datetime` field is not backed by a `timestamp`, `timestamptz`, or `date` column, or the plan is malformed |
156
+ | `EXECUTION_FAILED` | The database query failed, its caller-facing message carrying only the SQLSTATE when one is available, or a selected date/time value has no ISO 8601 form |
157
+
158
+ Now the raw driver error, including SQL and parameter detail, is sent to `onError(error, plan)` and never returned to the caller. Keep that hook for server-side logging and observability.
159
+
160
+ ## 🧪 Development
161
+
162
+ ```sh
163
+ pnpm --filter @wardql/drizzle test
164
+ pnpm --filter @wardql/drizzle typecheck
165
+ ```
@@ -0,0 +1,66 @@
1
+ import { Catalog, ErrorPath, Filter, Plan, Result } from "@wardql/core";
2
+ import { SQL } from "drizzle-orm";
3
+ import { PgColumn, PgDatabase, PgTable } from "drizzle-orm/pg-core";
4
+ /** Catalog entity name to the Drizzle table that stores it */
5
+ type TableMap = Readonly<Record<string, PgTable>>;
6
+ /** Catalog field name to column, keyed by the table's JS property names */
7
+ type ColumnMap = Readonly<Record<string, PgColumn>>;
8
+ /** The columns a filter may reference, plus the entity name for error messages */
9
+ interface FilterScope {
10
+ readonly entity: string;
11
+ readonly columns: ColumnMap;
12
+ }
13
+ /**
14
+ * Translates a wardql filter tree into a parameterized Drizzle SQL condition.
15
+ * Values only ever reach the database as bound parameters
16
+ * @params filter - the filter from a plan
17
+ * @params scope - the entity's columns and name
18
+ * @params path - JSON path of the filter inside the plan
19
+ * @returns {Result<SQL>} - the condition, or the first translation error
20
+ */
21
+ export declare function translateFilter(filter: Filter, scope: FilterScope, path?: ErrorPath): Result<SQL>;
22
+ type DrizzlePgDatabase = PgDatabase<any, any, any>;
23
+ /** Raw adapter output, the input to core's `shapeResult` */
24
+ type DrizzleOutput = {
25
+ readonly rows: Record<string, unknown>[];
26
+ } | {
27
+ readonly count: number;
28
+ };
29
+ interface DrizzleExecutorOptions {
30
+ /** A Drizzle Postgres database or transaction */
31
+ readonly db: DrizzlePgDatabase;
32
+ /** Catalog entity name to pgTable. Catalog fields map to columns by JS property name */
33
+ readonly tables: TableMap;
34
+ /** When given, every catalog entity and field must be mapped, checked once at creation */
35
+ readonly catalog?: Catalog;
36
+ /** Receives the raw database error for server side logging, it is never returned to the caller */
37
+ readonly onError?: (error: unknown, plan: Plan) => void;
38
+ }
39
+ interface DrizzleExecutor {
40
+ execute(plan: Plan): Promise<Result<DrizzleOutput>>;
41
+ }
42
+ /**
43
+ * Creates an executor that runs wardql plans against Postgres through Drizzle
44
+ * @params options - the database, the entity to table map, and an optional error hook
45
+ * @returns {DrizzleExecutor} - `execute(plan)` resolving to `[error, { rows } | { count }]`
46
+ * @throws {WardConfigError} - when `catalog` is given and an entity or field has no table or column
47
+ */
48
+ export declare function createDrizzleExecutor(options: DrizzleExecutorOptions): DrizzleExecutor;
49
+ /**
50
+ * Checks that every catalog entity has a Drizzle table and every catalog field a column,
51
+ * so a mapping mistake shows up at startup instead of on the first query that touches it.
52
+ * A date/time column must be timestamp, timestamptz, or date and must back a `datetime` field,
53
+ * and a `datetime` field must be backed by one of those columns
54
+ * @params catalog - the parsed catalog, for example `ward.catalog`
55
+ * @params tables - catalog entity name to pgTable
56
+ * @returns {Result<void>} - the first `ADAPTER_MISCONFIGURED` error found, with a path into the catalog
57
+ */
58
+ export declare function checkDrizzleMapping(catalog: Catalog, tables: TableMap): Result<void>;
59
+ /**
60
+ * Escapes LIKE wildcards so a user string only ever matches literally.
61
+ * Backslash is the default LIKE escape character in Postgres, so no ESCAPE clause is needed
62
+ * @params text - the raw search string
63
+ * @returns {string} - the string with `\`, `%` and `_` escaped
64
+ */
65
+ export declare function escapeLikePattern(text: string): string;
66
+ export type { ColumnMap, DrizzleExecutor, DrizzleExecutorOptions, DrizzleOutput, DrizzlePgDatabase, FilterScope, TableMap };
package/dist/index.mjs ADDED
@@ -0,0 +1,576 @@
1
+ import { WardConfigError, fail, fromZodError, isComparison, ok, parseDatetime, planSchema, wardError } from "@wardql/core";
2
+ import { and, asc, count, desc, eq, getTableColumns, gt, gte, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, sql } from "drizzle-orm";
3
+ import { PgTable, alias } from "drizzle-orm/pg-core";
4
+ // src/errors.ts
5
+ const UNMAPPED_ENTITY_CODE = "ADAPTER_MISCONFIGURED";
6
+ const UNMAPPED_FIELD_CODE = "ADAPTER_MISCONFIGURED";
7
+ const MALFORMED_PLAN_CODE = "ADAPTER_MISCONFIGURED";
8
+ const EXECUTION_FAILED_CODE = "EXECUTION_FAILED";
9
+ const SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;
10
+ /**
11
+ * Builds the error for a plan entity that has no Drizzle table mapped
12
+ * @params entity - catalog entity name
13
+ * @params path - JSON path into the plan
14
+ * @returns {WardError} - the error value
15
+ */
16
+ function unmappedEntityError(entity, path) {
17
+ return wardError(UNMAPPED_ENTITY_CODE, `No Drizzle table is mapped for entity \`${entity}\``, path);
18
+ }
19
+ /**
20
+ * Builds the error for a plan field that has no column on the mapped table
21
+ * @params entity - catalog entity name
22
+ * @params field - catalog field name
23
+ * @params path - JSON path into the plan
24
+ * @returns {WardError} - the error value
25
+ */
26
+ function unmappedFieldError(entity, field, path) {
27
+ const message = `The Drizzle table for \`${entity}\` has no column property \`${field}\``;
28
+ return wardError(UNMAPPED_FIELD_CODE, message, path);
29
+ }
30
+ /**
31
+ * Builds the error for a plan the adapter cannot translate
32
+ * @params message - what is wrong with the plan
33
+ * @params path - JSON path into the plan
34
+ * @returns {WardError} - the error value
35
+ */
36
+ function malformedPlanError(message, path) {
37
+ return wardError(MALFORMED_PLAN_CODE, message, path);
38
+ }
39
+ /**
40
+ * Builds the error for a stored date/time value with no ISO 8601 UTC form, such as infinity,
41
+ * a BC date, or a year past 9999. The value itself is never echoed
42
+ * @returns {WardError} - the error value
43
+ */
44
+ function unrepresentableDatetimeError() {
45
+ return wardError(EXECUTION_FAILED_CODE, "A stored date/time value has no ISO 8601 form wardql can return");
46
+ }
47
+ function readCode(value) {
48
+ if (value === null || typeof value !== "object" || !("code" in value)) return null;
49
+ const { code } = value;
50
+ return typeof code === "string" && SQLSTATE_PATTERN.test(code) ? code : null;
51
+ }
52
+ function readSQLState(error) {
53
+ const cause = error instanceof Error ? error.cause : void 0;
54
+ return readCode(error) ?? readCode(cause);
55
+ }
56
+ /**
57
+ * Turns a thrown database error into a safe error value.
58
+ * Driver messages echo SQL text and parameter values, so only the SQLSTATE is kept
59
+ * @params error - whatever the database layer threw
60
+ * @returns {WardError} - the error value
61
+ */
62
+ function toExecutionError(error) {
63
+ const state = readSQLState(error);
64
+ const detail = state ? ` (SQLSTATE ${state})` : "";
65
+ return wardError(EXECUTION_FAILED_CODE, `Database query failed${detail}`);
66
+ }
67
+ // src/columns.ts
68
+ /**
69
+ * Looks up the Drizzle table mapped to a catalog entity
70
+ * @params tables - entity name to table
71
+ * @params entity - catalog entity name
72
+ * @params path - JSON path into the plan, used in the error
73
+ * @returns {Result<PgTable>} - the table, or an error when nothing is mapped
74
+ */
75
+ function resolveTable(tables, entity, path) {
76
+ const table = Object.hasOwn(tables, entity) ? tables[entity] : void 0;
77
+ if (!table || !is(table, PgTable)) return fail(unmappedEntityError(entity, path));
78
+ return ok(table);
79
+ }
80
+ /**
81
+ * Reads the columns of a table or table alias by JS property name
82
+ * @params table - a Drizzle pgTable or an alias of one
83
+ * @returns {ColumnMap} - property name to column
84
+ */
85
+ function columnsOf(table) {
86
+ return getTableColumns(table);
87
+ }
88
+ /**
89
+ * Looks up the column mapped to a catalog field
90
+ * @params columns - the entity's columns
91
+ * @params entity - catalog entity name, used in the error
92
+ * @params field - catalog field name
93
+ * @params path - JSON path into the plan, used in the error
94
+ * @returns {Result<PgColumn>} - the column, or an error when nothing is mapped
95
+ */
96
+ function resolveColumn(columns, entity, field, path) {
97
+ const column = Object.hasOwn(columns, field) ? columns[field] : void 0;
98
+ if (!column) return fail(unmappedFieldError(entity, field, path));
99
+ return ok(column);
100
+ }
101
+ /**
102
+ * Looks up several columns, stopping at the first one that is not mapped
103
+ * @params columns - the entity's columns
104
+ * @params entity - catalog entity name, used in the error
105
+ * @params fields - catalog field names
106
+ * @params path - JSON path of the field list in the plan
107
+ * @returns {Result<readonly PgColumn[]>} - columns in field order, or the first error
108
+ */
109
+ function resolveColumns(columns, entity, fields, path) {
110
+ const resolved = fields.map((field, index) => resolveColumn(columns, entity, field, [...path, index]));
111
+ const failed = resolved.find(([error]) => error !== null);
112
+ if (failed?.[0]) return fail(failed[0]);
113
+ return ok(resolved.flatMap(([, column]) => column ? [column] : []));
114
+ }
115
+ // src/temporal.ts
116
+ const SQL_TYPE_KINDS = [
117
+ [/^timestamp\s*(\(\s*\d+\s*\))?\s+with time zone$/, "timestamptz"],
118
+ [/^timestamptz\s*(\(\s*\d+\s*\))?$/, "timestamptz"],
119
+ [/^timestamp\s*(\(\s*\d+\s*\))?(\s+without time zone)?$/, "timestamp"],
120
+ [/^date$/, "date"]
121
+ ];
122
+ const TEMPORAL_WORD_PATTERN = /\b(date|time|timetz|timestamp|timestamptz|interval)\b/;
123
+ /**
124
+ * Classifies a column by its Postgres type, whatever Drizzle mode it was declared with.
125
+ * String mode and date mode columns of the same SQL type get the same kind
126
+ * @params column - the Drizzle column
127
+ * @returns {ColumnKind} - the temporal kind, `unsupportedTemporal` for other date/time types, or `other`
128
+ */
129
+ function columnKindOf(column) {
130
+ const sqlType = column.getSQLType().trim().toLowerCase();
131
+ const match = SQL_TYPE_KINDS.find(([pattern]) => pattern.test(sqlType));
132
+ if (match) return match[1];
133
+ return TEMPORAL_WORD_PATTERN.test(sqlType) ? "unsupportedTemporal" : "other";
134
+ }
135
+ // src/values.ts
136
+ const LIKE_SPECIAL_PATTERN = /[\\%_]/g;
137
+ /**
138
+ * Escapes LIKE wildcards so a user string only ever matches literally.
139
+ * Backslash is the default LIKE escape character in Postgres, so no ESCAPE clause is needed
140
+ * @params text - the raw search string
141
+ * @returns {string} - the string with `\`, `%` and `_` escaped
142
+ */
143
+ function escapeLikePattern(text) {
144
+ return text.replace(LIKE_SPECIAL_PATTERN, (special) => `\\${special}`);
145
+ }
146
+ function bindInstant(kind, instant) {
147
+ const isoText = instant.toISOString();
148
+ if (kind === "timestamptz") return sql`cast(${isoText} as timestamptz)`;
149
+ return sql`cast(${isoText.slice(0, -1)} as timestamp)`;
150
+ }
151
+ /**
152
+ * Converts a plan value into what is bound against the column. Every value compared with a date/time
153
+ * column is parsed as a datetime (no offset means UTC) and bound with an explicit cast, whatever
154
+ * mode the Drizzle column uses, so the result never depends on the session TimeZone
155
+ * @params column - the column being compared
156
+ * @params value - the literal from the plan
157
+ * @params path - JSON path of the value, used in the error
158
+ * @returns {Result<Scalar | SQL>} - the value or SQL expression to compare with
159
+ */
160
+ function toColumnValue(column, value, path) {
161
+ const kind = columnKindOf(column);
162
+ if (kind === "other") return ok(value);
163
+ if (kind === "unsupportedTemporal") return fail(malformedPlanError("Only timestamp, timestamptz, and date columns can be compared with a datetime", path));
164
+ const instant = typeof value === "string" ? parseDatetime(value) : /* @__PURE__ */ new Date(NaN);
165
+ if (Number.isNaN(instant.getTime())) return fail(malformedPlanError("Expected an ISO 8601 datetime string", path));
166
+ return ok(bindInstant(kind, instant));
167
+ }
168
+ // src/filter.ts
169
+ const SCALAR_OPERATORS = {
170
+ eq,
171
+ ne,
172
+ lt,
173
+ lte,
174
+ gt,
175
+ gte
176
+ };
177
+ function isScalarValue(value) {
178
+ return value !== void 0 && !Array.isArray(value);
179
+ }
180
+ function translateScalar(column, leaf, op, path) {
181
+ if (!isScalarValue(leaf.value)) return fail(malformedPlanError(`\`${op}\` requires a single value`, [...path, "value"]));
182
+ const [valueError, value] = toColumnValue(column, leaf.value, [...path, "value"]);
183
+ if (valueError) return fail(valueError);
184
+ return ok(SCALAR_OPERATORS[op](column, value));
185
+ }
186
+ function translateSet(column, leaf, op, path) {
187
+ const items = leaf.value;
188
+ if (items === void 0 || !Array.isArray(items) || items.length === 0) return fail(malformedPlanError(`\`${op}\` requires a non empty array`, [...path, "value"]));
189
+ const converted = items.map((item, index) => toColumnValue(column, item, [
190
+ ...path,
191
+ "value",
192
+ index
193
+ ]));
194
+ const failed = converted.find(([error]) => error !== null);
195
+ if (failed?.[0]) return fail(failed[0]);
196
+ const values = converted.flatMap(([, value]) => value === null ? [] : [value]);
197
+ return ok(op === "in" ? inArray(column, values) : notInArray(column, values));
198
+ }
199
+ function translateText(column, leaf, path) {
200
+ if (typeof leaf.value !== "string") return fail(malformedPlanError(`\`${leaf.op}\` requires a string`, [...path, "value"]));
201
+ if (columnKindOf(column) !== "other") return fail(malformedPlanError(`\`${leaf.op}\` cannot be used on a date/time column`, [...path, "op"]));
202
+ const escaped = escapeLikePattern(leaf.value);
203
+ return ok(like(column, leaf.op === "contains" ? `%${escaped}%` : `${escaped}%`));
204
+ }
205
+ function translateNull(column, leaf, path) {
206
+ if (typeof leaf.value !== "boolean") return fail(malformedPlanError("`isNull` takes true or false", [...path, "value"]));
207
+ return ok(leaf.value ? isNull(column) : isNotNull(column));
208
+ }
209
+ function translateComparison(leaf, scope, path) {
210
+ const [columnError, column] = resolveColumn(scope.columns, scope.entity, leaf.field, [...path, "field"]);
211
+ if (columnError) return fail(columnError);
212
+ switch (leaf.op) {
213
+ case "eq":
214
+ case "ne":
215
+ case "lt":
216
+ case "lte":
217
+ case "gt":
218
+ case "gte": return translateScalar(column, leaf, leaf.op, path);
219
+ case "in":
220
+ case "nin": return translateSet(column, leaf, leaf.op, path);
221
+ case "contains":
222
+ case "startsWith": return translateText(column, leaf, path);
223
+ case "isNull": return translateNull(column, leaf, path);
224
+ default: return fail(malformedPlanError("Unsupported operator", [...path, "op"]));
225
+ }
226
+ }
227
+ function translateGroup(key, children, scope, path) {
228
+ const translated = children.map((child, index) => translateFilter(child, scope, [
229
+ ...path,
230
+ key,
231
+ index
232
+ ]));
233
+ const failed = translated.find(([error]) => error !== null);
234
+ if (failed?.[0]) return fail(failed[0]);
235
+ const parts = translated.flatMap(([, part]) => part ? [part] : []);
236
+ const combined = key === "and" ? and(...parts) : or(...parts);
237
+ if (!combined) return fail(malformedPlanError(`\`${key}\` requires at least one filter`, [...path, key]));
238
+ return ok(combined);
239
+ }
240
+ /**
241
+ * Translates a wardql filter tree into a parameterized Drizzle SQL condition.
242
+ * Values only ever reach the database as bound parameters
243
+ * @params filter - the filter from a plan
244
+ * @params scope - the entity's columns and name
245
+ * @params path - JSON path of the filter inside the plan
246
+ * @returns {Result<SQL>} - the condition, or the first translation error
247
+ */
248
+ function translateFilter(filter, scope, path = ["where"]) {
249
+ if (isComparison(filter)) return translateComparison(filter, scope, path);
250
+ if ("and" in filter) return translateGroup("and", filter.and, scope, path);
251
+ if ("or" in filter) return translateGroup("or", filter.or, scope, path);
252
+ const [innerError, inner] = translateFilter(filter.not, scope, [...path, "not"]);
253
+ if (innerError) return fail(innerError);
254
+ return ok(not(inner));
255
+ }
256
+ // src/joins.ts
257
+ const JOIN_ALIAS_PREFIX = "__wardql_join_";
258
+ /**
259
+ * Names the flat result key that tells whether a related row matched
260
+ * @params relation - the relation name
261
+ * @returns {string} - the marker key
262
+ */
263
+ function matchKey(relation) {
264
+ return `${relation}.`;
265
+ }
266
+ /**
267
+ * Names the flat result key of a related column
268
+ * @params relation - the relation name
269
+ * @params field - the related field name
270
+ * @returns {string} - the flat key
271
+ */
272
+ function relatedKey(relation, field) {
273
+ return `${relation}.${field}`;
274
+ }
275
+ function buildOn(root, related, join, index) {
276
+ const [fromError, fromColumn] = resolveColumn(root.columns, root.entity, join.from, [
277
+ "joins",
278
+ index,
279
+ "from"
280
+ ]);
281
+ if (fromError) return fail(fromError);
282
+ const [toError, toColumn] = resolveColumn(related.columns, related.entity, join.to, [
283
+ "joins",
284
+ index,
285
+ "to"
286
+ ]);
287
+ if (toError) return fail(toError);
288
+ const keysMatch = eq(fromColumn, toColumn);
289
+ if (!join.where) return ok(keysMatch);
290
+ const [whereError, where] = translateFilter(join.where, related, [
291
+ "joins",
292
+ index,
293
+ "where"
294
+ ]);
295
+ if (whereError) return fail(whereError);
296
+ return ok(and(keysMatch, where) ?? keysMatch);
297
+ }
298
+ function buildSelection(columns, join, index) {
299
+ const [toError, toColumn] = resolveColumn(columns, join.entity, join.to, [
300
+ "joins",
301
+ index,
302
+ "to"
303
+ ]);
304
+ if (toError) return fail(toError);
305
+ const [selectError, selected] = resolveColumns(columns, join.entity, join.select, [
306
+ "joins",
307
+ index,
308
+ "select"
309
+ ]);
310
+ if (selectError) return fail(selectError);
311
+ const entries = join.select.flatMap((field, position) => {
312
+ const column = selected[position];
313
+ return column ? [[relatedKey(join.relation, field), column]] : [];
314
+ });
315
+ return ok(Object.fromEntries([[matchKey(join.relation), toColumn], ...entries]));
316
+ }
317
+ /**
318
+ * Resolves one plan join into an aliased table, ON condition, and flat selection
319
+ * @params tables - entity name to table
320
+ * @params root - the root entity's columns and name
321
+ * @params join - the join from the plan
322
+ * @params index - position of the join in the plan, used for the alias and error paths
323
+ * @returns {Result<JoinTarget>} - the join target, or a mapping error
324
+ */
325
+ function buildJoinTarget(tables, root, join, index) {
326
+ const [tableError, table] = resolveTable(tables, join.entity, [
327
+ "joins",
328
+ index,
329
+ "entity"
330
+ ]);
331
+ if (tableError) return fail(tableError);
332
+ const aliased = alias(table, `${JOIN_ALIAS_PREFIX}${index}`);
333
+ const related = {
334
+ entity: join.entity,
335
+ columns: columnsOf(aliased)
336
+ };
337
+ const [onError, on] = buildOn(root, related, join, index);
338
+ if (onError) return fail(onError);
339
+ const [selectionError, selection] = buildSelection(related.columns, join, index);
340
+ if (selectionError) return fail(selectionError);
341
+ return ok({
342
+ table: aliased,
343
+ on,
344
+ selection
345
+ });
346
+ }
347
+ /**
348
+ * Resolves every join in a plan, stopping at the first error
349
+ * @params tables - entity name to table
350
+ * @params root - the root entity's columns and name
351
+ * @params joins - the joins from the plan
352
+ * @returns {Result<readonly JoinTarget[]>} - join targets in plan order
353
+ */
354
+ function buildJoinTargets(tables, root, joins) {
355
+ const built = joins.map((join, index) => buildJoinTarget(tables, root, join, index));
356
+ const failed = built.find(([error]) => error !== null);
357
+ if (failed?.[0]) return fail(failed[0]);
358
+ return ok(built.flatMap(([, target]) => target ? [target] : []));
359
+ }
360
+ // src/output.ts
361
+ const INSTANT_FORMAT = `'BCYYYY-MM-DD"T"HH24:MI:SS.MS"Z"'`;
362
+ const DAY_FORMAT = `'BCYYYY-MM-DD'`;
363
+ const INSTANT_PATTERN = /^AD(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)$/;
364
+ const DAY_PATTERN = /^AD(\d{4}-\d{2}-\d{2})$/;
365
+ function formatTemporal(column, kind) {
366
+ const wallClock = kind === "timestamptz" ? sql`(${column} at time zone 'UTC')` : kind === "date" ? sql`cast(${column} as timestamp)` : sql`${column}`;
367
+ const format = sql.raw(kind === "date" ? DAY_FORMAT : INSTANT_FORMAT);
368
+ return sql`case when isfinite(${column}) then to_char(${wallClock}, ${format}) else cast(${column} as text) end`;
369
+ }
370
+ /**
371
+ * Replaces each timestamp, timestamptz, and date column in a select list with an expression that
372
+ * yields ISO 8601 UTC text whatever the Drizzle mode and the session TimeZone and DateStyle.
373
+ * Only the select list changes, filters and sorting keep using the real column
374
+ * @params columns - flat result key to column
375
+ * @returns {OutputSelection} - the select list to run and the keys whose text must be checked
376
+ */
377
+ function toOutputSelection(columns) {
378
+ const temporalKeys = new Map(Object.entries(columns).flatMap(([key, column]) => {
379
+ const kind = columnKindOf(column);
380
+ return isTemporalKind(kind) ? [[key, kind]] : [];
381
+ }));
382
+ return {
383
+ selection: Object.fromEntries(Object.entries(columns).map(([key, column]) => {
384
+ const kind = temporalKeys.get(key);
385
+ return [key, kind ? formatTemporal(column, kind) : column];
386
+ })),
387
+ temporalKeys
388
+ };
389
+ }
390
+ function isTemporalKind(kind) {
391
+ return kind === "timestamptz" || kind === "timestamp" || kind === "date";
392
+ }
393
+ function toISOValue(kind, value) {
394
+ if (value === null || value === void 0) return ok(null);
395
+ const match = typeof value === "string" ? (kind === "date" ? DAY_PATTERN : INSTANT_PATTERN).exec(value) : null;
396
+ if (!match?.[1]) return fail(unrepresentableDatetimeError());
397
+ return ok(match[1]);
398
+ }
399
+ /**
400
+ * Strips the era marker from each date/time value of a fetched row, refusing any value that is
401
+ * not a plain ISO 8601 UTC datetime or date, such as infinity, a BC value, or a year past 9999
402
+ * @params row - one flat row as Postgres returned it
403
+ * @params temporalKeys - the keys `toOutputSelection` formatted
404
+ * @returns {Result<Row>} - a new row with ISO strings or null, or `EXECUTION_FAILED`
405
+ */
406
+ function toOutputRow(row, temporalKeys) {
407
+ const converted = Object.entries(row).map(([key, value]) => {
408
+ const kind = temporalKeys.get(key);
409
+ return [key, kind ? toISOValue(kind, value) : ok(value)];
410
+ });
411
+ const failed = converted.find(([, [error]]) => error !== null);
412
+ if (failed?.[1][0]) return fail(failed[1][0]);
413
+ return ok(Object.fromEntries(converted.map(([key, [, value]]) => [key, value])));
414
+ }
415
+ // src/find.ts
416
+ function buildOrderBy(root, plan) {
417
+ const fields = plan.orderBy.map((order) => order.field);
418
+ const [error, columns] = resolveColumns(root.columns, root.entity, fields, ["orderBy"]);
419
+ if (error) return fail(error);
420
+ return ok(columns.map((column, index) => plan.orderBy[index]?.direction === "desc" ? desc(column) : asc(column)));
421
+ }
422
+ function buildRootSelection(root, plan) {
423
+ const [error, columns] = resolveColumns(root.columns, root.entity, plan.select, ["select"]);
424
+ if (error) return fail(error);
425
+ return ok(Object.fromEntries(columns.map((column, index) => [plan.select[index], column])));
426
+ }
427
+ /**
428
+ * Resolves a find plan against the mapped tables without touching the database
429
+ * @params tables - entity name to table
430
+ * @params plan - the find plan
431
+ * @returns {Result<FindStatement>} - the resolved statement, or a mapping error
432
+ */
433
+ function buildFindStatement(tables, plan) {
434
+ const [tableError, table] = resolveTable(tables, plan.entity, ["entity"]);
435
+ if (tableError) return fail(tableError);
436
+ const root = {
437
+ entity: plan.entity,
438
+ columns: columnsOf(table)
439
+ };
440
+ const [selectError, rootSelection] = buildRootSelection(root, plan);
441
+ if (selectError) return fail(selectError);
442
+ const [joinError, joins] = buildJoinTargets(tables, root, plan.joins);
443
+ if (joinError) return fail(joinError);
444
+ const [whereError, where] = plan.where ? translateFilter(plan.where, root) : ok(void 0);
445
+ if (whereError) return fail(whereError);
446
+ const [orderError, orderBy] = buildOrderBy(root, plan);
447
+ if (orderError) return fail(orderError);
448
+ const { selection, temporalKeys } = toOutputSelection(joins.reduce((merged, join) => ({
449
+ ...merged,
450
+ ...join.selection
451
+ }), rootSelection));
452
+ return ok({
453
+ table,
454
+ selection,
455
+ temporalKeys,
456
+ joins,
457
+ where,
458
+ orderBy
459
+ });
460
+ }
461
+ function nestRelated(join, flat) {
462
+ if (!(flat[matchKey(join.relation)] !== null && flat[matchKey(join.relation)] !== void 0)) return null;
463
+ return Object.fromEntries(join.select.map((field) => [field, flat[relatedKey(join.relation, field)]]));
464
+ }
465
+ function nestRow(plan, flat) {
466
+ const root = plan.select.map((field) => [field, flat[field]]);
467
+ const related = plan.joins.map((join) => [join.relation, nestRelated(join, flat)]);
468
+ return Object.fromEntries([...root, ...related]);
469
+ }
470
+ function toOutputRows(flatRows, temporalKeys) {
471
+ const converted = flatRows.map((flat) => toOutputRow(flat, temporalKeys));
472
+ const failed = converted.find(([error]) => error !== null);
473
+ if (failed?.[0]) return fail(failed[0]);
474
+ return ok(converted.flatMap(([, row]) => row ? [row] : []));
475
+ }
476
+ /**
477
+ * Runs a find plan and returns rows shaped for core's `shapeResult`
478
+ * @params db - the Drizzle Postgres database
479
+ * @params tables - entity name to table
480
+ * @params plan - the find plan
481
+ * @returns {Promise<Result<{ rows: Row[] }>>} - the rows, or a mapping error
482
+ */
483
+ async function runFind(db, tables, plan) {
484
+ const [error, statement] = buildFindStatement(tables, plan);
485
+ if (error) return fail(error);
486
+ const base = db.select(statement.selection).from(statement.table).$dynamic();
487
+ const [outputError, outputRows] = toOutputRows(await statement.joins.reduce((query, join) => query.leftJoin(join.table, join.on), base).where(statement.where).orderBy(...statement.orderBy).limit(plan.limit).offset(plan.offset), statement.temporalKeys);
488
+ if (outputError) return fail(outputError);
489
+ return ok({ rows: outputRows.map((flat) => nestRow(plan, flat)) });
490
+ }
491
+ // src/mapping.ts
492
+ function checkColumnType(field, column, path) {
493
+ const kind = columnKindOf(column);
494
+ if (kind === "unsupportedTemporal") return malformedPlanError("Only timestamp, timestamptz, and date columns are supported for date/time values", path);
495
+ const isDatetimeField = field.type === "datetime";
496
+ if (kind !== "other" && !isDatetimeField) return malformedPlanError("A timestamp, timestamptz, or date column must back a `datetime` field", path);
497
+ if (kind === "other" && isDatetimeField) return malformedPlanError("A `datetime` field must be backed by a timestamp, timestamptz, or date column", path);
498
+ return null;
499
+ }
500
+ function checkEntity(catalog, tables, entity) {
501
+ const [tableError, table] = resolveTable(tables, entity, ["entities", entity]);
502
+ if (tableError) return tableError;
503
+ const columns = columnsOf(table);
504
+ const fields = Object.entries(catalog.entities[entity]?.fields ?? {});
505
+ for (const [field, definition] of fields) {
506
+ const path = [
507
+ "entities",
508
+ entity,
509
+ "fields",
510
+ field
511
+ ];
512
+ const [columnError, column] = resolveColumn(columns, entity, field, path);
513
+ if (columnError) return columnError;
514
+ const typeError = checkColumnType(definition, column, path);
515
+ if (typeError) return typeError;
516
+ }
517
+ return null;
518
+ }
519
+ /**
520
+ * Checks that every catalog entity has a Drizzle table and every catalog field a column,
521
+ * so a mapping mistake shows up at startup instead of on the first query that touches it.
522
+ * A date/time column must be timestamp, timestamptz, or date and must back a `datetime` field,
523
+ * and a `datetime` field must be backed by one of those columns
524
+ * @params catalog - the parsed catalog, for example `ward.catalog`
525
+ * @params tables - catalog entity name to pgTable
526
+ * @returns {Result<void>} - the first `ADAPTER_MISCONFIGURED` error found, with a path into the catalog
527
+ */
528
+ function checkDrizzleMapping(catalog, tables) {
529
+ for (const entity of Object.keys(catalog.entities)) {
530
+ const error = checkEntity(catalog, tables, entity);
531
+ if (error) return fail(error);
532
+ }
533
+ return ok(void 0);
534
+ }
535
+ // src/execute.ts
536
+ async function runCount(db, tables, plan) {
537
+ const [tableError, table] = resolveTable(tables, plan.entity, ["entity"]);
538
+ if (tableError) return fail(tableError);
539
+ const scope = {
540
+ entity: plan.entity,
541
+ columns: columnsOf(table)
542
+ };
543
+ const [whereError, where] = plan.where ? translateFilter(plan.where, scope) : ok(void 0);
544
+ if (whereError) return fail(whereError);
545
+ const [row] = await db.select({ count: count() }).from(table).where(where);
546
+ return ok({ count: Number(row?.count ?? 0) });
547
+ }
548
+ function reportError(options, error, plan) {
549
+ try {
550
+ options.onError?.(error, plan);
551
+ } catch {}
552
+ }
553
+ /**
554
+ * Creates an executor that runs wardql plans against Postgres through Drizzle
555
+ * @params options - the database, the entity to table map, and an optional error hook
556
+ * @returns {DrizzleExecutor} - `execute(plan)` resolving to `[error, { rows } | { count }]`
557
+ * @throws {WardConfigError} - when `catalog` is given and an entity or field has no table or column
558
+ */
559
+ function createDrizzleExecutor(options) {
560
+ const { db, tables } = options;
561
+ const [mappingError] = options.catalog ? checkDrizzleMapping(options.catalog, tables) : ok(void 0);
562
+ if (mappingError) throw new WardConfigError(mappingError);
563
+ const execute = async (plan) => {
564
+ const parsed = planSchema.safeParse(plan);
565
+ if (!parsed.success) return fail(fromZodError("ADAPTER_MISCONFIGURED", parsed.error));
566
+ try {
567
+ const checked = parsed.data;
568
+ return checked.op === "find" ? await runFind(db, tables, checked) : await runCount(db, tables, checked);
569
+ } catch (error) {
570
+ reportError(options, error, plan);
571
+ return fail(toExecutionError(error));
572
+ }
573
+ };
574
+ return { execute };
575
+ }
576
+ export { checkDrizzleMapping, createDrizzleExecutor, escapeLikePattern, translateFilter };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@wardql/drizzle",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Drizzle ORM Postgres adapter for wardql: executes policy-scoped query plans with parameterized SQL",
5
+ "homepage": "https://github.com/saembit/wardql#readme",
6
+ "bugs": "https://github.com/saembit/wardql/issues",
7
+ "keywords": [
8
+ "ai",
9
+ "agents",
10
+ "llm",
11
+ "access-control",
12
+ "authorization",
13
+ "multi-tenant",
14
+ "drizzle"
15
+ ],
16
+ "license": "Apache-2.0",
17
+ "author": "Saembit LLC",
18
+ "contributors": [
19
+ {
20
+ "name": "Austin Choi",
21
+ "url": "https://github.com/choice404"
22
+ }
23
+ ],
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "files": [
27
+ "LICENSE",
28
+ "NOTICE",
29
+ "dist"
30
+ ],
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.mts",
34
+ "import": "./dist/index.mjs"
35
+ }
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "dependencies": {
41
+ "@wardql/core": "0.1.0"
42
+ },
43
+ "peerDependencies": {
44
+ "drizzle-orm": "^0.45.0"
45
+ },
46
+ "devDependencies": {
47
+ "@electric-sql/pglite": "^0.5.16",
48
+ "@vitest/coverage-v8": "^5.1.0",
49
+ "drizzle-orm": "^0.45.4"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/saembit/wardql.git",
54
+ "directory": "packages/drizzle"
55
+ },
56
+ "scripts": {
57
+ "build": "tsdown",
58
+ "test": "vitest run",
59
+ "test:watch": "vitest",
60
+ "typecheck": "tsc -p tsconfig.json"
61
+ }
6
62
  }