supatool 0.1.23 → 0.3.1

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,6 +2,7 @@
2
2
 
3
3
  A CLI tool that automatically generates TypeScript CRUD code from Supabase type definitions.
4
4
 
5
+
5
6
  ## Install
6
7
 
7
8
  ```
@@ -14,36 +15,88 @@ pnpm add -g supatool
14
15
 
15
16
  ## Usage
16
17
 
17
- 1. Generate Supabase type definition file
18
+ ### 1. Extract Database Schema (NEW in v0.3.0)
19
+
20
+ Extract and categorize all database objects from your Supabase project:
21
+
22
+ ```bash
23
+ # Set connection string in environment (recommended)
24
+ echo "SUPABASE_CONNECTION_STRING=postgresql://..." >> .env.local
25
+
26
+ # Extract all database objects with AI-friendly index
27
+ supatool extract --all -o supabase/schemas
28
+
29
+ # Extract only tables and views
30
+ supatool extract -o supabase/schemas
31
+
32
+ # Extract specific tables with pattern
33
+ supatool extract -t "user_*" -o supabase/schemas
34
+
35
+ # Extract from specific schemas (comma-separated)
36
+ supatool extract --all --schema public,auth,extensions -o supabase/schemas
37
+
38
+ # Alternative: specify connection directly
39
+ supatool extract --all -c "postgresql://..." -o supabase/schemas
40
+ ```
18
41
 
42
+ **Output structure:**
19
43
  ```
20
- npx supabase gen types typescript --project-id your_project_ref --schema public > shared/types.ts
44
+ supabase/schemas/
45
+ ├── index.md # Human-readable index with comments
46
+ ├── llms.txt # AI-friendly structured data with comments
47
+ ├── tables/ # Table definitions with comments
48
+ ├── views/ # View definitions with comments
49
+ ├── rls/ # RLS policies
50
+ └── rpc/ # Functions & triggers
21
51
  ```
22
52
 
23
- 2. Auto-generate CRUD code
53
+ ### 2. Generate CRUD Code
24
54
 
25
- ```
55
+ Generate TypeScript CRUD functions from Supabase types:
56
+
57
+ ```bash
58
+ # Generate from Supabase type definitions
26
59
  supatool crud
60
+
61
+ # Generate from schema SQL files
62
+ supatool gen:schema-crud --include-views --react-query
63
+
64
+ # Generate from model YAML
65
+ supatool gen:crud model.yaml
27
66
  ```
28
- - Output: `src/integrations/supabase/crud-autogen/`
29
67
 
30
- 3. Subcommands
68
+ **Output:** `src/integrations/supabase/crud-autogen/`
31
69
 
32
- For more extensible usage, execute with subcommands:
70
+ ### 3. Environment Configuration
71
+
72
+ For security and convenience, set your connection string in environment variables:
73
+
74
+ ```bash
75
+ # Create .env.local file with your connection details
76
+ cat > .env.local << EOF
77
+ SUPABASE_CONNECTION_STRING=postgresql://user:password@host:port/database
78
+ # Alternative: use DATABASE_URL
79
+ DATABASE_URL=postgresql://user:password@host:port/database
80
+ EOF
81
+
82
+ # Now you can run commands without -c flag
83
+ supatool extract --all -o supabase/schemas
84
+ ```
33
85
 
34
- - Show help text for all commands:
35
- ```sh
36
- supatool help
37
- ```
86
+ **Supported environment variables:**
87
+ - `SUPABASE_CONNECTION_STRING` (preferred)
88
+ - `DATABASE_URL` (fallback)
89
+ - `SUPATOOL_MAX_CONCURRENT` (max concurrent table processing, default: 20, max: 50)
38
90
 
39
- - Specify input and output folder:
40
- ```sh
41
- supatool -i path/to/type -o path/to/export
42
- ```
91
+ ### 4. Additional Commands
43
92
 
44
- For detailed usage, see:
45
- - [src/bin/helptext.ts](./src/bin/helptext.ts) (for development)
46
- - [dist/bin/helptext.js](./dist/bin/helptext.js) (for npm package)
93
+ ```bash
94
+ # Show help for all commands
95
+ supatool help
96
+
97
+ # Specify custom input/output paths
98
+ supatool crud -i path/to/types -o path/to/output
99
+ ```
47
100
 
48
101
  ## Note: Supabase Client Requirement
49
102
 
@@ -56,22 +109,41 @@ import { createClient } from '@supabase/supabase-js'
56
109
  export const supabase = createClient('YOUR_SUPABASE_URL', 'YOUR_SUPABASE_ANON_KEY')
