@agentuity/drizzle 0.1.41

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/AGENTS.md ADDED
@@ -0,0 +1,117 @@
1
+ # Agent Guidelines for @agentuity/drizzle
2
+
3
+ ## Package Overview
4
+
5
+ Drizzle ORM integration with resilient PostgreSQL connections for Agentuity projects. Combines the type-safety of Drizzle ORM with @agentuity/postgres's automatic reconnection capabilities.
6
+
7
+ ## Commands
8
+
9
+ - **Build**: `bun run build`
10
+ - **Typecheck**: `bun run typecheck`
11
+ - **Clean**: `bun run clean`
12
+
13
+ ## Architecture
14
+
15
+ - **Runtime**: Bun (required for native SQL driver)
16
+ - **Dependencies**: `@agentuity/postgres`, `drizzle-orm`, `better-auth`
17
+ - **Features**: Type-safe queries, automatic reconnection, schema definitions
18
+
19
+ ## Code Conventions
20
+
21
+ - **Factory function**: Use `createPostgresDrizzle()` to create instances
22
+ - **Schema-first**: Define schemas using Drizzle's `pgTable` and column types
23
+ - **Connection handling**: Automatic reconnection via @agentuity/postgres
24
+ - **Type safety**: Full TypeScript support with schema inference
25
+
26
+ ## Usage Pattern
27
+
28
+ ```typescript
29
+ import { createPostgresDrizzle, pgTable, text, serial, eq } from '@agentuity/drizzle';
30
+
31
+ // Define schema
32
+ const users = pgTable('users', {
33
+ id: serial('id').primaryKey(),
34
+ name: text('name').notNull(),
35
+ email: text('email').notNull().unique(),
36
+ });
37
+
38
+ // Create database instance (uses DATABASE_URL by default)
39
+ const { db, client, close } = createPostgresDrizzle({
40
+ schema: { users },
41
+ });
42
+
43
+ // Or with explicit configuration
44
+ const { db, close } = createPostgresDrizzle({
45
+ connectionString: 'postgres://user:pass@localhost:5432/mydb',
46
+ schema: { users },
47
+ logger: true,
48
+ reconnect: {
49
+ maxAttempts: 5,
50
+ initialDelayMs: 100,
51
+ },
52
+ onReconnected: () => console.log('Reconnected!'),
53
+ });
54
+
55
+ // Execute type-safe queries
56
+ const allUsers = await db.select().from(users);
57
+ const user = await db.select().from(users).where(eq(users.id, 1));
58
+
59
+ // Access underlying client for raw queries or stats
60
+ console.log(client.stats);
61
+ const raw = await client`SELECT NOW()`;
62
+
63
+ // Clean up
64
+ await close();
65
+ ```
66
+
67
+ ## Integration with @agentuity/auth
68
+
69
+ ```typescript
70
+ import { createPostgresDrizzle, drizzleAdapter } from '@agentuity/drizzle';
71
+ import { createAuth } from '@agentuity/auth';
72
+ import * as schema from './schema';
73
+
74
+ const { db, close } = createPostgresDrizzle({ schema });
75
+
76
+ const auth = createAuth({
77
+ database: drizzleAdapter(db, {
78
+ provider: 'pg',
79
+ }),
80
+ });
81
+ ```
82
+
83
+ ## Re-exports
84
+
85
+ This package re-exports commonly used items for convenience:
86
+
87
+ ### From @agentuity/postgres
88
+
89
+ - `postgres` - Factory function for creating postgres clients
90
+ - `PostgresClient` - Client class
91
+ - `CallablePostgresClient` - Callable client type
92
+ - `PostgresConfig`, `ReconnectConfig`, `ConnectionStats`, etc.
93
+
94
+ ### From drizzle-orm
95
+
96
+ - Query operators: `sql`, `eq`, `and`, `or`, `not`, `desc`, `asc`, `gt`, `gte`, `lt`, `lte`, `ne`, `isNull`, `isNotNull`, `inArray`, `notInArray`, `between`, `like`, `ilike`
97
+
98
+ ### From drizzle-orm/pg-core
99
+
100
+ - Schema definitions: `pgTable`, `pgSchema`, `pgEnum`
101
+ - Column types: `text`, `integer`, `serial`, `boolean`, `timestamp`, `uuid`, `json`, `jsonb`, etc.
102
+ - Constraints: `primaryKey`, `foreignKey`, `unique`, `uniqueIndex`, `index`, `check`
103
+
104
+ ### From better-auth
105
+
106
+ - `drizzleAdapter` - For use with @agentuity/auth
107
+
108
+ ## Testing
109
+
110
+ - Tests require a running PostgreSQL instance
111
+ - Use `@agentuity/test-utils` for mocking
112
+ - When running tests, prefer using a subagent (Task tool) to avoid context bloat
113
+
114
+ ## Publishing
115
+
116
+ 1. Run build and typecheck
117
+ 2. Publish **after** `@agentuity/postgres`
package/README.md ADDED
@@ -0,0 +1,239 @@
1
+ # @agentuity/drizzle
2
+
3
+ Drizzle ORM integration with resilient PostgreSQL connections for Agentuity projects.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @agentuity/drizzle
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **Type-safe queries** - Full TypeScript support with Drizzle ORM's schema inference
14
+ - **Automatic reconnection** - Built on @agentuity/postgres with exponential backoff
15
+ - **Convenient re-exports** - Common Drizzle utilities available from a single import
16
+ - **Auth integration** - Works seamlessly with @agentuity/auth via drizzleAdapter
17
+
18
+ ## Basic Usage
19
+
20
+ ```typescript
21
+ import { createPostgresDrizzle, pgTable, text, serial, eq } from '@agentuity/drizzle';
22
+
23
+ // Define your schema
24
+ const users = pgTable('users', {
25
+ id: serial('id').primaryKey(),
26
+ name: text('name').notNull(),
27
+ email: text('email').notNull().unique(),
28
+ });
29
+
30
+ // Create database instance (uses DATABASE_URL by default)
31
+ const { db, close } = createPostgresDrizzle({
32
+ schema: { users },
33
+ });
34
+
35
+ // Execute type-safe queries
36
+ const allUsers = await db.select().from(users);
37
+ const user = await db.select().from(users).where(eq(users.id, 1));
38
+
39
+ // Insert data
40
+ await db.insert(users).values({ name: 'Alice', email: 'alice@example.com' });
41
+
42
+ // Clean up when done
43
+ await close();
44
+ ```
45
+
46
+ ## Custom Configuration
47
+
48
+ ```typescript
49
+ import { createPostgresDrizzle } from '@agentuity/drizzle';
50
+ import * as schema from './schema';
51
+
52
+ const { db, client, close } = createPostgresDrizzle({
53
+ // Connection string (defaults to DATABASE_URL)
54
+ connectionString: 'postgres://user:pass@localhost:5432/mydb',
55
+
56
+ // Your Drizzle schema
57
+ schema,
58
+
59
+ // Enable query logging
60
+ logger: true,
61
+
62
+ // Reconnection settings
63
+ reconnect: {
64
+ maxAttempts: 5,
65
+ initialDelayMs: 100,
66
+ maxDelayMs: 30000,
67
+ },
68
+
69
+ // Callbacks
70
+ onConnect: () => console.log('Connected to database'),
71
+ onReconnected: () => console.log('Reconnected to database'),
72
+ });
73
+
74
+ // Access connection statistics
75
+ console.log(client.stats);
76
+ // { connected: true, reconnecting: false, totalConnections: 1, ... }
77
+ ```
78
+
79
+ ## Using with @agentuity/auth
80
+
81
+ ```typescript
82
+ import { createPostgresDrizzle, drizzleAdapter } from '@agentuity/drizzle';
83
+ import { createAuth } from '@agentuity/auth';
84
+ import * as schema from './schema';
85
+
86
+ // Create database instance
87
+ const { db, close } = createPostgresDrizzle({ schema });
88
+
89
+ // Create auth with Drizzle adapter
90
+ const auth = createAuth({
91
+ database: drizzleAdapter(db, {
92
+ provider: 'pg',
93
+ }),
94
+ });
95
+ ```
96
+
97
+ ## Accessing the Underlying Client
98
+
99
+ The `client` property gives you access to the @agentuity/postgres client for raw queries:
100
+
101
+ ```typescript
102
+ const { db, client, close } = createPostgresDrizzle({ schema });
103
+
104
+ // Use Drizzle for type-safe queries
105
+ const users = await db.select().from(schema.users);
106
+
107
+ // Use the client for raw queries
108
+ const result = await client`SELECT NOW()`;
109
+
110
+ // Check connection status
111
+ if (client.connected) {
112
+ console.log('Database is connected');
113
+ }
114
+
115
+ // Access connection statistics
116
+ console.log(client.stats);
117
+ ```
118
+
119
+ ## Available Re-exports
120
+
121
+ ### Query Operators (from drizzle-orm)
122
+
123
+ ```typescript
124
+ import {
125
+ sql,
126
+ eq,
127
+ and,
128
+ or,
129
+ not,
130
+ desc,
131
+ asc,
132
+ gt,
133
+ gte,
134
+ lt,
135
+ lte,
136
+ ne,
137
+ isNull,
138
+ isNotNull,
139
+ inArray,
140
+ notInArray,
141
+ between,
142
+ like,
143
+ ilike,
144
+ } from '@agentuity/drizzle';
145
+ ```
146
+
147
+ ### Schema Definitions (from drizzle-orm/pg-core)
148
+
149
+ ```typescript
150
+ import {
151
+ // Table and schema
152
+ pgTable,
153
+ pgSchema,
154
+ pgEnum,
155
+
156
+ // Column types
157
+ text,
158
+ varchar,
159
+ char,
160
+ integer,
161
+ smallint,
162
+ bigint,
163
+ serial,
164
+ smallserial,
165
+ bigserial,
166
+ boolean,
167
+ timestamp,
168
+ date,
169
+ time,
170
+ interval,
171
+ json,
172
+ jsonb,
173
+ uuid,
174
+ numeric,
175
+ real,
176
+ doublePrecision,
177
+ inet,
178
+ cidr,
179
+ macaddr,
180
+ macaddr8,
181
+
182
+ // Constraints
183
+ primaryKey,
184
+ foreignKey,
185
+ unique,
186
+ uniqueIndex,
187
+ index,
188
+ check,
189
+ } from '@agentuity/drizzle';
190
+ ```
191
+
192
+ ### Postgres Client (from @agentuity/postgres)
193
+
194
+ ```typescript
195
+ import {
196
+ postgres,
197
+ PostgresClient,
198
+ type CallablePostgresClient,
199
+ type PostgresConfig,
200
+ type ReconnectConfig,
201
+ type ConnectionStats,
202
+ } from '@agentuity/drizzle';
203
+ ```
204
+
205
+ ### Auth Adapter (from better-auth)
206
+
207
+ ```typescript
208
+ import { drizzleAdapter } from '@agentuity/drizzle';
209
+ ```
210
+
211
+ ## API Reference
212
+
213
+ ### createPostgresDrizzle(config?)
214
+
215
+ Creates a Drizzle ORM instance with a resilient PostgreSQL connection.
216
+
217
+ #### Parameters
218
+
219
+ | Parameter | Type | Description |
220
+ | ------------------------- | -------------------------- | ----------------------------------------------------- |
221
+ | `config.connectionString` | `string` | PostgreSQL connection URL. Defaults to `DATABASE_URL` |
222
+ | `config.connection` | `PostgresConfig` | Full connection configuration object |
223
+ | `config.schema` | `TSchema` | Drizzle schema for type-safe queries |
224
+ | `config.logger` | `boolean \| DrizzleLogger` | Enable query logging |
225
+ | `config.reconnect` | `ReconnectConfig` | Reconnection behavior configuration |
226
+ | `config.onConnect` | `() => void` | Called when initially connected |
227
+ | `config.onReconnected` | `() => void` | Called after successful reconnection |
228
+
229
+ #### Returns
230
+
231
+ | Property | Type | Description |
232
+ | -------- | ------------------------- | ------------------------------ |
233
+ | `db` | `BunSQLDatabase<TSchema>` | The Drizzle database instance |
234
+ | `client` | `CallablePostgresClient` | The underlying postgres client |
235
+ | `close` | `() => Promise<void>` | Cleanup function |
236
+
237
+ ## License
238
+
239
+ Apache-2.0
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @agentuity/drizzle - Drizzle ORM integration with resilient PostgreSQL connections
3
+ *
4
+ * This package provides a seamless integration between Drizzle ORM and
5
+ * @agentuity/postgres, combining type-safe database queries with automatic
6
+ * reconnection capabilities.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { createPostgresDrizzle, pgTable, text, serial } from '@agentuity/drizzle';
11
+ *
12
+ * // Define your schema
13
+ * const users = pgTable('users', {
14
+ * id: serial('id').primaryKey(),
15
+ * name: text('name').notNull(),
16
+ * email: text('email').notNull().unique(),
17
+ * });
18
+ *
19
+ * // Create the database instance
20
+ * const { db, close } = createPostgresDrizzle({
21
+ * schema: { users },
22
+ * });
23
+ *
24
+ * // Execute type-safe queries
25
+ * const allUsers = await db.select().from(users);
26
+ *
27
+ * // Clean up when done
28
+ * await close();
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ export { createPostgresDrizzle } from './postgres';
34
+ export type { PostgresDrizzleConfig, PostgresDrizzle } from './types';
35
+ export { postgres, PostgresClient, type CallablePostgresClient, type PostgresConfig, type ReconnectConfig, type ConnectionStats, type TLSConfig, type TransactionOptions, type ReserveOptions, } from '@agentuity/postgres';
36
+ export { sql, eq, and, or, not, desc, asc, gt, gte, lt, lte, ne, isNull, isNotNull, inArray, notInArray, between, like, ilike, } from 'drizzle-orm';
37
+ export { pgTable, pgSchema, pgEnum, bigint, bigserial, boolean, char, cidr, customType, date, doublePrecision, inet, integer, interval, json, jsonb, macaddr, macaddr8, numeric, real, serial, smallint, smallserial, text, time, timestamp, uuid, varchar, primaryKey, foreignKey, unique, uniqueIndex, index, check, } from 'drizzle-orm/pg-core';
38
+ export { drizzleAdapter } from 'better-auth/adapters/drizzle';
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAGH,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAGnD,YAAY,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAGtE,OAAO,EACN,QAAQ,EACR,cAAc,EACd,KAAK,sBAAsB,EAC3B,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,kBAAkB,EACvB,KAAK,cAAc,GACnB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACN,GAAG,EACH,EAAE,EACF,GAAG,EACH,EAAE,EACF,GAAG,EACH,IAAI,EACJ,GAAG,EACH,EAAE,EACF,GAAG,EACH,EAAE,EACF,GAAG,EACH,EAAE,EACF,MAAM,EACN,SAAS,EACT,OAAO,EACP,UAAU,EACV,OAAO,EACP,IAAI,EACJ,KAAK,GACL,MAAM,aAAa,CAAC;AAGrB,OAAO,EACN,OAAO,EACP,QAAQ,EACR,MAAM,EAEN,MAAM,EACN,SAAS,EACT,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,UAAU,EACV,IAAI,EACJ,eAAe,EACf,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,KAAK,EACL,OAAO,EACP,QAAQ,EACR,OAAO,EACP,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,WAAW,EACX,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,IAAI,EACJ,OAAO,EAEP,UAAU,EACV,UAAU,EACV,MAAM,EACN,WAAW,EACX,KAAK,EACL,KAAK,GACL,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @agentuity/drizzle - Drizzle ORM integration with resilient PostgreSQL connections
3
+ *
4
+ * This package provides a seamless integration between Drizzle ORM and
5
+ * @agentuity/postgres, combining type-safe database queries with automatic
6
+ * reconnection capabilities.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { createPostgresDrizzle, pgTable, text, serial } from '@agentuity/drizzle';
11
+ *
12
+ * // Define your schema
13
+ * const users = pgTable('users', {
14
+ * id: serial('id').primaryKey(),
15
+ * name: text('name').notNull(),
16
+ * email: text('email').notNull().unique(),
17
+ * });
18
+ *
19
+ * // Create the database instance
20
+ * const { db, close } = createPostgresDrizzle({
21
+ * schema: { users },
22
+ * });
23
+ *
24
+ * // Execute type-safe queries
25
+ * const allUsers = await db.select().from(users);
26
+ *
27
+ * // Clean up when done
28
+ * await close();
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ // Main factory function
34
+ export { createPostgresDrizzle } from './postgres';
35
+ // Re-export from @agentuity/postgres for convenience
36
+ export { postgres, PostgresClient, } from '@agentuity/postgres';
37
+ // Re-export common Drizzle utilities for convenience
38
+ export { sql, eq, and, or, not, desc, asc, gt, gte, lt, lte, ne, isNull, isNotNull, inArray, notInArray, between, like, ilike, } from 'drizzle-orm';
39
+ // Re-export pg-core table and column definitions
40
+ export { pgTable, pgSchema, pgEnum,
41
+ // Column types
42
+ bigint, bigserial, boolean, char, cidr, customType, date, doublePrecision, inet, integer, interval, json, jsonb, macaddr, macaddr8, numeric, real, serial, smallint, smallserial, text, time, timestamp, uuid, varchar,
43
+ // Constraints and indexes
44
+ primaryKey, foreignKey, unique, uniqueIndex, index, check, } from 'drizzle-orm/pg-core';
45
+ // Re-export better-auth drizzle adapter for use with @agentuity/auth
46
+ export { drizzleAdapter } from 'better-auth/adapters/drizzle';
47
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,wBAAwB;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAKnD,qDAAqD;AACrD,OAAO,EACN,QAAQ,EACR,cAAc,GAQd,MAAM,qBAAqB,CAAC;AAE7B,qDAAqD;AACrD,OAAO,EACN,GAAG,EACH,EAAE,EACF,GAAG,EACH,EAAE,EACF,GAAG,EACH,IAAI,EACJ,GAAG,EACH,EAAE,EACF,GAAG,EACH,EAAE,EACF,GAAG,EACH,EAAE,EACF,MAAM,EACN,SAAS,EACT,OAAO,EACP,UAAU,EACV,OAAO,EACP,IAAI,EACJ,KAAK,GACL,MAAM,aAAa,CAAC;AAErB,iDAAiD;AACjD,OAAO,EACN,OAAO,EACP,QAAQ,EACR,MAAM;AACN,eAAe;AACf,MAAM,EACN,SAAS,EACT,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,UAAU,EACV,IAAI,EACJ,eAAe,EACf,IAAI,EACJ,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,KAAK,EACL,OAAO,EACP,QAAQ,EACR,OAAO,EACP,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,WAAW,EACX,IAAI,EACJ,IAAI,EACJ,SAAS,EACT,IAAI,EACJ,OAAO;AACP,0BAA0B;AAC1B,UAAU,EACV,UAAU,EACV,MAAM,EACN,WAAW,EACX,KAAK,EACL,KAAK,GACL,MAAM,qBAAqB,CAAC;AAE7B,qEAAqE;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC"}
@@ -0,0 +1,47 @@
1
+ import type { PostgresDrizzleConfig, PostgresDrizzle } from './types';
2
+ /**
3
+ * Creates a Drizzle ORM instance with a resilient PostgreSQL connection.
4
+ *
5
+ * This function combines the power of Drizzle ORM with @agentuity/postgres's
6
+ * automatic reconnection capabilities. The underlying connection will
7
+ * automatically reconnect with exponential backoff if the connection is lost.
8
+ *
9
+ * @template TSchema - The Drizzle schema type for type-safe queries
10
+ * @param config - Configuration options for the database connection
11
+ * @returns An object containing the Drizzle instance, underlying client, and close function
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { createPostgresDrizzle } from '@agentuity/drizzle';
16
+ * import * as schema from './schema';
17
+ *
18
+ * // Basic usage with DATABASE_URL
19
+ * const { db, close } = createPostgresDrizzle({ schema });
20
+ *
21
+ * // Query with type safety
22
+ * const users = await db.select().from(schema.users);
23
+ *
24
+ * // Clean up when done
25
+ * await close();
26
+ * ```
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * // With custom connection configuration
31
+ * const { db, client, close } = createPostgresDrizzle({
32
+ * connectionString: 'postgres://user:pass@localhost:5432/mydb',
33
+ * schema,
34
+ * logger: true,
35
+ * reconnect: {
36
+ * maxAttempts: 5,
37
+ * initialDelayMs: 100,
38
+ * },
39
+ * onReconnected: () => console.log('Database reconnected'),
40
+ * });
41
+ *
42
+ * // Access connection stats
43
+ * console.log(client.stats);
44
+ * ```
45
+ */
46
+ export declare function createPostgresDrizzle<TSchema extends Record<string, unknown> = Record<string, never>>(config?: PostgresDrizzleConfig<TSchema>): PostgresDrizzle<TSchema>;
47
+ //# sourceMappingURL=postgres.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,wBAAgB,qBAAqB,CACpC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,EAC9D,MAAM,CAAC,EAAE,qBAAqB,CAAC,OAAO,CAAC,GAAG,eAAe,CAAC,OAAO,CAAC,CAoDnE"}
@@ -0,0 +1,94 @@
1
+ import { drizzle } from 'drizzle-orm/bun-sql';
2
+ import { postgres } from '@agentuity/postgres';
3
+ /**
4
+ * Creates a Drizzle ORM instance with a resilient PostgreSQL connection.
5
+ *
6
+ * This function combines the power of Drizzle ORM with @agentuity/postgres's
7
+ * automatic reconnection capabilities. The underlying connection will
8
+ * automatically reconnect with exponential backoff if the connection is lost.
9
+ *
10
+ * @template TSchema - The Drizzle schema type for type-safe queries
11
+ * @param config - Configuration options for the database connection
12
+ * @returns An object containing the Drizzle instance, underlying client, and close function
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { createPostgresDrizzle } from '@agentuity/drizzle';
17
+ * import * as schema from './schema';
18
+ *
19
+ * // Basic usage with DATABASE_URL
20
+ * const { db, close } = createPostgresDrizzle({ schema });
21
+ *
22
+ * // Query with type safety
23
+ * const users = await db.select().from(schema.users);
24
+ *
25
+ * // Clean up when done
26
+ * await close();
27
+ * ```
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * // With custom connection configuration
32
+ * const { db, client, close } = createPostgresDrizzle({
33
+ * connectionString: 'postgres://user:pass@localhost:5432/mydb',
34
+ * schema,
35
+ * logger: true,
36
+ * reconnect: {
37
+ * maxAttempts: 5,
38
+ * initialDelayMs: 100,
39
+ * },
40
+ * onReconnected: () => console.log('Database reconnected'),
41
+ * });
42
+ *
43
+ * // Access connection stats
44
+ * console.log(client.stats);
45
+ * ```
46
+ */
47
+ export function createPostgresDrizzle(config) {
48
+ // Build postgres client configuration by cloning the connection config
49
+ // to avoid mutating the caller's object
50
+ const clientConfig = config?.connection ? { ...config.connection } : {};
51
+ // Use connectionString only if no url is already present on the cloned config
52
+ // This ensures connection (when provided) keeps precedence over connectionString
53
+ if (!clientConfig.url) {
54
+ if (config?.connectionString) {
55
+ clientConfig.url = config.connectionString;
56
+ }
57
+ else if (process.env.DATABASE_URL) {
58
+ clientConfig.url = process.env.DATABASE_URL;
59
+ }
60
+ }
61
+ // Add reconnection configuration
62
+ if (config?.reconnect) {
63
+ clientConfig.reconnect = config.reconnect;
64
+ }
65
+ // Add callbacks
66
+ if (config?.onReconnected) {
67
+ clientConfig.onreconnected = config.onReconnected;
68
+ }
69
+ // Create the postgres client
70
+ const client = postgres(clientConfig);
71
+ // Wait for connection before calling onConnect callback
72
+ // This ensures the callback executes only after the connection is established
73
+ if (config?.onConnect) {
74
+ client.waitForConnection().then(() => {
75
+ config.onConnect();
76
+ });
77
+ }
78
+ // Create Drizzle instance using the client's raw SQL connection
79
+ // The bun-sql driver accepts a client that implements the Bun.SQL interface
80
+ const db = drizzle({
81
+ client: client.raw,
82
+ schema: config?.schema,
83
+ logger: config?.logger,
84
+ });
85
+ // Return the combined interface
86
+ return {
87
+ db,
88
+ client,
89
+ close: async () => {
90
+ await client.close();
91
+ },
92
+ };
93
+ }
94
+ //# sourceMappingURL=postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAA+B,MAAM,qBAAqB,CAAC;AAG5E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,MAAM,UAAU,qBAAqB,CAEnC,MAAuC;IACxC,uEAAuE;IACvE,wCAAwC;IACxC,MAAM,YAAY,GAAG,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAExE,8EAA8E;IAC9E,iFAAiF;IACjF,IAAI,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,MAAM,EAAE,gBAAgB,EAAE,CAAC;YAC9B,YAAY,CAAC,GAAG,GAAG,MAAM,CAAC,gBAAgB,CAAC;QAC5C,CAAC;aAAM,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,CAAC;YACrC,YAAY,CAAC,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC;QAC7C,CAAC;IACF,CAAC;IAED,iCAAiC;IACjC,IAAI,MAAM,EAAE,SAAS,EAAE,CAAC;QACvB,YAAY,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;IAC3C,CAAC;IAED,gBAAgB;IAChB,IAAI,MAAM,EAAE,aAAa,EAAE,CAAC;QAC3B,YAAY,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC;IACnD,CAAC;IAED,6BAA6B;IAC7B,MAAM,MAAM,GAA2B,QAAQ,CAAC,YAAY,CAAC,CAAC;IAE9D,wDAAwD;IACxD,8EAA8E;IAC9E,IAAI,MAAM,EAAE,SAAS,EAAE,CAAC;QACvB,MAAM,CAAC,iBAAiB,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;YACpC,MAAM,CAAC,SAAU,EAAE,CAAC;QACrB,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,gEAAgE;IAChE,4EAA4E;IAC5E,MAAM,EAAE,GAAG,OAAO,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC,GAAG;QAClB,MAAM,EAAE,MAAM,EAAE,MAAM;QACtB,MAAM,EAAE,MAAM,EAAE,MAAM;KACtB,CAAC,CAAC;IAEH,gCAAgC;IAChC,OAAO;QACN,EAAE;QACF,MAAM;QACN,KAAK,EAAE,KAAK,IAAI,EAAE;YACjB,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QACtB,CAAC;KACD,CAAC;AACH,CAAC"}
@@ -0,0 +1,63 @@
1
+ import type { Logger as DrizzleLogger } from 'drizzle-orm';
2
+ import type { BunSQLDatabase } from 'drizzle-orm/bun-sql';
3
+ import type { PostgresConfig, ReconnectConfig, CallablePostgresClient } from '@agentuity/postgres';
4
+ /**
5
+ * Configuration options for creating a PostgreSQL Drizzle instance.
6
+ *
7
+ * @template TSchema - The Drizzle schema type
8
+ */
9
+ export interface PostgresDrizzleConfig<TSchema extends Record<string, unknown> = Record<string, never>> {
10
+ /**
11
+ * PostgreSQL connection string.
12
+ * If not provided, uses `process.env.DATABASE_URL`.
13
+ */
14
+ connectionString?: string;
15
+ /**
16
+ * Full PostgreSQL connection configuration.
17
+ * Takes precedence over `connectionString` if both are provided.
18
+ */
19
+ connection?: PostgresConfig;
20
+ /**
21
+ * Drizzle schema for type-safe queries.
22
+ */
23
+ schema?: TSchema;
24
+ /**
25
+ * Enable query logging.
26
+ * - `true`: Use default console logger
27
+ * - `DrizzleLogger`: Custom logger implementation
28
+ */
29
+ logger?: boolean | DrizzleLogger;
30
+ /**
31
+ * Reconnection configuration passed to the underlying postgres client.
32
+ */
33
+ reconnect?: ReconnectConfig;
34
+ /**
35
+ * Callback invoked when the initial connection is established.
36
+ */
37
+ onConnect?: () => void;
38
+ /**
39
+ * Callback invoked when the connection is re-established after a disconnect.
40
+ */
41
+ onReconnected?: () => void;
42
+ }
43
+ /**
44
+ * The result of creating a PostgreSQL Drizzle instance.
45
+ *
46
+ * @template TSchema - The Drizzle schema type
47
+ */
48
+ export interface PostgresDrizzle<TSchema extends Record<string, unknown> = Record<string, never>> {
49
+ /**
50
+ * The Drizzle database instance for executing queries.
51
+ */
52
+ db: BunSQLDatabase<TSchema>;
53
+ /**
54
+ * The underlying PostgreSQL client with reconnection support.
55
+ * Can be used for raw queries or accessing connection state.
56
+ */
57
+ client: CallablePostgresClient;
58
+ /**
59
+ * Closes the database connection and releases resources.
60
+ */
61
+ close: () => Promise<void>;
62
+ }
63
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,aAAa,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAEnG;;;;GAIG;AACH,MAAM,WAAW,qBAAqB,CACrC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC;IAE/D;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,UAAU,CAAC,EAAE,cAAc,CAAC;IAE5B;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IAEjB;;;;OAIG;IACH,MAAM,CAAC,EAAE,OAAO,GAAG,aAAa,CAAC;IAEjC;;OAEG;IACH,SAAS,CAAC,EAAE,eAAe,CAAC;IAE5B;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IAEvB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,IAAI,CAAC;CAC3B;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC;IAC/F;;OAEG;IACH,EAAE,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC;IAE5B;;;OAGG;IACH,MAAM,EAAE,sBAAsB,CAAC;IAE/B;;OAEG;IACH,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@agentuity/drizzle",
3
+ "version": "0.1.41",
4
+ "license": "Apache-2.0",
5
+ "author": "Agentuity employees and contributors",
6
+ "type": "module",
7
+ "description": "Drizzle ORM integration with resilient PostgreSQL connections for Agentuity projects",
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "files": [
12
+ "AGENTS.md",
13
+ "README.md",
14
+ "src",
15
+ "dist"
16
+ ],
17
+ "exports": {
18
+ ".": "./dist/index.js"
19
+ },
20
+ "typesVersions": {
21
+ "*": {
22
+ ".": [
23
+ "./dist/index.d.ts"
24
+ ]
25
+ }
26
+ },
27
+ "scripts": {
28
+ "clean": "rm -rf dist tsconfig.tsbuildinfo",
29
+ "build": "bunx tsc --build --force",
30
+ "typecheck": "bunx tsc --noEmit",
31
+ "prepublishOnly": "bun run clean && bun run build"
32
+ },
33
+ "dependencies": {
34
+ "@agentuity/postgres": "0.1.41",
35
+ "drizzle-orm": "^0.45.0",
36
+ "better-auth": "^1.4.9"
37
+ },
38
+ "devDependencies": {
39
+ "@agentuity/test-utils": "0.1.41",
40
+ "@types/bun": "latest",
41
+ "bun-types": "latest",
42
+ "typescript": "^5.9.0"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "sideEffects": false
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * @agentuity/drizzle - Drizzle ORM integration with resilient PostgreSQL connections
3
+ *
4
+ * This package provides a seamless integration between Drizzle ORM and
5
+ * @agentuity/postgres, combining type-safe database queries with automatic
6
+ * reconnection capabilities.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { createPostgresDrizzle, pgTable, text, serial } from '@agentuity/drizzle';
11
+ *
12
+ * // Define your schema
13
+ * const users = pgTable('users', {
14
+ * id: serial('id').primaryKey(),
15
+ * name: text('name').notNull(),
16
+ * email: text('email').notNull().unique(),
17
+ * });
18
+ *
19
+ * // Create the database instance
20
+ * const { db, close } = createPostgresDrizzle({
21
+ * schema: { users },
22
+ * });
23
+ *
24
+ * // Execute type-safe queries
25
+ * const allUsers = await db.select().from(users);
26
+ *
27
+ * // Clean up when done
28
+ * await close();
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+
34
+ // Main factory function
35
+ export { createPostgresDrizzle } from './postgres';
36
+
37
+ // Types
38
+ export type { PostgresDrizzleConfig, PostgresDrizzle } from './types';
39
+
40
+ // Re-export from @agentuity/postgres for convenience
41
+ export {
42
+ postgres,
43
+ PostgresClient,
44
+ type CallablePostgresClient,
45
+ type PostgresConfig,
46
+ type ReconnectConfig,
47
+ type ConnectionStats,
48
+ type TLSConfig,
49
+ type TransactionOptions,
50
+ type ReserveOptions,
51
+ } from '@agentuity/postgres';
52
+
53
+ // Re-export common Drizzle utilities for convenience
54
+ export {
55
+ sql,
56
+ eq,
57
+ and,
58
+ or,
59
+ not,
60
+ desc,
61
+ asc,
62
+ gt,
63
+ gte,
64
+ lt,
65
+ lte,
66
+ ne,
67
+ isNull,
68
+ isNotNull,
69
+ inArray,
70
+ notInArray,
71
+ between,
72
+ like,
73
+ ilike,
74
+ } from 'drizzle-orm';
75
+
76
+ // Re-export pg-core table and column definitions
77
+ export {
78
+ pgTable,
79
+ pgSchema,
80
+ pgEnum,
81
+ // Column types
82
+ bigint,
83
+ bigserial,
84
+ boolean,
85
+ char,
86
+ cidr,
87
+ customType,
88
+ date,
89
+ doublePrecision,
90
+ inet,
91
+ integer,
92
+ interval,
93
+ json,
94
+ jsonb,
95
+ macaddr,
96
+ macaddr8,
97
+ numeric,
98
+ real,
99
+ serial,
100
+ smallint,
101
+ smallserial,
102
+ text,
103
+ time,
104
+ timestamp,
105
+ uuid,
106
+ varchar,
107
+ // Constraints and indexes
108
+ primaryKey,
109
+ foreignKey,
110
+ unique,
111
+ uniqueIndex,
112
+ index,
113
+ check,
114
+ } from 'drizzle-orm/pg-core';
115
+
116
+ // Re-export better-auth drizzle adapter for use with @agentuity/auth
117
+ export { drizzleAdapter } from 'better-auth/adapters/drizzle';
@@ -0,0 +1,103 @@
1
+ import { drizzle } from 'drizzle-orm/bun-sql';
2
+ import { postgres, type CallablePostgresClient } from '@agentuity/postgres';
3
+ import type { PostgresDrizzleConfig, PostgresDrizzle } from './types';
4
+
5
+ /**
6
+ * Creates a Drizzle ORM instance with a resilient PostgreSQL connection.
7
+ *
8
+ * This function combines the power of Drizzle ORM with @agentuity/postgres's
9
+ * automatic reconnection capabilities. The underlying connection will
10
+ * automatically reconnect with exponential backoff if the connection is lost.
11
+ *
12
+ * @template TSchema - The Drizzle schema type for type-safe queries
13
+ * @param config - Configuration options for the database connection
14
+ * @returns An object containing the Drizzle instance, underlying client, and close function
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { createPostgresDrizzle } from '@agentuity/drizzle';
19
+ * import * as schema from './schema';
20
+ *
21
+ * // Basic usage with DATABASE_URL
22
+ * const { db, close } = createPostgresDrizzle({ schema });
23
+ *
24
+ * // Query with type safety
25
+ * const users = await db.select().from(schema.users);
26
+ *
27
+ * // Clean up when done
28
+ * await close();
29
+ * ```
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * // With custom connection configuration
34
+ * const { db, client, close } = createPostgresDrizzle({
35
+ * connectionString: 'postgres://user:pass@localhost:5432/mydb',
36
+ * schema,
37
+ * logger: true,
38
+ * reconnect: {
39
+ * maxAttempts: 5,
40
+ * initialDelayMs: 100,
41
+ * },
42
+ * onReconnected: () => console.log('Database reconnected'),
43
+ * });
44
+ *
45
+ * // Access connection stats
46
+ * console.log(client.stats);
47
+ * ```
48
+ */
49
+ export function createPostgresDrizzle<
50
+ TSchema extends Record<string, unknown> = Record<string, never>,
51
+ >(config?: PostgresDrizzleConfig<TSchema>): PostgresDrizzle<TSchema> {
52
+ // Build postgres client configuration by cloning the connection config
53
+ // to avoid mutating the caller's object
54
+ const clientConfig = config?.connection ? { ...config.connection } : {};
55
+
56
+ // Use connectionString only if no url is already present on the cloned config
57
+ // This ensures connection (when provided) keeps precedence over connectionString
58
+ if (!clientConfig.url) {
59
+ if (config?.connectionString) {
60
+ clientConfig.url = config.connectionString;
61
+ } else if (process.env.DATABASE_URL) {
62
+ clientConfig.url = process.env.DATABASE_URL;
63
+ }
64
+ }
65
+
66
+ // Add reconnection configuration
67
+ if (config?.reconnect) {
68
+ clientConfig.reconnect = config.reconnect;
69
+ }
70
+
71
+ // Add callbacks
72
+ if (config?.onReconnected) {
73
+ clientConfig.onreconnected = config.onReconnected;
74
+ }
75
+
76
+ // Create the postgres client
77
+ const client: CallablePostgresClient = postgres(clientConfig);
78
+
79
+ // Wait for connection before calling onConnect callback
80
+ // This ensures the callback executes only after the connection is established
81
+ if (config?.onConnect) {
82
+ client.waitForConnection().then(() => {
83
+ config.onConnect!();
84
+ });
85
+ }
86
+
87
+ // Create Drizzle instance using the client's raw SQL connection
88
+ // The bun-sql driver accepts a client that implements the Bun.SQL interface
89
+ const db = drizzle({
90
+ client: client.raw,
91
+ schema: config?.schema,
92
+ logger: config?.logger,
93
+ });
94
+
95
+ // Return the combined interface
96
+ return {
97
+ db,
98
+ client,
99
+ close: async () => {
100
+ await client.close();
101
+ },
102
+ };
103
+ }
package/src/types.ts ADDED
@@ -0,0 +1,74 @@
1
+ import type { Logger as DrizzleLogger } from 'drizzle-orm';
2
+ import type { BunSQLDatabase } from 'drizzle-orm/bun-sql';
3
+ import type { PostgresConfig, ReconnectConfig, CallablePostgresClient } from '@agentuity/postgres';
4
+
5
+ /**
6
+ * Configuration options for creating a PostgreSQL Drizzle instance.
7
+ *
8
+ * @template TSchema - The Drizzle schema type
9
+ */
10
+ export interface PostgresDrizzleConfig<
11
+ TSchema extends Record<string, unknown> = Record<string, never>,
12
+ > {
13
+ /**
14
+ * PostgreSQL connection string.
15
+ * If not provided, uses `process.env.DATABASE_URL`.
16
+ */
17
+ connectionString?: string;
18
+
19
+ /**
20
+ * Full PostgreSQL connection configuration.
21
+ * Takes precedence over `connectionString` if both are provided.
22
+ */
23
+ connection?: PostgresConfig;
24
+
25
+ /**
26
+ * Drizzle schema for type-safe queries.
27
+ */
28
+ schema?: TSchema;
29
+
30
+ /**
31
+ * Enable query logging.
32
+ * - `true`: Use default console logger
33
+ * - `DrizzleLogger`: Custom logger implementation
34
+ */
35
+ logger?: boolean | DrizzleLogger;
36
+
37
+ /**
38
+ * Reconnection configuration passed to the underlying postgres client.
39
+ */
40
+ reconnect?: ReconnectConfig;
41
+
42
+ /**
43
+ * Callback invoked when the initial connection is established.
44
+ */
45
+ onConnect?: () => void;
46
+
47
+ /**
48
+ * Callback invoked when the connection is re-established after a disconnect.
49
+ */
50
+ onReconnected?: () => void;
51
+ }
52
+
53
+ /**
54
+ * The result of creating a PostgreSQL Drizzle instance.
55
+ *
56
+ * @template TSchema - The Drizzle schema type
57
+ */
58
+ export interface PostgresDrizzle<TSchema extends Record<string, unknown> = Record<string, never>> {
59
+ /**
60
+ * The Drizzle database instance for executing queries.
61
+ */
62
+ db: BunSQLDatabase<TSchema>;
63
+
64
+ /**
65
+ * The underlying PostgreSQL client with reconnection support.
66
+ * Can be used for raw queries or accessing connection state.
67
+ */
68
+ client: CallablePostgresClient;
69
+
70
+ /**
71
+ * Closes the database connection and releases resources.
72
+ */
73
+ close: () => Promise<void>;
74
+ }