masterrecord 1.5.5 → 1.5.7

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,446 @@
1
+ # Query Caching Guide - Like Active Record
2
+
3
+ MasterRecord's query caching works like **Active Record** in Rails:
4
+ - **Opt-in** with `.cache()`
5
+ - **Request-scoped** (cleared after each request)
6
+ - **Automatic invalidation** on data changes
7
+
8
+ ---
9
+
10
+ ## Quick Start
11
+
12
+ ### 1. Express Middleware (Recommended)
13
+
14
+ ```javascript
15
+ import express from 'express';
16
+ import AppContext from './models/AppContext.js';
17
+
18
+ const app = express();
19
+
20
+ // Middleware: Create context per request, auto-clear cache
21
+ app.use((req, res, next) => {
22
+ req.db = new AppContext();
23
+
24
+ // Clear cache when request ends (like Active Record)
25
+ res.on('finish', () => {
26
+ req.db.endRequest();
27
+ });
28
+
29
+ next();
30
+ });
31
+
32
+ // Routes
33
+ app.get('/api/categories', async (req, res) => {
34
+ // Opt-in caching with .cache()
35
+ const categories = await req.db.Categories.cache().toList();
36
+ res.json(categories);
37
+ // Cache auto-cleared after response
38
+ });
39
+
40
+ app.get('/api/users/:id', (req, res) => {
41
+ // No .cache() = always fresh (default)
42
+ const user = req.db.User.findById(req.params.id);
43
+ res.json(user);
44
+ });
45
+
46
+ app.listen(3000);
47
+ ```
48
+
49
+ ---
50
+
51
+ ## How It Works
52
+
53
+ ### Default Behavior (No Caching)
54
+
55
+ ```javascript
56
+ // Without .cache() - always hits database
57
+ const user1 = db.User.findById(1); // DB query
58
+ const user2 = db.User.findById(1); // DB query again (no cache)
59
+ ```
60
+
61
+ ### Opt-In Caching
62
+
63
+ ```javascript
64
+ // With .cache() - caches result
65
+ const categories1 = db.Categories.cache().toList(); // DB query, cached
66
+ const categories2 = db.Categories.cache().toList(); // Cache hit!
67
+ ```
68
+
69
+ ### Request-Scoped (Auto-Clear)
70
+
71
+ ```javascript
72
+ // Request 1
73
+ app.get('/route1', (req, res) => {
74
+ const cats = req.db.Categories.cache().toList(); // DB query
75
+ res.json(cats);
76
+ // Cache cleared after response
77
+ });
78
+
79
+ // Request 2 - starts with empty cache
80
+ app.get('/route2', (req, res) => {
81
+ const cats = req.db.Categories.cache().toList(); // DB query again (fresh)
82
+ res.json(cats);
83
+ });
84
+ ```
85
+
86
+ ---
87
+
88
+ ## When to Use `.cache()`
89
+
90
+ ### ✅ DO use .cache() for:
91
+
92
+ ```javascript
93
+ // Reference data (rarely changes)
94
+ const categories = db.Categories.cache().toList();
95
+ const countries = db.Countries.cache().toList();
96
+ const settings = db.Settings.cache().toList();
97
+
98
+ // Expensive aggregations (within a request)
99
+ const totalOrders = db.Orders
100
+ .where(o => o.status == $$, 'completed')
101
+ .cache()
102
+ .count();
103
+
104
+ // Lookup tables
105
+ const roles = db.Roles.cache().toList();
106
+ const permissions = db.Permissions.cache().toList();
107
+ ```
108
+
109
+ ### ❌ DON'T use .cache() for:
110
+
111
+ ```javascript
112
+ // User-specific data (default is safe)
113
+ const user = db.User.findById(userId); // No .cache()
114
+
115
+ // Real-time data
116
+ const liveOrders = db.Orders
117
+ .where(o => o.status == $$, 'pending')
118
+ .toList(); // No .cache()
119
+
120
+ // Financial/sensitive data
121
+ const transactions = db.Transactions
122
+ .where(t => t.user_id == $$, userId)
123
+ .toList(); // No .cache()
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Complete Examples
129
+
130
+ ### Example 1: E-Commerce API
131
+
132
+ ```javascript
133
+ import express from 'express';
134
+ import AppContext from './models/AppContext.js';
135
+
136
+ const app = express();
137
+
138
+ // Middleware: Request-scoped caching
139
+ app.use((req, res, next) => {
140
+ req.db = new AppContext();
141
+ res.on('finish', () => req.db.endRequest());
142
+ next();
143
+ });
144
+
145
+ // Categories - cache (rarely changes)
146
+ app.get('/api/categories', (req, res) => {
147
+ const categories = req.db.Categories
148
+ .cache() // Cache for this request
149
+ .toList();
150
+ res.json(categories);
151
+ });
152
+
153
+ // Products - cache (within request)
154
+ app.get('/api/products', (req, res) => {
155
+ const products = req.db.Products
156
+ .where(p => p.active == true)
157
+ .cache() // Cache for this request
158
+ .toList();
159
+ res.json(products);
160
+ });
161
+
162
+ // User profile - NO cache (user-specific)
163
+ app.get('/api/profile', (req, res) => {
164
+ const user = req.db.User.findById(req.user.id); // No .cache()
165
+ res.json(user);
166
+ });
167
+
168
+ // Cart - NO cache (real-time)
169
+ app.get('/api/cart', (req, res) => {
170
+ const cart = req.db.Cart
171
+ .where(c => c.user_id == $$, req.user.id)
172
+ .toList(); // No .cache()
173
+ res.json(cart);
174
+ });
175
+
176
+ app.listen(3000);
177
+ ```
178
+
179
+ ### Example 2: Admin Dashboard
180
+
181
+ ```javascript
182
+ app.get('/admin/dashboard', async (req, res) => {
183
+ const db = new AppContext();
184
+
185
+ // Multiple queries with caching
186
+ const stats = {
187
+ // Cache expensive aggregations
188
+ totalUsers: db.User.cache().count(),
189
+ totalOrders: db.Orders.cache().count(),
190
+
191
+ // Cache reference data
192
+ categories: db.Categories.cache().toList(),
193
+
194
+ // No cache for real-time data
195
+ recentOrders: db.Orders
196
+ .orderByDescending(o => o.created_at)
197
+ .take(10)
198
+ .toList() // No .cache() - always fresh
199
+ };
200
+
201
+ res.render('dashboard', stats);
202
+
203
+ // Clear cache after response
204
+ db.endRequest();
205
+ });
206
+ ```
207
+
208
+ ### Example 3: Background Job
209
+
210
+ ```javascript
211
+ // Cron job - process orders
212
+ cron.schedule('*/5 * * * *', async () => {
213
+ const db = new AppContext();
214
+
215
+ // Get pending orders (no cache - real-time)
216
+ const orders = db.Orders
217
+ .where(o => o.status == $$, 'pending')
218
+ .toList(); // No .cache()
219
+
220
+ for (const order of orders) {
221
+ await processOrder(order);
222
+ order.status = 'processed';
223
+ }
224
+
225
+ await db.saveChanges(); // Invalidates cache
226
+
227
+ // Clear cache after job
228
+ db.endRequest();
229
+ });
230
+ ```
231
+
232
+ ---
233
+
234
+ ## Cache Invalidation
235
+
236
+ Cache is automatically invalidated when you modify data:
237
+
238
+ ```javascript
239
+ app.post('/api/categories', (req, res) => {
240
+ const db = new AppContext();
241
+
242
+ // Cache categories
243
+ const cats = db.Categories.cache().toList(); // DB query, cached
244
+
245
+ // Add new category
246
+ const newCat = db.Categories.new();
247
+ newCat.name = req.body.name;
248
+ db.saveChanges(); // Automatically invalidates Categories cache!
249
+
250
+ // Next query hits database (fresh)
251
+ const freshCats = db.Categories.cache().toList(); // DB query (not cached)
252
+
253
+ res.json(newCat);
254
+ db.endRequest();
255
+ });
256
+ ```
257
+
258
+ ---
259
+
260
+ ## Comparison with Active Record
261
+
262
+ ### Active Record (Rails)
263
+
264
+ ```ruby
265
+ # Rails controller
266
+ class CategoriesController < ApplicationController
267
+ def index
268
+ # Query cache automatically enabled for request
269
+ @categories = Category.where(active: true).to_a
270
+ # Cache automatically cleared after request
271
+ end
272
+ end
273
+ ```
274
+
275
+ ### MasterRecord (Node.js)
276
+
277
+ ```javascript
278
+ // Express route
279
+ app.get('/categories', (req, res) => {
280
+ // Opt-in caching with .cache()
281
+ const categories = req.db.Categories
282
+ .where(c => c.active == true)
283
+ .cache() // Explicitly opt-in
284
+ .toList();
285
+ res.json(categories);
286
+ // Cache cleared by middleware
287
+ });
288
+ ```
289
+
290
+ **Key differences:**
291
+ - Active Record: Cache **enabled by default** for all queries
292
+ - MasterRecord: Cache **opt-in** with `.cache()` (safer)
293
+ - Both: **Request-scoped** (cleared after each request)
294
+
295
+ ---
296
+
297
+ ## Configuration
298
+
299
+ ### Environment Variables
300
+
301
+ ```bash
302
+ # .env
303
+ QUERY_CACHE_TTL=5000 # 5 seconds (request-scoped)
304
+ QUERY_CACHE_SIZE=1000 # Max 1000 cached queries
305
+ QUERY_CACHE_ENABLED=true # Enable caching
306
+ ```
307
+
308
+ ### Custom TTL per Query
309
+
310
+ ```javascript
311
+ // Use default TTL (5 seconds)
312
+ const cats = db.Categories.cache().toList();
313
+
314
+ // For longer-lived cache, increase TTL in config:
315
+ // QUERY_CACHE_TTL=60000 // 1 minute
316
+ ```
317
+
318
+ ---
319
+
320
+ ## Testing
321
+
322
+ ### Unit Tests
323
+
324
+ ```javascript
325
+ import { describe, test, beforeEach, afterEach } from 'node:test';
326
+ import AppContext from '../models/AppContext.js';
327
+
328
+ describe('Category API', () => {
329
+ let db;
330
+
331
+ beforeEach(() => {
332
+ db = new AppContext();
333
+ });
334
+
335
+ afterEach(() => {
336
+ db.endRequest(); // Clear cache after each test
337
+ });
338
+
339
+ it('caches category queries', () => {
340
+ const cats1 = db.Categories.cache().toList();
341
+ const cats2 = db.Categories.cache().toList();
342
+
343
+ const stats = db.getCacheStats();
344
+ expect(stats.hits).toBe(1); // Second query hit cache
345
+ });
346
+
347
+ it('does not cache without .cache()', () => {
348
+ const cats1 = db.Categories.toList(); // No .cache()
349
+ const cats2 = db.Categories.toList(); // No .cache()
350
+
351
+ const stats = db.getCacheStats();
352
+ expect(stats.size).toBe(0); // Nothing cached
353
+ });
354
+ });
355
+ ```
356
+
357
+ ---
358
+
359
+ ## Best Practices
360
+
361
+ ### ✅ DO:
362
+ - Use middleware to auto-clear cache per request
363
+ - Cache reference data (categories, settings, countries)
364
+ - Cache within a request for duplicate queries
365
+ - Call `db.endRequest()` at end of request
366
+ - Monitor cache stats in development
367
+
368
+ ### ❌ DON'T:
369
+ - Cache user-specific data
370
+ - Cache real-time data
371
+ - Cache financial/sensitive data
372
+ - Forget to call `endRequest()` in long-running processes
373
+ - Use `.cache()` on frequently updated tables
374
+
375
+ ---
376
+
377
+ ## Troubleshooting
378
+
379
+ ### Cache not clearing between requests
380
+
381
+ ```javascript
382
+ // ❌ BAD: No cache clearing
383
+ app.use((req, res, next) => {
384
+ req.db = new AppContext();
385
+ next();
386
+ });
387
+
388
+ // ✅ GOOD: Auto-clear cache
389
+ app.use((req, res, next) => {
390
+ req.db = new AppContext();
391
+ res.on('finish', () => req.db.endRequest()); // Clear cache
392
+ next();
393
+ });
394
+ ```
395
+
396
+ ### Stale data across requests
397
+
398
+ ```javascript
399
+ // Check TTL - should be short (5 seconds default)
400
+ console.log(process.env.QUERY_CACHE_TTL); // Should be 5000
401
+
402
+ // Make sure endRequest() is called
403
+ db.endRequest(); // Clears cache
404
+ ```
405
+
406
+ ### Low cache hit rate
407
+
408
+ ```javascript
409
+ // Check if queries are actually using .cache()
410
+ const stats = db.getCacheStats();
411
+ console.log(stats);
412
+ // {
413
+ // size: 0, // No cached queries?
414
+ // hits: 0, // No cache hits?
415
+ // misses: 10 // All misses?
416
+ // }
417
+
418
+ // Make sure to use .cache()
419
+ const cats = db.Categories.cache().toList(); // Must have .cache()!
420
+ ```
421
+
422
+ ---
423
+
424
+ ## Summary
425
+
426
+ **MasterRecord caching = Active Record style:**
427
+
428
+ 1. **Opt-in** with `.cache()` (safer than default-on)
429
+ 2. **Request-scoped** with `endRequest()` (auto-clear)
430
+ 3. **Automatic invalidation** on `saveChanges()`
431
+
432
+ **Use it like this:**
433
+ ```javascript
434
+ // Setup (once)
435
+ app.use((req, res, next) => {
436
+ req.db = new AppContext();
437
+ res.on('finish', () => req.db.endRequest());
438
+ next();
439
+ });
440
+
441
+ // Use (in routes)
442
+ const categories = req.db.Categories.cache().toList(); // Cached
443
+ const user = req.db.User.findById(id); // Not cached (default)
444
+ ```
445
+
446
+ **It just works!** ✅
@@ -0,0 +1,95 @@
1
+ # Security & Production Guide
2
+
3
+ MasterRecord is designed to be safe by default. This page documents the guarantees, the sharp edges, and the settings you should turn on for a production / enterprise deployment across SQLite, MySQL, and Postgres.
4
+
5
+ ## 1. Query parameterization (SQL injection)
6
+
7
+ **Always pass runtime values through the `$$` (or `$`) placeholder** — never interpolate them into the lambda string yourself.
8
+
9
+ ```js
10
+ // ✅ SAFE — the value is bound as a parameter (?, $1) on every engine
11
+ ctx.User.where(u => u.email == $$, req.body.email).toList();
12
+ ctx.User.where(u => $$.includes(u.id), req.query.ids).toList(); // IN (...)
13
+ ctx.User.where(u => u.name.like($$), `${term}%`).toList(); // LIKE
14
+
15
+ // ❌ UNSAFE — you built SQL from untrusted input by hand
16
+ ctx.User.where(`u => u.email == '${req.body.email}'`).toList();
17
+ ```
18
+
19
+ Values bound via `$$` / `$` go through prepared-statement parameters (`?` on SQLite/MySQL, `$1,$2,…` on Postgres) and are type-validated (`only primitives, null, Date, Buffer`). The lambda parser also restricts column names to word characters and operators to a fixed set, and every engine re-asserts the operator against an allowlist before emitting SQL.
20
+
21
+ Inline literals (e.g. `u => u.status == "active"`) are single-quote-escaped (`'` → `''`) as defense-in-depth, but the placeholder path above is the contract for anything user-supplied.
22
+
23
+ ## 2. Pagination values (`.take()` / `.skip()`)
24
+
25
+ `LIMIT` / `OFFSET` **cannot** be parameterized on any engine, so pagination is a classic injection point. MasterRecord validates these for you:
26
+
27
+ ```js
28
+ ctx.User.take(req.query.limit).skip(req.query.offset).toList();
29
+ ```
30
+
31
+ - A non-negative integer (or a clean numeric string like `'25'`) is accepted.
32
+ - Anything else (a value that appends extra SQL after the number, `-1`, `1.5`, `NaN`) **throws** before it can reach the SQL string — both at the `.take()`/`.skip()` setter and again at the engine boundary.
33
+
34
+ Clamp `limit` to a sane maximum in your own code to avoid unbounded result sets.
35
+
36
+ ## 3. Raw SQL
37
+
38
+ There are two raw escape hatches — know which one you're using:
39
+
40
+ ```js
41
+ // ✅ Parameterized and portable — prefer this for anything with user input.
42
+ await ctx.query('SELECT * FROM "User" WHERE email = $1', [email]); // Postgres
43
+ await ctx.query('SELECT * FROM User WHERE email = ?', [email]); // SQLite/MySQL
44
+
45
+ // ⚠️ Verbatim — the string is executed as-is (no binding). NEVER interpolate
46
+ // untrusted input into it.
47
+ ctx.User.raw('SELECT * FROM User WHERE active = 1').toList();
48
+ ```
49
+
50
+ `ctx.query(sql, params)` / `ctx.execute(sql, params)` bind their parameters. The query-builder `.raw(sql)` runs the string verbatim — treat it like writing SQL by hand.
51
+
52
+ ## 4. Atomic writes
53
+
54
+ `saveChanges()` wraps **all** tracked inserts/updates/deletes in a single transaction on every engine (SQLite, MySQL, Postgres). If any statement fails, the entire batch is rolled back — you never get partial data. No extra code required:
55
+
56
+ ```js
57
+ ctx.Order.add(order);
58
+ ctx.LineItem.add(item1);
59
+ ctx.LineItem.add(item2);
60
+ await ctx.saveChanges(); // all-or-nothing
61
+ ```
62
+
63
+ (Internally, the bulk-write fast paths are savepoint-protected so a fallback to per-row writes still works inside the enclosing transaction.)
64
+
65
+ ## 5. Transport encryption (TLS/SSL)
66
+
67
+ **MySQL and Postgres connect in plaintext unless you supply an `ssl` option.** For any non-local database, enable TLS in your environment config:
68
+
69
+ ```jsonc
70
+ // Postgres — managed provider with a CA cert
71
+ { "AppCtx": { "type": "pg", "host": "…", "database": "…", "user": "…", "password": "…",
72
+ "ssl": { "rejectUnauthorized": true, "ca": "<PEM>" } } }
73
+
74
+ // MySQL — verify the server certificate
75
+ { "AppCtx": { "type": "mysql", "host": "…", "database": "…", "user": "…", "password": "…",
76
+ "ssl": { "rejectUnauthorized": true } } }
77
+ ```
78
+
79
+ MasterRecord never forces `rejectUnauthorized: false`; whatever you pass in `ssl` is handed to the underlying driver (`mysql2` / `pg`) unchanged. Do **not** disable certificate verification in production.
80
+
81
+ SQLite is a local file — protect it with filesystem permissions and disk encryption.
82
+
83
+ ## 6. Credentials
84
+
85
+ - Connection passwords are never logged. `getConnectionInfo()` deliberately omits the password.
86
+ - Keep DB credentials in environment config / secrets, not in source.
87
+ - In production set `NODE_ENV=production` to silence per-query SQL logging (runtime SQL is only logged outside production or when `LOG_SQL=true`).
88
+
89
+ ## 7. Schema / migration identifiers
90
+
91
+ DDL identifiers (table, column, index names) can't be parameterized, and migrations are developer-authored code, so MasterRecord treats them as trusted. **Do not build entity, table, column, or index names — or index `where` predicates — from untrusted input.** Database names passed to the auto-create bootstrap are validated against a strict pattern before use.
92
+
93
+ ---
94
+
95
+ Found a security issue? Please report it privately to the maintainer rather than opening a public issue.