57
110
  ```
58
111
 
59
- ## VSCode/Cursor: Run Supabase CLI and supatool together
112
+ ## VSCode/Cursor Integration
60
113
 
61
- You can add a task to `.vscode/tasks.json` to run both commands at once:
114
+ Add these tasks to `.vscode/tasks.json` for quick access:
62
115
 
63
- > **Note:**
64
- > After installing supatool, please restart VSCode (or your terminal) before using the task, so that the new command is recognized.
116
+ > **Note:** Restart VSCode/Cursor after installing supatool to ensure the command is recognized.
65
117
 
66
118
  ```json
67
119
  {
68
120
  "version": "2.0.0",
69
121
  "tasks": [
70
122
  {
71
- "label": "Generate Supabase types and CRUD",
123
+ "label": "Extract Schema and Generate CRUD",
124
+ "type": "shell",
125
+ "command": "supatool extract --all -o supabase/schemas && supatool gen:schema-crud --react-query",
126
+ "group": "build",
127
+ "dependsOn": "setup-env"
128
+ },
129
+ {
130
+ "label": "setup-env",
72
131
  "type": "shell",
73
- "command": "mkdir -p shared && npx supabase gen types typescript --project-id your_project_id --schema public > shared/types.ts && supatool crud --force",
132
+ "command": "echo 'Ensure SUPABASE_CONNECTION_STRING is set in .env.local'",
74
133
  "group": "build"
134
+ },
135
+ {
136
+ "label": "Generate Types and CRUD (Legacy)",
137
+ "type": "shell",
138
+ "command": "mkdir -p shared && npx supabase gen types typescript --project-id ${input:projectId} --schema public > shared/types.ts && supatool crud --force",
139
+ "group": "build"
140
+ }
141
+ ],
142
+ "inputs": [
143
+ {
144
+ "id": "projectId",
145
+ "description": "Supabase project ID",
146
+ "default": "your_project_id"
75
147
  }
76
148
  ]
77
149
  }
@@ -84,7 +156,7 @@ CRUD utility files for the `apps` table will be generated in `src/integrations/s
84
156
  You can import and use these functions in your application as follows:
85
157
 
86
158
  ```ts
