drizzle-multitenant 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(npm install:*)",
5
+ "Bash(npm test)",
6
+ "Bash(npm run build:*)",
7
+ "Bash(npm test:*)",
8
+ "Bash(tree:*)",
9
+ "Bash(find:*)",
10
+ "Bash(mkdir:*)",
11
+ "Bash(node ./bin/drizzle-multitenant.js:*)"
12
+ ]
13
+ }
14
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Mateus Florez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,262 @@
1
+ # drizzle-multitenant
2
+
3
+ [![npm version](https://img.shields.io/npm/v/drizzle-multitenant.svg)](https://www.npmjs.com/package/drizzle-multitenant)
4
+ [![GitHub](https://img.shields.io/github/stars/mateusflorez/drizzle-multitenant?style=social)](https://github.com/mateusflorez/drizzle-multitenant)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ Multi-tenancy toolkit for Drizzle ORM with schema isolation, tenant context, and parallel migrations.
8
+
9
+ ```
10
+ ┌─────────────────────────────────────────────────────────────────────┐
11
+ │ ╔═══════════════════════════════════════════════════════════════╗ │
12
+ │ ║ drizzle-multitenant ║ │
13
+ │ ║ ━━━━━━━━━━━━━━━━━━━━ ║ │
14
+ │ ║ ║ │
15
+ │ ║ Schema isolation • Context propagation • Migrations ║ │
16
+ │ ╚═══════════════════════════════════════════════════════════════╝ │
17
+ └─────────────────────────────────────────────────────────────────────┘
18
+ ```
19
+
20
+ ## Features
21
+
22
+ - **Schema Isolation** - Automatic PostgreSQL schema-per-tenant with LRU pool management
23
+ - **Context Propagation** - AsyncLocalStorage-based tenant context across your entire stack
24
+ - **Parallel Migrations** - Apply migrations to all tenants concurrently with progress tracking
25
+ - **Cross-Schema Queries** - Type-safe queries joining tenant and shared schemas
26
+ - **Framework Integrations** - Express, Fastify, NestJS, and Hono middleware/plugins
27
+ - **CLI Tools** - Generate migrations, manage tenants, check status
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ npm install drizzle-multitenant drizzle-orm pg
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ### 1. Define your configuration
38
+
39
+ ```typescript
40
+ // tenant.config.ts
41
+ import { defineConfig } from 'drizzle-multitenant';
42
+ import * as tenantSchema from './schemas/tenant';
43
+ import * as sharedSchema from './schemas/shared';
44
+
45
+ export default defineConfig({
46
+ connection: {
47
+ url: process.env.DATABASE_URL!,
48
+ },
49
+ isolation: {
50
+ strategy: 'schema',
51
+ schemaNameTemplate: (tenantId) => `tenant_${tenantId}`,
52
+ maxPools: 50,
53
+ poolTtlMs: 60 * 60 * 1000,
54
+ },
55
+ schemas: {
56
+ tenant: tenantSchema,
57
+ shared: sharedSchema,
58
+ },
59
+ });
60
+ ```
61
+
62
+ ### 2. Create the tenant manager
63
+
64
+ ```typescript
65
+ import { createTenantManager } from 'drizzle-multitenant';
66
+ import config from './tenant.config';
67
+
68
+ const tenants = createTenantManager(config);
69
+
70
+ // Get typed DB for a tenant
71
+ const db = tenants.getDb('tenant-123');
72
+ const users = await db.select().from(schema.users);
73
+
74
+ // Get shared DB (public schema)
75
+ const shared = tenants.getSharedDb();
76
+ const plans = await shared.select().from(sharedSchema.plans);
77
+ ```
78
+
79
+ ### 3. Use context propagation
80
+
81
+ ```typescript
82
+ import { createTenantContext } from 'drizzle-multitenant';
83
+
84
+ const ctx = createTenantContext(tenants);
85
+
86
+ // Run code within tenant context
87
+ await ctx.runWithTenant({ tenantId: 'tenant-123' }, async () => {
88
+ const db = ctx.getTenantDb();
89
+ // All queries automatically scoped to tenant
90
+ const users = await db.select().from(schema.users);
91
+ });
92
+ ```
93
+
94
+ ## Framework Integrations
95
+
96
+ ### Express
97
+
98
+ ```typescript
99
+ import { createExpressMiddleware } from 'drizzle-multitenant/express';
100
+
101
+ const middleware = createExpressMiddleware({
102
+ manager: tenants,
103
+ extractTenantId: (req) => req.headers['x-tenant-id'] as string,
104
+ validateTenant: async (id) => checkTenantExists(id),
105
+ });
106
+
107
+ app.use('/api/:tenantId/*', middleware);
108
+ ```
109
+
110
+ ### Fastify
111
+
112
+ ```typescript
113
+ import { fastifyTenantPlugin } from 'drizzle-multitenant/fastify';
114
+
115
+ await fastify.register(fastifyTenantPlugin, {
116
+ manager: tenants,
117
+ extractTenantId: (req) => req.headers['x-tenant-id'] as string,
118
+ });
119
+ ```
120
+
121
+ ### NestJS
122
+
123
+ ```typescript
124
+ import { TenantModule, InjectTenantDb } from 'drizzle-multitenant/nestjs';
125
+
126
+ @Module({
127
+ imports: [
128
+ TenantModule.forRoot({
129
+ config: tenantConfig,
130
+ extractTenantId: (req) => req.headers['x-tenant-id'],
131
+ isGlobal: true,
132
+ }),
133
+ ],
134
+ })
135
+ export class AppModule {}
136
+
137
+ @Injectable()
138
+ export class UserService {
139
+ constructor(@InjectTenantDb() private readonly db: TenantDb) {}
140
+
141
+ async findAll() {
142
+ return this.db.select().from(users);
143
+ }
144
+ }
145
+ ```
146
+
147
+ ## CLI Commands
148
+
149
+ ```bash
150
+ # Generate a new migration
151
+ npx drizzle-multitenant generate --name=add-users-table
152
+
153
+ # Apply migrations to all tenants
154
+ npx drizzle-multitenant migrate --all --concurrency=10
155
+
156
+ # Check migration status
157
+ npx drizzle-multitenant status
158
+
159
+ # Create a new tenant schema
160
+ npx drizzle-multitenant tenant:create --id=new-tenant
161
+
162
+ # Drop a tenant schema
163
+ npx drizzle-multitenant tenant:drop --id=old-tenant --force
164
+ ```
165
+
166
+ ### Status Output
167
+
168
+ ```
169
+ ┌─────────────────────┬─────────┬─────────┬──────────┐
170
+ │ Tenant │ Applied │ Pending │ Status │
171
+ ├─────────────────────┼─────────┼─────────┼──────────┤
172
+ │ tenant_abc123 │ 15 │ 0 │ OK │
173
+ │ tenant_def456 │ 15 │ 0 │ OK │
174
+ │ tenant_ghi789 │ 14 │ 1 │ Behind │
175
+ └─────────────────────┴─────────┴─────────┴──────────┘
176
+ ```
177
+
178
+ ## Cross-Schema Queries
179
+
180
+ ```typescript
181
+ import { createCrossSchemaQuery } from 'drizzle-multitenant/cross-schema';
182
+
183
+ const query = createCrossSchemaQuery({
184
+ tenantDb: tenants.getDb('tenant-123'),
185
+ sharedDb: tenants.getSharedDb(),
186
+ tenantSchema: 'tenant_123',
187
+ sharedSchema: 'public',
188
+ });
189
+
190
+ // Type-safe join between tenant and shared tables
191
+ const result = await query
192
+ .select({
193
+ orderId: orders.id,
194
+ planName: subscriptionPlans.name,
195
+ })
196
+ .from(orders)
197
+ .leftJoin(subscriptionPlans, eq(orders.planId, subscriptionPlans.id));
198
+ ```
199
+
200
+ ## API Reference
201
+
202
+ ### Core
203
+
204
+ | Export | Description |
205
+ |--------|-------------|
206
+ | `defineConfig()` | Create typed configuration |
207
+ | `createTenantManager()` | Create pool manager instance |
208
+ | `createTenantContext()` | Create AsyncLocalStorage context |
209
+
210
+ ### Manager Methods
211
+
212
+ | Method | Description |
213
+ |--------|-------------|
214
+ | `getDb(tenantId)` | Get Drizzle instance for tenant |
215
+ | `getSharedDb()` | Get Drizzle instance for shared schema |
216
+ | `getSchemaName(tenantId)` | Get schema name for tenant |
217
+ | `hasPool(tenantId)` | Check if pool exists |
218
+ | `evictPool(tenantId)` | Force evict a pool |
219
+ | `dispose()` | Cleanup all pools |
220
+
221
+ ### NestJS Decorators
222
+
223
+ | Decorator | Description |
224
+ |-----------|-------------|
225
+ | `@InjectTenantDb()` | Inject tenant database |
226
+ | `@InjectSharedDb()` | Inject shared database |
227
+ | `@InjectTenantContext()` | Inject tenant context |
228
+ | `@InjectTenantManager()` | Inject tenant manager |
229
+ | `@RequiresTenant()` | Mark route as requiring tenant |
230
+ | `@PublicRoute()` | Mark route as public |
231
+
232
+ ## Requirements
233
+
234
+ - Node.js 18+
235
+ - PostgreSQL 12+
236
+ - Drizzle ORM 0.29+
237
+
238
+ ## Tech Stack
239
+
240
+ | Package | Purpose |
241
+ |---------|---------|
242
+ | `drizzle-orm` | Type-safe ORM |
243
+ | `pg` | PostgreSQL driver |
244
+ | `lru-cache` | Pool management |
245
+ | `commander` | CLI framework |
246
+ | `chalk` | Terminal styling |
247
+ | `ora` | Loading spinners |
248
+ | `cli-table3` | Table formatting |
249
+
250
+ ## Comparison
251
+
252
+ | Feature | drizzle-multitenant | Manual Implementation |
253
+ |---------|---------------------|----------------------|
254
+ | Pool management | Automatic LRU | Manual |
255
+ | Context propagation | AsyncLocalStorage | Pass through params |
256
+ | Parallel migrations | Built-in CLI | Custom scripts |
257
+ | Cross-schema queries | Type-safe builder | Raw SQL |
258
+ | Framework support | Express/Fastify/NestJS/Hono | DIY |
259
+
260
+ ## License
261
+
262
+ MIT
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../dist/cli/index.js';
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node