dzql 0.1.3 → 0.1.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.
@@ -0,0 +1,326 @@
1
+ # DZQL Compiler - Quick Start Guide
2
+
3
+ Get up and running with the DZQL Compiler in 5 minutes.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ cd /home/user/dzql/packages/dzql-compiler
9
+ bun install
10
+ ```
11
+
12
+ ## Basic Usage
13
+
14
+ ### 1. Compile Your First Entity
15
+
16
+ ```bash
17
+ # Compile the venues domain (9 entities)
18
+ bun src/cli/index.js /home/user/dzql/packages/venues/database/init_db/009_venues_domain.sql -o compiled/
19
+
20
+ # Output will be in compiled/ directory
21
+ ```
22
+
23
+ ### 2. Examine the Output
24
+
25
+ ```bash
26
+ # View generated SQL for venues
27
+ cat compiled/venues.sql
28
+
29
+ # Check checksums
30
+ cat compiled/checksums.json
31
+ ```
32
+
33
+ ### 3. Run the Tests
34
+
35
+ ```bash
36
+ # All tests should pass
37
+ bun test
38
+ ```
39
+
40
+ ## What You Get
41
+
42
+ For each entity, the compiler generates:
43
+
44
+ ### Permission Functions
45
+ ```sql
46
+ can_create_venues(p_user_id INT, p_record JSONB) → BOOLEAN
47
+ can_update_venues(p_user_id INT, p_record JSONB) → BOOLEAN
48
+ can_delete_venues(p_user_id INT, p_record JSONB) → BOOLEAN
49
+ can_view_venues(p_user_id INT, p_record JSONB) → BOOLEAN
50
+ ```
51
+
52
+ ### CRUD Operations
53
+ ```sql
54
+ get_venues(p_user_id INT, p_id INT) → JSONB
55
+ save_venues(p_user_id INT, p_data JSONB) → JSONB
56
+ delete_venues(p_user_id INT, p_id INT) → JSONB
57
+ lookup_venues(p_user_id INT, p_filter TEXT) → JSONB
58
+ search_venues(p_user_id INT, p_filters JSONB, p_search TEXT, ...) → JSONB
59
+ ```
60
+
61
+ > **Note:** `p_user_id` is always the first parameter in all functions. See [CODING_STANDARDS.md](./CODING_STANDARDS.md).
62
+
63
+ ## Example: Compile a Simple Entity
64
+
65
+ Create `examples/todos.sql`:
66
+
67
+ ```sql
68
+ select dzql.register_entity(
69
+ 'todos',
70
+ 'title',
71
+ array['title', 'description'],
72
+ '{}', -- no FK includes
73
+ false, -- no soft delete
74
+ '{}', -- no temporal fields
75
+ '{}', -- no notifications
76
+ jsonb_build_object(
77
+ 'view', array[]::text[], -- public
78
+ 'create', array[]::text[], -- public
79
+ 'update', array['@owner_id'], -- owner only
80
+ 'delete', array['@owner_id'] -- owner only
81
+ )
82
+ );
83
+ ```
84
+
85
+ Compile it:
86
+
87
+ ```bash
88
+ bun src/cli/index.js examples/todos.sql -o compiled/
89
+ ```
90
+
91
+ Result: `compiled/todos.sql` with 5 operations + 4 permission checks.
92
+
93
+ ## Using Compiled Functions
94
+
95
+ Once deployed to PostgreSQL:
96
+
97
+ ```sql
98
+ -- Get a todo (p_user_id first, then p_id)
99
+ SELECT get_todos(42, 1); -- user_id=42, id=1
100
+
101
+ -- Create a todo (p_user_id first, then p_data)
102
+ SELECT save_todos(42, '{"title": "Learn DZQL", "owner_id": 42}'::jsonb);
103
+
104
+ -- Search todos (p_user_id first)
105
+ SELECT search_todos(
106
+ 42, -- user_id
107
+ '{}', -- filters
108
+ 'DZQL', -- search text
109
+ '{"field": "title", "order": "asc"}', -- sort
110
+ 1, -- page
111
+ 25 -- limit
112
+ );
113
+
114
+ -- Delete a todo (p_user_id first, then p_id)
115
+ SELECT delete_todos(42, 1);
116
+ ```
117
+
118
+ ## Development Workflow
119
+
120
+ ### 1. Define Entity
121
+
122
+ Edit `entities/my_entity.sql`:
123
+
124
+ ```sql
125
+ select dzql.register_entity(
126
+ 'my_entity',
127
+ 'name',
128
+ array['name'],
129
+ '{}',
130
+ false
131
+ );
132
+ ```
133
+
134
+ ### 2. Compile
135
+
136
+ ```bash
137
+ bun src/cli/index.js entities/my_entity.sql -o compiled/
138
+ ```
139
+
140
+ ### 3. Deploy
141
+
142
+ ```bash
143
+ psql -U dzql -d dzql < compiled/my_entity.sql
144
+ ```
145
+
146
+ ### 4. Use
147
+
148
+ ```sql
149
+ SELECT save_my_entity(1, '{"name": "Test"}'::jsonb); -- user_id first, then data
150
+ ```
151
+
152
+ ## Programmatic API
153
+
154
+ ```javascript
155
+ import { DZQLCompiler } from './src/compiler.js';
156
+
157
+ const compiler = new DZQLCompiler();
158
+
159
+ // Compile from object
160
+ const result = compiler.compile({
161
+ tableName: 'posts',
162
+ labelField: 'title',
163
+ searchableFields: ['title', 'body'],
164
+ permissionPaths: {
165
+ view: [],
166
+ update: ['@author_id']
167
+ }
168
+ });
169
+
170
+ console.log(result.sql);
171
+ console.log(result.checksum);
172
+
173
+ // Compile from SQL
174
+ import { readFileSync } from 'fs';
175
+
176
+ const sql = readFileSync('entities/posts.sql', 'utf-8');
177
+ const results = compiler.compileFromSQL(sql);
178
+
179
+ for (const entity of results.results) {
180
+ console.log(`Compiled ${entity.tableName}: ${entity.checksum}`);
181
+ }
182
+ ```
183
+
184
+ ## Verifying Compilation
185
+
186
+ ### Check Checksums
187
+
188
+ ```javascript
189
+ import { readFileSync } from 'fs';
190
+
191
+ const checksums = JSON.parse(readFileSync('compiled/checksums.json', 'utf-8'));
192
+
193
+ console.log(checksums.venues);
194
+ // {
195
+ // checksum: "9c116484...",
196
+ // generatedAt: "2025-11-16T01:38:54.321Z",
197
+ // compilationTime: 12
198
+ // }
199
+ ```
200
+
201
+ ### Test Functions
202
+
203
+ ```sql
204
+ -- Test permission check (p_user_id first)
205
+ SELECT can_update_venues(42, '{"org_id": 1}'::jsonb);
206
+
207
+ -- Test GET with FK expansion (p_user_id first, then p_id)
208
+ SELECT get_venues(42, 1);
209
+ -- Returns: { id: 1, name: "...", org: { id: 1, name: "..." }, sites: [...] }
210
+
211
+ -- Test SEARCH (p_user_id first)
212
+ SELECT search_venues(42, '{}', 'garden', null, 1, 10);
213
+ -- Returns: { data: [...], total: 5, page: 1, limit: 10 }
214
+ ```
215
+
216
+ ## Common Patterns
217
+
218
+ ### Public Read, Owner Write
219
+
220
+ ```sql
221
+ select dzql.register_entity(
222
+ 'blog_posts',
223
+ 'title',
224
+ array['title', 'body'],
225
+ '{}',
226
+ false,
227
+ '{}',
228
+ '{}',
229
+ jsonb_build_object(
230
+ 'view', array[]::text[], -- anyone can read
231
+ 'create', array[]::text[], -- anyone can create
232
+ 'update', array['@author_id'], -- only author can update
233
+ 'delete', array['@author_id'] -- only author can delete
234
+ )
235
+ );
236
+ ```
237
+
238
+ ### Organization-Scoped
239
+
240
+ ```sql
241
+ select dzql.register_entity(
242
+ 'projects',
243
+ 'name',
244
+ array['name', 'description'],
245
+ '{"org": "organisations"}',
246
+ false,
247
+ '{}',
248
+ '{}',
249
+ jsonb_build_object(
250
+ 'view', array['@org_id->members[org_id=$]{active}.user_id'],
251
+ 'update', array['@org_id->members[org_id=$,role=admin]{active}.user_id'],
252
+ 'delete', array['@org_id->members[org_id=$,role=admin]{active}.user_id'],
253
+ 'create', array['@org_id->members[org_id=$]{active}.user_id']
254
+ )
255
+ );
256
+ ```
257
+
258
+ ### Temporal Data
259
+
260
+ ```sql
261
+ select dzql.register_entity(
262
+ 'memberships',
263
+ 'user_id',
264
+ array['user_id', 'org_id'],
265
+ '{"user": "users", "org": "organisations"}',
266
+ false,
267
+ '{"valid_from": "valid_from", "valid_to": "valid_to"}', -- temporal!
268
+ '{}',
269
+ '{}'
270
+ );
271
+ ```
272
+
273
+ ## Debugging
274
+
275
+ ### View Generated SQL
276
+
277
+ ```bash
278
+ # Pretty print generated SQL
279
+ cat compiled/venues.sql | less
280
+
281
+ # Search for specific function
282
+ grep -A 20 "CREATE OR REPLACE FUNCTION get_venues" compiled/venues.sql
283
+ ```
284
+
285
+ ### Check Compilation Errors
286
+
287
+ ```bash
288
+ # Compile with verbose output
289
+ DZQL_COMPILER_VERBOSE=true bun src/cli/index.js entities/my_entity.sql -o compiled/
290
+ ```
291
+
292
+ ### Test in PostgreSQL
293
+
294
+ ```sql
295
+ -- Enable query logging
296
+ SET log_statement = 'all';
297
+
298
+ -- Test function (p_user_id first)
299
+ SELECT get_venues(42, 1);
300
+
301
+ -- View execution plan
302
+ EXPLAIN ANALYZE SELECT get_venues(42, 1);
303
+ ```
304
+
305
+ ## Next Steps
306
+
307
+ 1. **Compile existing entities** - Try compiling your current DZQL entities
308
+ 2. **Review generated SQL** - Understand what the compiler produces
309
+ 3. **Test in staging** - Deploy to a test database and verify behavior
310
+ 4. **Benchmark performance** - Compare runtime vs compiled versions
311
+ 5. **Report issues** - Let us know what works and what doesn't!
312
+
313
+ ## Need Help?
314
+
315
+ - **README.md** - Complete documentation
316
+ - **SUMMARY.md** - What was built and how
317
+ - **tests/compiler.test.js** - Usage examples
318
+ - **examples/compiled/** - Real compiled output
319
+
320
+ ## Resources
321
+
322
+ - Vision document: `/home/user/dzql/vision.md`
323
+ - Current DZQL: `/home/user/dzql/packages/dzql/`
324
+ - Example apps: `/home/user/dzql/packages/venues/`
325
+
326
+ Happy compiling! 🚀
@@ -0,0 +1,266 @@
1
+ # Compiler Development Session Summary
2
+
3
+ ## Latest Session: Coding Standards Compliance (2025-11-16)
4
+
5
+ This session enforced DZQL coding standards across all generated functions to ensure consistency, security, and proper WebSocket API protection.
6
+
7
+ ### ✅ Coding Standards Fixes
8
+
9
+ **What Changed**: Fixed the compiler to generate code compliant with DZQL conventions:
10
+
11
+ 1. **Parameter Ordering** - `p_user_id INT` now FIRST in all functions
12
+ - ✅ `get_*(p_user_id INT, p_id INT, ...)`
13
+ - ✅ `save_*(p_user_id INT, p_data JSONB)`
14
+ - ✅ `delete_*(p_user_id INT, p_id INT)`
15
+ - ✅ `lookup_*(p_user_id INT, p_filter TEXT, ...)`
16
+ - ✅ `search_*(p_user_id INT, p_filters JSONB, ...)`
17
+
18
+ 2. **Helper Function Prefixes** - Internal functions now use `_` prefix
19
+ - ✅ `_graph_*_on_create(p_user_id INT, p_record JSONB)`
20
+ - ✅ `_resolve_notification_paths_*(p_user_id INT, p_record JSONB)`
21
+ - Prevents direct websocket client access to internal functions
22
+
23
+ 3. **Standard Permission Functions** - All 4 always generated
24
+ - ✅ `can_view_*`, `can_create_*`, `can_update_*`, `can_delete_*`
25
+ - Even for public access (returns `true`)
26
+
27
+ 4. **Clean Function Names** - Fixed malformed names with embedded comments
28
+ - ❌ Before: `can_-- Anyone can create...'update_organisations`
29
+ - ✅ After: `can_update_organisations`
30
+
31
+ **Files Modified**:
32
+ - `src/codegen/permission-codegen.js` - Clean operation names, generate all 4 functions
33
+ - `src/codegen/operation-codegen.js` - Fix parameter ordering, update helper calls
34
+ - `src/codegen/notification-codegen.js` - Add underscore prefix, p_user_id first
35
+ - `src/codegen/graph-rules-codegen.js` - Add underscore prefix, p_user_id first
36
+ - `tests/sql-validation.test.js` - Update expectations to match standards
37
+
38
+ **Documentation Added**:
39
+ - `CODING_STANDARDS.md` - Complete coding standards reference
40
+ - Updated `README.md` with correct function signatures
41
+ - Updated `QUICKSTART.md` with correct examples
42
+
43
+ **Test Results**: ✅ All 55 tests passing
44
+
45
+ ---
46
+
47
+ ## Previous Session: Graph Rules & Advanced Filters
48
+
49
+ This session continued work on the DZQL Compiler from a previous session where the core compilation infrastructure was built.
50
+
51
+ ## Completed Features
52
+
53
+ ### 1. ✅ Graph Rules Compilation
54
+
55
+ **What**: Transforms declarative graph rules into executable PostgreSQL functions
56
+
57
+ **Implementation**:
58
+ - Created `GraphRulesCodegen` class
59
+ - Supports all action types: `create`, `update`, `delete`, `validate`, `execute`
60
+ - Resolves special variables:
61
+ - `@user_id` → `p_user_id`
62
+ - `@today` → `CURRENT_DATE`
63
+ - `@now` → `NOW()`
64
+ - `@field` → `(p_record->>'field')`
65
+ - Generates trigger-based functions: `graph_{table}_{on_create|on_update|on_delete}`
66
+ - Integrated into SAVE and DELETE operations
67
+
68
+ **Example Generated Code** (now with correct coding standards):
69
+ ```sql
70
+ CREATE OR REPLACE FUNCTION _graph_organisations_on_create(
71
+ p_user_id INT,
72
+ p_record JSONB
73
+ ) RETURNS VOID AS $$
74
+ BEGIN
75
+ -- Creator becomes owner
76
+ INSERT INTO acts_for (user_id, org_id, valid_from)
77
+ VALUES (p_user_id, (p_record->>'id'), CURRENT_DATE);
78
+ END;
79
+ $$ LANGUAGE plpgsql SECURITY DEFINER;
80
+ ```
81
+
82
+ > Note: Helper functions now use `_` prefix and have `p_user_id` first
83
+
84
+ **Files Changed**:
85
+ - `src/codegen/graph-rules-codegen.js` (new)
86
+ - `src/compiler.js` (integrated)
87
+ - `src/codegen/operation-codegen.js` (calls graph functions)
88
+
89
+ ### 2. ✅ Advanced SEARCH Filter Operators
90
+
91
+ **What**: Comprehensive JSONB-based filtering with multiple operators
92
+
93
+ **Operators Implemented**:
94
+ - **Comparison**: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`
95
+ - **Array Membership**: `in`
96
+ - **Pattern Matching**: `like`, `ilike`
97
+
98
+ **Features**:
99
+ - Dynamic WHERE clause builder
100
+ - Type-safe value handling
101
+ - SQL injection protection via `format()`
102
+ - Combines with text search and temporal filters
103
+ - Multiple operators per field
104
+ - Multiple fields per query
105
+
106
+ **Example Usage**:
107
+ ```json
108
+ {
109
+ "age": {"gte": 18, "lte": 65},
110
+ "status": {"in": ["active", "pending"]},
111
+ "email": {"ilike": "%@company.com"}
112
+ }
113
+ ```
114
+
115
+ **Generated SQL**:
116
+ ```sql
117
+ WHERE TRUE
118
+ AND age >= '18'
119
+ AND age <= '65'
120
+ AND status = ANY(ARRAY['active', 'pending']::TEXT[])
121
+ AND email ILIKE '%@company.com'
122
+ ```
123
+
124
+ **Files Changed**:
125
+ - `src/codegen/operation-codegen.js` (enhanced SEARCH function)
126
+ - `docs/ADVANCED_FILTERS.md` (comprehensive documentation)
127
+
128
+ ### 3. ✅ Comprehensive Test Suite
129
+
130
+ **SQL Validation Tests** (42 tests):
131
+ - Function signature validation
132
+ - Permission logic verification
133
+ - CRUD operation structure
134
+ - Graph rules generation
135
+ - Filter operator inclusion
136
+ - SQL syntax validation
137
+ - Metadata verification
138
+
139
+ **Integration Tests** (prepared):
140
+ - Full workflow testing
141
+ - Real database operations
142
+ - Permission enforcement
143
+ - Advanced filter testing
144
+ - Graph rules execution
145
+
146
+ **Test Organization**:
147
+ ```bash
148
+ bun test # Unit + validation (55 tests)
149
+ bun test:integration # Integration tests (requires PostgreSQL)
150
+ bun test:all # Everything
151
+ ```
152
+
153
+ **Files Added**:
154
+ - `tests/sql-validation.test.js` (42 tests)
155
+ - `tests/integration.test.skip.js` (prepared for PostgreSQL)
156
+ - `tests/integration-README.md` (setup instructions)
157
+
158
+ ## Test Results
159
+
160
+ ✅ **55 tests passing** (13 compiler + 42 validation)
161
+ - All core compiler functionality verified
162
+ - All generated SQL validated
163
+ - No regressions introduced
164
+
165
+ ## Commits Made
166
+
167
+ 1. **feat: Complete graph rules compilation** (95d4257)
168
+ - Full graph rules compilation implementation
169
+ - Integration with SAVE/DELETE operations
170
+ - All action types supported
171
+
172
+ 2. **feat: Add advanced SEARCH filter operators** (dc8b0fe)
173
+ - 9 filter operators implemented
174
+ - Dynamic WHERE clause building
175
+ - Comprehensive documentation
176
+
177
+ 3. **test: Add comprehensive test suite for compiled SQL** (1d14209)
178
+ - 42 SQL validation tests
179
+ - Integration test framework
180
+ - Test documentation
181
+
182
+ ## Code Statistics
183
+
184
+ **Lines Added**: ~1,500 lines across:
185
+ - Graph rules code generation
186
+ - Advanced filter implementation
187
+ - Test suites
188
+ - Documentation
189
+
190
+ **Files Created**: 6
191
+ - `src/codegen/graph-rules-codegen.js`
192
+ - `docs/ADVANCED_FILTERS.md`
193
+ - `tests/sql-validation.test.js`
194
+ - `tests/integration.test.skip.js`
195
+ - `tests/integration-README.md`
196
+ - `docs/SESSION_SUMMARY.md`
197
+
198
+ **Files Modified**: 4
199
+ - `src/compiler.js`
200
+ - `src/codegen/operation-codegen.js`
201
+ - `package.json`
202
+ - (various generated files)
203
+
204
+ ## Current Compiler Capabilities
205
+
206
+ The DZQL Compiler now supports:
207
+
208
+ ### ✅ Entity Definition Parsing
209
+ - Complete DZQL entity syntax
210
+ - Nested JSONB structures
211
+ - Array parameters with depth tracking
212
+
213
+ ### ✅ Permission Compilation
214
+ - Direct field checks
215
+ - Graph traversal with filters
216
+ - Temporal filtering (`{active}`)
217
+ - All CRUD operations (view, create, update, delete)
218
+
219
+ ### ✅ Notification Path Compilation
220
+ - User resolution via graph traversal
221
+ - Temporal filtering
222
+ - Multiple notification paths
223
+
224
+ ### ✅ Graph Rules Compilation
225
+ - on_create, on_update, on_delete triggers
226
+ - All action types
227
+ - Special variable resolution
228
+ - Automatic integration with operations
229
+
230
+ ### ✅ CRUD Operations
231
+ - GET with FK expansion
232
+ - SAVE with upsert logic
233
+ - DELETE (soft or hard)
234
+ - LOOKUP with filtering
235
+ - SEARCH with advanced filters
236
+
237
+ ### ✅ Advanced Features
238
+ - 9 filter operators in SEARCH
239
+ - Dynamic WHERE clause building
240
+ - Reproducible builds (SHA-256 checksums)
241
+ - Git-trackable output
242
+ - Comprehensive error handling
243
+
244
+ ## What's Next?
245
+
246
+ Potential future enhancements:
247
+ - [ ] Performance benchmarking vs runtime DZQL
248
+ - [ ] Migration generator (schema changes)
249
+ - [ ] Index recommendation based on paths
250
+ - [ ] Query plan analysis
251
+ - [ ] Incremental compilation
252
+ - [ ] Type inference for better error messages
253
+ - [ ] GraphQL/REST API generation from entities
254
+
255
+ ## Branch Status
256
+
257
+ Branch: `claude/new-features-planning-015GH92pzBxTkA1uWjnjJqbZ`
258
+
259
+ All changes committed and pushed. Ready for review or PR creation.
260
+
261
+ ---
262
+
263
+ **Session Duration**: Continued from previous session
264
+ **Total Tests**: 55 passing
265
+ **Code Coverage**: All major compilation paths tested
266
+ **Documentation**: Comprehensive docs for all features