masterrecord 1.5.5 → 1.5.6
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/CHANGES.md +631 -0
- package/docs/ACTIVE_RECORD_PATTERN.md +477 -0
- package/docs/DETACHED_ENTITIES_GUIDE.md +453 -0
- package/docs/FULL_TEXT_SEARCH.md +219 -0
- package/docs/INCLUDES_CLARIFICATION.md +202 -0
- package/docs/METHODS_REFERENCE.md +199 -0
- package/docs/MIGRATIONS_GUIDE.md +532 -0
- package/docs/POSTGRESQL_SETUP.md +445 -0
- package/docs/QUERY_CACHING_GUIDE.md +446 -0
- package/docs/SECURITY.md +95 -0
- package/docs/TROUBLESHOOTING.md +348 -0
- package/docs/belongsTo-relationships.md +222 -0
- package/package.json +3 -1
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
# PostgreSQL Setup for MasterRecord
|
|
2
|
+
|
|
3
|
+
Complete guide for using PostgreSQL with MasterRecord ORM.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install pg@^8.16.3
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Basic Setup
|
|
12
|
+
|
|
13
|
+
### 1. Initialize PostgreSQL Connection
|
|
14
|
+
|
|
15
|
+
```javascript
|
|
16
|
+
import context from 'masterrecord/context';
|
|
17
|
+
|
|
18
|
+
// Create a new context
|
|
19
|
+
const db = new context();
|
|
20
|
+
|
|
21
|
+
// Configure PostgreSQL connection
|
|
22
|
+
await db.env({
|
|
23
|
+
type: 'postgres', // or 'postgresql'
|
|
24
|
+
host: 'localhost',
|
|
25
|
+
port: 5432,
|
|
26
|
+
database: 'your_database',
|
|
27
|
+
user: 'your_user',
|
|
28
|
+
password: 'your_password',
|
|
29
|
+
max: 20, // Maximum pool size
|
|
30
|
+
idleTimeoutMillis: 30000, // Idle connection timeout
|
|
31
|
+
connectionTimeoutMillis: 2000 // Connection timeout
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### 2. Define Entities
|
|
36
|
+
|
|
37
|
+
```javascript
|
|
38
|
+
const User = db.dbset('User')
|
|
39
|
+
.key('id').auto()
|
|
40
|
+
.field('name').string().notNull()
|
|
41
|
+
.field('email').string().notNull()
|
|
42
|
+
.field('age').integer().nullable()
|
|
43
|
+
.field('created_at').datetime()
|
|
44
|
+
.create();
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### 3. Query with Parameterized Placeholders
|
|
48
|
+
|
|
49
|
+
MasterRecord automatically handles PostgreSQL's `$1, $2, $3...` placeholder format:
|
|
50
|
+
|
|
51
|
+
```javascript
|
|
52
|
+
// Single parameter
|
|
53
|
+
const user = db.User
|
|
54
|
+
.where(u => u.email == $$, 'john@example.com')
|
|
55
|
+
.single();
|
|
56
|
+
|
|
57
|
+
// Multiple parameters
|
|
58
|
+
const users = db.User
|
|
59
|
+
.where(u => u.age > $$ && u.status == $$, 25, 'active')
|
|
60
|
+
.all();
|
|
61
|
+
|
|
62
|
+
// OR conditions with single $ placeholder
|
|
63
|
+
const results = db.User
|
|
64
|
+
.where(u => u.status == $ || u.status == null, 'active')
|
|
65
|
+
.all();
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 4. Insert Records
|
|
69
|
+
|
|
70
|
+
```javascript
|
|
71
|
+
const newUser = db.User.new();
|
|
72
|
+
newUser.name = 'Jane Smith';
|
|
73
|
+
newUser.email = 'jane@example.com';
|
|
74
|
+
newUser.age = 28;
|
|
75
|
+
newUser.created_at = new Date();
|
|
76
|
+
|
|
77
|
+
// Save to database
|
|
78
|
+
await db.saveChanges();
|
|
79
|
+
|
|
80
|
+
// ID is available after saveChanges()
|
|
81
|
+
console.log(newUser.id); // PostgreSQL auto-increment ID
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### 5. Update Records
|
|
85
|
+
|
|
86
|
+
```javascript
|
|
87
|
+
const user = db.User
|
|
88
|
+
.where(u => u.id == $$, 123)
|
|
89
|
+
.single();
|
|
90
|
+
|
|
91
|
+
user.age = 30;
|
|
92
|
+
await db.saveChanges();
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### 6. Delete Records
|
|
96
|
+
|
|
97
|
+
```javascript
|
|
98
|
+
const user = db.User.findById(123);
|
|
99
|
+
db.remove(user);
|
|
100
|
+
await db.saveChanges();
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Advanced Features
|
|
104
|
+
|
|
105
|
+
### Schemas (multi-schema / search_path)
|
|
106
|
+
|
|
107
|
+
By default MasterRecord uses the connection's default `search_path` (typically `public`). To put your tables in a specific Postgres schema — for multi-tenant deployments, or when your tables don't live in the default schema — set `schema` (or `searchPath`) in the connection config:
|
|
108
|
+
|
|
109
|
+
```javascript
|
|
110
|
+
await db.env({
|
|
111
|
+
type: 'postgres',
|
|
112
|
+
host: 'localhost',
|
|
113
|
+
database: 'your_database',
|
|
114
|
+
user: 'your_user',
|
|
115
|
+
password: 'your_password',
|
|
116
|
+
schema: 'tenant1', // tables created/queried in "tenant1"
|
|
117
|
+
// or, for an explicit list (first entry is where new tables are created):
|
|
118
|
+
// searchPath: 'tenant1,public'
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
How it works:
|
|
123
|
+
- The schema is applied to **every pooled connection** via libpq's `search_path` startup option, so introspection, migrations (DDL), and runtime queries all resolve to it — no per-query schema qualification needed.
|
|
124
|
+
- **Connection pools are keyed by schema.** Two contexts pointed at the same database but different schemas get **separate** pools, so one context's `search_path` can never bleed into another's — a `CREATE TABLE` always lands in the intended schema. (This is what makes `update-database-all` safe across multi-schema contexts.)
|
|
125
|
+
- On connect, MasterRecord runs `CREATE SCHEMA IF NOT EXISTS "<schema>"`, so a fresh deploy self-creates the schema before any table is created in it.
|
|
126
|
+
- `schema: 'x'` expands to a search_path of `x,public` (so shared objects in `public` remain reachable). Use `searchPath` to control the full list/order.
|
|
127
|
+
|
|
128
|
+
Identifiers are validated (letters, digits, underscore; not starting with a digit) — an invalid schema name throws at connect rather than being interpolated into SQL.
|
|
129
|
+
|
|
130
|
+
> Without this option, behavior is unchanged. (This closes the prior gap where a table in a non-search-path schema was misread as "absent" during migrations.)
|
|
131
|
+
|
|
132
|
+
### Transactions
|
|
133
|
+
|
|
134
|
+
```javascript
|
|
135
|
+
import PostgresSyncConnect from 'masterrecord/postgresSyncConnect';
|
|
136
|
+
|
|
137
|
+
const connection = new PostgresSyncConnect();
|
|
138
|
+
await connection.connect(config);
|
|
139
|
+
|
|
140
|
+
// Execute in transaction
|
|
141
|
+
const result = await connection.transaction(async (client) => {
|
|
142
|
+
// Insert
|
|
143
|
+
const userResult = await client.query(
|
|
144
|
+
'INSERT INTO User (name, email) VALUES ($1, $2) RETURNING id',
|
|
145
|
+
['Bob', 'bob@example.com']
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
// Update
|
|
149
|
+
await client.query(
|
|
150
|
+
'UPDATE User SET verified = $1 WHERE id = $2',
|
|
151
|
+
[true, userResult.rows[0].id]
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
return userResult.rows[0].id;
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### IN Clauses with .any()
|
|
159
|
+
|
|
160
|
+
```javascript
|
|
161
|
+
// Array parameter
|
|
162
|
+
const users = db.User
|
|
163
|
+
.where(u => u.id.any($$), [1, 2, 3, 4, 5])
|
|
164
|
+
.all();
|
|
165
|
+
|
|
166
|
+
// Comma-separated string (auto-splits)
|
|
167
|
+
const ids = '10,20,30,40';
|
|
168
|
+
const users = db.User
|
|
169
|
+
.where(u => u.id.any($$), ids)
|
|
170
|
+
.all();
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### Array Filtering with .includes()
|
|
174
|
+
|
|
175
|
+
```javascript
|
|
176
|
+
const tags = ['javascript', 'node', 'postgres'];
|
|
177
|
+
const posts = db.Post
|
|
178
|
+
.where(p => $$.includes(p.category), tags)
|
|
179
|
+
.all();
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### Find by Primary Key
|
|
183
|
+
|
|
184
|
+
```javascript
|
|
185
|
+
// Convenience method - auto-detects primary key
|
|
186
|
+
const user = db.User.findById(123);
|
|
187
|
+
|
|
188
|
+
// Equivalent to:
|
|
189
|
+
const user = db.User
|
|
190
|
+
.where(u => u.id == $$, 123)
|
|
191
|
+
.single();
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Pagination
|
|
195
|
+
|
|
196
|
+
```javascript
|
|
197
|
+
// Skip 20, take 10
|
|
198
|
+
const users = db.User
|
|
199
|
+
.orderBy('created_at')
|
|
200
|
+
.skip(20)
|
|
201
|
+
.take(10)
|
|
202
|
+
.all();
|
|
203
|
+
|
|
204
|
+
// PostgreSQL generates: LIMIT 10 OFFSET 20
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Joins
|
|
208
|
+
|
|
209
|
+
```javascript
|
|
210
|
+
const userPosts = db.User
|
|
211
|
+
.join('Post', (u, p) => u.id == p.user_id)
|
|
212
|
+
.where(u => u.id == $$, 123)
|
|
213
|
+
.all();
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### NULL Handling
|
|
217
|
+
|
|
218
|
+
```javascript
|
|
219
|
+
// Find users with no email
|
|
220
|
+
const users = db.User
|
|
221
|
+
.where(u => u.email == null)
|
|
222
|
+
.all();
|
|
223
|
+
|
|
224
|
+
// Find users with email OR age is null
|
|
225
|
+
const users = db.User
|
|
226
|
+
.where(u => u.email != null)
|
|
227
|
+
.and(u => u.age == null)
|
|
228
|
+
.all();
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## Connection Management
|
|
232
|
+
|
|
233
|
+
### Health Check
|
|
234
|
+
|
|
235
|
+
```javascript
|
|
236
|
+
const health = await connection.healthCheck();
|
|
237
|
+
|
|
238
|
+
if (health.healthy) {
|
|
239
|
+
console.log('Server time:', health.serverTime);
|
|
240
|
+
console.log('PostgreSQL version:', health.version);
|
|
241
|
+
console.log('Pool size:', health.poolSize);
|
|
242
|
+
console.log('Idle connections:', health.idleCount);
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
### Connection Info
|
|
247
|
+
|
|
248
|
+
```javascript
|
|
249
|
+
const info = connection.getConnectionInfo();
|
|
250
|
+
console.log(`Connected to ${info.database} at ${info.host}:${info.port}`);
|
|
251
|
+
console.log(`Max connections: ${info.maxConnections}`);
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### Close Connection
|
|
255
|
+
|
|
256
|
+
```javascript
|
|
257
|
+
await connection.close();
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
## Placeholder Syntax Reference
|
|
261
|
+
|
|
262
|
+
MasterRecord uses double dollar signs (`$$`) for placeholders that get converted to PostgreSQL format:
|
|
263
|
+
|
|
264
|
+
| MasterRecord Syntax | PostgreSQL SQL | Parameters |
|
|
265
|
+
|---------------------|----------------|------------|
|
|
266
|
+
| `.where(u => u.id == $$, 5)` | `WHERE id = $1` | `[5]` |
|
|
267
|
+
| `.where(u => u.age > $$ && u.status == $$, 25, 'active')` | `WHERE age > $1 AND status = $2` | `[25, 'active']` |
|
|
268
|
+
| `.where(u => u.id.any($$), [1,2,3])` | `WHERE id IN ($1, $2, $3)` | `[1, 2, 3]` |
|
|
269
|
+
|
|
270
|
+
**Single `$` for OR conditions:**
|
|
271
|
+
```javascript
|
|
272
|
+
.where(u => u.status == $ || u.status == null, 'active')
|
|
273
|
+
// Generates: WHERE status = $1 OR status IS NULL
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
## Field Transformers
|
|
277
|
+
|
|
278
|
+
Custom serialization for complex types:
|
|
279
|
+
|
|
280
|
+
```javascript
|
|
281
|
+
const Post = db.dbset('Post')
|
|
282
|
+
.key('id').auto()
|
|
283
|
+
.field('title').string()
|
|
284
|
+
.field('tags').string().transform({
|
|
285
|
+
toDatabase: (value) => {
|
|
286
|
+
// Array → JSON string
|
|
287
|
+
return Array.isArray(value) ? JSON.stringify(value) : value;
|
|
288
|
+
},
|
|
289
|
+
fromDatabase: (value) => {
|
|
290
|
+
// JSON string → Array
|
|
291
|
+
return typeof value === 'string' ? JSON.parse(value) : value;
|
|
292
|
+
}
|
|
293
|
+
})
|
|
294
|
+
.create();
|
|
295
|
+
|
|
296
|
+
// Use as array in code
|
|
297
|
+
const post = db.Post.new();
|
|
298
|
+
post.tags = ['javascript', 'postgres', 'node'];
|
|
299
|
+
await db.saveChanges();
|
|
300
|
+
|
|
301
|
+
// Stored as: '["javascript","postgres","node"]'
|
|
302
|
+
// Retrieved as: ['javascript', 'postgres', 'node']
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
## Performance Tips
|
|
306
|
+
|
|
307
|
+
1. **Use Connection Pooling**: Adjust `max` pool size based on your needs
|
|
308
|
+
2. **Parameterized Queries**: Always use `$$` placeholders (automatic SQL injection protection)
|
|
309
|
+
3. **Indexes**: Create indexes on frequently queried columns
|
|
310
|
+
4. **Pagination**: Use `.skip()` and `.take()` for large result sets
|
|
311
|
+
5. **Transactions**: Group related operations in transactions
|
|
312
|
+
|
|
313
|
+
## Common Issues
|
|
314
|
+
|
|
315
|
+
### Issue: "Cannot find module 'pg'"
|
|
316
|
+
**Solution**: Install pg library: `npm install pg@^8.16.3`
|
|
317
|
+
|
|
318
|
+
### Issue: "Connection refused"
|
|
319
|
+
**Solution**: Ensure PostgreSQL is running on the specified host/port
|
|
320
|
+
|
|
321
|
+
### Issue: "database does not exist"
|
|
322
|
+
**Solution**: Create the database first:
|
|
323
|
+
```sql
|
|
324
|
+
CREATE DATABASE your_database;
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
### Issue: "password authentication failed"
|
|
328
|
+
**Solution**: Check your credentials and pg_hba.conf settings
|
|
329
|
+
|
|
330
|
+
### Issue: "too many clients"
|
|
331
|
+
**Solution**: Reduce `max` pool size or increase PostgreSQL's max_connections
|
|
332
|
+
|
|
333
|
+
## Migration from MySQL/SQLite
|
|
334
|
+
|
|
335
|
+
Key differences when migrating to PostgreSQL:
|
|
336
|
+
|
|
337
|
+
1. **Placeholder Format**:
|
|
338
|
+
- MySQL/SQLite: `?`
|
|
339
|
+
- PostgreSQL: `$1, $2, $3...`
|
|
340
|
+
- MasterRecord handles this automatically with `$$`
|
|
341
|
+
|
|
342
|
+
2. **Auto-increment**:
|
|
343
|
+
- MySQL: `AUTO_INCREMENT`
|
|
344
|
+
- PostgreSQL: `SERIAL` or `BIGSERIAL`
|
|
345
|
+
- MasterRecord uses `.auto()` for both
|
|
346
|
+
|
|
347
|
+
3. **Boolean Type**:
|
|
348
|
+
- SQLite: 0/1
|
|
349
|
+
- PostgreSQL: true/false
|
|
350
|
+
- MasterRecord handles type coercion
|
|
351
|
+
|
|
352
|
+
4. **Date/Time**:
|
|
353
|
+
- Temporal types (`date`/`time`/`datetime`/`timestamp`) are stored as `TEXT`
|
|
354
|
+
on **every** engine (SQLite, MySQL, PostgreSQL) for cross-engine portability
|
|
355
|
+
- Write epoch-millis or ISO-8601 strings; a native PostgreSQL temporal column
|
|
356
|
+
would reject those values at INSERT
|
|
357
|
+
- Set the value in app code or a `beforeSave` hook (not a DB-side default)
|
|
358
|
+
|
|
359
|
+
5. **RETURNING Clause**:
|
|
360
|
+
- PostgreSQL requires `RETURNING id` for INSERT
|
|
361
|
+
- MasterRecord adds this automatically
|
|
362
|
+
|
|
363
|
+
## Testing
|
|
364
|
+
|
|
365
|
+
Run PostgreSQL tests:
|
|
366
|
+
|
|
367
|
+
```bash
|
|
368
|
+
# Unit tests (no database required)
|
|
369
|
+
node test/postgresEngineTest.js
|
|
370
|
+
|
|
371
|
+
# Integration tests (requires PostgreSQL running)
|
|
372
|
+
node test/postgresIntegrationTest.js
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
## Version Compatibility
|
|
376
|
+
|
|
377
|
+
- **MasterRecord**: 1.0+ (ESM-only)
|
|
378
|
+
- **pg (node-postgres)**: 8.17+
|
|
379
|
+
- **PostgreSQL Server**: 9.6+ (tested with 12+, 13+, 14+)
|
|
380
|
+
- **Node.js**: 22.12+ (better-sqlite3@13 requires Node 22+)
|
|
381
|
+
|
|
382
|
+
## Complete Example
|
|
383
|
+
|
|
384
|
+
```javascript
|
|
385
|
+
import context from 'masterrecord/context';
|
|
386
|
+
|
|
387
|
+
async function main() {
|
|
388
|
+
// Initialize
|
|
389
|
+
const db = new context();
|
|
390
|
+
await db.env({
|
|
391
|
+
type: 'postgres',
|
|
392
|
+
host: 'localhost',
|
|
393
|
+
port: 5432,
|
|
394
|
+
database: 'myapp',
|
|
395
|
+
user: 'postgres',
|
|
396
|
+
password: 'password',
|
|
397
|
+
max: 20
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
// Define entity
|
|
401
|
+
const User = db.dbset('User')
|
|
402
|
+
.key('id').auto()
|
|
403
|
+
.field('name').string().notNull()
|
|
404
|
+
.field('email').string().notNull()
|
|
405
|
+
.field('age').integer()
|
|
406
|
+
.create();
|
|
407
|
+
|
|
408
|
+
// Create
|
|
409
|
+
const newUser = db.User.new();
|
|
410
|
+
newUser.name = 'Alice';
|
|
411
|
+
newUser.email = 'alice@example.com';
|
|
412
|
+
newUser.age = 25;
|
|
413
|
+
await db.saveChanges();
|
|
414
|
+
|
|
415
|
+
// Read
|
|
416
|
+
const user = db.User.findById(newUser.id);
|
|
417
|
+
console.log(user.name); // "Alice"
|
|
418
|
+
|
|
419
|
+
// Update
|
|
420
|
+
user.age = 26;
|
|
421
|
+
await db.saveChanges();
|
|
422
|
+
|
|
423
|
+
// Query
|
|
424
|
+
const adults = db.User
|
|
425
|
+
.where(u => u.age >= $$, 18)
|
|
426
|
+
.orderBy('name')
|
|
427
|
+
.all();
|
|
428
|
+
|
|
429
|
+
// Delete
|
|
430
|
+
db.remove(user);
|
|
431
|
+
await db.saveChanges();
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
main();
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
## Support
|
|
438
|
+
|
|
439
|
+
For issues or questions:
|
|
440
|
+
- GitHub: [MasterRecord Issues](https://github.com/yourusername/MasterRecord/issues)
|
|
441
|
+
- Documentation: [docs/](../docs/)
|
|
442
|
+
|
|
443
|
+
## License
|
|
444
|
+
|
|
445
|
+
MIT License - see LICENSE file for details
|