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,174 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * DZQL Compiler CLI
4
+ * Command-line interface for compiling entity definitions
5
+ */
6
+
7
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
8
+ import { resolve, dirname, basename } from 'path';
9
+ import { DZQLCompiler } from '../compiler.js';
10
+
11
+ const USAGE = `
12
+ DZQL Compiler - Transform entity definitions into PostgreSQL functions
13
+
14
+ Usage:
15
+ dzql-compile <input-file> [options]
16
+
17
+ Options:
18
+ -o, --output <dir> Output directory (default: ./compiled)
19
+ -w, --watch Watch for changes and recompile
20
+ -v, --verbose Verbose output
21
+ -h, --help Show this help message
22
+
23
+ Examples:
24
+ dzql-compile entities/venues.sql
25
+ dzql-compile database/init_db/009_venues_domain.sql -o compiled/
26
+ dzql-compile entities/*.sql -o dist/compiled/
27
+
28
+ Environment Variables:
29
+ DZQL_COMPILER_VERBOSE Enable verbose output
30
+ `;
31
+
32
+ class CLI {
33
+ constructor() {
34
+ this.args = process.argv.slice(2);
35
+ this.options = {
36
+ output: './compiled',
37
+ watch: false,
38
+ verbose: process.env.DZQL_COMPILER_VERBOSE === 'true'
39
+ };
40
+ this.compiler = new DZQLCompiler();
41
+ }
42
+
43
+ run() {
44
+ this.parseArgs();
45
+
46
+ if (this.options.help || this.args.length === 0) {
47
+ console.log(USAGE);
48
+ process.exit(0);
49
+ }
50
+
51
+ const inputFile = this.args[0];
52
+
53
+ if (!existsSync(inputFile)) {
54
+ console.error(`Error: File not found: ${inputFile}`);
55
+ process.exit(1);
56
+ }
57
+
58
+ this.compileFile(inputFile);
59
+
60
+ if (this.options.watch) {
61
+ this.watchFile(inputFile);
62
+ }
63
+ }
64
+
65
+ parseArgs() {
66
+ for (let i = 0; i < this.args.length; i++) {
67
+ const arg = this.args[i];
68
+
69
+ switch (arg) {
70
+ case '-o':
71
+ case '--output':
72
+ this.options.output = this.args[++i];
73
+ break;
74
+
75
+ case '-w':
76
+ case '--watch':
77
+ this.options.watch = true;
78
+ break;
79
+
80
+ case '-v':
81
+ case '--verbose':
82
+ this.options.verbose = true;
83
+ break;
84
+
85
+ case '-h':
86
+ case '--help':
87
+ this.options.help = true;
88
+ break;
89
+ }
90
+ }
91
+ }
92
+
93
+ compileFile(inputFile) {
94
+ try {
95
+ console.log(`\n🔨 Compiling: ${inputFile}`);
96
+
97
+ // Read input file
98
+ const sqlContent = readFileSync(inputFile, 'utf-8');
99
+
100
+ // Compile
101
+ const result = this.compiler.compileFromSQL(sqlContent);
102
+
103
+ // Display results
104
+ console.log(`\n📊 Compilation Summary:`);
105
+ console.log(` Total entities: ${result.summary.total}`);
106
+ console.log(` Successful: ${result.summary.successful}`);
107
+ console.log(` Failed: ${result.summary.failed}`);
108
+
109
+ if (result.errors.length > 0) {
110
+ console.log(`\n❌ Errors:`);
111
+ for (const error of result.errors) {
112
+ console.log(` - ${error.entity}: ${error.error}`);
113
+ }
114
+ }
115
+
116
+ // Write output files
117
+ if (result.results.length > 0) {
118
+ this.writeOutputFiles(result.results);
119
+ }
120
+
121
+ console.log(`\n✅ Compilation complete!\n`);
122
+ } catch (error) {
123
+ console.error(`\n❌ Compilation failed:`, error.message);
124
+ if (this.options.verbose) {
125
+ console.error(error.stack);
126
+ }
127
+ process.exit(1);
128
+ }
129
+ }
130
+
131
+ writeOutputFiles(results) {
132
+ // Ensure output directory exists
133
+ if (!existsSync(this.options.output)) {
134
+ mkdirSync(this.options.output, { recursive: true });
135
+ }
136
+
137
+ console.log(`\n📝 Writing compiled files to: ${this.options.output}`);
138
+
139
+ const checksums = {};
140
+
141
+ for (const result of results) {
142
+ const outputFile = resolve(this.options.output, `${result.tableName}.sql`);
143
+
144
+ // Write SQL file
145
+ writeFileSync(outputFile, result.sql, 'utf-8');
146
+
147
+ // Store checksum
148
+ checksums[result.tableName] = {
149
+ checksum: result.checksum,
150
+ generatedAt: result.generatedAt,
151
+ compilationTime: result.compilationTime
152
+ };
153
+
154
+ console.log(` ✓ ${result.tableName}.sql (${result.checksum.substring(0, 8)}...)`);
155
+ }
156
+
157
+ // Write checksums file
158
+ const checksumsFile = resolve(this.options.output, 'checksums.json');
159
+ writeFileSync(checksumsFile, JSON.stringify(checksums, null, 2), 'utf-8');
160
+
161
+ console.log(` ✓ checksums.json`);
162
+ }
163
+
164
+ watchFile(inputFile) {
165
+ console.log(`\n👀 Watching for changes...`);
166
+
167
+ // TODO: Implement file watching
168
+ console.log(` (Watch mode not yet implemented)`);
169
+ }
170
+ }
171
+
172
+ // Run CLI
173
+ const cli = new CLI();
174
+ cli.run();
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Graph Rules Code Generator
3
+ * Generates PostgreSQL functions for graph rule execution
4
+ */
5
+
6
+ export class GraphRulesCodegen {
7
+ constructor(tableName, graphRules) {
8
+ this.tableName = tableName;
9
+ this.graphRules = graphRules;
10
+ }
11
+
12
+ /**
13
+ * Generate all graph rule functions
14
+ * @returns {string} SQL for graph rule functions
15
+ */
16
+ generate() {
17
+ if (!this.graphRules || Object.keys(this.graphRules).length === 0) {
18
+ return ''; // No functions if no rules
19
+ }
20
+
21
+ const functions = [];
22
+
23
+ // Generate function for each trigger (on_create, on_update, on_delete)
24
+ for (const [trigger, rules] of Object.entries(this.graphRules)) {
25
+ const functionSQL = this._generateTriggerFunction(trigger, rules);
26
+ if (functionSQL) {
27
+ functions.push(functionSQL);
28
+ }
29
+ }
30
+
31
+ return functions.join('\n\n');
32
+ }
33
+
34
+ /**
35
+ * Generate function for a specific trigger
36
+ * @private
37
+ */
38
+ _generateTriggerFunction(trigger, rules) {
39
+ const operation = trigger.replace('on_', ''); // on_create -> create
40
+ const functionName = `_graph_${this.tableName}_${trigger}`;
41
+
42
+ const actionBlocks = [];
43
+
44
+ // Process each rule
45
+ for (const [ruleName, ruleConfig] of Object.entries(rules)) {
46
+ const description = ruleConfig.description || ruleName;
47
+ const actions = Array.isArray(ruleConfig.actions)
48
+ ? ruleConfig.actions
49
+ : (ruleConfig.actions ? [ruleConfig.actions] : []);
50
+
51
+ for (const action of actions) {
52
+ const actionSQL = this._generateAction(action, ruleName, description);
53
+ if (actionSQL) {
54
+ actionBlocks.push(actionSQL);
55
+ }
56
+ }
57
+ }
58
+
59
+ if (actionBlocks.length === 0) {
60
+ return null; // No actions, no function
61
+ }
62
+
63
+ // Determine parameters based on operation - p_user_id ALWAYS FIRST
64
+ const params = operation === 'delete'
65
+ ? `p_user_id INT,\n p_old_record JSONB`
66
+ : operation === 'update'
67
+ ? `p_user_id INT,\n p_old_record JSONB,\n p_new_record JSONB`
68
+ : `p_user_id INT,\n p_record JSONB`;
69
+
70
+ return `-- Graph rules: ${trigger} on ${this.tableName}
71
+ CREATE OR REPLACE FUNCTION ${functionName}(
72
+ ${params}
73
+ ) RETURNS VOID AS $$
74
+ BEGIN
75
+ ${actionBlocks.join('\n\n')}
76
+ END;
77
+ $$ LANGUAGE plpgsql SECURITY DEFINER;`;
78
+ }
79
+
80
+ /**
81
+ * Generate SQL for a single action
82
+ * @private
83
+ */
84
+ _generateAction(action, ruleName, description) {
85
+ const comment = ` -- ${description}`;
86
+
87
+ switch (action.type) {
88
+ case 'create':
89
+ return this._generateCreateAction(action, comment);
90
+
91
+ case 'update':
92
+ return this._generateUpdateAction(action, comment);
93
+
94
+ case 'delete':
95
+ return this._generateDeleteAction(action, comment);
96
+
97
+ case 'validate':
98
+ return this._generateValidateAction(action, comment);
99
+
100
+ case 'execute':
101
+ return this._generateExecuteAction(action, comment);
102
+
103
+ default:
104
+ console.warn('Unknown action type:', action.type);
105
+ return null;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Generate CREATE action
111
+ * @private
112
+ */
113
+ _generateCreateAction(action, comment) {
114
+ const entity = action.entity;
115
+ const data = action.data;
116
+
117
+ const fields = [];
118
+ const values = [];
119
+
120
+ for (const [field, value] of Object.entries(data)) {
121
+ fields.push(field);
122
+ values.push(this._resolveValue(value));
123
+ }
124
+
125
+ return `${comment}
126
+ INSERT INTO ${entity} (${fields.join(', ')})
127
+ VALUES (${values.join(', ')});`;
128
+ }
129
+
130
+ /**
131
+ * Generate UPDATE action
132
+ * @private
133
+ */
134
+ _generateUpdateAction(action, comment) {
135
+ const entity = action.entity;
136
+ const data = action.data;
137
+ const match = action.match;
138
+
139
+ const setClauses = [];
140
+ for (const [field, value] of Object.entries(data)) {
141
+ setClauses.push(`${field} = ${this._resolveValue(value)}`);
142
+ }
143
+
144
+ const whereClauses = [];
145
+ for (const [field, value] of Object.entries(match)) {
146
+ whereClauses.push(`${field} = ${this._resolveValue(value)}`);
147
+ }
148
+
149
+ return `${comment}
150
+ UPDATE ${entity}
151
+ SET ${setClauses.join(', ')}
152
+ WHERE ${whereClauses.join(' AND ')};`;
153
+ }
154
+
155
+ /**
156
+ * Generate DELETE action
157
+ * @private
158
+ */
159
+ _generateDeleteAction(action, comment) {
160
+ const entity = action.entity;
161
+ const match = action.match;
162
+
163
+ const whereClauses = [];
164
+ for (const [field, value] of Object.entries(match)) {
165
+ whereClauses.push(`${field} = ${this._resolveValue(value)}`);
166
+ }
167
+
168
+ return `${comment}
169
+ DELETE FROM ${entity}
170
+ WHERE ${whereClauses.join(' AND ')};`;
171
+ }
172
+
173
+ /**
174
+ * Generate VALIDATE action
175
+ * @private
176
+ */
177
+ _generateValidateAction(action, comment) {
178
+ const functionName = action.function;
179
+ const params = action.params || {};
180
+ const errorMessage = action.error_message || 'Validation failed';
181
+
182
+ const paramList = [];
183
+ for (const [key, value] of Object.entries(params)) {
184
+ paramList.push(`${key} => ${this._resolveValue(value)}`);
185
+ }
186
+
187
+ const paramSQL = paramList.length > 0 ? paramList.join(', ') : '';
188
+
189
+ return `${comment}
190
+ IF NOT ${functionName}(${paramSQL}) THEN
191
+ RAISE EXCEPTION '${errorMessage}';
192
+ END IF;`;
193
+ }
194
+
195
+ /**
196
+ * Generate EXECUTE action
197
+ * @private
198
+ */
199
+ _generateExecuteAction(action, comment) {
200
+ const functionName = action.function;
201
+ const params = action.params || {};
202
+
203
+ const paramList = [];
204
+ for (const [key, value] of Object.entries(params)) {
205
+ paramList.push(`${key} => ${this._resolveValue(value)}`);
206
+ }
207
+
208
+ const paramSQL = paramList.length > 0 ? paramList.join(', ') : '';
209
+
210
+ return `${comment}
211
+ PERFORM ${functionName}(${paramSQL});`;
212
+ }
213
+
214
+ /**
215
+ * Resolve a value (variable reference or literal)
216
+ * @private
217
+ */
218
+ _resolveValue(value) {
219
+ if (typeof value !== 'string') {
220
+ // Number or other type
221
+ return value;
222
+ }
223
+
224
+ // Handle special variables
225
+ if (value.startsWith('@')) {
226
+ const varName = value.substring(1);
227
+
228
+ // Special keywords
229
+ switch (varName) {
230
+ case 'user_id':
231
+ return 'p_user_id';
232
+
233
+ case 'today':
234
+ return 'CURRENT_DATE';
235
+
236
+ case 'now':
237
+ return 'NOW()';
238
+
239
+ default:
240
+ // Field reference from record
241
+ return `(p_record->>'${varName}')`;
242
+ }
243
+ }
244
+
245
+ // String literal
246
+ return `'${value}'`;
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Generate graph rule functions for an entity
252
+ * @param {string} tableName - Table name
253
+ * @param {Object} graphRules - Graph rules object
254
+ * @returns {string} SQL for graph rule functions
255
+ */
256
+ export function generateGraphRuleFunctions(tableName, graphRules) {
257
+ const codegen = new GraphRulesCodegen(tableName, graphRules);
258
+ return codegen.generate();
259
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Notification Path Code Generator
3
+ * Generates PostgreSQL notification resolution functions from path ASTs
4
+ */
5
+
6
+ import { PathParser } from '../parser/path-parser.js';
7
+
8
+ export class NotificationCodegen {
9
+ constructor(tableName, notificationPaths) {
10
+ this.tableName = tableName;
11
+ this.notificationPaths = notificationPaths;
12
+ this.parser = new PathParser();
13
+ }
14
+
15
+ /**
16
+ * Generate notification path resolution function
17
+ * @returns {string} SQL for notification function
18
+ */
19
+ generate() {
20
+ if (!this.notificationPaths || Object.keys(this.notificationPaths).length === 0) {
21
+ return this._generateEmptyFunction();
22
+ }
23
+
24
+ const pathCollectors = [];
25
+
26
+ // Generate SQL for each notification path
27
+ for (const [pathName, paths] of Object.entries(this.notificationPaths)) {
28
+ if (!paths || paths.length === 0) continue;
29
+
30
+ for (const path of paths) {
31
+ const ast = this.parser.parse(path);
32
+ const sql = this._generatePathSQL(ast);
33
+ if (sql) {
34
+ pathCollectors.push(`
35
+ -- ${pathName} notification path
36
+ v_users := v_users || ARRAY(${sql});`);
37
+ }
38
+ }
39
+ }
40
+
41
+ const pathSQL = pathCollectors.length > 0
42
+ ? pathCollectors.join('\n')
43
+ : ' -- No notification paths configured';
44
+
45
+ return `-- Notification path resolution for ${this.tableName}
46
+ CREATE OR REPLACE FUNCTION _resolve_notification_paths_${this.tableName}(
47
+ p_user_id INT,
48
+ p_record JSONB
49
+ ) RETURNS INT[] AS $$
50
+ DECLARE
51
+ v_users INT[] := ARRAY[]::INT[];
52
+ BEGIN
53
+ ${pathSQL}
54
+
55
+ -- Return unique user IDs
56
+ RETURN ARRAY(SELECT DISTINCT unnest(v_users));
57
+ END;
58
+ $$ LANGUAGE plpgsql STABLE SECURITY DEFINER;`;
59
+ }
60
+
61
+ /**
62
+ * Generate empty function (no notifications)
63
+ * @private
64
+ */
65
+ _generateEmptyFunction() {
66
+ return `-- Notification path resolution for ${this.tableName}
67
+ CREATE OR REPLACE FUNCTION _resolve_notification_paths_${this.tableName}(
68
+ p_user_id INT,
69
+ p_record JSONB
70
+ ) RETURNS INT[] AS $$
71
+ BEGIN
72
+ RETURN ARRAY[]::INT[]; -- No notification paths configured
73
+ END;
74
+ $$ LANGUAGE plpgsql STABLE SECURITY DEFINER;`;
75
+ }
76
+
77
+ /**
78
+ * Generate SQL for a path AST
79
+ * @private
80
+ */
81
+ _generatePathSQL(ast) {
82
+ switch (ast.type) {
83
+ case 'empty':
84
+ return null; // No users
85
+
86
+ case 'direct_field':
87
+ return this._generateDirectFieldQuery(ast);
88
+
89
+ case 'traversal':
90
+ return this._generateTraversalQuery(ast);
91
+
92
+ case 'dot_path':
93
+ return this._generateDotPathQuery(ast);
94
+
95
+ default:
96
+ console.warn('Unknown AST type for notification:', ast.type);
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Generate direct field query: @owner_id
103
+ * Returns single user ID
104
+ * @private
105
+ */
106
+ _generateDirectFieldQuery(ast) {
107
+ return `
108
+ SELECT (p_record->>'${ast.field}')::int
109
+ WHERE (p_record->>'${ast.field}') IS NOT NULL
110
+ `;
111
+ }
112
+
113
+ /**
114
+ * Generate traversal query: @org_id->acts_for[org_id=$]{active}.user_id
115
+ * Returns array of user IDs
116
+ * @private
117
+ */
118
+ _generateTraversalQuery(ast) {
119
+ const steps = ast.steps;
120
+
121
+ // Extract components from the path
122
+ let sourceField = null;
123
+ let targetTable = null;
124
+ let targetField = null;
125
+ let filters = [];
126
+ let temporal = false;
127
+
128
+ for (const step of steps) {
129
+ if (step.type === 'field_ref') {
130
+ if (!sourceField) {
131
+ sourceField = step.field;
132
+ } else {
133
+ targetField = step.field;
134
+ }
135
+ } else if (step.type === 'table_ref') {
136
+ targetTable = step.table;
137
+
138
+ if (step.filter) {
139
+ filters = step.filter;
140
+ }
141
+
142
+ if (step.temporal) {
143
+ temporal = true;
144
+ }
145
+
146
+ if (step.targetField) {
147
+ targetField = step.targetField;
148
+ }
149
+ } else if (step.type === 'dot_path') {
150
+ // Handle dot path: posts.author_id
151
+ targetTable = step.fields[0];
152
+ targetField = step.fields[step.fields.length - 1];
153
+ }
154
+ }
155
+
156
+ // Build WHERE conditions
157
+ const conditions = [];
158
+
159
+ // Add filter conditions
160
+ for (const filter of filters) {
161
+ if (filter.operator === '=' && filter.value.type === 'param') {
162
+ conditions.push(`${targetTable}.${filter.field} = (p_record->>'${sourceField}')::int`);
163
+ } else if (filter.operator === '=') {
164
+ const value = this._formatValue(filter.value);
165
+ conditions.push(`${targetTable}.${filter.field} = ${value}`);
166
+ }
167
+ }
168
+
169
+ // Default condition: join on source field
170
+ if (sourceField && targetTable && conditions.length === 0) {
171
+ conditions.push(`${targetTable}.id = (p_record->>'${sourceField}')::int`);
172
+ }
173
+
174
+ // Add temporal condition
175
+ if (temporal) {
176
+ conditions.push(`${targetTable}.valid_to IS NULL`);
177
+ }
178
+
179
+ // Build WHERE clause
180
+ const whereClause = conditions.length > 0
181
+ ? 'WHERE ' + conditions.join('\n AND ')
182
+ : '';
183
+
184
+ return `
185
+ SELECT ${targetTable}.${targetField}
186
+ FROM ${targetTable}
187
+ ${whereClause}
188
+ `;
189
+ }
190
+
191
+ /**
192
+ * Generate dot path query
193
+ * @private
194
+ */
195
+ _generateDotPathQuery(ast) {
196
+ const lastField = ast.fields[ast.fields.length - 1];
197
+ return `
198
+ SELECT (p_record->>'${lastField}')::int
199
+ WHERE (p_record->>'${lastField}') IS NOT NULL
200
+ `;
201
+ }
202
+
203
+ /**
204
+ * Format a value for SQL
205
+ * @private
206
+ */
207
+ _formatValue(value) {
208
+ switch (value.type) {
209
+ case 'literal':
210
+ return `'${value.value}'`;
211
+ case 'number':
212
+ return value.value;
213
+ case 'field':
214
+ return `(p_record->>'${value.value}')`;
215
+ case 'param':
216
+ return '?';
217
+ default:
218
+ return 'NULL';
219
+ }
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Generate notification path resolution function for an entity
225
+ * @param {string} tableName - Table name
226
+ * @param {Object} notificationPaths - Notification paths object
227
+ * @returns {string} SQL for notification function
228
+ */
229
+ export function generateNotificationFunction(tableName, notificationPaths) {
230
+ const codegen = new NotificationCodegen(tableName, notificationPaths);
231
+ return codegen.generate();
232
+ }