masterrecord 1.3.2 → 1.5.5

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.
@@ -1,441 +0,0 @@
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
- - 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.
125
- - `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.
126
-
127
- Identifiers are validated (letters, digits, underscore; not starting with a digit) — an invalid schema name throws at connect rather than being interpolated into SQL.
128
-
129
- > 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.)
130
-
131
- ### Transactions
132
-
133
- ```javascript
134
- import PostgresSyncConnect from 'masterrecord/postgresSyncConnect';
135
-
136
- const connection = new PostgresSyncConnect();
137
- await connection.connect(config);
138
-
139
- // Execute in transaction
140
- const result = await connection.transaction(async (client) => {
141
- // Insert
142
- const userResult = await client.query(
143
- 'INSERT INTO User (name, email) VALUES ($1, $2) RETURNING id',
144
- ['Bob', 'bob@example.com']
145
- );
146
-
147
- // Update
148
- await client.query(
149
- 'UPDATE User SET verified = $1 WHERE id = $2',
150
- [true, userResult.rows[0].id]
151
- );
152
-
153
- return userResult.rows[0].id;
154
- });
155
- ```
156
-
157
- ### IN Clauses with .any()
158
-
159
- ```javascript
160
- // Array parameter
161
- const users = db.User
162
- .where(u => u.id.any($$), [1, 2, 3, 4, 5])
163
- .all();
164
-
165
- // Comma-separated string (auto-splits)
166
- const ids = '10,20,30,40';
167
- const users = db.User
168
- .where(u => u.id.any($$), ids)
169
- .all();
170
- ```
171
-
172
- ### Array Filtering with .includes()
173
-
174
- ```javascript
175
- const tags = ['javascript', 'node', 'postgres'];
176
- const posts = db.Post
177
- .where(p => $$.includes(p.category), tags)
178
- .all();
179
- ```
180
-
181
- ### Find by Primary Key
182
-
183
- ```javascript
184
- // Convenience method - auto-detects primary key
185
- const user = db.User.findById(123);
186
-
187
- // Equivalent to:
188
- const user = db.User
189
- .where(u => u.id == $$, 123)
190
- .single();
191
- ```
192
-
193
- ### Pagination
194
-
195
- ```javascript
196
- // Skip 20, take 10
197
- const users = db.User
198
- .orderBy('created_at')
199
- .skip(20)
200
- .take(10)
201
- .all();
202
-
203
- // PostgreSQL generates: LIMIT 10 OFFSET 20
204
- ```
205
-
206
- ### Joins
207
-
208
- ```javascript
209
- const userPosts = db.User
210
- .join('Post', (u, p) => u.id == p.user_id)
211
- .where(u => u.id == $$, 123)
212
- .all();
213
- ```
214
-
215
- ### NULL Handling
216
-
217
- ```javascript
218
- // Find users with no email
219
- const users = db.User
220
- .where(u => u.email == null)
221
- .all();
222
-
223
- // Find users with email OR age is null
224
- const users = db.User
225
- .where(u => u.email != null)
226
- .and(u => u.age == null)
227
- .all();
228
- ```
229
-
230
- ## Connection Management
231
-
232
- ### Health Check
233
-
234
- ```javascript
235
- const health = await connection.healthCheck();
236
-
237
- if (health.healthy) {
238
- console.log('Server time:', health.serverTime);
239
- console.log('PostgreSQL version:', health.version);
240
- console.log('Pool size:', health.poolSize);
241
- console.log('Idle connections:', health.idleCount);
242
- }
243
- ```
244
-
245
- ### Connection Info
246
-
247
- ```javascript
248
- const info = connection.getConnectionInfo();
249
- console.log(`Connected to ${info.database} at ${info.host}:${info.port}`);
250
- console.log(`Max connections: ${info.maxConnections}`);
251
- ```
252
-
253
- ### Close Connection
254
-
255
- ```javascript
256
- await connection.close();
257
- ```
258
-
259
- ## Placeholder Syntax Reference
260
-
261
- MasterRecord uses double dollar signs (`$$`) for placeholders that get converted to PostgreSQL format:
262
-
263
- | MasterRecord Syntax | PostgreSQL SQL | Parameters |
264
- |---------------------|----------------|------------|
265
- | `.where(u => u.id == $$, 5)` | `WHERE id = $1` | `[5]` |
266
- | `.where(u => u.age > $$ && u.status == $$, 25, 'active')` | `WHERE age > $1 AND status = $2` | `[25, 'active']` |
267
- | `.where(u => u.id.any($$), [1,2,3])` | `WHERE id IN ($1, $2, $3)` | `[1, 2, 3]` |
268
-
269
- **Single `$` for OR conditions:**
270
- ```javascript
271
- .where(u => u.status == $ || u.status == null, 'active')
272
- // Generates: WHERE status = $1 OR status IS NULL
273
- ```
274
-
275
- ## Field Transformers
276
-
277
- Custom serialization for complex types:
278
-
279
- ```javascript
280
- const Post = db.dbset('Post')
281
- .key('id').auto()
282
- .field('title').string()
283
- .field('tags').string().transform({
284
- toDatabase: (value) => {
285
- // Array → JSON string
286
- return Array.isArray(value) ? JSON.stringify(value) : value;
287
- },
288
- fromDatabase: (value) => {
289
- // JSON string → Array
290
- return typeof value === 'string' ? JSON.parse(value) : value;
291
- }
292
- })
293
- .create();
294
-
295
- // Use as array in code
296
- const post = db.Post.new();
297
- post.tags = ['javascript', 'postgres', 'node'];
298
- await db.saveChanges();
299
-
300
- // Stored as: '["javascript","postgres","node"]'
301
- // Retrieved as: ['javascript', 'postgres', 'node']
302
- ```
303
-
304
- ## Performance Tips
305
-
306
- 1. **Use Connection Pooling**: Adjust `max` pool size based on your needs
307
- 2. **Parameterized Queries**: Always use `$$` placeholders (automatic SQL injection protection)
308
- 3. **Indexes**: Create indexes on frequently queried columns
309
- 4. **Pagination**: Use `.skip()` and `.take()` for large result sets
310
- 5. **Transactions**: Group related operations in transactions
311
-
312
- ## Common Issues
313
-
314
- ### Issue: "Cannot find module 'pg'"
315
- **Solution**: Install pg library: `npm install pg@^8.16.3`
316
-
317
- ### Issue: "Connection refused"
318
- **Solution**: Ensure PostgreSQL is running on the specified host/port
319
-
320
- ### Issue: "database does not exist"
321
- **Solution**: Create the database first:
322
- ```sql
323
- CREATE DATABASE your_database;
324
- ```
325
-
326
- ### Issue: "password authentication failed"
327
- **Solution**: Check your credentials and pg_hba.conf settings
328
-
329
- ### Issue: "too many clients"
330
- **Solution**: Reduce `max` pool size or increase PostgreSQL's max_connections
331
-
332
- ## Migration from MySQL/SQLite
333
-
334
- Key differences when migrating to PostgreSQL:
335
-
336
- 1. **Placeholder Format**:
337
- - MySQL/SQLite: `?`
338
- - PostgreSQL: `$1, $2, $3...`
339
- - MasterRecord handles this automatically with `$$`
340
-
341
- 2. **Auto-increment**:
342
- - MySQL: `AUTO_INCREMENT`
343
- - PostgreSQL: `SERIAL` or `BIGSERIAL`
344
- - MasterRecord uses `.auto()` for both
345
-
346
- 3. **Boolean Type**:
347
- - SQLite: 0/1
348
- - PostgreSQL: true/false
349
- - MasterRecord handles type coercion
350
-
351
- 4. **Date/Time**:
352
- - Both use Date objects in JavaScript
353
- - PostgreSQL has more precise timestamp handling
354
-
355
- 5. **RETURNING Clause**:
356
- - PostgreSQL requires `RETURNING id` for INSERT
357
- - MasterRecord adds this automatically
358
-
359
- ## Testing
360
-
361
- Run PostgreSQL tests:
362
-
363
- ```bash
364
- # Unit tests (no database required)
365
- node test/postgresEngineTest.js
366
-
367
- # Integration tests (requires PostgreSQL running)
368
- node test/postgresIntegrationTest.js
369
- ```
370
-
371
- ## Version Compatibility
372
-
373
- - **MasterRecord**: 1.0+ (ESM-only)
374
- - **pg (node-postgres)**: 8.17+
375
- - **PostgreSQL Server**: 9.6+ (tested with 12+, 13+, 14+)
376
- - **Node.js**: 20+
377
-
378
- ## Complete Example
379
-
380
- ```javascript
381
- import context from 'masterrecord/context';
382
-
383
- async function main() {
384
- // Initialize
385
- const db = new context();
386
- await db.env({
387
- type: 'postgres',
388
- host: 'localhost',
389
- port: 5432,
390
- database: 'myapp',
391
- user: 'postgres',
392
- password: 'password',
393
- max: 20
394
- });
395
-
396
- // Define entity
397
- const User = db.dbset('User')
398
- .key('id').auto()
399
- .field('name').string().notNull()
400
- .field('email').string().notNull()
401
- .field('age').integer()
402
- .create();
403
-
404
- // Create
405
- const newUser = db.User.new();
406
- newUser.name = 'Alice';
407
- newUser.email = 'alice@example.com';
408
- newUser.age = 25;
409
- await db.saveChanges();
410
-
411
- // Read
412
- const user = db.User.findById(newUser.id);
413
- console.log(user.name); // "Alice"
414
-
415
- // Update
416
- user.age = 26;
417
- await db.saveChanges();
418
-
419
- // Query
420
- const adults = db.User
421
- .where(u => u.age >= $$, 18)
422
- .orderBy('name')
423
- .all();
424
-
425
- // Delete
426
- db.remove(user);
427
- await db.saveChanges();
428
- }
429
-
430
- main();
431
- ```
432
-
433
- ## Support
434
-
435
- For issues or questions:
436
- - GitHub: [MasterRecord Issues](https://github.com/yourusername/MasterRecord/issues)
437
- - Documentation: [docs/](../docs/)
438
-
439
- ## License
440
-
441
- MIT License - see LICENSE file for details