@prisma-next/sql-lane-query-builder 0.0.1 → 0.3.0-dev.100

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Prisma Data, Inc]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @prisma-next/lane-sql-query-builder
1
+ # @prisma-next/sql-lane-query-builder
2
2
 
3
3
  SQL query builder lane for Prisma Next.
4
4
 
package/dist/index.d.mts CHANGED
@@ -1 +1,214 @@
1
- export { };
1
+ import { Brand, StorageHashBase } from "@prisma-next/contract/types";
2
+ import { ExtractCodecTypes, SqlContract, StorageColumn } from "@prisma-next/sql-contract/types";
3
+
4
+ //#region src/type-errors.d.ts
5
+
6
+ /**
7
+ * An error message type, prefixed with `[error]`.
8
+ *
9
+ * @template TMessage The error message.
10
+ */
11
+ type ErrorMessage = `[error] ${string}`;
12
+ /**
13
+ * An error type indicating that the previous function call had bad input.
14
+ * To be used as a return type.
15
+ *
16
+ * @template TMessage The error message.
17
+ */
18
+ type PreviousFunctionReceivedBadInputError<TMessage extends ErrorMessage> = Brand<TMessage>;
19
+ //#endregion
20
+ //#region src/column-reference.d.ts
21
+ /**
22
+ * An object representing a reference to a column in a table in the database.
23
+ *
24
+ * @template TColumnName The name of the column.
25
+ * @template TTableName The name of the table this column belongs to.
26
+ * @template THash The contract storage hash belonging to the database this column is in.
27
+ */
28
+ type ColumnReference<TColumnName extends string = string, TTableName extends string = string, THash extends StorageHashBase<string> = StorageHashBase<string>> = {
29
+ readonly '~name': TColumnName;
30
+ readonly '~table': TTableName;
31
+ } & Brand<'[info] this column reference belongs to the following table reference:', `${TTableName}@${THash}`>;
32
+ /**
33
+ * An error type indicating that the provided column reference is out of the contract's scope.
34
+ * To be used in reference creators, e.g. `createRef()`.
35
+ *
36
+ * @template TMessage The error message.
37
+ */
38
+ type ColumnReferenceOutOfContractError<TMessage extends ErrorMessage> = Brand<TMessage>;
39
+ /**
40
+ * A type representing a reference to all columns in the current query context.
41
+ */
42
+ type Asterisk = {
43
+ readonly '~name': '*';
44
+ readonly '~table': null;
45
+ } & Brand<'[info] referencing all columns in the current query context'>;
46
+ /**
47
+ * A type representing a reference to all columns in a specific table.
48
+ *
49
+ * @template TTableName The name of the table whose columns are being referenced.
50
+ * @template THash The contract storage hash belonging to the database this column is in.
51
+ */
52
+ type TableAsterisk<TTableName extends string = string, THash extends StorageHashBase<string> = StorageHashBase<string>> = {
53
+ readonly '~name': '*';
54
+ readonly '~table': TTableName;
55
+ } & Brand<'[info] referencing all columns that belong to the following table reference:', `${TTableName}@${THash}`>;
56
+ //#endregion
57
+ //#region src/table-reference.d.ts
58
+ /**
59
+ * An object representing a reference to a table in the database.
60
+ *
61
+ * @template TName The name of the table. `string` is all tables, a union of string literals is a set of specific tables, a single string literal is a specific table.
62
+ * @template THash The contract storage hash belonging to the database this table is in.
63
+ */
64
+ type TableReference<TName extends string = string, THash extends StorageHashBase<string> = StorageHashBase<string>> = {
65
+ readonly '~name': TName;
66
+ } & Brand<'[info] this table reference belongs to the contract with the following storage hash:', THash>;
67
+ /**
68
+ * An error type indicating that the provided table reference is out of the contract's scope.
69
+ * To be used in reference creators, e.g. `createRef()`.
70
+ *
71
+ * @template TMessage The error message.
72
+ */
73
+ type TableReferenceOutOfContractError<TMessage extends ErrorMessage> = Brand<TMessage>;
74
+ /**
75
+ * An error type indicating that the provided table reference is too wide.
76
+ * To be used as a `never` alternative in conditional types.
77
+ *
78
+ * @template TMessage The error message.
79
+ */
80
+ type TableReferenceTooWideError<TMessage extends ErrorMessage> = Brand<TMessage>;
81
+ //#endregion
82
+ //#region src/ref.d.ts
83
+ /**
84
+ * A fluent API representing references to tables and columns in a SQL contract.
85
+ *
86
+ * @template TContract The contract that describes the database.
87
+ */
88
+ type Ref<TContract extends SqlContract> = { readonly [TableName in keyof TContract['storage']['tables'] & string]: TableReference<TableName, TContract['storageHash']> & { readonly [ColumnName in Exclude<keyof TContract['storage']['tables'][TableName]['columns'], keyof TableReference> & string]: ColumnReference<ColumnName, TableName, TContract['storageHash']> } & {
89
+ readonly ['*']: TableAsterisk<TableName, TContract['storageHash']>;
90
+ } & Record<PropertyKey, ColumnReferenceOutOfContractError<`[error] reference to a non-existing column in the '${TableName}' table`>> } & {
91
+ readonly ['*']: Asterisk;
92
+ } & Record<PropertyKey, TableReferenceOutOfContractError<`[error] reference to a non-existing table in the contract`>>;
93
+ /**
94
+ * Creates a reference object for the given SQL contract.
95
+ *
96
+ * @template TContract The contract that describes the database.
97
+ */
98
+ declare function createRef<TContract extends SqlContract>(_contract: TContract): Ref<TContract>;
99
+ //#endregion
100
+ //#region src/type-atoms.d.ts
101
+ /**
102
+ * A utility type to drain outer generics from a type. A compiler micro-optimization.
103
+ *
104
+ * @template TThing The type to drain.
105
+ */
106
+ type DrainOuterGeneric<TThing> = [TThing] extends [unknown] ? TThing : never;
107
+ /**
108
+ * A utility type to ensure that exactly one property of an object type is present.
109
+ *
110
+ * @template TObject The object type to check.
111
+ */
112
+ type ExactlyOneProperty<TObject extends object> = { [K in keyof TObject]-?: IsNever<Exclude<keyof TObject, K>> }[keyof TObject];
113
+ /**
114
+ * A utility type to merge two objects.
115
+ *
116
+ * @template TObject0 The first object.
117
+ * @template TObject1 The second object.
118
+ */
119
+ type MergeObjects<TObject0 extends object, TObject1 extends object> = DrainOuterGeneric<IsNever<TObject0> extends true ? TObject1 : { readonly [K in keyof TObject0 | keyof TObject1]: K extends keyof TObject1 ? TObject1[K] : K extends keyof TObject0 ? TObject0[K] : never }>;
120
+ /**
121
+ * A utility type to determine if a type is `never`.
122
+ *
123
+ * @template TThing The type to check.
124
+ */
125
+ type IsNever<TThing> = [TThing] extends [never] ? true : false;
126
+ /**
127
+ * A utility type to simplify an object type for better readability.
128
+ *
129
+ * @template TObject The object type to simplify.
130
+ */
131
+ type Simplify<TObject extends object> = DrainOuterGeneric<{ [K in keyof TObject]: TObject[K] } & {}>;
132
+ //#endregion
133
+ //#region src/selection.d.ts
134
+ /**
135
+ * A utility type to extract the output type of a referenced column from a contract.
136
+ * Uses the type-only codec channel (ExtractCodecTypes), not runtime mappings.
137
+ *
138
+ * @template TContract The contract that describes the database.
139
+ * @template TTableName The name of the table containing the column.
140
+ * @template TColumnName The name of the column whose output type is to be extracted.
141
+ */
142
+ type ExtractOutputType<TContract extends SqlContract, TTableName extends keyof TContract['storage']['tables'] & string, TColumnName extends keyof TContract['storage']['tables'][TTableName]['columns'] & string, _TColumn = TContract['storage']['tables'][TTableName]['columns'][TColumnName]> = _TColumn extends StorageColumn ? (_TColumn['nullable'] extends true ? null : never) | ExtractCodecTypes<TContract>[_TColumn['codecId']]['output'] : never;
143
+ /**
144
+ * A type representing a selection of columns in a SQL `select` query in the
145
+ * most generic form.
146
+ */
147
+ type Selection = Record<string, SelectionValue<unknown, unknown>>;
148
+ /**
149
+ * A type representing the value of a selected column in a SQL `select` query.
150
+ *
151
+ * @template TOutput The output type of the selected column.
152
+ * @template TDatatype The database-side datatype of the selected column.
153
+ */
154
+ interface SelectionValue<TOutput, TDatatype extends string | unknown = unknown> {
155
+ readonly '~datatype': TDatatype;
156
+ readonly '~output': TOutput;
157
+ }
158
+ /**
159
+ * A utility type to convert a table's columns into a {@link Selection}.
160
+ *
161
+ * @template TContract The contract that describes the database.
162
+ * @template TTableName The name of the table whose columns will be included in the selection.
163
+ */
164
+ type TableToSelection<TContract extends SqlContract, TTableName extends keyof TContract['storage']['tables'] & string> = DrainOuterGeneric<{ readonly [ColumnName in keyof TContract['storage']['tables'][TTableName]['columns'] & string]: SelectionValue<ExtractOutputType<TContract, TTableName, ColumnName>, TContract['storage']['tables'][TTableName]['columns'][ColumnName]['nativeType']> }>;
165
+ //#endregion
166
+ //#region src/select-builder.d.ts
167
+ /**
168
+ * A builder for SQL `select` queries.
169
+ *
170
+ * @template TContract The contract that describes the database.
171
+ * @template TTables The tables involved in the current `select` query.
172
+ * @template TSelection The current selection of the `select` query.
173
+ */
174
+ declare class SelectBuilder<TContract extends SqlContract, TTables extends SqlContract['storage']['tables'], TSelection extends Selection = never> {
175
+ #private;
176
+ constructor(contract: TContract);
177
+ select(asterisk: Asterisk): ExactlyOneProperty<TTables> extends true ? SelectBuilder<TContract, TTables, MergeObjects<TSelection, TableToSelection<TContract, keyof TTables & string>>> : PreviousFunctionReceivedBadInputError<'[error] selecting all columns via `*` results in ambiguity when multiple tables are involved in the query'>;
178
+ select<TTableName extends keyof TTables & string>(asterisk: TableAsterisk<TTableName, TContract['storageHash']>): SelectBuilder<TContract, TTables, MergeObjects<TSelection, TableToSelection<TContract, TTableName>>>;
179
+ select(arg: never): PreviousFunctionReceivedBadInputError<'[error] invalid input in previous `select()` call'>;
180
+ build(): IsNever<TSelection> extends true ? never : Simplify<TSelection>;
181
+ }
182
+ //#endregion
183
+ //#region src/root.d.ts
184
+ /**
185
+ * The root of all builder.
186
+ *
187
+ * @template TContract The contract that describes the database.
188
+ */
189
+ declare class Root<TContract extends SqlContract> {
190
+ #private;
191
+ constructor(contract: TContract);
192
+ /**
193
+ * SQL's `from` clause, where all `select` queries actually start from.
194
+ *
195
+ * @param table The table to select from.
196
+ */
197
+ from(table: TableReference<never>): PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;
198
+ /**
199
+ * @template TName The name of the table to select from.
200
+ */
201
+ from<TName extends string>(table: string extends TName ? TableReferenceTooWideError<'[error] `root.from()` call received a table reference without a specific table name'> : TableReference<TName, TContract['storageHash']>): TName extends string ? SelectBuilder<TContract, Pick<TContract['storage']['tables'], TName>> : PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;
202
+ from(table: TableReferenceTooWideError<'[error] `root.from()` call received a table reference without a specific table name'>): PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;
203
+ }
204
+ /**
205
+ * Creates a new `Root` instance.
206
+ */
207
+ declare function createRoot(contract: never): PreviousFunctionReceivedBadInputError<'[error] root creation will likely fail at runtime given the passed contract is not valid or verified'>;
208
+ /**
209
+ * @template TContract The contract that describes the database.
210
+ */
211
+ declare function createRoot<TContract extends SqlContract>(contract: TContract): Root<TContract>;
212
+ //#endregion
213
+ export { type Asterisk, type ColumnReference, type ColumnReferenceOutOfContractError, type DrainOuterGeneric, type ErrorMessage, type ExactlyOneProperty, type ExtractOutputType, type IsNever, type MergeObjects, type PreviousFunctionReceivedBadInputError, type Ref, type Root, type SelectBuilder, type Selection, type SelectionValue, type Simplify, type TableAsterisk, type TableReference, type TableReferenceOutOfContractError, type TableReferenceTooWideError, type TableToSelection, createRef, createRoot };
214
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/type-errors.ts","../src/column-reference.ts","../src/table-reference.ts","../src/ref.ts","../src/type-atoms.ts","../src/selection.ts","../src/select-builder.ts","../src/root.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAOA;AAQA;AAAmE,KARvD,YAAA,GAQuD,WAAA,MAAA,EAAA;;;;;;;ACLvD,KDKA,qCCLe,CAAA,iBDKwC,YCLxC,CAAA,GDKwD,KCLxD,CDK8D,QCL9D,CAAA;;;;;ADH3B;AAQA;;;;AAAwF,KCL5E,eDK4E,CAAA,oBAAA,MAAA,GAAA,MAAA,EAAA,mBAAA,MAAA,GAAA,MAAA,EAAA,cCFxE,eDEwE,CAAA,MAAA,CAAA,GCF9C,eDE8C,CAAA,MAAA,CAAA,CAAA,GAAA;oBCApE;qBACC;IACjB,mFAEC,cAAc;AATnB;;;;;;AASmB,KASP,iCATO,CAAA,iBAS4C,YAT5C,CAAA,GAS4D,KAT5D,CASkE,QATlE,CAAA;;;AASnB;AAA+D,KAKnD,QAAA,GALmD;EAAsB,SAAA,OAAA,EAAA,GAAA;EAAN,SAAA,QAAA,EAAA,IAAA;CAAK,GAQhF,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4BhB,qCL5BgB,CAAA,mDAAA,CAAA;EAGhB,KAAA,CAAA,CAAA,EKiCM,OLjCN,CKiCc,ULjCd,CAAA,SAAA,IAAA,GAAA,KAAA,GKoCC,QLpCD,CKoCU,ULpCV,CAAA;;;;ADZL;AAQA;;;;AAAwF,cOL3E,IPK2E,CAAA,kBOLpD,WPKoD,CAAA,CAAA;;wBOFhE;;ANHxB;;;;EAMqB,IAAA,CAAA,KAAA,EMOV,cNPU,CAAA,KAAA,CAAA,CAAA,EMQhB,qCNRgB,CAAA,mGAAA,CAAA;EAGhB;;;EAFI,IAAA,CAAA,cAAA,MAAA,CAAA,CAAA,KAAA,EAAA,MAAA,SMYiB,KNZjB,GMaD,0BNbC,CAAA,qFAAA,CAAA,GMcD,cNdC,CMcc,KNdd,EMcqB,SNdrB,CAAA,aAAA,CAAA,CAAA,CAAA,EMeJ,KNfI,SAAA,MAAA,GMgBH,aNhBG,CMgBW,SNhBX,EMgBsB,INhBtB,CMgB2B,SNhB3B,CAAA,SAAA,CAAA,CAAA,QAAA,CAAA,EMgB2D,KNhB3D,CAAA,CAAA,GMiBH,qCNjBG,CAAA,mGAAA,CAAA;EAWG,IAAA,CAAA,KAAA,EMQD,0BNRkC,CAAA,qFAAA,CAAA,CAAA,EMSxC,qCNTwC,CAAA,mGAAA,CAAA;;;;;AAKjC,iBMiBI,UAAA,CNdP,QAAA,EAAA,KAAA,CAAA,EMgBN,qCNhBM,CAAA,sGAAA,CAAA;AAQT;;;AAKqB,iBMOL,UNPK,CAAA,kBMOwB,WNPxB,CAAA,CAAA,QAAA,EMO+C,SNP/C,CAAA,EMO2D,INP3D,CMOgE,SNPhE,CAAA"}
package/dist/index.mjs CHANGED
@@ -1 +1,73 @@
1
- export { };
1
+ //#region src/ref.ts
2
+ /**
3
+ * Creates a reference object for the given SQL contract.
4
+ *
5
+ * @template TContract The contract that describes the database.
6
+ */
7
+ function createRef(_contract) {
8
+ return new Proxy({}, { get(_target, tableName) {
9
+ if (tableName === "*") return Object.freeze({
10
+ "~name": tableName,
11
+ "~table": null
12
+ });
13
+ return new Proxy({}, { get(_target$1, columnName) {
14
+ if (columnName === "~name") return tableName;
15
+ return Object.freeze({
16
+ "~name": columnName,
17
+ "~table": tableName
18
+ });
19
+ } });
20
+ } });
21
+ }
22
+
23
+ //#endregion
24
+ //#region src/select-builder.ts
25
+ /**
26
+ * A builder for SQL `select` queries.
27
+ *
28
+ * @template TContract The contract that describes the database.
29
+ * @template TTables The tables involved in the current `select` query.
30
+ * @template TSelection The current selection of the `select` query.
31
+ */
32
+ var SelectBuilder = class {
33
+ #contract;
34
+ constructor(contract) {
35
+ this.#contract = contract;
36
+ }
37
+ select(..._args) {
38
+ return this;
39
+ }
40
+ build() {
41
+ return {};
42
+ }
43
+ };
44
+
45
+ //#endregion
46
+ //#region src/root.ts
47
+ /**
48
+ * The root of all builder.
49
+ *
50
+ * @template TContract The contract that describes the database.
51
+ */
52
+ var Root = class {
53
+ #contract;
54
+ constructor(contract) {
55
+ this.#contract = contract;
56
+ }
57
+ /**
58
+ * @internal
59
+ */
60
+ from(_table) {
61
+ return new SelectBuilder(this.#contract);
62
+ }
63
+ };
64
+ /**
65
+ * @internal
66
+ */
67
+ function createRoot(contract) {
68
+ return new Root(contract);
69
+ }
70
+
71
+ //#endregion
72
+ export { createRef, createRoot };
73
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["#contract","#contract"],"sources":["../src/ref.ts","../src/select-builder.ts","../src/root.ts"],"sourcesContent":["import type { SqlContract } from '@prisma-next/sql-contract/types';\nimport type {\n Asterisk,\n ColumnReference,\n ColumnReferenceOutOfContractError,\n TableAsterisk,\n} from './column-reference';\nimport type { TableReference, TableReferenceOutOfContractError } from './table-reference';\n\n/**\n * A fluent API representing references to tables and columns in a SQL contract.\n *\n * @template TContract The contract that describes the database.\n */\nexport type Ref<TContract extends SqlContract> = {\n readonly [TableName in keyof TContract['storage']['tables'] & string]: TableReference<\n TableName,\n TContract['storageHash']\n > & {\n readonly [ColumnName in Exclude<\n keyof TContract['storage']['tables'][TableName]['columns'],\n keyof TableReference\n > &\n string]: ColumnReference<ColumnName, TableName, TContract['storageHash']>;\n } & {\n readonly ['*']: TableAsterisk<TableName, TContract['storageHash']>;\n } & Record<\n PropertyKey,\n ColumnReferenceOutOfContractError<`[error] reference to a non-existing column in the '${TableName}' table`>\n >;\n} & {\n readonly ['*']: Asterisk;\n} & Record<\n PropertyKey,\n TableReferenceOutOfContractError<`[error] reference to a non-existing table in the contract`>\n >;\n\n/**\n * Creates a reference object for the given SQL contract.\n *\n * @template TContract The contract that describes the database.\n */\nexport function createRef<TContract extends SqlContract>(_contract: TContract): Ref<TContract> {\n return new Proxy({} as Ref<TContract>, {\n get(_target, tableName) {\n if (tableName === '*') {\n return Object.freeze({\n '~name': tableName,\n '~table': null,\n });\n }\n\n return new Proxy(\n {},\n {\n get(_target, columnName) {\n if (columnName === '~name') {\n return tableName;\n }\n\n return Object.freeze({\n '~name': columnName,\n '~table': tableName,\n });\n },\n },\n );\n },\n });\n}\n","import type { SqlContract } from '@prisma-next/sql-contract/types';\nimport type { Asterisk, TableAsterisk } from './column-reference';\nimport type { Selection, TableToSelection } from './selection';\nimport type { ExactlyOneProperty, IsNever, MergeObjects, Simplify } from './type-atoms';\nimport type { PreviousFunctionReceivedBadInputError } from './type-errors';\n\n/**\n * A builder for SQL `select` queries.\n *\n * @template TContract The contract that describes the database.\n * @template TTables The tables involved in the current `select` query.\n * @template TSelection The current selection of the `select` query.\n */\nexport class SelectBuilder<\n TContract extends SqlContract,\n TTables extends SqlContract['storage']['tables'],\n TSelection extends Selection = never,\n> {\n // @ts-expect-error\n // biome-ignore lint/correctness/noUnusedPrivateClassMembers: will be used soon.\n readonly #contract: TContract;\n\n constructor(contract: TContract) {\n this.#contract = contract;\n }\n\n select(\n asterisk: Asterisk,\n ): ExactlyOneProperty<TTables> extends true\n ? SelectBuilder<\n TContract,\n TTables,\n MergeObjects<TSelection, TableToSelection<TContract, keyof TTables & string>>\n >\n : PreviousFunctionReceivedBadInputError<'[error] selecting all columns via `*` results in ambiguity when multiple tables are involved in the query'>;\n select<TTableName extends keyof TTables & string>(\n asterisk: TableAsterisk<TTableName, TContract['storageHash']>,\n ): SelectBuilder<\n TContract,\n TTables,\n MergeObjects<TSelection, TableToSelection<TContract, TTableName>>\n >;\n select(\n arg: never,\n ): PreviousFunctionReceivedBadInputError<'[error] invalid input in previous `select()` call'>;\n select(..._args: unknown[]): unknown {\n // TODO: do runtime stuff.\n return this;\n }\n\n // TODO: the return type here is not the real one we'll use eventually.\n // I'm using something to test the selection stuff.\n build(): IsNever<TSelection> extends true\n ? // TODO: either split to two builders or provide a type-level error here.\n never\n : Simplify<TSelection> {\n // TODO: do runtime stuff.\n return {} as never;\n }\n}\n","import type { SqlContract } from '@prisma-next/sql-contract/types';\nimport { SelectBuilder } from './select-builder';\nimport type { TableReference, TableReferenceTooWideError } from './table-reference';\nimport type { PreviousFunctionReceivedBadInputError } from './type-errors';\n\n/**\n * The root of all builder.\n *\n * @template TContract The contract that describes the database.\n */\nexport class Root<TContract extends SqlContract> {\n readonly #contract: TContract;\n\n constructor(contract: TContract) {\n this.#contract = contract;\n }\n\n /**\n * SQL's `from` clause, where all `select` queries actually start from.\n *\n * @param table The table to select from.\n */\n from(\n table: TableReference<never>,\n ): PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;\n /**\n * @template TName The name of the table to select from.\n */\n from<TName extends string>(\n table: string extends TName\n ? TableReferenceTooWideError<'[error] `root.from()` call received a table reference without a specific table name'>\n : TableReference<TName, TContract['storageHash']>,\n ): TName extends string\n ? SelectBuilder<TContract, Pick<TContract['storage']['tables'], TName>>\n : PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;\n from(\n table: TableReferenceTooWideError<'[error] `root.from()` call received a table reference without a specific table name'>,\n ): PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;\n /**\n * @internal\n */\n from(_table: unknown): unknown {\n // TODO: use runtime table reference value to do something \"AST\"-related.\n return new SelectBuilder(this.#contract);\n }\n}\n\n/**\n * Creates a new `Root` instance.\n */\nexport function createRoot(\n contract: never,\n): PreviousFunctionReceivedBadInputError<'[error] root creation will likely fail at runtime given the passed contract is not valid or verified'>;\n/**\n * @template TContract The contract that describes the database.\n */\nexport function createRoot<TContract extends SqlContract>(contract: TContract): Root<TContract>;\n/**\n * @internal\n */\nexport function createRoot(contract: unknown): unknown {\n return new Root(contract as SqlContract);\n}\n"],"mappings":";;;;;;AA0CA,SAAgB,UAAyC,WAAsC;AAC7F,QAAO,IAAI,MAAM,EAAE,EAAoB,EACrC,IAAI,SAAS,WAAW;AACtB,MAAI,cAAc,IAChB,QAAO,OAAO,OAAO;GACnB,SAAS;GACT,UAAU;GACX,CAAC;AAGJ,SAAO,IAAI,MACT,EAAE,EACF,EACE,IAAI,WAAS,YAAY;AACvB,OAAI,eAAe,QACjB,QAAO;AAGT,UAAO,OAAO,OAAO;IACnB,SAAS;IACT,UAAU;IACX,CAAC;KAEL,CACF;IAEJ,CAAC;;;;;;;;;;;;ACvDJ,IAAa,gBAAb,MAIE;CAGA,CAASA;CAET,YAAY,UAAqB;AAC/B,QAAKA,WAAY;;CAsBnB,OAAO,GAAG,OAA2B;AAEnC,SAAO;;CAKT,QAGyB;AAEvB,SAAO,EAAE;;;;;;;;;;;AC/Cb,IAAa,OAAb,MAAiD;CAC/C,CAASC;CAET,YAAY,UAAqB;AAC/B,QAAKA,WAAY;;;;;CA2BnB,KAAK,QAA0B;AAE7B,SAAO,IAAI,cAAc,MAAKA,SAAU;;;;;;AAiB5C,SAAgB,WAAW,UAA4B;AACrD,QAAO,IAAI,KAAK,SAAwB"}
package/package.json CHANGED
@@ -1,25 +1,17 @@
1
1
  {
2
2
  "name": "@prisma-next/sql-lane-query-builder",
3
- "version": "0.0.1",
3
+ "version": "0.3.0-dev.100",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "SQL query builder lane for Prisma Next",
7
- "scripts": {
8
- "build": "tsdown",
9
- "test": "vitest run --passWithNoTests",
10
- "test:coverage": "vitest run --coverage --passWithNoTests",
11
- "typecheck": "tsc --noEmit",
12
- "lint": "biome check . --error-on-warnings",
13
- "lint:fix": "biome check --write .",
14
- "lint:fix:unsafe": "biome check --write --unsafe .",
15
- "clean": "rm -rf dist coverage .tmp-output"
16
- },
17
7
  "devDependencies": {
18
- "@prisma-next/tsconfig": "workspace:*",
19
- "@prisma-next/tsdown": "workspace:*",
20
- "tsdown": "catalog:",
21
- "typescript": "catalog:",
22
- "vitest": "catalog:"
8
+ "tsdown": "0.18.4",
9
+ "typescript": "5.9.3",
10
+ "vitest": "4.0.17",
11
+ "@prisma-next/contract": "0.3.0-dev.100",
12
+ "@prisma-next/sql-contract": "0.3.0-dev.100",
13
+ "@prisma-next/tsdown": "0.0.0",
14
+ "@prisma-next/tsconfig": "0.0.0"
23
15
  },
24
16
  "files": [
25
17
  "dist",
@@ -34,5 +26,20 @@
34
26
  },
35
27
  "main": "./dist/index.mjs",
36
28
  "module": "./dist/index.mjs",
37
- "types": "./dist/index.d.mts"
38
- }
29
+ "types": "./dist/index.d.mts",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/prisma/prisma-next.git",
33
+ "directory": "packages/2-sql/4-lanes/query-builder"
34
+ },
35
+ "scripts": {
36
+ "build": "tsdown",
37
+ "test": "vitest run --passWithNoTests",
38
+ "~test:coverage": "vitest run --coverage --passWithNoTests",
39
+ "typecheck": "tsc --noEmit",
40
+ "lint": "biome check . --error-on-warnings",
41
+ "lint:fix": "biome check --write .",
42
+ "lint:fix:unsafe": "biome check --write --unsafe .",
43
+ "clean": "rm -rf dist dist-tsc dist-tsc-prod coverage .tmp-output"
44
+ }
45
+ }
@@ -0,0 +1,54 @@
1
+ import type { Brand, StorageHashBase } from '@prisma-next/contract/types';
2
+ import type { ErrorMessage } from './type-errors';
3
+
4
+ /**
5
+ * An object representing a reference to a column in a table in the database.
6
+ *
7
+ * @template TColumnName The name of the column.
8
+ * @template TTableName The name of the table this column belongs to.
9
+ * @template THash The contract storage hash belonging to the database this column is in.
10
+ */
11
+ export type ColumnReference<
12
+ TColumnName extends string = string,
13
+ TTableName extends string = string,
14
+ THash extends StorageHashBase<string> = StorageHashBase<string>,
15
+ > = {
16
+ readonly '~name': TColumnName;
17
+ readonly '~table': TTableName;
18
+ } & Brand<
19
+ '[info] this column reference belongs to the following table reference:',
20
+ `${TTableName}@${THash}`
21
+ >;
22
+
23
+ /**
24
+ * An error type indicating that the provided column reference is out of the contract's scope.
25
+ * To be used in reference creators, e.g. `createRef()`.
26
+ *
27
+ * @template TMessage The error message.
28
+ */
29
+ export type ColumnReferenceOutOfContractError<TMessage extends ErrorMessage> = Brand<TMessage>;
30
+
31
+ /**
32
+ * A type representing a reference to all columns in the current query context.
33
+ */
34
+ export type Asterisk = {
35
+ readonly '~name': '*';
36
+ readonly '~table': null;
37
+ } & Brand<'[info] referencing all columns in the current query context'>;
38
+
39
+ /**
40
+ * A type representing a reference to all columns in a specific table.
41
+ *
42
+ * @template TTableName The name of the table whose columns are being referenced.
43
+ * @template THash The contract storage hash belonging to the database this column is in.
44
+ */
45
+ export type TableAsterisk<
46
+ TTableName extends string = string,
47
+ THash extends StorageHashBase<string> = StorageHashBase<string>,
48
+ > = {
49
+ readonly '~name': '*';
50
+ readonly '~table': TTableName;
51
+ } & Brand<
52
+ '[info] referencing all columns that belong to the following table reference:',
53
+ `${TTableName}@${THash}`
54
+ >;
package/src/index.ts CHANGED
@@ -1,2 +1,34 @@
1
- // SQL query builder lane for Prisma Next
2
- // This package will contain query builder utilities
1
+ export type {
2
+ Asterisk,
3
+ ColumnReference,
4
+ ColumnReferenceOutOfContractError,
5
+ TableAsterisk,
6
+ } from './column-reference';
7
+ export {
8
+ createRef,
9
+ type Ref,
10
+ } from './ref';
11
+ export { createRoot, type Root } from './root';
12
+ export type { SelectBuilder } from './select-builder';
13
+ export type {
14
+ ExtractOutputType,
15
+ Selection,
16
+ SelectionValue,
17
+ TableToSelection,
18
+ } from './selection';
19
+ export type {
20
+ TableReference,
21
+ TableReferenceOutOfContractError,
22
+ TableReferenceTooWideError,
23
+ } from './table-reference';
24
+ export type {
25
+ DrainOuterGeneric,
26
+ ExactlyOneProperty,
27
+ IsNever,
28
+ MergeObjects,
29
+ Simplify,
30
+ } from './type-atoms';
31
+ export type {
32
+ ErrorMessage,
33
+ PreviousFunctionReceivedBadInputError,
34
+ } from './type-errors';
package/src/ref.ts ADDED
@@ -0,0 +1,70 @@
1
+ import type { SqlContract } from '@prisma-next/sql-contract/types';
2
+ import type {
3
+ Asterisk,
4
+ ColumnReference,
5
+ ColumnReferenceOutOfContractError,
6
+ TableAsterisk,
7
+ } from './column-reference';
8
+ import type { TableReference, TableReferenceOutOfContractError } from './table-reference';
9
+
10
+ /**
11
+ * A fluent API representing references to tables and columns in a SQL contract.
12
+ *
13
+ * @template TContract The contract that describes the database.
14
+ */
15
+ export type Ref<TContract extends SqlContract> = {
16
+ readonly [TableName in keyof TContract['storage']['tables'] & string]: TableReference<
17
+ TableName,
18
+ TContract['storageHash']
19
+ > & {
20
+ readonly [ColumnName in Exclude<
21
+ keyof TContract['storage']['tables'][TableName]['columns'],
22
+ keyof TableReference
23
+ > &
24
+ string]: ColumnReference<ColumnName, TableName, TContract['storageHash']>;
25
+ } & {
26
+ readonly ['*']: TableAsterisk<TableName, TContract['storageHash']>;
27
+ } & Record<
28
+ PropertyKey,
29
+ ColumnReferenceOutOfContractError<`[error] reference to a non-existing column in the '${TableName}' table`>
30
+ >;
31
+ } & {
32
+ readonly ['*']: Asterisk;
33
+ } & Record<
34
+ PropertyKey,
35
+ TableReferenceOutOfContractError<`[error] reference to a non-existing table in the contract`>
36
+ >;
37
+
38
+ /**
39
+ * Creates a reference object for the given SQL contract.
40
+ *
41
+ * @template TContract The contract that describes the database.
42
+ */
43
+ export function createRef<TContract extends SqlContract>(_contract: TContract): Ref<TContract> {
44
+ return new Proxy({} as Ref<TContract>, {
45
+ get(_target, tableName) {
46
+ if (tableName === '*') {
47
+ return Object.freeze({
48
+ '~name': tableName,
49
+ '~table': null,
50
+ });
51
+ }
52
+
53
+ return new Proxy(
54
+ {},
55
+ {
56
+ get(_target, columnName) {
57
+ if (columnName === '~name') {
58
+ return tableName;
59
+ }
60
+
61
+ return Object.freeze({
62
+ '~name': columnName,
63
+ '~table': tableName,
64
+ });
65
+ },
66
+ },
67
+ );
68
+ },
69
+ });
70
+ }
package/src/root.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { SqlContract } from '@prisma-next/sql-contract/types';
2
+ import { SelectBuilder } from './select-builder';
3
+ import type { TableReference, TableReferenceTooWideError } from './table-reference';
4
+ import type { PreviousFunctionReceivedBadInputError } from './type-errors';
5
+
6
+ /**
7
+ * The root of all builder.
8
+ *
9
+ * @template TContract The contract that describes the database.
10
+ */
11
+ export class Root<TContract extends SqlContract> {
12
+ readonly #contract: TContract;
13
+
14
+ constructor(contract: TContract) {
15
+ this.#contract = contract;
16
+ }
17
+
18
+ /**
19
+ * SQL's `from` clause, where all `select` queries actually start from.
20
+ *
21
+ * @param table The table to select from.
22
+ */
23
+ from(
24
+ table: TableReference<never>,
25
+ ): PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;
26
+ /**
27
+ * @template TName The name of the table to select from.
28
+ */
29
+ from<TName extends string>(
30
+ table: string extends TName
31
+ ? TableReferenceTooWideError<'[error] `root.from()` call received a table reference without a specific table name'>
32
+ : TableReference<TName, TContract['storageHash']>,
33
+ ): TName extends string
34
+ ? SelectBuilder<TContract, Pick<TContract['storage']['tables'], TName>>
35
+ : PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;
36
+ from(
37
+ table: TableReferenceTooWideError<'[error] `root.from()` call received a table reference without a specific table name'>,
38
+ ): PreviousFunctionReceivedBadInputError<'[error] invalid table reference in previous `root.from()` call will probably cause runtime errors'>;
39
+ /**
40
+ * @internal
41
+ */
42
+ from(_table: unknown): unknown {
43
+ // TODO: use runtime table reference value to do something "AST"-related.
44
+ return new SelectBuilder(this.#contract);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Creates a new `Root` instance.
50
+ */
51
+ export function createRoot(
52
+ contract: never,
53
+ ): PreviousFunctionReceivedBadInputError<'[error] root creation will likely fail at runtime given the passed contract is not valid or verified'>;
54
+ /**
55
+ * @template TContract The contract that describes the database.
56
+ */
57
+ export function createRoot<TContract extends SqlContract>(contract: TContract): Root<TContract>;
58
+ /**
59
+ * @internal
60
+ */
61
+ export function createRoot(contract: unknown): unknown {
62
+ return new Root(contract as SqlContract);
63
+ }
@@ -0,0 +1,60 @@
1
+ import type { SqlContract } from '@prisma-next/sql-contract/types';
2
+ import type { Asterisk, TableAsterisk } from './column-reference';
3
+ import type { Selection, TableToSelection } from './selection';
4
+ import type { ExactlyOneProperty, IsNever, MergeObjects, Simplify } from './type-atoms';
5
+ import type { PreviousFunctionReceivedBadInputError } from './type-errors';
6
+
7
+ /**
8
+ * A builder for SQL `select` queries.
9
+ *
10
+ * @template TContract The contract that describes the database.
11
+ * @template TTables The tables involved in the current `select` query.
12
+ * @template TSelection The current selection of the `select` query.
13
+ */
14
+ export class SelectBuilder<
15
+ TContract extends SqlContract,
16
+ TTables extends SqlContract['storage']['tables'],
17
+ TSelection extends Selection = never,
18
+ > {
19
+ // @ts-expect-error
20
+ // biome-ignore lint/correctness/noUnusedPrivateClassMembers: will be used soon.
21
+ readonly #contract: TContract;
22
+
23
+ constructor(contract: TContract) {
24
+ this.#contract = contract;
25
+ }
26
+
27
+ select(
28
+ asterisk: Asterisk,
29
+ ): ExactlyOneProperty<TTables> extends true
30
+ ? SelectBuilder<
31
+ TContract,
32
+ TTables,
33
+ MergeObjects<TSelection, TableToSelection<TContract, keyof TTables & string>>
34
+ >
35
+ : PreviousFunctionReceivedBadInputError<'[error] selecting all columns via `*` results in ambiguity when multiple tables are involved in the query'>;
36
+ select<TTableName extends keyof TTables & string>(
37
+ asterisk: TableAsterisk<TTableName, TContract['storageHash']>,
38
+ ): SelectBuilder<
39
+ TContract,
40
+ TTables,
41
+ MergeObjects<TSelection, TableToSelection<TContract, TTableName>>
42
+ >;
43
+ select(
44
+ arg: never,
45
+ ): PreviousFunctionReceivedBadInputError<'[error] invalid input in previous `select()` call'>;
46
+ select(..._args: unknown[]): unknown {
47
+ // TODO: do runtime stuff.
48
+ return this;
49
+ }
50
+
51
+ // TODO: the return type here is not the real one we'll use eventually.
52
+ // I'm using something to test the selection stuff.
53
+ build(): IsNever<TSelection> extends true
54
+ ? // TODO: either split to two builders or provide a type-level error here.
55
+ never
56
+ : Simplify<TSelection> {
57
+ // TODO: do runtime stuff.
58
+ return {} as never;
59
+ }
60
+ }
@@ -0,0 +1,59 @@
1
+ import type {
2
+ ExtractCodecTypes,
3
+ SqlContract,
4
+ StorageColumn,
5
+ } from '@prisma-next/sql-contract/types';
6
+ import type { DrainOuterGeneric } from './type-atoms';
7
+
8
+ /**
9
+ * A utility type to extract the output type of a referenced column from a contract.
10
+ * Uses the type-only codec channel (ExtractCodecTypes), not runtime mappings.
11
+ *
12
+ * @template TContract The contract that describes the database.
13
+ * @template TTableName The name of the table containing the column.
14
+ * @template TColumnName The name of the column whose output type is to be extracted.
15
+ */
16
+ export type ExtractOutputType<
17
+ TContract extends SqlContract,
18
+ TTableName extends keyof TContract['storage']['tables'] & string,
19
+ TColumnName extends keyof TContract['storage']['tables'][TTableName]['columns'] & string,
20
+ _TColumn = TContract['storage']['tables'][TTableName]['columns'][TColumnName],
21
+ > = _TColumn extends StorageColumn
22
+ ?
23
+ | (_TColumn['nullable'] extends true ? null : never)
24
+ | ExtractCodecTypes<TContract>[_TColumn['codecId']]['output']
25
+ : never;
26
+
27
+ /**
28
+ * A type representing a selection of columns in a SQL `select` query in the
29
+ * most generic form.
30
+ */
31
+ export type Selection = Record<string, SelectionValue<unknown, unknown>>;
32
+
33
+ /**
34
+ * A type representing the value of a selected column in a SQL `select` query.
35
+ *
36
+ * @template TOutput The output type of the selected column.
37
+ * @template TDatatype The database-side datatype of the selected column.
38
+ */
39
+ export interface SelectionValue<TOutput, TDatatype extends string | unknown = unknown> {
40
+ readonly '~datatype': TDatatype;
41
+ readonly '~output': TOutput;
42
+ }
43
+
44
+ /**
45
+ * A utility type to convert a table's columns into a {@link Selection}.
46
+ *
47
+ * @template TContract The contract that describes the database.
48
+ * @template TTableName The name of the table whose columns will be included in the selection.
49
+ */
50
+ export type TableToSelection<
51
+ TContract extends SqlContract,
52
+ TTableName extends keyof TContract['storage']['tables'] & string,
53
+ > = DrainOuterGeneric<{
54
+ readonly [ColumnName in keyof TContract['storage']['tables'][TTableName]['columns'] &
55
+ string]: SelectionValue<
56
+ ExtractOutputType<TContract, TTableName, ColumnName>,
57
+ TContract['storage']['tables'][TTableName]['columns'][ColumnName]['nativeType']
58
+ >;
59
+ }>;
@@ -0,0 +1,34 @@
1
+ import type { Brand, StorageHashBase } from '@prisma-next/contract/types';
2
+ import type { ErrorMessage } from './type-errors';
3
+
4
+ /**
5
+ * An object representing a reference to a table in the database.
6
+ *
7
+ * @template TName The name of the table. `string` is all tables, a union of string literals is a set of specific tables, a single string literal is a specific table.
8
+ * @template THash The contract storage hash belonging to the database this table is in.
9
+ */
10
+ export type TableReference<
11
+ TName extends string = string,
12
+ THash extends StorageHashBase<string> = StorageHashBase<string>,
13
+ > = {
14
+ readonly '~name': TName;
15
+ } & Brand<
16
+ '[info] this table reference belongs to the contract with the following storage hash:',
17
+ THash
18
+ >;
19
+
20
+ /**
21
+ * An error type indicating that the provided table reference is out of the contract's scope.
22
+ * To be used in reference creators, e.g. `createRef()`.
23
+ *
24
+ * @template TMessage The error message.
25
+ */
26
+ export type TableReferenceOutOfContractError<TMessage extends ErrorMessage> = Brand<TMessage>;
27
+
28
+ /**
29
+ * An error type indicating that the provided table reference is too wide.
30
+ * To be used as a `never` alternative in conditional types.
31
+ *
32
+ * @template TMessage The error message.
33
+ */
34
+ export type TableReferenceTooWideError<TMessage extends ErrorMessage> = Brand<TMessage>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A utility type to drain outer generics from a type. A compiler micro-optimization.
3
+ *
4
+ * @template TThing The type to drain.
5
+ */
6
+ export type DrainOuterGeneric<TThing> = [TThing] extends [unknown] ? TThing : never;
7
+
8
+ /**
9
+ * A utility type to ensure that exactly one property of an object type is present.
10
+ *
11
+ * @template TObject The object type to check.
12
+ */
13
+ export type ExactlyOneProperty<TObject extends object> = {
14
+ [K in keyof TObject]-?: IsNever<Exclude<keyof TObject, K>>;
15
+ }[keyof TObject];
16
+
17
+ /**
18
+ * A utility type to merge two objects.
19
+ *
20
+ * @template TObject0 The first object.
21
+ * @template TObject1 The second object.
22
+ */
23
+ export type MergeObjects<TObject0 extends object, TObject1 extends object> = DrainOuterGeneric<
24
+ IsNever<TObject0> extends true
25
+ ? TObject1
26
+ : {
27
+ readonly [K in keyof TObject0 | keyof TObject1]: K extends keyof TObject1
28
+ ? TObject1[K]
29
+ : K extends keyof TObject0
30
+ ? TObject0[K]
31
+ : never;
32
+ }
33
+ >;
34
+
35
+ /**
36
+ * A utility type to determine if a type is `never`.
37
+ *
38
+ * @template TThing The type to check.
39
+ */
40
+ export type IsNever<TThing> = [TThing] extends [never] ? true : false;
41
+
42
+ /**
43
+ * A utility type to simplify an object type for better readability.
44
+ *
45
+ * @template TObject The object type to simplify.
46
+ */
47
+ export type Simplify<TObject extends object> = DrainOuterGeneric<
48
+ { [K in keyof TObject]: TObject[K] } & {}
49
+ >;
@@ -0,0 +1,16 @@
1
+ import type { Brand } from '@prisma-next/contract/types';
2
+
3
+ /**
4
+ * An error message type, prefixed with `[error]`.
5
+ *
6
+ * @template TMessage The error message.
7
+ */
8
+ export type ErrorMessage = `[error] ${string}`;
9
+
10
+ /**
11
+ * An error type indicating that the previous function call had bad input.
12
+ * To be used as a return type.
13
+ *
14
+ * @template TMessage The error message.
15
+ */
16
+ export type PreviousFunctionReceivedBadInputError<TMessage extends ErrorMessage> = Brand<TMessage>;