@duckdbfan/drizzle-duckdb 0.0.1
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/.prettierrc +7 -0
- package/LICENSE +201 -0
- package/README.md +66 -0
- package/bun.lockb +0 -0
- package/package.json +38 -0
- package/src/columns.ts +1 -0
- package/src/dialect.ts +108 -0
- package/src/driver.ts +273 -0
- package/src/index.ts +3 -0
- package/src/migrator.ts +18 -0
- package/src/session.ts +237 -0
- package/src/utils.ts +216 -0
- package/tsconfig.json +25 -0
package/.prettierrc
ADDED
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 [yyyy] [name of copyright owner]
|
|
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
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# drizzle-duckdb
|
|
2
|
+
|
|
3
|
+
## Description
|
|
4
|
+
A drizzle ORM client for use with DuckDB. Based on drizzle's Postgres client. As of writing this, certain things will work, and others won't. Notably, DuckDB-specific column types such as `struct`, `list`, `array` are not implemented, but this could be done using [drizzle custom types](https://orm.drizzle.team/docs/custom-types). (This is planned to be implemented in the package later on)
|
|
5
|
+
|
|
6
|
+
## Disclaimers
|
|
7
|
+
- **Experimental**: This project is in an experimental stage. Certain features may be broken or not function as expected.
|
|
8
|
+
- **Use at Your Own Risk**: Users should proceed with caution and use this project at their own risk.
|
|
9
|
+
- **Maintenance**: This project may not be actively maintained. Updates and bug fixes are not guaranteed.
|
|
10
|
+
|
|
11
|
+
## Getting Started
|
|
12
|
+
1. Install dependencies:
|
|
13
|
+
```sh
|
|
14
|
+
bun add @duckdbfan/drizzle-duckdb
|
|
15
|
+
```
|
|
16
|
+
2. Figure it out! (sorry, might flesh this out later- see tests for some examples)
|
|
17
|
+
```typescript
|
|
18
|
+
import { Database } from 'duckdb-async';
|
|
19
|
+
import { drizzle } from '@duckdbfan/drizzle-duckdb';
|
|
20
|
+
import { DefaultLogger, sql } from 'drizzle-orm';
|
|
21
|
+
import { char, integer, pgSchema, text } from 'drizzle-orm/pg-core';
|
|
22
|
+
|
|
23
|
+
const client = await Database.create(':memory:');
|
|
24
|
+
const db = drizzle(client, { logger: new DefaultLogger() });
|
|
25
|
+
|
|
26
|
+
const customSchema = pgSchema('custom');
|
|
27
|
+
|
|
28
|
+
await db.execute(sql`CREATE SCHEMA IF NOT EXISTS ${customSchema}`);
|
|
29
|
+
|
|
30
|
+
const citiesTable = customSchema.table('cities', {
|
|
31
|
+
id: integer('id')
|
|
32
|
+
.primaryKey()
|
|
33
|
+
.default(sql`nextval('serial_cities')`),
|
|
34
|
+
name: text('name').notNull(),
|
|
35
|
+
state: char('state', { length: 2 }),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
await db.execute(sql`CREATE SEQUENCE IF NOT EXISTS serial_cities;`);
|
|
39
|
+
|
|
40
|
+
await db.execute(
|
|
41
|
+
sql`
|
|
42
|
+
create table if not exists ${citiesTable} (
|
|
43
|
+
id integer primary key default nextval('serial_cities'),
|
|
44
|
+
name text not null,
|
|
45
|
+
state char(2)
|
|
46
|
+
)
|
|
47
|
+
`
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
const insertedIds = await db
|
|
51
|
+
.insert(citiesTable)
|
|
52
|
+
.values([
|
|
53
|
+
{ name: 'Paris', state: 'FR' },
|
|
54
|
+
{ name: 'London', state: 'UK' },
|
|
55
|
+
])
|
|
56
|
+
.returning({ id: citiesTable.id });
|
|
57
|
+
|
|
58
|
+
console.log(insertedIds);
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Contributing
|
|
63
|
+
Contributions are welcome, although I may not be very responsive.
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
This project is licensed under the Apache License.
|
package/bun.lockb
ADDED
|
Binary file
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@duckdbfan/drizzle-duckdb",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "A drizzle ORM client for use with DuckDB. Based on drizzle's Postgres client.",
|
|
5
|
+
"main": "./src/index.ts",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "vitest",
|
|
8
|
+
"t": "vitest --watch --ui"
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"drizzle-orm": "0.40.0",
|
|
12
|
+
"duckdb-async": "^1.2.0"
|
|
13
|
+
},
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@types/bun": "^1.2.5",
|
|
16
|
+
"@types/uuid": "^10.0.0",
|
|
17
|
+
"@vitest/ui": "^1.6.0",
|
|
18
|
+
"uuid": "^10.0.0",
|
|
19
|
+
"vitest": "^1.6.0"
|
|
20
|
+
},
|
|
21
|
+
"directories": {
|
|
22
|
+
"test": "test"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/duckdbfan/drizzle-duckdb.git"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"drizzle",
|
|
30
|
+
"duckdb"
|
|
31
|
+
],
|
|
32
|
+
"author": "M L",
|
|
33
|
+
"license": "Apache-2.0",
|
|
34
|
+
"bugs": {
|
|
35
|
+
"url": "https://github.com/duckdbfan/drizzle-duckdb/issues"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/duckdbfan/drizzle-duckdb#readme"
|
|
38
|
+
}
|
package/src/columns.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/src/dialect.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { entityKind, is } from 'drizzle-orm/entity';
|
|
2
|
+
import type { MigrationConfig, MigrationMeta } from 'drizzle-orm/migrator';
|
|
3
|
+
import {
|
|
4
|
+
PgDate,
|
|
5
|
+
PgDateString,
|
|
6
|
+
PgDialect,
|
|
7
|
+
PgJson,
|
|
8
|
+
PgJsonb,
|
|
9
|
+
PgNumeric,
|
|
10
|
+
PgSession,
|
|
11
|
+
PgTime,
|
|
12
|
+
PgTimestamp,
|
|
13
|
+
PgTimestampString,
|
|
14
|
+
PgUUID,
|
|
15
|
+
} from 'drizzle-orm/pg-core';
|
|
16
|
+
import { DuckDBSession } from './session';
|
|
17
|
+
import {
|
|
18
|
+
sql,
|
|
19
|
+
type DriverValueEncoder,
|
|
20
|
+
type QueryTypingsValue,
|
|
21
|
+
} from 'drizzle-orm';
|
|
22
|
+
|
|
23
|
+
export class DuckDBDialect extends PgDialect {
|
|
24
|
+
static readonly [entityKind]: string = 'DuckDBPgDialect';
|
|
25
|
+
|
|
26
|
+
override async migrate(
|
|
27
|
+
migrations: MigrationMeta[],
|
|
28
|
+
session: PgSession,
|
|
29
|
+
config: MigrationConfig
|
|
30
|
+
): Promise<void> {
|
|
31
|
+
const migrationsSchema = config.migrationsSchema ?? 'drizzle';
|
|
32
|
+
|
|
33
|
+
const migrationsTable = config.migrationsTable ?? '__drizzle_migrations';
|
|
34
|
+
|
|
35
|
+
const migrationTableCreate = sql`
|
|
36
|
+
CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(
|
|
37
|
+
migrationsTable
|
|
38
|
+
)} (
|
|
39
|
+
id integer PRIMARY KEY default nextval('migrations_pk_seq'),
|
|
40
|
+
hash text NOT NULL,
|
|
41
|
+
created_at bigint
|
|
42
|
+
)
|
|
43
|
+
`;
|
|
44
|
+
|
|
45
|
+
await session.execute(
|
|
46
|
+
sql.raw('CREATE SEQUENCE IF NOT EXISTS migrations_pk_seq')
|
|
47
|
+
);
|
|
48
|
+
await session.execute(
|
|
49
|
+
sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`
|
|
50
|
+
);
|
|
51
|
+
await session.execute(migrationTableCreate);
|
|
52
|
+
|
|
53
|
+
const dbMigrations = await session.all<{
|
|
54
|
+
id: number;
|
|
55
|
+
hash: string;
|
|
56
|
+
created_at: string;
|
|
57
|
+
}>(
|
|
58
|
+
sql`select id, hash, created_at from ${sql.identifier(
|
|
59
|
+
migrationsSchema
|
|
60
|
+
)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
const lastDbMigration = dbMigrations[0];
|
|
64
|
+
|
|
65
|
+
await session.transaction(async (tx) => {
|
|
66
|
+
for await (const migration of migrations) {
|
|
67
|
+
if (
|
|
68
|
+
!lastDbMigration ||
|
|
69
|
+
Number(lastDbMigration.created_at) < migration.folderMillis
|
|
70
|
+
) {
|
|
71
|
+
for (const stmt of migration.sql) {
|
|
72
|
+
await tx.execute(sql.raw(stmt));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
await tx.execute(
|
|
76
|
+
sql`insert into ${sql.identifier(
|
|
77
|
+
migrationsSchema
|
|
78
|
+
)}.${sql.identifier(
|
|
79
|
+
migrationsTable
|
|
80
|
+
)} ("hash", "created_at") values(${migration.hash}, ${
|
|
81
|
+
migration.folderMillis
|
|
82
|
+
})`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
override prepareTyping(
|
|
90
|
+
encoder: DriverValueEncoder<unknown, unknown>
|
|
91
|
+
): QueryTypingsValue {
|
|
92
|
+
if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
|
|
93
|
+
throw new Error('JSON and JSONB types are not supported in DuckDB');
|
|
94
|
+
} else if (is(encoder, PgNumeric)) {
|
|
95
|
+
return 'decimal';
|
|
96
|
+
} else if (is(encoder, PgTime)) {
|
|
97
|
+
return 'time';
|
|
98
|
+
} else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
|
|
99
|
+
return 'timestamp';
|
|
100
|
+
} else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
|
|
101
|
+
return 'date';
|
|
102
|
+
} else if (is(encoder, PgUUID)) {
|
|
103
|
+
return 'uuid';
|
|
104
|
+
} else {
|
|
105
|
+
return 'none';
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
package/src/driver.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { entityKind, is } from 'drizzle-orm/entity';
|
|
2
|
+
import type { Logger } from 'drizzle-orm/logger';
|
|
3
|
+
import { DefaultLogger } from 'drizzle-orm/logger';
|
|
4
|
+
import { PgDatabase } from 'drizzle-orm/pg-core/db';
|
|
5
|
+
import { PgDialect } from 'drizzle-orm/pg-core/dialect';
|
|
6
|
+
import {
|
|
7
|
+
createTableRelationsHelpers,
|
|
8
|
+
extractTablesRelationalConfig,
|
|
9
|
+
type ExtractTablesWithRelations,
|
|
10
|
+
type RelationalSchemaConfig,
|
|
11
|
+
type TablesRelationalConfig,
|
|
12
|
+
} from 'drizzle-orm/relations';
|
|
13
|
+
import {
|
|
14
|
+
getTableColumns,
|
|
15
|
+
type DrizzleConfig,
|
|
16
|
+
type DrizzleTypeError,
|
|
17
|
+
} from 'drizzle-orm/utils';
|
|
18
|
+
import type {
|
|
19
|
+
DuckDBClient,
|
|
20
|
+
DuckDBQueryResultHKT,
|
|
21
|
+
DuckDBTransaction,
|
|
22
|
+
} from './session';
|
|
23
|
+
import { DuckDBSession } from './session.ts';
|
|
24
|
+
import { DuckDBDialect } from './dialect.ts';
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
PgSelectBase,
|
|
28
|
+
PgSelectBuilder,
|
|
29
|
+
type CreatePgSelectFromBuilderMode,
|
|
30
|
+
type SelectedFields,
|
|
31
|
+
type TableLikeHasEmptySelection,
|
|
32
|
+
} from 'drizzle-orm/pg-core/query-builders';
|
|
33
|
+
import {
|
|
34
|
+
PgColumn,
|
|
35
|
+
PgTable,
|
|
36
|
+
type PgSession,
|
|
37
|
+
type PgTransactionConfig,
|
|
38
|
+
} from 'drizzle-orm/pg-core';
|
|
39
|
+
import { sql, SQL, type ColumnsSelection } from 'drizzle-orm/sql/sql';
|
|
40
|
+
import { Column } from 'drizzle-orm/column';
|
|
41
|
+
import { Subquery, ViewBaseConfig, type SQLWrapper } from 'drizzle-orm';
|
|
42
|
+
import { PgViewBase } from 'drizzle-orm/pg-core/view-base';
|
|
43
|
+
import type {
|
|
44
|
+
GetSelectTableName,
|
|
45
|
+
GetSelectTableSelection,
|
|
46
|
+
} from 'drizzle-orm/query-builders/select.types';
|
|
47
|
+
import { aliasFields } from './utils.ts';
|
|
48
|
+
|
|
49
|
+
export interface PgDriverOptions {
|
|
50
|
+
logger?: Logger;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const selectionRegex = /select\s+(.+)\s+from/i;
|
|
54
|
+
const aliasRegex = /as\s+(.+)$/i;
|
|
55
|
+
|
|
56
|
+
export class DuckDBDriver {
|
|
57
|
+
static readonly [entityKind]: string = 'DuckDBDriver';
|
|
58
|
+
|
|
59
|
+
constructor(
|
|
60
|
+
private client: DuckDBClient,
|
|
61
|
+
private dialect: DuckDBDialect,
|
|
62
|
+
private options: PgDriverOptions = {}
|
|
63
|
+
) {
|
|
64
|
+
// const clientProxy = new Proxy(client, {
|
|
65
|
+
// get(target, prop, receiver) {
|
|
66
|
+
// if (prop === 'all') {
|
|
67
|
+
// return (query: string, params: Parameters<typeof target.all>) => {
|
|
68
|
+
// // DuckDB names returned variables differently than Postgres
|
|
69
|
+
// // so we need to remap them to match the Postgres names
|
|
70
|
+
// const selection = selectionRegex.exec(query);
|
|
71
|
+
// if (selection?.length !== 2) {
|
|
72
|
+
// return target.all(query, params);
|
|
73
|
+
// }
|
|
74
|
+
// const fields = selection[1].split(',').map((field) => {});
|
|
75
|
+
// return target.all(query, params);
|
|
76
|
+
// };
|
|
77
|
+
// }
|
|
78
|
+
// return Reflect.get(target, prop, receiver);
|
|
79
|
+
// },
|
|
80
|
+
// });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
createSession(
|
|
84
|
+
schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined
|
|
85
|
+
): DuckDBSession<Record<string, unknown>, TablesRelationalConfig> {
|
|
86
|
+
return new DuckDBSession(this.client, this.dialect, schema, {
|
|
87
|
+
logger: this.options.logger,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Need to work around omitted internal types from drizzle...
|
|
93
|
+
// interface DuckDBDatabaseInternal<
|
|
94
|
+
// TSchema extends Record<string, unknown> = Record<string, never>
|
|
95
|
+
// > extends PgDatabase<DuckDBQueryResultHKT, TSchema> {
|
|
96
|
+
// dialect: PgDialect;
|
|
97
|
+
// session: DuckDBSession<Record<string, unknown>, TablesRelationalConfig>;
|
|
98
|
+
// }
|
|
99
|
+
|
|
100
|
+
// export type DuckDBDatabase<
|
|
101
|
+
// TSchema extends Record<string, unknown> = Record<string, never>
|
|
102
|
+
// > = DuckDBDatabaseInternal<TSchema>;
|
|
103
|
+
|
|
104
|
+
export function drizzle<
|
|
105
|
+
TSchema extends Record<string, unknown> = Record<string, never>
|
|
106
|
+
>(
|
|
107
|
+
client: DuckDBClient,
|
|
108
|
+
config: DrizzleConfig<TSchema> = {}
|
|
109
|
+
): DuckDBDatabase<TSchema, ExtractTablesWithRelations<TSchema>> {
|
|
110
|
+
const dialect = new DuckDBDialect();
|
|
111
|
+
|
|
112
|
+
const logger =
|
|
113
|
+
config.logger === true ? new DefaultLogger() : config.logger || undefined;
|
|
114
|
+
|
|
115
|
+
let schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined;
|
|
116
|
+
|
|
117
|
+
if (config.schema) {
|
|
118
|
+
const tablesConfig = extractTablesRelationalConfig(
|
|
119
|
+
config.schema,
|
|
120
|
+
createTableRelationsHelpers
|
|
121
|
+
);
|
|
122
|
+
schema = {
|
|
123
|
+
fullSchema: config.schema,
|
|
124
|
+
schema: tablesConfig.tables,
|
|
125
|
+
tableNamesMap: tablesConfig.tableNamesMap,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const driver = new DuckDBDriver(client, dialect, { logger });
|
|
130
|
+
const session = driver.createSession(schema);
|
|
131
|
+
|
|
132
|
+
return new DuckDBDatabase(dialect, session, schema) as DuckDBDatabase<
|
|
133
|
+
TSchema,
|
|
134
|
+
ExtractTablesWithRelations<TSchema>
|
|
135
|
+
>;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export class DuckDBDatabase<
|
|
139
|
+
TFullSchema extends Record<string, unknown> = Record<string, never>,
|
|
140
|
+
TSchema extends TablesRelationalConfig = ExtractTablesWithRelations<TFullSchema>
|
|
141
|
+
> extends PgDatabase<DuckDBQueryResultHKT, TFullSchema, TSchema> {
|
|
142
|
+
static readonly [entityKind]: string = 'DuckDBDatabase';
|
|
143
|
+
|
|
144
|
+
constructor(
|
|
145
|
+
readonly dialect: DuckDBDialect,
|
|
146
|
+
readonly session: DuckDBSession<TFullSchema, TSchema>,
|
|
147
|
+
schema: RelationalSchemaConfig<TSchema> | undefined
|
|
148
|
+
) {
|
|
149
|
+
super(dialect, session, schema);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
select(): PgSelectBuilder<undefined>;
|
|
153
|
+
select<TSelection extends SelectedFields>(
|
|
154
|
+
fields: TSelection
|
|
155
|
+
): PgSelectBuilder<TSelection>;
|
|
156
|
+
select(fields?: SelectedFields): PgSelectBuilder<SelectedFields | undefined> {
|
|
157
|
+
if (!fields) {
|
|
158
|
+
// iterate over all fields and do the same as below (may have to extend/override `.from()`)
|
|
159
|
+
|
|
160
|
+
return new DuckDBSelectBuilder({
|
|
161
|
+
fields: fields ?? undefined,
|
|
162
|
+
session: this.session as unknown as PgSession<DuckDBQueryResultHKT>,
|
|
163
|
+
dialect: this.dialect,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const aliasedFields: SelectedFields = aliasFields(fields);
|
|
168
|
+
|
|
169
|
+
return new DuckDBSelectBuilder({
|
|
170
|
+
fields: aliasedFields,
|
|
171
|
+
session: this.session as unknown as PgSession<DuckDBQueryResultHKT>,
|
|
172
|
+
dialect: this.dialect,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
override async transaction<T>(
|
|
177
|
+
transaction: (tx: DuckDBTransaction<TFullSchema, TSchema>) => Promise<T>
|
|
178
|
+
): Promise<T> {
|
|
179
|
+
return await this.session.transaction<T>(transaction);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
interface PgViewBaseInternal<
|
|
184
|
+
TName extends string = string,
|
|
185
|
+
TExisting extends boolean = boolean,
|
|
186
|
+
TSelectedFields extends ColumnsSelection = ColumnsSelection
|
|
187
|
+
> extends PgViewBase<TName, TExisting, TSelectedFields> {
|
|
188
|
+
[ViewBaseConfig]?: {
|
|
189
|
+
selectedFields: SelectedFields;
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export class DuckDBSelectBuilder<
|
|
194
|
+
TSelection extends SelectedFields | undefined,
|
|
195
|
+
TBuilderMode extends 'db' | 'qb' = 'db'
|
|
196
|
+
> extends PgSelectBuilder<TSelection, TBuilderMode> {
|
|
197
|
+
private _fields: TSelection;
|
|
198
|
+
private _session: PgSession | undefined;
|
|
199
|
+
private _dialect: DuckDBDialect;
|
|
200
|
+
private _withList: Subquery[] = [];
|
|
201
|
+
private _distinct:
|
|
202
|
+
| boolean
|
|
203
|
+
| {
|
|
204
|
+
on: (PgColumn | SQLWrapper)[];
|
|
205
|
+
}
|
|
206
|
+
| undefined;
|
|
207
|
+
|
|
208
|
+
constructor(config: {
|
|
209
|
+
fields: TSelection;
|
|
210
|
+
session: PgSession | undefined;
|
|
211
|
+
dialect: PgDialect;
|
|
212
|
+
withList?: Subquery[];
|
|
213
|
+
distinct?:
|
|
214
|
+
| boolean
|
|
215
|
+
| {
|
|
216
|
+
on: (PgColumn | SQLWrapper)[];
|
|
217
|
+
};
|
|
218
|
+
}) {
|
|
219
|
+
super(config);
|
|
220
|
+
this._fields = config.fields;
|
|
221
|
+
this._session = config.session;
|
|
222
|
+
this._dialect = config.dialect;
|
|
223
|
+
if (config.withList) {
|
|
224
|
+
this._withList = config.withList;
|
|
225
|
+
}
|
|
226
|
+
this._distinct = config.distinct;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
from<TFrom extends PgTable | Subquery | PgViewBaseInternal | SQL>(
|
|
230
|
+
source: TableLikeHasEmptySelection<TFrom> extends true
|
|
231
|
+
? DrizzleTypeError<"Cannot reference a data-modifying statement subquery if it doesn't contain a `returning` clause">
|
|
232
|
+
: TFrom
|
|
233
|
+
): CreatePgSelectFromBuilderMode<
|
|
234
|
+
TBuilderMode,
|
|
235
|
+
GetSelectTableName<TFrom>,
|
|
236
|
+
TSelection extends undefined ? GetSelectTableSelection<TFrom> : TSelection,
|
|
237
|
+
TSelection extends undefined ? 'single' : 'partial'
|
|
238
|
+
> {
|
|
239
|
+
const isPartialSelect = !!this._fields;
|
|
240
|
+
const src = source as TFrom;
|
|
241
|
+
|
|
242
|
+
let fields: SelectedFields;
|
|
243
|
+
if (this._fields) {
|
|
244
|
+
fields = this._fields;
|
|
245
|
+
} else if (is(src, Subquery)) {
|
|
246
|
+
// This is required to use the proxy handler to get the correct field values from the subquery
|
|
247
|
+
fields = Object.fromEntries(
|
|
248
|
+
Object.keys(src._.selectedFields).map((key) => [
|
|
249
|
+
key,
|
|
250
|
+
src[
|
|
251
|
+
key as unknown as keyof typeof src
|
|
252
|
+
] as unknown as SelectedFields[string],
|
|
253
|
+
])
|
|
254
|
+
);
|
|
255
|
+
} else if (is(src, PgViewBase)) {
|
|
256
|
+
fields = src[ViewBaseConfig]?.selectedFields as SelectedFields;
|
|
257
|
+
} else if (is(src, SQL)) {
|
|
258
|
+
fields = {};
|
|
259
|
+
} else {
|
|
260
|
+
fields = aliasFields(getTableColumns<PgTable>(src), !isPartialSelect);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return new PgSelectBase({
|
|
264
|
+
table: src,
|
|
265
|
+
fields,
|
|
266
|
+
isPartialSelect,
|
|
267
|
+
session: this._session,
|
|
268
|
+
dialect: this._dialect,
|
|
269
|
+
withList: this._withList,
|
|
270
|
+
distinct: this._distinct,
|
|
271
|
+
}) as any;
|
|
272
|
+
}
|
|
273
|
+
}
|
package/src/index.ts
ADDED
package/src/migrator.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { MigrationConfig } from 'drizzle-orm/migrator';
|
|
2
|
+
import { readMigrationFiles } from 'drizzle-orm/migrator';
|
|
3
|
+
import type { DuckDBDatabase } from './driver';
|
|
4
|
+
import type { PgSession } from 'drizzle-orm/pg-core/session';
|
|
5
|
+
|
|
6
|
+
export async function migrate<TSchema extends Record<string, unknown>>(
|
|
7
|
+
db: DuckDBDatabase<TSchema>,
|
|
8
|
+
config: MigrationConfig
|
|
9
|
+
) {
|
|
10
|
+
const migrations = readMigrationFiles(config);
|
|
11
|
+
|
|
12
|
+
await db.dialect.migrate(
|
|
13
|
+
migrations,
|
|
14
|
+
// Need to work around omitted internal types from drizzle...
|
|
15
|
+
db.session as unknown as PgSession,
|
|
16
|
+
config
|
|
17
|
+
);
|
|
18
|
+
}
|
package/src/session.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import type { Connection, Database, RowData } from 'duckdb-async';
|
|
2
|
+
import { entityKind } from 'drizzle-orm/entity';
|
|
3
|
+
import { type Logger, NoopLogger } from 'drizzle-orm/logger';
|
|
4
|
+
import type { PgDialect } from 'drizzle-orm/pg-core/dialect';
|
|
5
|
+
import { PgTransaction } from 'drizzle-orm/pg-core';
|
|
6
|
+
import type { SelectedFieldsOrdered } from 'drizzle-orm/pg-core/query-builders/select.types';
|
|
7
|
+
import type {
|
|
8
|
+
PgTransactionConfig,
|
|
9
|
+
PreparedQueryConfig,
|
|
10
|
+
PgQueryResultHKT,
|
|
11
|
+
} from 'drizzle-orm/pg-core/session';
|
|
12
|
+
import { PgPreparedQuery, PgSession } from 'drizzle-orm/pg-core/session';
|
|
13
|
+
import type {
|
|
14
|
+
RelationalSchemaConfig,
|
|
15
|
+
TablesRelationalConfig,
|
|
16
|
+
} from 'drizzle-orm/relations';
|
|
17
|
+
import { fillPlaceholders, type Query, SQL, sql } from 'drizzle-orm/sql/sql';
|
|
18
|
+
import type { Assume } from 'drizzle-orm/utils';
|
|
19
|
+
import { mapResultRow } from './utils';
|
|
20
|
+
import type { DuckDBDialect } from './dialect';
|
|
21
|
+
import { TransactionRollbackError } from 'drizzle-orm/errors';
|
|
22
|
+
|
|
23
|
+
export type DuckDBClient = Database;
|
|
24
|
+
|
|
25
|
+
export class DuckDBPreparedQuery<
|
|
26
|
+
T extends PreparedQueryConfig
|
|
27
|
+
> extends PgPreparedQuery<T> {
|
|
28
|
+
static readonly [entityKind]: string = 'DuckDBPreparedQuery';
|
|
29
|
+
|
|
30
|
+
// private rawQueryConfig: QueryOptions;
|
|
31
|
+
// private queryConfig: QueryOptions;
|
|
32
|
+
|
|
33
|
+
constructor(
|
|
34
|
+
private client: DuckDBClient | Connection,
|
|
35
|
+
private queryString: string,
|
|
36
|
+
private params: unknown[],
|
|
37
|
+
private logger: Logger,
|
|
38
|
+
private fields: SelectedFieldsOrdered | undefined,
|
|
39
|
+
private _isResponseInArrayMode: boolean,
|
|
40
|
+
private customResultMapper?: (rows: unknown[][]) => T['execute']
|
|
41
|
+
) {
|
|
42
|
+
super({ sql: queryString, params });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async execute(
|
|
46
|
+
placeholderValues: Record<string, unknown> | undefined = {}
|
|
47
|
+
): Promise<T['execute']> {
|
|
48
|
+
const params = fillPlaceholders(this.params, placeholderValues);
|
|
49
|
+
|
|
50
|
+
this.logger.logQuery(this.queryString, params);
|
|
51
|
+
|
|
52
|
+
const {
|
|
53
|
+
fields,
|
|
54
|
+
client,
|
|
55
|
+
joinsNotNullableMap,
|
|
56
|
+
customResultMapper,
|
|
57
|
+
queryString,
|
|
58
|
+
} = this as typeof this & { joinsNotNullableMap?: Record<string, boolean> };
|
|
59
|
+
|
|
60
|
+
const rows = (await client.all(queryString, ...params)) ?? [];
|
|
61
|
+
|
|
62
|
+
if (rows.length === 0 || !fields) {
|
|
63
|
+
return rows;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const rowValues = rows.map((row) => Object.values(row));
|
|
67
|
+
|
|
68
|
+
return customResultMapper
|
|
69
|
+
? customResultMapper(rowValues)
|
|
70
|
+
: rowValues.map((row) =>
|
|
71
|
+
mapResultRow<T['execute']>(fields!, row, joinsNotNullableMap)
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
all(
|
|
76
|
+
placeholderValues: Record<string, unknown> | undefined = {}
|
|
77
|
+
): Promise<T['all']> {
|
|
78
|
+
return this.execute(placeholderValues);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
isResponseInArrayMode(): boolean {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface DuckDBSessionOptions {
|
|
87
|
+
logger?: Logger;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class DuckDBSession<
|
|
91
|
+
TFullSchema extends Record<string, unknown> = Record<string, never>,
|
|
92
|
+
TSchema extends TablesRelationalConfig = Record<string, never>
|
|
93
|
+
> extends PgSession<DuckDBQueryResultHKT, TFullSchema, TSchema> {
|
|
94
|
+
static readonly [entityKind]: string = 'DuckDBSession';
|
|
95
|
+
|
|
96
|
+
private logger: Logger;
|
|
97
|
+
|
|
98
|
+
constructor(
|
|
99
|
+
private client: DuckDBClient | Connection,
|
|
100
|
+
dialect: DuckDBDialect,
|
|
101
|
+
private schema: RelationalSchemaConfig<TSchema> | undefined,
|
|
102
|
+
private options: DuckDBSessionOptions = {}
|
|
103
|
+
) {
|
|
104
|
+
super(dialect);
|
|
105
|
+
this.logger = options.logger ?? new NoopLogger();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
prepareQuery<T extends PreparedQueryConfig = PreparedQueryConfig>(
|
|
109
|
+
query: Query,
|
|
110
|
+
fields: SelectedFieldsOrdered | undefined,
|
|
111
|
+
name: string | undefined,
|
|
112
|
+
isResponseInArrayMode: boolean,
|
|
113
|
+
customResultMapper?: (rows: unknown[][]) => T['execute']
|
|
114
|
+
): PgPreparedQuery<T> {
|
|
115
|
+
return new DuckDBPreparedQuery(
|
|
116
|
+
this.client,
|
|
117
|
+
query.sql,
|
|
118
|
+
query.params,
|
|
119
|
+
this.logger,
|
|
120
|
+
fields,
|
|
121
|
+
isResponseInArrayMode,
|
|
122
|
+
customResultMapper
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
override async transaction<T>(
|
|
127
|
+
transaction: (tx: DuckDBTransaction<TFullSchema, TSchema>) => Promise<T>
|
|
128
|
+
): Promise<T> {
|
|
129
|
+
const connection =
|
|
130
|
+
'connect' in this.client ? await this.client.connect() : this.client;
|
|
131
|
+
|
|
132
|
+
const session = new DuckDBSession(
|
|
133
|
+
connection,
|
|
134
|
+
this.dialect,
|
|
135
|
+
this.schema,
|
|
136
|
+
this.options
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
const tx = new DuckDBTransaction<TFullSchema, TSchema>(
|
|
140
|
+
this.dialect,
|
|
141
|
+
session,
|
|
142
|
+
this.schema
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
await tx.execute(sql`BEGIN TRANSACTION;`);
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
const result = await transaction(tx);
|
|
149
|
+
await tx.execute(sql`commit`);
|
|
150
|
+
return result;
|
|
151
|
+
} catch (error) {
|
|
152
|
+
await tx.execute(sql`rollback`);
|
|
153
|
+
throw error;
|
|
154
|
+
} finally {
|
|
155
|
+
await connection.close();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
type PgTransactionInternals<
|
|
161
|
+
TFullSchema extends Record<string, unknown> = Record<string, never>,
|
|
162
|
+
TSchema extends TablesRelationalConfig = Record<string, never>
|
|
163
|
+
> = {
|
|
164
|
+
dialect: DuckDBDialect;
|
|
165
|
+
session: DuckDBSession<TFullSchema, TSchema>;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
type DuckDBTransactionWithInternals<
|
|
169
|
+
TFullSchema extends Record<string, unknown> = Record<string, never>,
|
|
170
|
+
TSchema extends TablesRelationalConfig = Record<string, never>
|
|
171
|
+
> = PgTransactionInternals<TFullSchema, TSchema> &
|
|
172
|
+
DuckDBTransaction<TFullSchema, TSchema>;
|
|
173
|
+
|
|
174
|
+
export class DuckDBTransaction<
|
|
175
|
+
TFullSchema extends Record<string, unknown>,
|
|
176
|
+
TSchema extends TablesRelationalConfig
|
|
177
|
+
> extends PgTransaction<DuckDBQueryResultHKT, TFullSchema, TSchema> {
|
|
178
|
+
static readonly [entityKind]: string = 'DuckDBTransaction';
|
|
179
|
+
|
|
180
|
+
rollback(): never {
|
|
181
|
+
throw new TransactionRollbackError();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
getTransactionConfigSQL(config: PgTransactionConfig): SQL {
|
|
185
|
+
const chunks: string[] = [];
|
|
186
|
+
if (config.isolationLevel) {
|
|
187
|
+
chunks.push(`isolation level ${config.isolationLevel}`);
|
|
188
|
+
}
|
|
189
|
+
if (config.accessMode) {
|
|
190
|
+
chunks.push(config.accessMode);
|
|
191
|
+
}
|
|
192
|
+
if (typeof config.deferrable === 'boolean') {
|
|
193
|
+
chunks.push(config.deferrable ? 'deferrable' : 'not deferrable');
|
|
194
|
+
}
|
|
195
|
+
return sql.raw(chunks.join(' '));
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
setTransaction(config: PgTransactionConfig): Promise<void> {
|
|
199
|
+
// Need to work around omitted internal types from drizzle...
|
|
200
|
+
type Tx = DuckDBTransactionWithInternals<TFullSchema, TSchema>;
|
|
201
|
+
return (this as unknown as Tx).session.execute(
|
|
202
|
+
sql`set transaction ${this.getTransactionConfigSQL(config)}`
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
override async transaction<T>(
|
|
207
|
+
transaction: (tx: DuckDBTransaction<TFullSchema, TSchema>) => Promise<T>
|
|
208
|
+
): Promise<T> {
|
|
209
|
+
// Need to work around omitted internal types from drizzle...
|
|
210
|
+
type Tx = DuckDBTransactionWithInternals<TFullSchema, TSchema>;
|
|
211
|
+
|
|
212
|
+
const savepointName = `sp${this.nestedIndex + 1}`;
|
|
213
|
+
const tx = new DuckDBTransaction<TFullSchema, TSchema>(
|
|
214
|
+
(this as unknown as Tx).dialect,
|
|
215
|
+
(this as unknown as Tx).session,
|
|
216
|
+
this.schema,
|
|
217
|
+
this.nestedIndex + 1
|
|
218
|
+
);
|
|
219
|
+
await tx.execute(sql.raw(`savepoint ${savepointName}`));
|
|
220
|
+
try {
|
|
221
|
+
const result = await transaction(tx);
|
|
222
|
+
await tx.execute(sql.raw(`release savepoint ${savepointName}`));
|
|
223
|
+
return result;
|
|
224
|
+
} catch (err) {
|
|
225
|
+
await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));
|
|
226
|
+
throw err;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export type GenericRowData<T extends RowData = RowData> = T;
|
|
232
|
+
|
|
233
|
+
export type GenericTableData<T = RowData> = T[];
|
|
234
|
+
|
|
235
|
+
export interface DuckDBQueryResultHKT extends PgQueryResultHKT {
|
|
236
|
+
type: GenericTableData<Assume<this['row'], RowData>>;
|
|
237
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/* Marked as internal in the original source, so we need to copy it here */
|
|
2
|
+
import {
|
|
3
|
+
type SelectedFieldsOrdered,
|
|
4
|
+
type AnyColumn,
|
|
5
|
+
type DriverValueDecoder,
|
|
6
|
+
is,
|
|
7
|
+
Column,
|
|
8
|
+
SQL,
|
|
9
|
+
getTableName,
|
|
10
|
+
sql,
|
|
11
|
+
} from 'drizzle-orm';
|
|
12
|
+
import { PgColumn, type SelectedFields } from 'drizzle-orm/pg-core';
|
|
13
|
+
|
|
14
|
+
// Need to get around "decoder" property being marked as internal
|
|
15
|
+
type SQLInternal<T = unknown> = SQL<T> & {
|
|
16
|
+
decoder: DriverValueDecoder<T, any>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function mapResultRow<TResult>(
|
|
20
|
+
columns: SelectedFieldsOrdered<AnyColumn>,
|
|
21
|
+
row: unknown[],
|
|
22
|
+
joinsNotNullableMap: Record<string, boolean> | undefined
|
|
23
|
+
): TResult {
|
|
24
|
+
// Key -> nested object key, value -> table name if all fields in the nested object are from the same table, false otherwise
|
|
25
|
+
const nullifyMap: Record<string, string | false> = {};
|
|
26
|
+
|
|
27
|
+
const result = columns.reduce<Record<string, any>>(
|
|
28
|
+
(result, { path, field }, columnIndex) => {
|
|
29
|
+
let decoder: DriverValueDecoder<unknown, unknown>;
|
|
30
|
+
if (is(field, Column)) {
|
|
31
|
+
decoder = field;
|
|
32
|
+
} else if (is(field, SQL)) {
|
|
33
|
+
decoder = (field as SQLInternal).decoder;
|
|
34
|
+
} else {
|
|
35
|
+
decoder = (field.sql as SQLInternal).decoder;
|
|
36
|
+
}
|
|
37
|
+
let node = result;
|
|
38
|
+
for (const [pathChunkIndex, pathChunk] of path.entries()) {
|
|
39
|
+
if (pathChunkIndex < path.length - 1) {
|
|
40
|
+
if (!(pathChunk in node)) {
|
|
41
|
+
node[pathChunk] = {};
|
|
42
|
+
}
|
|
43
|
+
node = node[pathChunk];
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const rawValue = row[columnIndex]!;
|
|
48
|
+
|
|
49
|
+
const value = (node[pathChunk] =
|
|
50
|
+
rawValue === null ? null : decoder.mapFromDriverValue(rawValue));
|
|
51
|
+
|
|
52
|
+
if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
|
|
53
|
+
const objectName = path[0]!;
|
|
54
|
+
if (!(objectName in nullifyMap)) {
|
|
55
|
+
nullifyMap[objectName] =
|
|
56
|
+
value === null ? getTableName(field.table) : false;
|
|
57
|
+
} else if (
|
|
58
|
+
typeof nullifyMap[objectName] === 'string' &&
|
|
59
|
+
nullifyMap[objectName] !== getTableName(field.table)
|
|
60
|
+
) {
|
|
61
|
+
nullifyMap[objectName] = false;
|
|
62
|
+
}
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// may need to add a condition for non-Aliased SQL
|
|
67
|
+
if (
|
|
68
|
+
joinsNotNullableMap &&
|
|
69
|
+
is(field, SQL.Aliased) &&
|
|
70
|
+
path.length === 2
|
|
71
|
+
) {
|
|
72
|
+
const col = field.sql.queryChunks.find((chunk) => is(chunk, Column));
|
|
73
|
+
const tableName = col?.table && getTableName(col?.table);
|
|
74
|
+
|
|
75
|
+
if (!tableName) {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const objectName = path[0]!;
|
|
80
|
+
|
|
81
|
+
if (!(objectName in nullifyMap)) {
|
|
82
|
+
nullifyMap[objectName] = value === null ? tableName : false;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (nullifyMap[objectName] && nullifyMap[objectName] !== tableName) {
|
|
87
|
+
nullifyMap[objectName] = false;
|
|
88
|
+
}
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
},
|
|
94
|
+
{}
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
// Nullify all nested objects from nullifyMap that are nullable
|
|
98
|
+
if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
|
|
99
|
+
for (const [objectName, tableName] of Object.entries(nullifyMap)) {
|
|
100
|
+
if (typeof tableName === 'string' && !joinsNotNullableMap[tableName]) {
|
|
101
|
+
result[objectName] = null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return result as TResult;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function aliasFields(
|
|
110
|
+
fields: SelectedFields,
|
|
111
|
+
fullJoin = false
|
|
112
|
+
): SelectedFields {
|
|
113
|
+
return Object.fromEntries(
|
|
114
|
+
Object.entries(fields)
|
|
115
|
+
.filter(([key]) => key !== 'enableRLS')
|
|
116
|
+
.map(([key, value]) => {
|
|
117
|
+
if (fullJoin && is(value, Column)) {
|
|
118
|
+
return [
|
|
119
|
+
key,
|
|
120
|
+
sql`${value}`.as(`${getTableName(value.table)}.${value.name}`),
|
|
121
|
+
];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (fullJoin && is(value, SQL)) {
|
|
125
|
+
const col = value
|
|
126
|
+
.getSQL()
|
|
127
|
+
.queryChunks.find((chunk) => is(chunk, Column));
|
|
128
|
+
|
|
129
|
+
const tableName = col?.table && getTableName(col?.table);
|
|
130
|
+
|
|
131
|
+
return [key, value.as(tableName ? `${tableName}.${key}` : key)];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (is(value, SQL) || is(value, Column)) {
|
|
135
|
+
return [key, (is(value, SQL) ? value : sql`${value}`).as(key)];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (is(value, SQL.Aliased)) {
|
|
139
|
+
return [key, value];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// todo: should probably make this recursive?
|
|
143
|
+
if (typeof value === 'object') {
|
|
144
|
+
const parentKey = key;
|
|
145
|
+
|
|
146
|
+
return [
|
|
147
|
+
key,
|
|
148
|
+
Object.fromEntries(
|
|
149
|
+
Object.entries(value)
|
|
150
|
+
.filter(([childKey]) => childKey !== 'enableRLS')
|
|
151
|
+
.map(([childKey, childValue]) => [
|
|
152
|
+
childKey,
|
|
153
|
+
(is(childValue, SQL) ? childValue : sql`${childValue}`).as(
|
|
154
|
+
`${parentKey}.${childKey}`
|
|
155
|
+
),
|
|
156
|
+
])
|
|
157
|
+
),
|
|
158
|
+
];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return [key, value];
|
|
162
|
+
})
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// DuckDB names returned variables differently than Postgres
|
|
167
|
+
// so we need to remap them to match the Postgres names
|
|
168
|
+
|
|
169
|
+
const selectionRegex = /select\s+(.+)\s+from/i;
|
|
170
|
+
// const tableIdPropSelectionRegex = /("(.+)"\."(.+)")(\s+as\s+'?(.+?)'?\.'?(.+?)'?)?/i;
|
|
171
|
+
const tableIdPropSelectionRegex = new RegExp(
|
|
172
|
+
[
|
|
173
|
+
`("(.+)"\\."(.+)")`, // table identifier + property
|
|
174
|
+
`(\\s+as\\s+'?(.+?)'?\\.'?(.+?)'?)?`, // optional AS clause
|
|
175
|
+
].join(''),
|
|
176
|
+
'i'
|
|
177
|
+
);
|
|
178
|
+
const noTableIdPropSelectionRegex = /"(.+)"(\s+as\s+'?\1'?)?/i;
|
|
179
|
+
|
|
180
|
+
const tablePropRegex = /"(.+)"\."(.+)"/i;
|
|
181
|
+
const asClauseRegex = /as\s+(.+)$/i;
|
|
182
|
+
const aliasRegex = /as\s+'?(.+)'?\.'?(.+)'?$/i;
|
|
183
|
+
|
|
184
|
+
/* Takes an SQL query as a string, and adds or updates "AS" clauses
|
|
185
|
+
* to the form: `AS 'table_name.column_name'`
|
|
186
|
+
* instead of : `AS "table_name"."column_name"`
|
|
187
|
+
*/
|
|
188
|
+
export function queryAdapter(query: string): string {
|
|
189
|
+
// Things to consider:
|
|
190
|
+
// - need to handle nested selects
|
|
191
|
+
// - what about full joins?
|
|
192
|
+
const selection = selectionRegex.exec(query);
|
|
193
|
+
|
|
194
|
+
if (selection?.length !== 2) {
|
|
195
|
+
return query;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const fields = selection[1].split(',').map((field) => {
|
|
199
|
+
const trimmedField = field.trim();
|
|
200
|
+
|
|
201
|
+
// - different scenarios:
|
|
202
|
+
// - no table identifier + no AS clause -> ignore
|
|
203
|
+
// - no table identifier + AS clause -> ensure AS clause format
|
|
204
|
+
// - table identifier + no AS clause -> add AS clause
|
|
205
|
+
// - table identifier + AS clause -> ensure AS clause format
|
|
206
|
+
const propSelection = tableIdPropSelectionRegex
|
|
207
|
+
.exec(trimmedField)
|
|
208
|
+
?.filter(Boolean);
|
|
209
|
+
|
|
210
|
+
if (!propSelection) {
|
|
211
|
+
return trimmedField;
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
return query.replace(selection[1], fields.join(', '));
|
|
216
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"lib": ["ESNext"],
|
|
4
|
+
"target": "ESNext",
|
|
5
|
+
"module": "ESNext",
|
|
6
|
+
"moduleDetection": "force",
|
|
7
|
+
"isolatedModules": true, // need?
|
|
8
|
+
"composite": false, // need?
|
|
9
|
+
"moduleResolution": "bundler",
|
|
10
|
+
"allowImportingTsExtensions": true,
|
|
11
|
+
"verbatimModuleSyntax": true,
|
|
12
|
+
"noEmit": true,
|
|
13
|
+
"strict": true,
|
|
14
|
+
"skipLibCheck": true,
|
|
15
|
+
"noFallthroughCasesInSwitch": true,
|
|
16
|
+
"sourceMap": true,
|
|
17
|
+
"allowSyntheticDefaultImports": true,
|
|
18
|
+
"esModuleInterop": true,
|
|
19
|
+
"strictNullChecks": true,
|
|
20
|
+
"strictFunctionTypes": true,
|
|
21
|
+
"strictBindCallApply": true,
|
|
22
|
+
"strictPropertyInitialization": true,
|
|
23
|
+
"noImplicitThis": true
|
|
24
|
+
}
|
|
25
|
+
}
|