87
- // Example: Using CRUD functions for the apps table
159
+ // Example: Using CRUD functions for the apps table (v0.3.0+)
88
160
  import {
89
161
  selectAppsRowsWithFilters,
90
162
  selectAppsSingleRowWithFilters,
@@ -94,23 +166,26 @@ import {
94
166
  deleteAppsRow,
95
167
  } from 'src/integrations/supabase/crud-autogen/apps';
96
168
 
97
- // Get multiple rows with filters
98
- const apps = await selectAppsRowsWithFilters({ status: 'active' });
169
+ // Select multiple rows with filters (NEW: destructuring parameters)
170
+ const apps = await selectAppsRowsWithFilters({ filters: { status: 'active' } });
99
171
 
100
- // Get a single row with filters
101
- const app = await selectAppsSingleRowWithFilters({ id: 'your-app-id' });
172
+ // Select a single row with filters
173
+ const app = await selectAppsSingleRowWithFilters({ filters: { id: 'your-app-id' } });
102
174
 
103
- // Get by ID
104
- const appById = await selectAppsRowById('your-app-id');
175
+ // Select by ID (NEW: destructuring parameters)
176
+ const appById = await selectAppsRowById({ id: 'your-app-id' });
105
177
 
106
- // Create new row
107
- const newApp = await insertAppsRow({ name: 'New App', status: 'active' });
178
+ // Insert new row (NEW: destructuring parameters)
179
+ const newApp = await insertAppsRow({ data: { name: 'New App', status: 'active' } });
108
180
 
109
- // Update row
110
- const updatedApp = await updateAppsRow({ id: 'your-app-id', name: 'Updated Name' });
181
+ // Update row (NEW: destructuring parameters)
182
+ const updatedApp = await updateAppsRow({
183
+ id: 'your-app-id',
184
+ data: { name: 'Updated Name' }
185
+ });
111
186
 
112
- // Delete row
113
- const deletedApp = await deleteAppsRow('your-app-id');
187
+ // Delete row (NEW: destructuring parameters)
188
+ const success = await deleteAppsRow({ id: 'your-app-id' });
114
189
  ```
115
190
 
116
191
  - All functions are async and return the corresponding row type.
@@ -128,4 +203,151 @@ For more details, see the project on GitHub: [https://github.com/idea-garage/sup
128
203
 
129
204
  ## Acknowledgements
130
205
 
131
- This project is inspired by and made possible thanks to the amazing work of [Supabase](https://supabase.com/).
206
+ This project is inspired by and made possible thanks to the amazing work of [Supabase](https://supabase.com/).
207
+
208
+ ## Complete Workflow Examples
209
+
210
+ ### Database-First Development
211
+
212
+ Extract your existing database schema and generate CRUD code using [Supabase's declarative schema workflow](https://supabase.com/docs/guides/local-development/declarative-database-schemas):
213
+
214
+ ```bash
215
+ # 1. Set connection string in .env.local
216
+ echo "SUPABASE_CONNECTION_STRING=postgresql://..." >> .env.local
217
+
218
+ # 2. Extract all database objects to supabase/schemas (declarative schema format)
219
+ supatool extract --all -o supabase/schemas
220
+
221
+ # 3. Generate migrations from declarative schema
222
+ supabase db diff -f initial_schema
223
+
224
+ # 4. Generate TypeScript types with Supabase CLI
225
+ npx supabase gen types typescript --local > src/types/database.ts
226
+
227
+ # 5. Generate CRUD functions with React Query support
228
+ supatool gen:schema-crud --include-views --react-query
229
+ ```
230
+
231
+ ### Model-First Development
232
+
233
+ Start from YAML model definitions:
234
+
235
+ ```bash
236
+ # 1. Create model definition
237
+ supatool create model.yaml
238
+
239
+ # 2. Generate everything from model
240
+ supatool gen:all model.yaml
241
+ ```
242
+
243
+ ### Extract Command Options
244
+
245
+ Extract database objects in Supabase declarative schema format:
246
+
247
+ ```bash
248
+ # Recommended: Set connection in .env.local first
249
+ echo "SUPABASE_CONNECTION_STRING=postgresql://..." >> .env.local
250
+
251
+ # Extract all database objects to categorized directories (recommended)
252
+ supatool extract --all -o supabase/schemas
253
+ # Output: supabase/schemas/{index.md,tables/,views/,rls/,rpc/}
254
+ # Compatible with: supabase db diff
255
+
256
+ # Extract only tables and views
257
+ supatool extract -o supabase/schemas
258
+ # Output: supabase/schemas/{index.md,tables/,views/}
259
+
260
+ # Extract to single directory (for simple projects)
261
+ supatool extract --no-separate -o supabase/schemas
262
+ # Output: supabase/schemas/{index.md,*.sql}
263
+
264
+ # Extract with pattern matching
265
+ supatool extract -t "user_*" -o ./user-tables
266
+
267
+ # Extract from specific schemas (default: public)
268
+ supatool extract --all --schema public,auth,extensions -o supabase/schemas
269
+
270
+ # Alternative: specify connection directly
271
+ supatool extract --all -c "postgresql://..." -o supabase/schemas
272
+ ```
273
+
274
+ ## New Features (v0.3.0)
275
+
276
+ - **🔍 Schema Extraction**: Extract and categorize all database objects (tables, views, RLS, functions, triggers)
277
+ - **📋 Supabase Declarative Schema**: Fully compliant with [Supabase's declarative database schemas](https://supabase.com/docs/guides/local-development/declarative-database-schemas) workflow
278
+ - **🤖 AI-Friendly Index**: Auto-generated index.md and llms.txt files for better AI understanding of schema structure
279
+ - **💬 Comment Support**: Automatically extracts and includes database comments in generated files
280
+ - **📁 Organized Output**: Separate directories for different object types with flexible organization options
281
+ - **🎯 Pattern Matching**: Extract specific tables/views using wildcard patterns
282
+ - **👁️ View Support**: Enhanced CRUD generation with SELECT-only operations for database views
283
+ - **⚛️ React Query Integration**: Generate modern React hooks for data fetching
284
+ - **🔧 Flexible Workflows**: Support both database-first and model-first development approaches
285
+
286
+ ## Changelog
287
+
288
+ ## Database Comments
289
+
290
+ Supatool automatically extracts and includes PostgreSQL comments in all generated files. Comments enhance documentation and AI understanding of your schema.
291
+
292
+ ### Adding Comments to Your Database
293
+
294
+ ```sql
295
+ -- Table comments
296
+ COMMENT ON TABLE users IS 'User account information and authentication data';
297
+
298
+ -- View comments
299
+ COMMENT ON VIEW user_profiles IS 'Combined user data with profile information';
300
+
301
+ -- Function comments
302
+ COMMENT ON FUNCTION update_timestamp() IS 'Automatically updates the updated_at column';
303
+
304
+ -- Custom type comments
305
+ COMMENT ON TYPE user_status IS 'Enumeration of possible user account statuses';
306
+ ```
307
+
308
+ ### Comment Integration
309
+
310
+ Comments appear in:
311
+ - **index.md**: Human-readable file listings with descriptions (tables/views only)
312
+ - **llms.txt**: AI-friendly format (`type:name:path:comment`)
313
+ - **Generated SQL**: As `COMMENT ON` statements for full schema recreation
314
+
315
+ **Example output:**
316
+ ```markdown
317
+ ## Tables
318
+ - [users](tables/users.sql) - User account information and authentication data
319
+ - [posts](tables/posts.sql) - User-generated content and blog posts
320
+ ```
321
+
322
+ ## Changelog
323
+
324
+ ### v0.3.0
325
+
326
+ **NEW Features:**
327
+ - **NEW**: `extract` command for database schema extraction
328
+ - **NEW**: Full compliance with Supabase declarative database schemas workflow
329
+ - **NEW**: AI-friendly index.md and llms.txt generation for better schema understanding
330
+ - **NEW**: Database comment extraction and integration
331
+ - **NEW**: Organized directory structure (tables/, views/, rls/, rpc/)
332
+ - **NEW**: Pattern matching for selective extraction
333
+ - **ENHANCED**: Support for all database object types (RLS, functions, triggers, cron jobs, custom types)
334
+ - **ENHANCED**: Flexible output options with --no-separate compatibility
335
+
336
+ **Enhanced Error Handling:**
337
+ - Comprehensive try-catch blocks for all CRUD operations
338
+ - Enhanced null/undefined checks with proper fallbacks
339
+ - Detailed error messages with contextual information
340
+ - Special handling for PGRST116 errors (record not found)
341
+ - Parameter validation for required fields
342
+ - Proper error logging and debugging support
343
+
344
+ **Breaking Changes:**
345
+ - **Function Parameter Format**: All CRUD functions now use destructuring assignment
346
+ - Before: `selectTableRowById(id: string)`
347
+ - After: `selectTableRowById({ id }: { id: string })`
348
+ - **Type Safety**: Enhanced TypeScript type annotations for all functions
349
+
350
+ ### v0.2.0
351
+ - Added `gen:` commands for code and schema generation
352
+ - Enhanced `create` command
353
+ - Introduced model schema support (`schemas/supatool-data.schema.ts`)
@@ -1,36 +1,122 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.helpText = void 0;
3
+ exports.modelSchemaHelp = exports.helpText = void 0;
4
4
  // See: [src/bin/helptext.ts](./src/bin/helptext.ts) from project root
5
5
  // Help text (command section from README, English only)
6
6
  exports.helpText = `
7
- Supatool CLI - Generate TypeScript CRUD code from Supabase type definitions
7
+ Supatool CLI - Supabase database schema extraction and TypeScript CRUD generation
8
8
 
9
9
  Usage:
10
- supatool crud [options]
11
- supatool help
10
+ supatool <command> [options]
12
11
 
13
12
  Commands:
14
- crud Generate CRUD code
15
- help Show help
13
+ extract Extract and categorize database objects from Supabase
14
+ gen:schema-crud Generate CRUD code from supabase/schemas SQL files
15
+ crud Generate CRUD code from Supabase type definitions
16
+ gen:types Generate TypeScript types from model YAML
17
+ gen:crud Generate CRUD TypeScript code from model YAML
18
+ gen:docs Generate Markdown documentation from model YAML
19
+ gen:sql Generate SQL (tables, relations, RLS/security) from model YAML
20
+ gen:rls Generate RLS/security SQL from model YAML
21
+ gen:all Generate all outputs from model YAML
22
+ create Generate a template model YAML
23
+ config:init Generate configuration template
24
+ help Show help
16
25
 
17
- Options:
18
- -i, --import <path> Import path for type definitions (default: shared/)
19
- -e, --export <path> Output path for CRUD code (default: src/integrations/supabase/)
20
- -t, --tables <names> Generate code for specific tables only (comma separated, e.g. table1,table2)
21
- -f, --force Overwrite output folder without confirmation
22
- -h, --help Show help
23
- -V, --version Show version
26
+ Extract Options:
27
+ -c, --connection <string> Supabase connection string
28
+ -o, --output-dir <path> Output directory (default: ./supabase/schemas)
29
+ -t, --tables <pattern> Table pattern with wildcards (default: *)
30
+ --tables-only Extract only table definitions
31
+ --views-only Extract only view definitions
32
+ --all Extract all DB objects (tables, views, RLS, functions, triggers, cron, types)
33
+ --no-separate Output all objects in same directory
34
+ --schema <schemas> Target schemas, comma-separated (default: public)
24
35
 
25
36
  Examples:
37
+ # Set connection in .env.local (recommended)
38
+ echo "SUPABASE_CONNECTION_STRING=postgresql://..." >> .env.local
39
+
40
+ # Extract all database objects with AI-friendly index
41
+ supatool extract --all -o supabase/schemas
42
+ # Output:
43
+ # supabase/schemas/index.md (Human-readable index with table/view comments)
44
+ # supabase/schemas/llms.txt (AI-friendly structured data with comments)
45
+ # supabase/schemas/tables/*.sql (Tables with comments)
46
+ # supabase/schemas/views/*.sql (Views with comments)
47
+ # supabase/schemas/rls/*.sql (RLS policies)
48
+ # supabase/schemas/rpc/*.sql (Functions & triggers)
49
+ # supabase/schemas/cron/*.sql (Cron jobs)
50
+ # supabase/schemas/types/*.sql (Custom types)
51
+
52
+ # Extract only tables and views (default)
53
+ supatool extract -o supabase/schemas
54
+
55
+ # Extract to single directory (legacy mode)
56
+ supatool extract --no-separate -o supabase/schemas
57
+
58
+ # Extract specific pattern
59
+ supatool extract -t "user_*" -o ./user-tables
60
+
61
+ # Extract from specific schemas (default: public)
62
+ supatool extract --all --schema public,auth,extensions -o supabase/schemas
63
+
64
+ # Alternative: specify connection directly
65
+ supatool extract --all -c "postgresql://..." -o supabase/schemas
66
+
67
+ # Complete database-first workflow
68
+ echo "SUPABASE_CONNECTION_STRING=postgresql://..." >> .env.local
69
+ supatool extract --all -o supabase/schemas
70
+ supatool gen:schema-crud --include-views --react-query
71
+
72
+ # Model-first workflow
73
+ supatool create model.yaml
74
+ supatool gen:all model.yaml
75
+
76
+ # Legacy CRUD generation
26
77
  supatool crud
27
- - Import path: shared/
28
- - Export path: src/integrations/supabase/
29
78
 
30
- supatool crud -i path/to/import -e path/to/export
31
- - Import path: path/to/import
32
- - Export path: path/to/export
79
+ Database Comments:
80
+ Supatool automatically extracts and includes database comments in generated files.
81
+
82
+ To add comments to your database objects:
83
+
84
+ # Table comments
85
+ COMMENT ON TABLE users IS 'User account information';eha,
86
+
87
+ # View comments
88
+ COMMENT ON VIEW user_profiles IS 'Combined user data with profile information';
89
+
90
+ # Function comments
91
+ COMMENT ON FUNCTION update_timestamp() IS 'Automatically updates the updated_at column';
92
+
93
+ # Custom type comments
94
+ COMMENT ON TYPE user_status IS 'Enumeration of possible user account statuses';
95
+
96
+ Comments will appear in:
97
+ - index.md: Human-readable list with descriptions (tables/views only)
98
+ - llms.txt: AI-friendly format (type:name:path:comment)
99
+ - Generated SQL files: As COMMENT statements
100
+ `;
101
+ // Model Schema Usage
102
+ exports.modelSchemaHelp = `
103
+ Model Schema Usage (schemas/supatool-data.schema.ts):
104
+
105
+ - Import in TypeScript:
106
+ import { SUPATOOL_MODEL_SCHEMA } from 'supatool/schemas/supatool-data.schema';
107
+
108
+ - Validate with ajv:
109
+ import Ajv from 'ajv';
110
+ const ajv = new Ajv();
111
+ const validate = ajv.compile(SUPATOOL_MODEL_SCHEMA);
112
+ const data = /* your YAML/JSON parsed object */;
113
+ if (!validate(data)) {
114
+ console.error(validate.errors);
115
+ } else {
116
+ console.log('Valid!');
117
+ }
33
118
 
34
- supatool crud -t users,posts
35
- - Only generate for users and posts tables
119
+ - Use with AI:
120
+ const schemaJson = JSON.stringify(SUPATOOL_MODEL_SCHEMA, null, 2);
121
+ // Pass schemaJson to your AI prompt or API
36
122
  `;