-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.cursorrules
More file actions
1304 lines (1081 loc) · 48.7 KB
/
Copy path.cursorrules
File metadata and controls
1304 lines (1081 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# schemax - Project Context
## Overview
schemax is a comprehensive toolkit for managing Databricks Unity Catalog schemas using a declarative, version-controlled approach. It consists of a VS Code extension for visual schema design and a Python SDK/CLI for automation and CI/CD integration.
## 🔥 Quick Rules (Always Follow)
1. **Type Annotations**: ALL Python functions must have parameter and return types (see Python section)
2. **Formatting**: Ruff format with 100 char line length (auto on save)
3. **Testing**: Run pytest before commit (169 passed, 12 skipped)
4. **Logging**: Use `outputChannel.appendLine()` in extension (never `console.log()`)
5. **Immutability**: Never mutate state directly, always create new objects
## Repository Structure (Monorepo)
```
schemax/
├── packages/
│ ├── vscode-extension/ # VS Code Extension (TypeScript + React)
│ │ ├── src/
│ │ │ ├── extension.ts # Extension commands
│ │ │ ├── storage-v4.ts # V4 file storage (multi-environment)
│ │ │ ├── providers/ # Provider-based architecture
│ │ │ │ ├── base/ # Base provider contracts
│ │ │ │ │ ├── models.ts # Zod schemas
│ │ │ │ │ ├── operations.ts # Operation definitions
│ │ │ │ │ └── sql-generator.ts # SQL generation
│ │ │ │ └── unity/ # Unity Catalog provider
│ │ │ │ ├── sql-generator.ts
│ │ │ │ ├── state-reducer.ts
│ │ │ │ └── operations.ts
│ │ │ └── webview/ # React UI
│ │ └── package.json
│ │
│ └── python-sdk/ # Python SDK & CLI
│ ├── src/schemax/
│ │ ├── core/ # Core infrastructure (NEW)
│ │ │ ├── storage.py # V4 file storage (multi-environment)
│ │ │ ├── deployment.py # Deployment tracking
│ │ │ └── version.py # Semantic versioning utilities
│ │ ├── providers/ # Provider-based architecture
│ │ │ ├── base/ # Base provider contracts
│ │ │ │ ├── models.py # Pydantic models
│ │ │ │ ├── operations.py # Operation types
│ │ │ │ ├── sql_generator.py # SQL generation
│ │ │ │ ├── state_differ.py # State diffing
│ │ │ │ ├── provider.py # Provider protocol
│ │ │ │ ├── executor.py # SQL execution protocol
│ │ │ │ └── reverse_generator.py # Safety validation
│ │ │ ├── unity/ # Unity Catalog provider
│ │ │ │ ├── models.py
│ │ │ │ ├── operations.py
│ │ │ │ ├── sql_generator.py
│ │ │ │ ├── state_reducer.py
│ │ │ │ ├── state_differ.py
│ │ │ │ ├── provider.py
│ │ │ │ ├── auth.py # Databricks authentication
│ │ │ │ ├── executor.py # Databricks SQL executor
│ │ │ │ └── safety_validator.py # Rollback safety
│ │ │ └── registry.py # Provider registry
│ │ ├── commands/ # CLI command modules
│ │ │ ├── apply.py # Apply command (with auto-rollback)
│ │ │ ├── rollback.py # Rollback command (NEW)
│ │ │ ├── snapshot_rebase.py # Snapshot rebase (NEW)
│ │ │ ├── sql.py # SQL generation command
│ │ │ ├── validate.py # Validation command
│ │ │ ├── diff.py # Diff command
│ │ │ └── deployment.py # Deployment recording
│ │ └── cli.py # CLI routing layer
│ └── pyproject.toml
│
├── examples/ # Working examples
│ ├── basic-schema/ # Sample project
│ ├── github-actions/ # CI/CD templates
│ └── python-scripts/ # SDK usage examples
│
├── docs/ # Documentation
│ ├── README.md # Documentation index
│ ├── QUICKSTART.md # Getting started guide
│ ├── ARCHITECTURE.md # Technical design
│ └── DEVELOPMENT.md # Development guide
│
├── scripts/
│ └── smoke-test.sh # Quick validation
│
├── .github/workflows/ # CI/CD pipelines
│ ├── extension-ci.yml
│ ├── python-sdk-ci.yml
│ └── integration-tests.yml
│
├── README.md # Project overview
├── TESTING.md # Testing guide
├── CONTRIBUTING.md # Contributing guidelines
└── .cursorrules # This file
```
## Architecture (V4)
### File Structure (.schemax/)
```
project-root/
└── .schemax/
├── project.json # Project metadata (version, snapshots list, settings)
├── changelog.json # Working changes (ops since last snapshot)
├── snapshots/
│ ├── v0.1.0.json # Full state snapshots
│ ├── v0.2.0.json
│ └── v0.3.0.json
└── migrations/ # Generated SQL files
└── migration_*.sql
```
### Core Concepts
1. **Operations (Ops)**: Append-only log of all user actions
- Each op has: `{id, ts, op, target, payload}`
- Ops are immutable and never edited
- Examples: `add_catalog`, `rename_column`, `reorder_columns`
- All ops have UUIDs for tracking
2. **Changelog**: `changelog.json` contains ops since last snapshot
- Cleared when snapshot is created
- Tracks `sinceSnapshot` version
- This is the "working directory" of changes
3. **Snapshots**: Point-in-time full state captures
- Stored as separate files: `.schemax/snapshots/vX.Y.Z.json`
- Contains complete state + list of ops included
- Metadata stored in `project.json`, full state in snapshot file
- Semantic versioning (v0.1.0, v0.2.0, etc.)
4. **State Loading**:
- Load latest snapshot (or start with empty state)
- Apply changelog ops to get current state
- This is what the UI displays
5. **SQL Generation**:
- Convert changelog ops to SQL DDL
- Idempotent statements (safe to run multiple times)
- Saved to `.schemax/migrations/` directory
### Data Models
**Project File** (`project.json` - v4 Schema):
```typescript
{
version: 4,
name: string,
provider: {
type: string, // e.g., "unity"
version: string, // e.g., "1.0.0"
environments: {
[envName: string]: {
topLevelName: string, // Physical catalog name (for Unity Catalog)
description?: string,
allowDrift: boolean,
requireSnapshot: boolean,
requireApproval?: boolean,
autoCreateTopLevel: boolean,
autoCreateSchemaxSchema: boolean
}
}
},
managedLocations: { // Project-level managed locations (for catalog/schema MANAGED LOCATION)
[locationName: string]: {
paths: {
[envName: string]: string // Environment-specific physical paths
},
description?: string
}
},
externalLocations: { // Project-level external locations (for external tables)
[locationName: string]: {
paths: {
[envName: string]: string // Environment-specific physical paths
},
description?: string
}
},
snapshots: SnapshotMetadata[], // Just metadata, references to files
deployments: Deployment[],
settings: ProjectSettings,
latestSnapshot: string | null // version string
}
```
**Note:** v4 refactors locations from environment-specific to project-level with per-environment paths, enabling consistent location names across environments while allowing different physical paths.
**Changelog File** (`changelog.json`):
```typescript
{
version: 1,
sinceSnapshot: string | null, // version
ops: Op[],
lastModified: string // ISO timestamp
}
```
**Snapshot File** (`.schemax/snapshots/vX.Y.Z.json`):
```typescript
{
id: string,
version: string,
name: string,
ts: string,
createdBy: string,
state: { catalogs: Catalog[] }, // Full state
opsIncluded: string[], // Op IDs
previousSnapshot: string | null,
hash: string, // SHA-256 for integrity
tags: string[],
comment?: string
}
```
**Unity Catalog Model** (Enhanced with Governance & Storage Features):
```
Catalog
├── id, name
├── managedLocationName?: string // Reference to project-level managed location
├── Schema[]
├── id, name
├── managedLocationName?: string // Reference to project-level managed location
└── Table[]
├── id, name, format (delta/iceberg)
├── external?: boolean // Is external table
├── externalLocationName?: string // Reference to project-level external location
├── path?: string // Relative path within external location
├── partitionColumns?: string[] // PARTITIONED BY columns
├── clusterColumns?: string[] // CLUSTER BY columns (Liquid Clustering)
├── columns: Column[]
│ ├── id, name, type, nullable, comment
│ ├── tags?: Record<string, string> // Column-level tags
│ └── maskId?: string // Reference to column mask
├── properties: Record<string, string> // TBLPROPERTIES
├── constraints: Constraint[] // PK, FK, CHECK
├── grants: Grant[]
├── rowFilters?: RowFilter[] // Row-level security
└── columnMasks?: ColumnMask[] // Column masking
```
**Column**:
```typescript
{
id: string,
name: string,
type: string,
nullable: boolean,
comment?: string,
tags?: Record<string, string>, // { tag_name: tag_value }
maskId?: string // Reference to active mask
}
```
**Constraint** (Supports PRIMARY KEY, FOREIGN KEY, CHECK):
```typescript
{
id: string,
type: 'primary_key' | 'foreign_key' | 'check',
name?: string, // CONSTRAINT name
columns: string[], // column IDs
// For PRIMARY KEY
timeseries?: boolean,
// For FOREIGN KEY
parentTable?: string,
parentColumns?: string[],
matchFull?: boolean,
onUpdate?: 'NO_ACTION',
onDelete?: 'NO_ACTION',
// For CHECK
expression?: string, // SQL expression
// Constraint options (all types)
notEnforced?: boolean,
deferrable?: boolean,
initiallyDeferred?: boolean,
rely?: boolean // For Photon query optimization
}
```
**RowFilter** (Row-level security):
```typescript
{
id: string,
name: string,
enabled: boolean,
udfExpression: string, // e.g., "region = current_user()"
description?: string
}
```
**ColumnMask** (Column-level masking):
```typescript
{
id: string,
columnId: string,
name: string,
enabled: boolean,
maskFunction: string, // e.g., "REDACT_EMAIL(email)"
description?: string
}
```
## VS Code Extension
### Storage Layer (`packages/vscode-extension/src/storage-v4.ts`)
**Key Functions**:
- `ensureProjectFile()` - Initialize new v4 project with environments
- `loadCurrentState()` - Load snapshot + apply changelog
- `appendOps()` - Add ops to changelog
- `createSnapshot()` - Create snapshot file, update metadata, clear changelog
- `readProject()`, `readChangelog()`, `readSnapshot()`
- `getEnvironmentConfig()` - Get environment-specific configuration
**Op Reducer**: `applyOpsToState()` applies ops to state immutably
**Catalog Mode**: Supports `single` mode with implicit catalog (`__implicit__`)
### SQL Generator (`packages/vscode-extension/src/providers/unity/sql-generator.ts`)
**UnitySQLGenerator class**:
- `generateSQL(ops: Op[]): string` - Main entry point
- Accepts `catalogNameMapping` for environment-specific SQL
- Private methods for each operation type
- Generates idempotent DDL (CREATE IF NOT EXISTS, etc.)
- Handles all 29 Unity Catalog operations
- Orders SQL by dependency (catalog → schema → table → operations)
- Includes operation tracking in comments
### Extension (`packages/vscode-extension/src/extension.ts`)
**Commands**:
1. `schemax.openDesigner` - Opens React webview
2. `schemax.showLastOps` - Shows changelog ops
3. `schemax.createSnapshot` - Creates new snapshot
4. `schemax.generateSQL` - Generates SQL migration file
**Message Flow**:
- Webview → Extension: `load-project`, `append-ops`
- Extension → Webview: `project-loaded`, `project-updated`
### Webview (`packages/vscode-extension/src/webview/`)
**Architecture**: React + Vite + Zustand
**Components**:
- `App.tsx` - Main layout, message handling
- `Sidebar.tsx` - Tree view with context-aware inline "+" buttons
- `TableDesigner.tsx` - Comprehensive table editor
- `ColumnGrid.tsx` - Inline column editing + tags
- `TableProperties.tsx` - TBLPROPERTIES management
- `TableConstraints.tsx` - PRIMARY KEY, FOREIGN KEY, CHECK
- `SecurityGovernance.tsx` - Row filters & column masks
- `SnapshotPanel.tsx` - Timeline view
**State Management** (`useDesignerStore.ts`):
- Zustand store holds current project state
- All mutations generate ops via `emitOps()`
- Ops sent to extension via `vscode.postMessage()`
- Extension applies ops and sends back updated state
### Build System
**Extension**: esbuild (`esbuild.config.mjs`)
- Bundles `src/extension.ts` → `dist/extension.js`
- External: `vscode` module
**Webview**: Vite (`vite.config.ts`)
- Builds React app → `media/`
- Entry: `src/webview/main.tsx`
- Output: `media/index.html`, `media/assets/index.js`, `media/assets/index.css`
**Scripts**:
- `npm run build` - Build both
- `npm run build:ext` - Extension only
- `npm run build:webview` - Webview only
- `npm run watch` - Watch mode (both)
## Python SDK & CLI
### Package Structure
**Location**: `packages/python-sdk/`
**Core Modules**:
- `storage_v4.py` - V4 file I/O with multi-environment support
- `storage_v3.py` - V3 file I/O (deprecated)
- `deployment_tracker.py` - Database-backed deployment tracking
- `cli.py` - Click-based CLI routing layer
**Provider Architecture** (`providers/`):
- `base/` - Provider contracts (models, operations, SQL generation, execution)
- `unity/` - Unity Catalog implementation
- `models.py` - Pydantic models
- `operations.py` - Operation types (29 operations)
- `sql_generator.py` - SQL DDL generation with catalog mapping
- `state_reducer.py` - State reducer
- `provider.py` - Provider implementation
- `auth.py` - Databricks authentication helpers
- `executor.py` - SQL execution via Databricks API
- `registry.py` - Provider registry
**Command Modules** (`commands/`):
- `apply.py` - Apply SQL to environment with deployment tracking and auto-rollback
- `rollback.py` - Rollback failed/partial deployments (partial or complete)
- `snapshot_rebase.py` - Rebase snapshots after Git rebase
- `sql.py` - Generate SQL migrations
- `validate.py` - Validate project files and detect stale snapshots
- `diff.py` - Compare snapshots and generate diffs
- `deployment.py` - Manual deployment recording
### CLI Commands
```bash
# Generate SQL migration (with environment-specific catalog mapping)
schemax sql [--output FILE] [--target ENV]
# Apply SQL to environment with deployment tracking
schemax apply --target ENV --profile PROFILE --warehouse-id WAREHOUSE_ID [--sql FILE] [--dry-run] [--no-interaction] [--auto-rollback]
# Rollback a failed/partial deployment
schemax rollback --deployment DEPLOYMENT_ID --partial --target ENV --profile PROFILE --warehouse-id WAREHOUSE_ID [--dry-run]
# Rollback to a previous snapshot (complete rollback)
schemax rollback --to-snapshot VERSION --target ENV --profile PROFILE --warehouse-id WAREHOUSE_ID [--dry-run]
# Validate schema files and detect stale snapshots
schemax validate [workspace_path]
# Create a snapshot from current changelog
schemax snapshot create --name "Snapshot name" [--version v0.2.0] [--comment "Description"] [--tags tag1]
# Validate snapshots after Git rebase
schemax snapshot validate
# Rebase a stale snapshot onto new base
schemax snapshot rebase VERSION
# Compare snapshots
schemax diff --from-version V1 --to-version V2 [--target ENV]
# Record deployment manually
schemax record-deployment --target ENV [--version VERSION] [--mark-deployed]
```
### Python API
```python
from pathlib import Path
from schemax.core.storage import load_current_state, read_project, get_environment_config
from schemax.providers.unity.sql_generator import UnitySQLGenerator
# Load schema
state, changelog, provider = load_current_state(Path.cwd())
# Get environment config
project = read_project(Path.cwd())
env_config = get_environment_config(project, "dev")
# Build catalog mapping
catalog_mapping = {"__implicit__": env_config["topLevelName"]}
# Generate environment-specific SQL
generator = UnitySQLGenerator(state, catalog_mapping)
sql = generator.generate_sql(changelog["ops"])
```
### Deployment Tracking
**Database-backed tracking** in `{catalog}.schemax` schema:
Tables:
- `deployments` - Main deployment records
- `deployment_ops` - Individual operation tracking
**Local tracking** in `project.json` → `deployments` array
**Execution Flow** (`schemax apply`):
1. Authenticate with Databricks
2. Execute SQL statements (creates catalog if needed)
3. Create tracking schema in `{catalog}.schemax`
4. Record deployment to database
5. Track individual operations
6. Save deployment record to local `project.json`
### Code Formatting
**Python**: Uses Black with 100 character line length
```bash
cd packages/python-sdk
black src/ --line-length 100
```
**Configuration** (`pyproject.toml`):
```toml
[tool.black]
line-length = 100
target-version = ['py39', 'py310', 'py311', 'py312']
```
## Operation Types (Complete List - 50+ Unity Catalog Operations)
**Catalog Operations** (4):
- `add_catalog` - payload: `{catalogId, name, managedLocationName?}`
- `rename_catalog` - payload: `{newName}`
- `update_catalog` - payload: `{managedLocationName?}` - Update catalog properties (e.g., managed location)
- `drop_catalog` - payload: `{}`
**Schema Operations** (4):
- `add_schema` - payload: `{schemaId, name, catalogId, managedLocationName?}`
- `rename_schema` - payload: `{newName}`
- `update_schema` - payload: `{managedLocationName?}` - Update schema properties (e.g., managed location)
- `drop_schema` - payload: `{}`
**Table Operations** (6):
- `add_table` - payload: `{tableId, name, schemaId, format, external?, externalLocationName?, path?, partitionColumns?, clusterColumns?, managedLocationName?}`
- `rename_table` - payload: `{newName}`
- `drop_table` - payload: `{}`
- `set_table_comment` - payload: `{tableId, comment}`
- `set_table_property` - payload: `{tableId, key, value}`
- `unset_table_property` - payload: `{tableId, key}`
**Column Operations** (7):
- `add_column` - payload: `{tableId, colId, name, type, nullable, comment?}`
- `rename_column` - payload: `{tableId, colId, newName}`
- `drop_column` - payload: `{tableId, colId}`
- `reorder_columns` - payload: `{tableId, order: string[]}`
- `change_column_type` - payload: `{tableId, colId, newType}`
- `set_nullable` - payload: `{tableId, colId, nullable}`
- `set_column_comment` - payload: `{tableId, colId, comment}`
**Column Tag Operations** (2):
- `set_column_tag` - payload: `{tableId, colId, tagName, tagValue}`
- `unset_column_tag` - payload: `{tableId, colId, tagName}`
**Constraint Operations** (2):
- `add_constraint` - payload: `{tableId, constraintId, type, name?, columns, ...typeSpecificFields}`
- `drop_constraint` - payload: `{tableId, constraintId}`
**Row Filter Operations** (3):
- `add_row_filter` - payload: `{tableId, filterId, name, udfExpression, enabled?, description?}`
- `update_row_filter` - payload: `{tableId, filterId, name?, udfExpression?, enabled?, description?}`
- `remove_row_filter` - payload: `{tableId, filterId}`
**Column Mask Operations** (3):
- `add_column_mask` - payload: `{tableId, maskId, columnId, name, maskFunction, enabled?, description?}`
- `update_column_mask` - payload: `{tableId, maskId, name?, maskFunction?, enabled?, description?}`
- `remove_column_mask` - payload: `{tableId, maskId}`
## Implementation Status
### ✅ Completed Features (v0.2.0)
**Core Functionality**:
- ✅ Visual schema designer (VS Code extension)
- ✅ Snapshot-based versioning
- ✅ Operation log architecture
- ✅ All 50+ Unity Catalog operation types (incl. volumes, functions, materialized views)
- ✅ Inline column editing
- ✅ Context-aware UI elements
- ✅ Implicit catalog mode for single-catalog projects
**Multi-Environment Support (V4)**:
- ✅ Project schema v4 with rich environment configurations
- ✅ Environment-specific catalog mapping (logical → physical)
- Fixed: Catalog name mapping now correctly applies during SQL generation
- `__implicit__` and logical names resolve to physical names per environment
- ✅ `dev`, `test`, `prod` environment templates
- ✅ Per-environment settings (allowDrift, requireSnapshot, autoCreateCatalog, etc.)
- ✅ Environment-specific SQL generation with resolved names
- ✅ Custom environment wizard with presets
- ✅ Project-level managed locations (for catalog/schema MANAGED LOCATION)
- ✅ Project-level external locations (for external tables)
- ✅ Environment-specific location path resolution
**Data Governance & Storage**:
- ✅ Column tags (key-value metadata)
- ✅ Table constraints (PRIMARY KEY, FOREIGN KEY, CHECK)
- ✅ Row filters (row-level security)
- ✅ Column masks (data masking)
- ✅ Table properties (TBLPROPERTIES)
- ✅ External tables with named external locations
- ✅ Managed locations for catalogs and schemas (physical isolation)
- ✅ Partitioning (PARTITIONED BY)
- ✅ Liquid Clustering (CLUSTER BY)
**SQL Generation**:
- ✅ TypeScript implementation (VS Code)
- ✅ Python implementation (SDK/CLI)
- ✅ Idempotent DDL statements
- ✅ All 50+ Unity Catalog operations supported (catalogs, schemas, tables, views, volumes, functions, materialized views, columns, constraints, grants, etc.)
- ✅ Environment-specific catalog name mapping (fixed: id_name_map rebuild)
- ✅ SQL dependency ordering (catalog → schema → table → operations)
- ✅ SQL file export with environment suffix
- ✅ Unified operation batching (catalogs, schemas, tables)
- ✅ CREATE + UPDATE squashing optimization (single CREATE statement)
- ✅ External location path resolution per environment
**Databricks Integration**:
- ✅ `schemax apply` command for executing SQL
- ✅ Databricks CLI profile authentication
- ✅ SQL Statement Execution API integration
- ✅ Fail-fast execution with error handling
- ✅ Terraform-like preview with confirmation
- ✅ Dry-run mode and no-interaction mode
**Deployment Tracking**:
- ✅ Database-backed tracking in `{catalog}.schemax` schema
- ✅ `deployments` and `deployment_ops` tables
- ✅ Local tracking in `project.json`
- ✅ Deployment status tracking (success/failed/partial)
- ✅ Individual operation tracking
- ✅ Execution time and error logging
**Rollback & Recovery** (NEW):
- ✅ Partial rollback (revert successful operations from failed deployment)
- ✅ Complete rollback (rollback to previous snapshot)
- ✅ Auto-rollback option in `schemax apply --auto-rollback`
- ✅ Safety validation (SAFE, RISKY, DESTRUCTIVE levels)
- ✅ Rollback uses state_differ for accurate reverse operations
- ✅ Database query for latest deployment (source of truth)
- ✅ Deployment status: `success`, `failed`, `partial` (0 statements = failed)
- ✅ Idempotent rollback (checks database state to prevent redundant operations)
- ✅ SQL preview in rollback (matches apply command UX)
**Snapshot Management** (NEW):
- ✅ Snapshot creation via CLI with optional manual version override
- ✅ Snapshot validation (detect stale snapshots after Git rebase)
- ✅ Snapshot rebase (unpack, replay on new base, conflict detection)
- ✅ Conflict detection and logging for manual UI resolution
- ✅ Smart changelog management during rebase conflicts
- ✅ Semantic versioning utilities (MAJOR.MINOR.PATCH)
- ✅ `schemax snapshot create`, `validate`, and `rebase` commands
**CLI Improvements** (NEW):
- ✅ Interactive snapshot prompts in `schemax apply` (with --no-interaction flag)
- ✅ Improved SQL preview (per-statement display, pagination)
- ✅ `schemax rollback` command (--partial and --to-snapshot options)
- ✅ `schemax diff` command for snapshot comparison
- ✅ Consistent `--target` flag across all commands
**UI Improvements** (NEW):
- ✅ Conflict indicators in VS Code extension
- ✅ Stale snapshot warnings in UI
- ✅ Manual refresh button with loading spinner
- ✅ File system watchers for auto-reload (conflicts, snapshots, project.json)
- ✅ Codicon icons for theme consistency (settings, refresh, add, edit, delete buttons)
- ✅ Real-time UI updates via `FileSystemWatcher`
**Code Organization** (NEW):
- ✅ `core/` package for infrastructure (storage, deployment, version)
- ✅ Absolute imports (PEP 8 compliant) - 82 conversions
- ✅ Removed version suffix from storage.py
- ✅ Clean separation: core (infrastructure) vs providers vs commands
**Python SDK & CLI**:
- ✅ Provider-based architecture (Unity Catalog)
- ✅ Modular command structure (`commands/` folder)
- ✅ CLI commands: `apply`, `rollback`, `sql`, `validate`, `diff`, `record-deployment`, `snapshot validate`, `snapshot rebase`
- ✅ Python API for custom scripts
- ✅ Databricks authentication helpers
- ✅ Ruff formatting (100 char line length)
- ✅ Ruff linting with auto-fix
**Testing**:
- ✅ 240 passing pytest tests (unit + integration)
- ⏭️ 11 tests skipped (features in development)
- ✅ Test coverage: v4 storage, catalog mapping, auth, executor, rollback, snapshot rebase
- ✅ SQLGlot validation for generated SQL
- ✅ OperationBuilder pattern for test utilities
- ✅ Smoke tests (extension build, SDK install, CLI validation)
**Infrastructure**:
- ✅ Monorepo structure
- ✅ CI/CD workflows (GitHub Actions)
- ✅ Comprehensive documentation
- ✅ Quality checks pipeline (formatting, linting, tests)
- ✅ Examples and templates
### ⏭️ Future Enhancements (Not Yet Implemented)
**Databricks Integration**:
- Schema import from Databricks
- Drift detection and reconciliation
- Databricks Asset Bundle (DAB) generation
- Multi-table transaction support
**Testing**:
- Real integration tests against Databricks workspace
- End-to-end tests for `schemax apply`
- Performance tests for large schemas
- Concurrency tests
**Advanced Features**:
- Visual diff viewer
- Template library
- Multi-catalog project support
- Constraint validation UI
- Multi-user collaboration
- Schema versioning with git integration
**Tooling**:
- VS Code Marketplace publication
- PyPI package publication
- Homebrew formula
- Docker images
## Documentation Structure
**Clean, focused documentation** - no redundant files!
**Root Level**:
- `README.md` - Project overview & quick start
- `TESTING.md` - Testing guide
- `CONTRIBUTING.md` - Contributing guidelines (with code formatting standards)
**docs/ Directory**:
- `README.md` - Documentation index & navigation
- `QUICKSTART.md` - Complete getting started guide
- `ARCHITECTURE.md` - Technical design & concepts
- `DEVELOPMENT.md` - Development guide
**Package Documentation**:
- `packages/vscode-extension/README.md` - Extension-specific
- `packages/vscode-extension/CHANGELOG.md` - Version history
- `packages/python-sdk/README.md` - SDK & CLI reference
**Examples**:
- `examples/basic-schema/` - Sample project
- `examples/github-actions/` - CI/CD templates
- `examples/python-scripts/` - SDK usage examples
## Coding Guidelines
### General Principles
1. **Logging**: Always use `outputChannel.appendLine()` in extension, never `console.log()`
2. **File Structure**: All schemax files in `.schemax/` folder
3. **Immutability**: Never mutate state directly, always create new objects
4. **Op IDs**: Always generate UUIDs for new ops: `id: \`op_${uuidv4()}\``
5. **Validation**: TypeScript (Zod) and Python (Pydantic) for all data models
6. **Error Handling**: Catch errors, log details, show user-friendly messages
7. **Free-form Input**: Allow SQL expressions freely (no restrictive dropdowns)
8. **Modal Dialogs**: Use custom React modals (webview is sandboxed)
9. **Type Safety**: TypeScript strict mode, Python type hints
10. **State Management**: All mutations via Zustand → emit ops → apply → update UI
### TypeScript
**Standards**:
- Use TypeScript strict mode
- Avoid `any` types
- 2 spaces indentation
- Single quotes for strings
- Max line length: 100 characters
- Semicolons required
**Naming**:
- `camelCase` for variables and functions
- `PascalCase` for types, interfaces, and classes
- `UPPER_CASE` for constants
**Example**:
```typescript
// ✅ Good
interface TableOptions {
format: 'delta' | 'iceberg';
properties?: Record<string, string>;
}
export async function createTable(
name: string,
options: TableOptions
): Promise<Table> {
try {
const table = await tableService.create(name, options);
outputChannel.appendLine(`[schemax] Created table: ${name}`);
return table;
} catch (error) {
outputChannel.appendLine(`[schemax] ERROR: ${error}`);
throw new Error(`Failed to create table: ${error}`);
}
}
```
### Python
**Standards**:
- Use Ruff formatter (100 char line length)
- Type hints for all function signatures (REQUIRED - see below)
- Use Pydantic models for data structures
- Follow PEP 8
- Docstrings for public APIs
**Type Annotations (REQUIRED)**:
ALL function and method definitions MUST include complete type annotations:
```python
# ✅ GOOD - Complete type annotations
def process_data(name: str, count: int, options: Optional[Dict[str, Any]] = None) -> List[str]:
"""Process data and return results"""
return []
def __init__(self, config: Config) -> None:
"""Initialize with config"""
self.config = config
# ❌ BAD - Missing type annotations
def process_data(name, count, options=None):
return []
def __init__(self, config):
self.config = config
```
**Type Annotation Rules**:
1. ✅ ALL parameters must have type hints (except `self` and `cls`)
2. ✅ Return type must be specified (use `-> None` for void functions)
3. ✅ Use `Optional[Type]` for parameters with `None` default
4. ✅ Use `List`, `Dict`, `Tuple` from `typing` module (or `list`, `dict` for Python 3.9+)
5. ✅ Use `Any` sparingly - prefer specific types
6. ✅ Complex types: Use `Union`, `Literal`, `TypeVar` as needed
**More Examples**:
```python
from typing import Any, Dict, Generator, List, Optional, Tuple, Union
# Simple function
def add(a: int, b: int) -> int:
return a + b
# Optional parameters
def create_user(name: str, email: Optional[str] = None) -> User:
return User(name=name, email=email)
# Complex types
def process_records(
data: List[Dict[str, Any]],
filters: Optional[Dict[str, Union[str, int]]] = None
) -> Tuple[List[Record], int]:
return [], 0
# Generator functions
def iter_items(data: List[str]) -> Generator[str, None, None]:
for item in data:
yield item
# Pydantic models
def validate_config(config: Dict[str, Any]) -> Config:
return Config(**config)
# Protocol/Interface
def get_executor(config: ExecutionConfig) -> SQLExecutor:
return UnitySQLExecutor(config)
```
**Enforcement**:
- Pre-commit hooks check with mypy
- VS Code/Cursor shows errors inline
- CI/CD blocks PRs with missing type annotations
**Naming**:
- `snake_case` for variables, functions, and methods
- `PascalCase` for classes
- `UPPER_CASE` for constants
**Formatting**:
```bash
# Format code before committing
cd packages/python-sdk
black src/ --line-length 100
```
**Example**:
```python
# ✅ Good
from typing import List
from pydantic import BaseModel
class Table(BaseModel):
id: str
name: str
columns: List[Column] = []
def create_table(name: str, schema_id: str) -> Table:
"""Create a new table in the specified schema.
Args:
name: Table name
schema_id: Parent schema ID
Returns:
Table: Created table object
Raises:
ValueError: If name is invalid
"""
if not name:
raise ValueError("Table name cannot be empty")
return Table(id=f"table_{uuid4().hex[:8]}", name=name)
```
### Documentation
**When to Update**:
- Feature added → Update relevant docs + README
- Architecture changed → Update `docs/ARCHITECTURE.md`
- Build process changed → Update `docs/DEVELOPMENT.md`
- New test → Update `TESTING.md`
**Best Practices**:
- ✅ Keep single source of truth per topic
- ✅ Use clear, concise language
- ✅ Include code examples
- ✅ Add cross-references
- ❌ Don't create duplicate documentation
- ❌ Don't create redundant status/summary files
## Local Development Workflow
### Before Every Commit/PR
**Always run the complete quality checks**:
```bash
# Run all checks (formatting, linting, tests, smoke tests)
./devops/run-checks.sh
```
This script runs:
1. ✅ Python code formatting check (Black, 100 char line length)
2. ✅ Python linting (Ruff)
3. ✅ Python SDK tests (pytest - 138 passing, 12 skipped)
4. ✅ Smoke tests (extension build, SDK install, CLI validation)
**Exit code 0** = All checks passed, ready to commit
**Exit code 1** = One or more checks failed, fix before committing
---
### Quick Commands Reference
**Python SDK Testing**:
```bash
cd packages/python-sdk
# Run all tests (fast)
pytest tests/ -q
# Run with verbose output
pytest tests/ -v
# Run specific test file
pytest tests/unit/test_sql_generator.py -v
# Run specific test
pytest tests/unit/test_sql_generator.py::TestCatalogSQL::test_add_catalog -xvs
# Run with coverage
pytest tests/ --cov=src/schemax --cov-report=term-missing
# Run with coverage HTML report
pytest tests/ --cov=src/schemax --cov-report=html
open htmlcov/index.html
```
**Python Formatting & Linting**:
```bash
cd packages/python-sdk
# Check formatting (Black)
black src/ tests/ --check --line-length 100
# Fix formatting (Black)
black src/ tests/ --line-length 100
# Or use Ruff format (faster, recommended)
ruff format src/ tests/
# Check linting
ruff check src/ tests/
# Fix linting issues
ruff check src/ tests/ --fix
# Fix with unsafe fixes (removes unused variables, etc.)
ruff check src/ tests/ --fix --unsafe-fixes
```
**VS Code Extension Testing**:
```bash
cd packages/vscode-extension
# Build extension