dzql 0.5.14 → 0.5.16

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/README.md CHANGED
@@ -2,24 +2,29 @@
2
2
 
3
3
  PostgreSQL-powered framework with automatic CRUD operations, live query subscriptions, and real-time WebSocket synchronization.
4
4
 
5
- ## Documentation
6
-
7
- - **[Documentation Hub](docs/)** - Complete documentation index
8
- - **[Getting Started Tutorial](docs/getting-started/tutorial.md)** - Complete tutorial with working todo app
9
- - **[API Reference](docs/reference/api.md)** - Complete API documentation
10
- - **[Live Query Subscriptions](docs/getting-started/subscriptions-quick-start.md)** - Real-time denormalized documents
11
- - **[Compiler Documentation](docs/compiler/)** - Entity compilation guide and coding standards
12
- - **[Claude Guide](docs/for-ai/claude-guide.md)** - Development guide for AI assistants
13
- - **[Venues Example](../venues/)** - Full working application
14
-
15
- ## Quick Install
5
+ ## Quick Start
16
6
 
17
7
  ```bash
18
8
  bun add dzql
19
- # or
20
- npm install dzql
9
+
10
+ export DATABASE_URL="postgresql://user:pass@localhost:5432/mydb"
11
+ bunx dzql db:init
12
+
13
+ bunx dzql compile entities.sql -o init_db/
14
+ psql $DATABASE_URL -f init_db/*.sql
21
15
  ```
22
16
 
17
+ See **[Quick Start Guide](docs/getting-started/quickstart.md)** for the full 5-minute setup.
18
+
19
+ ## Documentation
20
+
21
+ - **[Quick Start](docs/getting-started/quickstart.md)** - 5-minute setup
22
+ - **[Full Tutorial](docs/getting-started/tutorial.md)** - Complete tutorial with working app
23
+ - **[API Reference](docs/reference/api.md)** - Complete API documentation
24
+ - **[Subscriptions](docs/getting-started/subscriptions-quick-start.md)** - Real-time denormalized documents
25
+ - **[Compiler Guide](docs/compiler/)** - Entity compilation and coding standards
26
+ - **[Claude Guide](docs/for-ai/claude-guide.md)** - Development guide for AI assistants
27
+
23
28
  ## Quick Example
24
29
 
25
30
  ```javascript
package/bin/cli.js CHANGED
@@ -16,8 +16,8 @@ switch (command) {
16
16
  case 'dev':
17
17
  console.log('🚧 Dev command coming soon');
18
18
  break;
19
- case 'db:up':
20
- console.log('🚧 Database commands coming soon');
19
+ case 'db:init':
20
+ await runDbInit(args);
21
21
  break;
22
22
  case 'compile':
23
23
  await runCompile(args);
@@ -44,25 +44,24 @@ switch (command) {
44
44
  console.log(`
45
45
  DZQL CLI
46
46
 
