@gl-life/gl-life-database 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.
- package/API.md +1486 -0
- package/LICENSE +190 -0
- package/README.md +480 -0
- package/dist/cache/index.d.ts +4 -0
- package/dist/cache/index.d.ts.map +1 -0
- package/dist/cache/invalidation.d.ts +156 -0
- package/dist/cache/invalidation.d.ts.map +1 -0
- package/dist/cache/kv-cache.d.ts +79 -0
- package/dist/cache/kv-cache.d.ts.map +1 -0
- package/dist/cache/memory-cache.d.ts +68 -0
- package/dist/cache/memory-cache.d.ts.map +1 -0
- package/dist/cloudforge/d1-adapter.d.ts +67 -0
- package/dist/cloudforge/d1-adapter.d.ts.map +1 -0
- package/dist/cloudforge/do-storage.d.ts +51 -0
- package/dist/cloudforge/do-storage.d.ts.map +1 -0
- package/dist/cloudforge/index.d.ts +4 -0
- package/dist/cloudforge/index.d.ts.map +1 -0
- package/dist/cloudforge/r2-backup.d.ts +38 -0
- package/dist/cloudforge/r2-backup.d.ts.map +1 -0
- package/dist/connection/index.d.ts +2 -0
- package/dist/connection/index.d.ts.map +1 -0
- package/dist/connection/manager.d.ts +54 -0
- package/dist/connection/manager.d.ts.map +1 -0
- package/dist/index.cjs +4762 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4701 -0
- package/dist/index.js.map +1 -0
- package/dist/migration/index.d.ts +4 -0
- package/dist/migration/index.d.ts.map +1 -0
- package/dist/migration/loader.d.ts +88 -0
- package/dist/migration/loader.d.ts.map +1 -0
- package/dist/migration/runner.d.ts +91 -0
- package/dist/migration/runner.d.ts.map +1 -0
- package/dist/migration/seeder.d.ts +95 -0
- package/dist/migration/seeder.d.ts.map +1 -0
- package/dist/query/builder.d.ts +47 -0
- package/dist/query/builder.d.ts.map +1 -0
- package/dist/query/index.d.ts +3 -0
- package/dist/query/index.d.ts.map +1 -0
- package/dist/query/raw.d.ts +92 -0
- package/dist/query/raw.d.ts.map +1 -0
- package/dist/tenant/context.d.ts +52 -0
- package/dist/tenant/context.d.ts.map +1 -0
- package/dist/tenant/index.d.ts +4 -0
- package/dist/tenant/index.d.ts.map +1 -0
- package/dist/tenant/query-wrapper.d.ts +96 -0
- package/dist/tenant/query-wrapper.d.ts.map +1 -0
- package/dist/tenant/schema-manager.d.ts +185 -0
- package/dist/tenant/schema-manager.d.ts.map +1 -0
- package/dist/transaction/index.d.ts +2 -0
- package/dist/transaction/index.d.ts.map +1 -0
- package/dist/transaction/transaction.d.ts +51 -0
- package/dist/transaction/transaction.d.ts.map +1 -0
- package/dist/types/cache.d.ts +214 -0
- package/dist/types/cache.d.ts.map +1 -0
- package/dist/types/cloudforge.d.ts +753 -0
- package/dist/types/cloudforge.d.ts.map +1 -0
- package/dist/types/connection.d.ts +91 -0
- package/dist/types/connection.d.ts.map +1 -0
- package/dist/types/index.d.ts +10 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/migration.d.ts +225 -0
- package/dist/types/migration.d.ts.map +1 -0
- package/dist/types/plugin.d.ts +432 -0
- package/dist/types/plugin.d.ts.map +1 -0
- package/dist/types/query-builder.d.ts +217 -0
- package/dist/types/query-builder.d.ts.map +1 -0
- package/dist/types/seed.d.ts +187 -0
- package/dist/types/seed.d.ts.map +1 -0
- package/dist/types/tenant.d.ts +140 -0
- package/dist/types/tenant.d.ts.map +1 -0
- package/dist/types/transaction.d.ts +144 -0
- package/dist/types/transaction.d.ts.map +1 -0
- package/package.json +78 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
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 Support. 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
|
+
Copyright 2025 GL.Life
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
# @gl-life/gl-life-database
|
|
2
|
+
|
|
3
|
+
Enhanced gl-life-data wrapper with CloudForge features - Type-safe database abstraction layer with multi-tenancy, caching, migrations, and Cloudflare Workers support.
|
|
4
|
+
|
|
5
|
+
## About
|
|
6
|
+
|
|
7
|
+
`@gl-life/gl-life-database` is a comprehensive database abstraction layer that extends gl-life-data with enterprise features for multi-tenant SaaS applications running on Cloudflare Workers. Built with TypeScript and designed for type safety, it provides a robust foundation for building scalable database-driven applications.
|
|
8
|
+
|
|
9
|
+
### Key Features
|
|
10
|
+
|
|
11
|
+
- 🗄️ **Type-Safe Query Builder** - Fluent API with full TypeScript support extending gl-life-data
|
|
12
|
+
- 👥 **Multi-Tenancy** - Built-in tenant isolation with Row-Level Security (RLS)
|
|
13
|
+
- ⚡ **Caching Layer** - High-performance query result caching with memory and Cloudflare KV backends
|
|
14
|
+
- 🔄 **Migrations** - Version-controlled database migrations with rollback support
|
|
15
|
+
- ☁️ **CloudForge Integration** - Native support for D1, Durable Objects, Workers KV, and R2
|
|
16
|
+
- 🔒 **SQL Injection Protection** - Parameterized queries with automatic sanitization
|
|
17
|
+
- 🧪 **Well-Tested** - >95% test coverage with comprehensive security tests
|
|
18
|
+
- 📊 **Performance Optimized** - Query building overhead <1ms (P95)
|
|
19
|
+
|
|
20
|
+
### Part of GoodLife Sargam
|
|
21
|
+
|
|
22
|
+
This package is part of the **GoodLife Sargam** ecosystem - a comprehensive suite of 80 packages for building modern cloud applications. Visit [gl.life](https://gl.life) for more information.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install @gl-life/gl-life-database
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Dependencies
|
|
31
|
+
|
|
32
|
+
The package has minimal dependencies:
|
|
33
|
+
|
|
34
|
+
- `@gl-life/gl-life-core` ^1.0.1 - Foundation utilities (Result, Option, Logger)
|
|
35
|
+
- `gl-life-data` latest - Base database package
|
|
36
|
+
- `zod` ^4.2.1 - Runtime type validation
|
|
37
|
+
|
|
38
|
+
## Quick Start
|
|
39
|
+
|
|
40
|
+
### Basic Usage
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
import {
|
|
44
|
+
ConnectionManager,
|
|
45
|
+
TypeSafeQueryBuilder,
|
|
46
|
+
Logger
|
|
47
|
+
} from '@gl-life/gl-life-database';
|
|
48
|
+
|
|
49
|
+
// Create a connection manager
|
|
50
|
+
const logger = new Logger({ level: 'info' });
|
|
51
|
+
const connectionManager = new ConnectionManager(logger);
|
|
52
|
+
|
|
53
|
+
// Connect to database
|
|
54
|
+
const connection = await connectionManager.connect({
|
|
55
|
+
type: 'sqlite',
|
|
56
|
+
filename: './myapp.db'
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Build and execute a query
|
|
60
|
+
const builder = new TypeSafeQueryBuilder('users', null, logger);
|
|
61
|
+
const sql = builder
|
|
62
|
+
.select(['id', 'name', 'email'])
|
|
63
|
+
.where('status', '=', 'active')
|
|
64
|
+
.orderBy('created_at', 'DESC')
|
|
65
|
+
.limit(10)
|
|
66
|
+
.toSQL();
|
|
67
|
+
|
|
68
|
+
const result = await connection.execute(sql);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Multi-Tenant Application
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
import {
|
|
75
|
+
TenantContext,
|
|
76
|
+
QueryWrapper,
|
|
77
|
+
Logger
|
|
78
|
+
} from '@gl-life/gl-life-database';
|
|
79
|
+
|
|
80
|
+
// Set up tenant context
|
|
81
|
+
const logger = new Logger({ level: 'info' });
|
|
82
|
+
const tenantContext = new TenantContext(logger);
|
|
83
|
+
|
|
84
|
+
// Set current tenant
|
|
85
|
+
tenantContext.setTenant({
|
|
86
|
+
tenantId: 'tenant-123',
|
|
87
|
+
isAdmin: false
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// Queries automatically include tenant_id filtering
|
|
91
|
+
const wrapper = new QueryWrapper(tenantContext, logger);
|
|
92
|
+
const users = await wrapper.query('users', {
|
|
93
|
+
where: { status: 'active' }
|
|
94
|
+
});
|
|
95
|
+
// Automatically adds: WHERE tenant_id = 'tenant-123' AND status = 'active'
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Caching
|
|
99
|
+
|
|
100
|
+
```typescript
|
|
101
|
+
import {
|
|
102
|
+
MemoryCache,
|
|
103
|
+
CacheConfig,
|
|
104
|
+
Logger
|
|
105
|
+
} from '@gl-life/gl-life-database';
|
|
106
|
+
|
|
107
|
+
const config: CacheConfig = {
|
|
108
|
+
enabled: true,
|
|
109
|
+
backend: 'MEMORY',
|
|
110
|
+
maxItems: 1000,
|
|
111
|
+
defaultTTL: 300,
|
|
112
|
+
evictionPolicy: 'LRU',
|
|
113
|
+
invalidationStrategy: 'TIME_BASED'
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const logger = new Logger({ level: 'info' });
|
|
117
|
+
const cache = new MemoryCache(config, logger);
|
|
118
|
+
|
|
119
|
+
// Cache query results
|
|
120
|
+
await cache.set('user:123', { id: 123, name: 'Alice' }, 60);
|
|
121
|
+
const user = await cache.get('user:123');
|
|
122
|
+
|
|
123
|
+
// Pattern-based invalidation
|
|
124
|
+
await cache.invalidatePattern('user:*');
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### Database Migrations
|
|
128
|
+
|
|
129
|
+
```typescript
|
|
130
|
+
import {
|
|
131
|
+
MigrationPlanner,
|
|
132
|
+
MigrationConfig,
|
|
133
|
+
Logger
|
|
134
|
+
} from '@gl-life/gl-life-database';
|
|
135
|
+
|
|
136
|
+
const config: MigrationConfig = {
|
|
137
|
+
enabled: true,
|
|
138
|
+
migrationTable: 'migrations',
|
|
139
|
+
autoRun: false
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const logger = new Logger({ level: 'info' });
|
|
143
|
+
const planner = new MigrationPlanner(config, logger);
|
|
144
|
+
|
|
145
|
+
// Load migrations from directory
|
|
146
|
+
const migrations = [
|
|
147
|
+
{
|
|
148
|
+
version: '001',
|
|
149
|
+
name: 'create_users_table',
|
|
150
|
+
up: 'CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)',
|
|
151
|
+
down: 'DROP TABLE users'
|
|
152
|
+
}
|
|
153
|
+
];
|
|
154
|
+
|
|
155
|
+
await planner.loadMigrations(migrations);
|
|
156
|
+
|
|
157
|
+
// Plan migration execution
|
|
158
|
+
const plan = planner.planMigration('001');
|
|
159
|
+
// Execute: await executor.executeMigration(plan);
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Cloudflare D1 Integration
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
import { D1Adapter, Logger } from '@gl-life/gl-life-database';
|
|
166
|
+
|
|
167
|
+
// In Cloudflare Worker
|
|
168
|
+
export default {
|
|
169
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
170
|
+
const logger = new Logger({ level: 'info' });
|
|
171
|
+
const adapter = new D1Adapter(env.DB, logger);
|
|
172
|
+
|
|
173
|
+
const result = await adapter.execute(
|
|
174
|
+
'SELECT * FROM users WHERE id = ?',
|
|
175
|
+
[123]
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
return new Response(JSON.stringify(result));
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## Usage
|
|
184
|
+
|
|
185
|
+
### Query Builder
|
|
186
|
+
|
|
187
|
+
The type-safe query builder provides a fluent API for constructing SQL queries:
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
import { TypeSafeQueryBuilder, Logger } from '@gl-life/gl-life-database';
|
|
191
|
+
|
|
192
|
+
const logger = new Logger({ level: 'info' });
|
|
193
|
+
const builder = new TypeSafeQueryBuilder('orders', null, logger);
|
|
194
|
+
|
|
195
|
+
// Complex query with joins
|
|
196
|
+
const sql = builder
|
|
197
|
+
.select(['orders.id', 'orders.total', 'customers.name'])
|
|
198
|
+
.join('customers', 'customers.id', '=', 'orders.customer_id')
|
|
199
|
+
.where('orders.status', '=', 'completed')
|
|
200
|
+
.where('orders.total', '>', 100)
|
|
201
|
+
.orderBy('orders.created_at', 'DESC')
|
|
202
|
+
.limit(20)
|
|
203
|
+
.offset(0)
|
|
204
|
+
.toSQL();
|
|
205
|
+
|
|
206
|
+
// Outputs: SELECT orders.id, orders.total, customers.name
|
|
207
|
+
// FROM orders
|
|
208
|
+
// JOIN customers ON customers.id = orders.customer_id
|
|
209
|
+
// WHERE orders.status = ? AND orders.total > ?
|
|
210
|
+
// ORDER BY orders.created_at DESC
|
|
211
|
+
// LIMIT 20 OFFSET 0
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Transactions
|
|
215
|
+
|
|
216
|
+
Execute multiple operations atomically:
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
import {
|
|
220
|
+
TransactionManager,
|
|
221
|
+
TransactionConfig,
|
|
222
|
+
Logger
|
|
223
|
+
} from '@gl-life/gl-life-database';
|
|
224
|
+
|
|
225
|
+
const config: TransactionConfig = {
|
|
226
|
+
isolationLevel: 'READ_COMMITTED',
|
|
227
|
+
timeout: 30000,
|
|
228
|
+
retryAttempts: 3
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const logger = new Logger({ level: 'info' });
|
|
232
|
+
const txManager = new TransactionManager(connection, config, logger);
|
|
233
|
+
|
|
234
|
+
await txManager.execute(async (tx) => {
|
|
235
|
+
await tx.execute('INSERT INTO accounts (balance) VALUES (?)', [1000]);
|
|
236
|
+
await tx.execute('UPDATE accounts SET balance = balance - ? WHERE id = ?', [100, 1]);
|
|
237
|
+
await tx.execute('UPDATE accounts SET balance = balance + ? WHERE id = ?', [100, 2]);
|
|
238
|
+
// Automatically commits on success, rolls back on error
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Tenant Isolation
|
|
243
|
+
|
|
244
|
+
Ensure data isolation in multi-tenant applications:
|
|
245
|
+
|
|
246
|
+
```typescript
|
|
247
|
+
import {
|
|
248
|
+
TenantContext,
|
|
249
|
+
QueryWrapper,
|
|
250
|
+
Logger
|
|
251
|
+
} from '@gl-life/gl-life-database';
|
|
252
|
+
|
|
253
|
+
const logger = new Logger({ level: 'info' });
|
|
254
|
+
const tenantContext = new TenantContext(logger);
|
|
255
|
+
|
|
256
|
+
// Middleware to set tenant from request
|
|
257
|
+
function setTenantFromRequest(request: Request) {
|
|
258
|
+
const tenantId = request.headers.get('X-Tenant-ID');
|
|
259
|
+
if (!tenantId) {
|
|
260
|
+
throw new Error('Missing tenant ID');
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
tenantContext.setTenant({
|
|
264
|
+
tenantId,
|
|
265
|
+
isAdmin: false
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// All queries automatically filtered by tenant
|
|
270
|
+
const wrapper = new QueryWrapper(tenantContext, logger);
|
|
271
|
+
const data = await wrapper.query('products', {});
|
|
272
|
+
// Automatically adds: WHERE tenant_id = ?
|
|
273
|
+
|
|
274
|
+
// Admin queries can bypass tenant filter
|
|
275
|
+
tenantContext.setTenant({
|
|
276
|
+
tenantId: 'admin',
|
|
277
|
+
isAdmin: true
|
|
278
|
+
});
|
|
279
|
+
const allData = await wrapper.query('products', {}, { bypassTenantFilter: true });
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Cache Invalidation Strategies
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
import {
|
|
286
|
+
MemoryCache,
|
|
287
|
+
CacheConfig,
|
|
288
|
+
InvalidationStrategy,
|
|
289
|
+
Logger
|
|
290
|
+
} from '@gl-life/gl-life-database';
|
|
291
|
+
|
|
292
|
+
const logger = new Logger({ level: 'info' });
|
|
293
|
+
|
|
294
|
+
// Time-based invalidation
|
|
295
|
+
const timeCache = new MemoryCache({
|
|
296
|
+
enabled: true,
|
|
297
|
+
backend: 'MEMORY',
|
|
298
|
+
maxItems: 1000,
|
|
299
|
+
defaultTTL: 300,
|
|
300
|
+
evictionPolicy: 'LRU',
|
|
301
|
+
invalidationStrategy: 'TIME_BASED'
|
|
302
|
+
}, logger);
|
|
303
|
+
|
|
304
|
+
// Event-based invalidation
|
|
305
|
+
const eventCache = new MemoryCache({
|
|
306
|
+
enabled: true,
|
|
307
|
+
backend: 'MEMORY',
|
|
308
|
+
maxItems: 1000,
|
|
309
|
+
defaultTTL: 0, // No TTL, manual invalidation
|
|
310
|
+
evictionPolicy: 'LRU',
|
|
311
|
+
invalidationStrategy: 'EVENT_BASED'
|
|
312
|
+
}, logger);
|
|
313
|
+
|
|
314
|
+
// Invalidate on data changes
|
|
315
|
+
await eventCache.set('user:123', userData);
|
|
316
|
+
// ... later after update
|
|
317
|
+
await eventCache.delete('user:123');
|
|
318
|
+
// or invalidate all users
|
|
319
|
+
await eventCache.invalidatePattern('user:*');
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
## API Overview
|
|
323
|
+
|
|
324
|
+
### Core Classes
|
|
325
|
+
|
|
326
|
+
- **ConnectionManager** - Manages database connections and connection pooling
|
|
327
|
+
- **TypeSafeQueryBuilder** - Fluent API for building type-safe SQL queries
|
|
328
|
+
- **TransactionManager** - Handles database transactions with isolation levels
|
|
329
|
+
- **TenantContext** - Manages multi-tenant context and isolation
|
|
330
|
+
- **QueryWrapper** - Wraps queries with automatic tenant filtering
|
|
331
|
+
- **MemoryCache** - In-memory LRU cache for query results
|
|
332
|
+
- **KVCache** - Cloudflare Workers KV-backed cache
|
|
333
|
+
- **MigrationPlanner** - Plans and validates database migrations
|
|
334
|
+
- **D1Adapter** - Cloudflare D1 database adapter
|
|
335
|
+
- **DurableObjectStorage** - Durable Objects storage adapter
|
|
336
|
+
|
|
337
|
+
### Type System
|
|
338
|
+
|
|
339
|
+
All operations return `Result<T, E>` types from `@gl-life/gl-life-core` for functional error handling:
|
|
340
|
+
|
|
341
|
+
```typescript
|
|
342
|
+
import { Result, Option } from '@gl-life/gl-life-database';
|
|
343
|
+
|
|
344
|
+
const result: Result<User[], DatabaseError> = await queryUsers();
|
|
345
|
+
|
|
346
|
+
if (result.isOk()) {
|
|
347
|
+
const users = result.unwrap();
|
|
348
|
+
console.log('Found users:', users);
|
|
349
|
+
} else {
|
|
350
|
+
const error = result.unwrapErr();
|
|
351
|
+
console.error('Query failed:', error.message);
|
|
352
|
+
}
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
### Configuration
|
|
356
|
+
|
|
357
|
+
All components accept configuration objects with sensible defaults:
|
|
358
|
+
|
|
359
|
+
```typescript
|
|
360
|
+
interface CacheConfig {
|
|
361
|
+
enabled: boolean;
|
|
362
|
+
backend: 'MEMORY' | 'KV' | 'HYBRID';
|
|
363
|
+
maxItems?: number;
|
|
364
|
+
defaultTTL?: number;
|
|
365
|
+
evictionPolicy?: 'LRU' | 'LFU' | 'FIFO';
|
|
366
|
+
invalidationStrategy?: 'TIME_BASED' | 'EVENT_BASED' | 'HYBRID';
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
interface TransactionConfig {
|
|
370
|
+
isolationLevel: 'READ_UNCOMMITTED' | 'READ_COMMITTED' | 'REPEATABLE_READ' | 'SERIALIZABLE';
|
|
371
|
+
timeout: number;
|
|
372
|
+
retryAttempts: number;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
interface MigrationConfig {
|
|
376
|
+
enabled: boolean;
|
|
377
|
+
migrationTable: string;
|
|
378
|
+
autoRun: boolean;
|
|
379
|
+
}
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
## Security
|
|
383
|
+
|
|
384
|
+
This library implements comprehensive security measures:
|
|
385
|
+
|
|
386
|
+
- ✅ **SQL Injection Protection** - All queries use parameterized statements
|
|
387
|
+
- ✅ **Tenant Isolation** - Automatic tenant_id filtering prevents data leaks
|
|
388
|
+
- ✅ **Type Safety** - TypeScript compile-time checks + Zod runtime validation
|
|
389
|
+
- ✅ **Audit Logging** - All operations are logged for security auditing
|
|
390
|
+
- ✅ **Zero Vulnerabilities** - Regular security audits with `npm audit`
|
|
391
|
+
|
|
392
|
+
See [SECURITY.md](./SECURITY.md) for detailed security audit results and best practices.
|
|
393
|
+
|
|
394
|
+
## Performance
|
|
395
|
+
|
|
396
|
+
Query building performance benchmarks (P95):
|
|
397
|
+
|
|
398
|
+
- Simple SELECT: <1ms
|
|
399
|
+
- Complex JOIN: <1ms
|
|
400
|
+
- GROUP BY with HAVING: <1ms
|
|
401
|
+
- Multiple WHERE conditions: <1ms
|
|
402
|
+
|
|
403
|
+
Cache performance benchmarks (P95):
|
|
404
|
+
|
|
405
|
+
- Cache GET (hit): <1ms
|
|
406
|
+
- Cache SET: <1ms
|
|
407
|
+
- Pattern invalidation (100 keys): <10ms
|
|
408
|
+
|
|
409
|
+
See [PERFORMANCE.md](./PERFORMANCE.md) for detailed benchmark results.
|
|
410
|
+
|
|
411
|
+
## Testing
|
|
412
|
+
|
|
413
|
+
Run the test suite:
|
|
414
|
+
|
|
415
|
+
```bash
|
|
416
|
+
# Run all tests
|
|
417
|
+
npm test
|
|
418
|
+
|
|
419
|
+
# Run tests in watch mode
|
|
420
|
+
npm run test:watch
|
|
421
|
+
|
|
422
|
+
# Generate coverage report
|
|
423
|
+
npm run test:coverage
|
|
424
|
+
|
|
425
|
+
# Run performance benchmarks
|
|
426
|
+
npm run bench
|
|
427
|
+
|
|
428
|
+
# Run specific benchmark
|
|
429
|
+
npm run bench:query
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
Current test coverage: **95.9%**
|
|
433
|
+
|
|
434
|
+
- Lines: 95.9%
|
|
435
|
+
- Functions: 96.2%
|
|
436
|
+
- Branches: 95.1%
|
|
437
|
+
- Statements: 95.9%
|
|
438
|
+
|
|
439
|
+
## Development
|
|
440
|
+
|
|
441
|
+
```bash
|
|
442
|
+
# Install dependencies
|
|
443
|
+
npm install
|
|
444
|
+
|
|
445
|
+
# Build the package
|
|
446
|
+
npm run build
|
|
447
|
+
|
|
448
|
+
# Run tests
|
|
449
|
+
npm test
|
|
450
|
+
|
|
451
|
+
# Run benchmarks
|
|
452
|
+
npm run bench
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
## Contributing
|
|
456
|
+
|
|
457
|
+
This package is part of the GoodLife Sargam ecosystem. For contribution guidelines, please visit [gl.life](https://gl.life).
|
|
458
|
+
|
|
459
|
+
## Support
|
|
460
|
+
|
|
461
|
+
For questions, issues, or feature requests:
|
|
462
|
+
|
|
463
|
+
- Email: [packages@gl.life](mailto:packages@gl.life)
|
|
464
|
+
- Website: [gl.life](https://gl.life)
|
|
465
|
+
|
|
466
|
+
## Documentation
|
|
467
|
+
|
|
468
|
+
- [API Documentation](./API.md) - Detailed API reference for AI agents
|
|
469
|
+
- [Security Audit](./SECURITY.md) - Security audit report and best practices
|
|
470
|
+
- [Performance Benchmarks](./PERFORMANCE.md) - Performance baselines and optimization guide
|
|
471
|
+
|
|
472
|
+
## License
|
|
473
|
+
|
|
474
|
+
Apache-2.0 © GoodLife
|
|
475
|
+
|
|
476
|
+
---
|
|
477
|
+
|
|
478
|
+
**Part of the GoodLife Sargam ecosystem**
|
|
479
|
+
|
|
480
|
+
For more information about the GoodLife Sargam ecosystem and our suite of 80 packages for building modern cloud applications, visit [gl.life](https://gl.life).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cache/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC"}
|