47
- Usage:
48
- dzql create <app-name> Create a new DZQL application
49
- dzql dev Start development server
50
- dzql db:up Start PostgreSQL database
51
- dzql db:down Stop PostgreSQL database
52
- dzql compile <input> Compile entity definitions to SQL
47
+ Quick Start:
48
+ 1. dzql db:init Initialize database with DZQL core (~70 lines SQL)
49
+ 2. dzql compile app.sql Compile your entities to PostgreSQL functions
50
+ 3. psql < compiled/*.sql Apply the compiled SQL to your database
51
+
52
+ Commands:
53
+ dzql db:init Initialize database with DZQL core schema
54
+ dzql compile <input> Compile entity definitions to SQL functions
53
55
 
54
56
  dzql migrate:new <name> Create a new migration file
55
57
  dzql migrate:up Apply pending migrations
56
- dzql migrate:down Rollback last migration
57
58
  dzql migrate:status Show migration status
58
59
 
59
60
  dzql --version Show version
60
61
 
61
62
  Examples:
62
- dzql create my-venue-app
63
+ dzql db:init
63
64
  dzql compile entities/blog.sql -o init_db/
64
- dzql migrate:new add_user_avatars
65
- dzql migrate:up
66
65
  `);
67
66
  }
68
67
 
@@ -666,3 +665,63 @@ async function runMigrateStatus(args) {
666
665
  await sql.end();
667
666
  }
668
667
  }
668
+
669
+ // ============================================================================
670
+ // Database Initialization
671
+ // ============================================================================
672
+
673
+ async function runDbInit(args) {
674
+ const databaseUrl = process.env.DATABASE_URL;
675
+
676
+ if (!databaseUrl) {
677
+ console.error('Error: DATABASE_URL environment variable not set');
678
+ console.log('Set it to your PostgreSQL connection string:');
679
+ console.log(' export DATABASE_URL="postgresql://user:pass@localhost:5432/dbname"');
680
+ process.exit(1);
681
+ }
682
+
683
+ console.log('\nšŸš€ DZQL Database Initialization\n');
684
+
685
+ const sql = postgres(databaseUrl);
686
+
687
+ try {
688
+ console.log('šŸ”Œ Connected to database');
689
+
690
+ // Read the core SQL file
691
+ const coreSQL = readFileSync(
692
+ new URL('../src/database/dzql-core.sql', import.meta.url),
693
+ 'utf-8'
694
+ );
695
+
696
+ console.log('šŸ“¦ Applying DZQL core schema...');
697
+ await sql.unsafe(coreSQL);
698
+
699
+ // Check version
700
+ const version = await sql`SELECT version FROM dzql.meta ORDER BY installed_at DESC LIMIT 1`;
701
+ console.log(`āœ… DZQL core initialized (v${version[0]?.version || 'unknown'})`);
702
+
703
+ console.log(`
704
+ Next steps:
705
+ 1. Create your entity definitions (schema + DZQL registrations)
706
+ 2. Compile: dzql compile entities.sql -o compiled/
707
+ 3. Apply: psql $DATABASE_URL -f compiled/*.sql
708
+
709
+ Example entity file (entities.sql):
710
+ -- Schema
711
+ CREATE TABLE users (
712
+ id SERIAL PRIMARY KEY,
713
+ email TEXT UNIQUE NOT NULL,
714
+ name TEXT
715
+ );
716
+
717
+ -- DZQL Registration
718
+ SELECT dzql.register_entity('users', 'name', ARRAY['name', 'email']);
719
+ `);
720
+
721
+ } catch (err) {
722
+ console.error('āŒ Initialization failed:', err.message);
723
+ process.exit(1);
724
+ } finally {
725
+ await sql.end();
726
+ }
727
+ }
@@ -0,0 +1,125 @@
1
+ # DZQL Quick Start
2
+
3
+ Get a real-time API with automatic CRUD in 5 minutes.
4
+
5
+ ## Prerequisites
6
+
7
+ - PostgreSQL (local or Docker)
8
+ - Bun or Node.js 18+
9
+
10
+ ## 1. Install
11
+
12
+ ```bash
13
+ mkdir my-app && cd my-app
14
+ bun init -y
15
+ bun add dzql
16
+ ```
17
+
18
+ ## 2. Start PostgreSQL
19
+
20
+ ```bash
21
+ docker run -d --name dzql-db \
22
+ -e POSTGRES_USER=dzql \
23
+ -e POSTGRES_PASSWORD=dzql \
24
+ -e POSTGRES_DB=dzql \
25
+ -p 5432:5432 \
26
+ postgres:latest
27
+
28
+ export DATABASE_URL="postgresql://dzql:dzql@localhost:5432/dzql"
29
+ ```
30
+
31
+ ## 3. Initialize Database
32
+
33
+ ```bash
34
+ bunx dzql db:init
35
+ ```
36
+
37
+ ## 4. Define Entities
38
+
39
+ Create `entities.sql`:
40
+
41
+ ```sql
42
+ -- Schema
43
+ CREATE TABLE users (
44
+ id SERIAL PRIMARY KEY,
45
+ email TEXT UNIQUE NOT NULL,
46
+ name TEXT,
47
+ created_at TIMESTAMPTZ DEFAULT now()
48
+ );
49
+
50
+ CREATE TABLE todos (
51
+ id SERIAL PRIMARY KEY,
52
+ title TEXT NOT NULL,
53
+ completed BOOLEAN DEFAULT false,
54
+ user_id INT REFERENCES users(id),
55
+ created_at TIMESTAMPTZ DEFAULT now()
56
+ );
57
+
58
+ -- Register with DZQL
59
+ SELECT dzql.register_entity('users', 'name', ARRAY['name', 'email']);
60
+ SELECT dzql.register_entity('todos', 'title', ARRAY['title']);
61
+ ```
62
+
63
+ ## 5. Compile
64
+
65
+ ```bash
66
+ bunx dzql compile entities.sql -o init_db/
67
+ ```
68
+
69
+ ## 6. Apply
70
+
71
+ ```bash
72
+ psql $DATABASE_URL -f init_db/001_schema.sql
73
+ psql $DATABASE_URL -f init_db/users.sql
74
+ psql $DATABASE_URL -f init_db/todos.sql
75
+ ```
76
+
77
+ ## 7. Create Server
78
+
79
+ Create `index.js`:
80
+
81
+ ```javascript
82
+ import { createServer } from 'dzql/server';
83
+
84
+ createServer({ port: 3000 });
85
+ console.log('Server running at http://localhost:3000');
86
+ ```
87
+
88
+ ## 8. Use
89
+
90
+ ```javascript
91
+ import { WebSocketManager } from 'dzql/client';
92
+
93
+ const ws = new WebSocketManager();
94
+ await ws.connect();
95
+
96
+ // Auto-generated CRUD
97
+ const todo = await ws.api.save.todos({ title: 'Buy milk' });
98
+ const todos = await ws.api.search.todos({});
99
+ await ws.api.save.todos({ id: todo.id, completed: true });
100
+ await ws.api.delete.todos({ id: todo.id });
101
+
102
+ // Real-time updates
103
+ ws.onBroadcast((method, params) => {
104
+ console.log('Change:', method, params);
105
+ });
106
+ ```
107
+
108
+ ## What You Get
109
+
110
+ For each entity:
111
+ - `get_<entity>(user_id, id)` - Get by ID
112
+ - `save_<entity>(user_id, data)` - Create or update
113
+ - `delete_<entity>(user_id, id)` - Delete
114
+ - `search_<entity>(user_id, filters, search, sort, page, limit)` - Search
115
+
116
+ Plus:
117
+ - Real-time updates via WebSocket
118
+ - Permission checks in SQL
119
+ - Audit trail in `dzql.events`
120
+
121
+ ## Next Steps
122
+
123
+ - [Full Tutorial](./tutorial.md) - Complete walkthrough
124
+ - [Subscriptions](./subscriptions-quick-start.md) - Real-time denormalized documents
125
+ - [API Reference](../reference/api.md) - All operations
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dzql",
3
- "version": "0.5.14",
3
+ "version": "0.5.16",
4
4
  "description": "PostgreSQL-powered framework with zero boilerplate CRUD operations and real-time WebSocket synchronization",
5
5
  "type": "module",
6
6
  "main": "src/server/index.js",
@@ -17,7 +17,7 @@
17
17
  "files": [
18
18
  "bin/**/*.js",
19
19
  "src/**/*.js",
20
- "src/database/migrations/**/*.sql",
20
+ "src/database/**/*.sql",
21
21
  "docs/**/*.md",
22
22
  "docs/examples/*.sql",
23
23
  "README.md",
@@ -0,0 +1,161 @@
1
+ -- ============================================================================
2
+ -- DZQL Core - Minimal Foundation
3
+ -- ============================================================================
4
+ -- This is the minimal SQL needed for DZQL compiled mode.
5
+ -- Run: dzql db:init
6
+ -- Or: psql $DATABASE_URL -f dzql-core.sql
7
+ -- ============================================================================
8
+
9
+ CREATE EXTENSION IF NOT EXISTS pgcrypto;
10
+
11
+ CREATE SCHEMA IF NOT EXISTS dzql;
12
+
13
+ -- Version tracking
14
+ CREATE TABLE IF NOT EXISTS dzql.meta (
15
+ installed_at TIMESTAMPTZ DEFAULT now(),
16
+ version TEXT NOT NULL
17
+ );
18
+
19
+ INSERT INTO dzql.meta (version)
20
+ SELECT '0.5.14'
21
+ WHERE NOT EXISTS (SELECT 1 FROM dzql.meta);
22
+
23
+ -- Entity registry
24
+ CREATE TABLE IF NOT EXISTS dzql.entities (
25
+ table_name TEXT PRIMARY KEY,
26
+ label_field TEXT NOT NULL,
27
+ searchable_fields TEXT[] NOT NULL,
28
+ fk_includes JSONB DEFAULT '{}',
29
+ soft_delete BOOLEAN DEFAULT false,
30
+ temporal_fields JSONB DEFAULT '{}',
31
+ notification_paths JSONB DEFAULT '{}',
32
+ permission_paths JSONB DEFAULT '{}',
33
+ graph_rules JSONB DEFAULT '{}',
34
+ field_defaults JSONB DEFAULT '{}',
35
+ many_to_many JSONB DEFAULT '{}'
36
+ );
37
+
38
+ -- Function allowlist
39
+ CREATE TABLE IF NOT EXISTS dzql.registry (
40
+ fn_regproc REGPROC PRIMARY KEY,
41
+ description TEXT
42
+ );
43
+
44
+ -- Event audit table
45
+ CREATE TABLE IF NOT EXISTS dzql.events (
46
+ event_id BIGSERIAL PRIMARY KEY,
47
+ table_name TEXT NOT NULL,
48
+ op TEXT NOT NULL,
49
+ pk JSONB NOT NULL,
50
+ data JSONB,
51
+ user_id INT,
52
+ notify_users INT[],
53
+ at TIMESTAMPTZ DEFAULT now()
54
+ );
55
+
56
+ CREATE INDEX IF NOT EXISTS dzql_events_at_idx ON dzql.events (at);
57
+ CREATE INDEX IF NOT EXISTS dzql_events_table_pk_idx ON dzql.events (table_name, pk, at);
58
+
59
+ -- NOTIFY trigger for real-time updates
60
+ CREATE OR REPLACE FUNCTION dzql.notify_event()
61
+ RETURNS TRIGGER LANGUAGE plpgsql AS $$
62
+ BEGIN
63
+ PERFORM pg_notify('dzql', jsonb_build_object(
64
+ 'event_id', NEW.event_id,
65
+ 'table', NEW.table_name,
66
+ 'op', NEW.op,
67
+ 'pk', NEW.pk,
68
+ 'data', NEW.data,
69
+ 'user_id', NEW.user_id,
70
+ 'at', NEW.at,
71
+ 'notify_users', NEW.notify_users
72
+ )::text);
73
+ RETURN NULL;
74
+ END $$;
75
+
76
+ DROP TRIGGER IF EXISTS dzql_events_notify ON dzql.events;
77
+ CREATE TRIGGER dzql_events_notify
78
+ AFTER INSERT ON dzql.events
79
+ FOR EACH ROW EXECUTE FUNCTION dzql.notify_event();
80
+
81
+ -- Subscribables registry (for compiled subscribables)
82
+ CREATE TABLE IF NOT EXISTS dzql.subscribables (
83
+ name TEXT PRIMARY KEY,
84
+ permission_paths JSONB DEFAULT '{}',
85
+ param_schema JSONB DEFAULT '{}',
86
+ root_entity TEXT NOT NULL,
87
+ relations JSONB DEFAULT '{}',
88
+ scope_tables TEXT[] DEFAULT '{}',
89
+ created_at TIMESTAMPTZ DEFAULT now()
90
+ );
91
+
92
+ -- Helper to register entities
93
+ CREATE OR REPLACE FUNCTION dzql.register_entity(
94
+ p_table_name TEXT,
95
+ p_label_field TEXT,
96
+ p_searchable_fields TEXT[],
97
+ p_fk_includes JSONB DEFAULT '{}',
98
+ p_soft_delete BOOLEAN DEFAULT false,
99
+ p_temporal_fields JSONB DEFAULT '{}',
100
+ p_notification_paths JSONB DEFAULT '{}',
101
+ p_permission_paths JSONB DEFAULT '{}',
102
+ p_graph_rules JSONB DEFAULT '{}',
103
+ p_field_defaults JSONB DEFAULT '{}',
104
+ p_many_to_many JSONB DEFAULT '{}'
105
+ ) RETURNS VOID AS $$
106
+ BEGIN
107
+ INSERT INTO dzql.entities (
108
+ table_name, label_field, searchable_fields, fk_includes,
109
+ soft_delete, temporal_fields, notification_paths, permission_paths,
110
+ graph_rules, field_defaults, many_to_many
111
+ ) VALUES (
112
+ p_table_name, p_label_field, p_searchable_fields, p_fk_includes,
113
+ p_soft_delete, p_temporal_fields, p_notification_paths, p_permission_paths,
114
+ p_graph_rules, p_field_defaults, p_many_to_many
115
+ )
116
+ ON CONFLICT (table_name) DO UPDATE SET
117
+ label_field = EXCLUDED.label_field,
118
+ searchable_fields = EXCLUDED.searchable_fields,
119
+ fk_includes = EXCLUDED.fk_includes,
120
+ soft_delete = EXCLUDED.soft_delete,
121
+ temporal_fields = EXCLUDED.temporal_fields,
122
+ notification_paths = EXCLUDED.notification_paths,
123
+ permission_paths = EXCLUDED.permission_paths,
124
+ graph_rules = EXCLUDED.graph_rules,
125
+ field_defaults = EXCLUDED.field_defaults,
126
+ many_to_many = EXCLUDED.many_to_many;
127
+ END;
128
+ $$ LANGUAGE plpgsql;
129
+
130
+ -- Helper to register subscribables
131
+ CREATE OR REPLACE FUNCTION dzql.register_subscribable(
132
+ p_name TEXT,
133
+ p_permission_paths JSONB,
134
+ p_param_schema JSONB,
135
+ p_root_entity TEXT,
136
+ p_relations JSONB DEFAULT '{}'
137
+ ) RETURNS VOID AS $$
138
+ DECLARE
139
+ v_scope_tables TEXT[];
140
+ BEGIN
141
+ -- Extract scope tables from relations
142
+ SELECT array_agg(DISTINCT tbl) INTO v_scope_tables
143
+ FROM (
144
+ SELECT p_root_entity AS tbl
145
+ UNION ALL
146
+ SELECT value->>'entity' AS tbl
147
+ FROM jsonb_each(p_relations)
148
+ WHERE value->>'entity' IS NOT NULL
149
+ ) t
150
+ WHERE tbl IS NOT NULL;
151
+
152
+ INSERT INTO dzql.subscribables (name, permission_paths, param_schema, root_entity, relations, scope_tables)
153
+ VALUES (p_name, p_permission_paths, p_param_schema, p_root_entity, p_relations, v_scope_tables)
154
+ ON CONFLICT (name) DO UPDATE SET
155
+ permission_paths = EXCLUDED.permission_paths,
156
+ param_schema = EXCLUDED.param_schema,
157
+ root_entity = EXCLUDED.root_entity,
158
+ relations = EXCLUDED.relations,
159
+ scope_tables = EXCLUDED.scope_tables;
160
+ END;
161
+ $$ LANGUAGE plpgsql;