duckrun 0.2.9.dev0__tar.gz → 0.2.9.dev1__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: duckrun
3
- Version: 0.2.9.dev0
3
+ Version: 0.2.9.dev1
4
4
  Summary: Lakehouse task runner powered by DuckDB for Microsoft Fabric
5
5
  Author: mim
6
6
  License: MIT
@@ -696,6 +696,45 @@ class Duckrun:
696
696
  print(f"❌ Error creating lakehouse '{lakehouse_name}': {e}")
697
697
  return False
698
698
 
699
+ def deploy(self, bim_url: str, dataset_name: Optional[str] = None,
700
+ wait_seconds: int = 5) -> int:
701
+ """
702
+ Deploy a semantic model from a BIM file using DirectLake mode.
703
+
704
+ Args:
705
+ bim_url: URL to the BIM file (e.g., GitHub raw URL)
706
+ dataset_name: Name for the semantic model (default: lakehouse_schema)
707
+ wait_seconds: Seconds to wait for permission propagation (default: 5)
708
+
709
+ Returns:
710
+ 1 for success, 0 for failure
711
+
712
+ Examples:
713
+ dr = Duckrun.connect("My Workspace/My Lakehouse.lakehouse/dbo")
714
+
715
+ # Deploy with auto-generated name
716
+ dr.deploy("https://raw.githubusercontent.com/.../model.bim")
717
+
718
+ # Deploy with custom name
719
+ dr.deploy("https://raw.githubusercontent.com/.../model.bim",
720
+ dataset_name="Sales Model")
721
+ """
722
+ from .semantic_model import deploy_semantic_model
723
+
724
+ # Auto-generate dataset name if not provided
725
+ if dataset_name is None:
726
+ dataset_name = f"{self.lakehouse_name}_{self.schema}"
727
+
728
+ # Call the deployment function (DirectLake only)
729
+ return deploy_semantic_model(
730
+ workspace_name=self.workspace,
731
+ lakehouse_name=self.lakehouse_name,
732
+ schema_name=self.schema,
733
+ dataset_name=dataset_name,
734
+ bim_url=bim_url,
735
+ wait_seconds=wait_seconds
736
+ )
737
+
699
738
  def _get_workspace_id_by_name(self, token: str, workspace_name: str) -> Optional[str]:
700
739
  """Helper method to get workspace ID from name"""
701
740
  try:
@@ -0,0 +1,367 @@
1
+ """
2
+ Semantic Model Deployer - DirectLake mode for Fabric Lakehouses
3
+ Uses duckrun's authentication. Works anywhere duckrun works.
4
+ """
5
+
6
+ import requests
7
+ import json
8
+ import time
9
+ import base64
10
+
11
+
12
+ class FabricRestClient:
13
+ """Fabric REST API client using duckrun's authentication."""
14
+
15
+ def __init__(self):
16
+ self.base_url = "https://api.fabric.microsoft.com"
17
+ self.token = None
18
+ self._get_token()
19
+
20
+ def _get_token(self):
21
+ """Get Fabric API token using duckrun's auth module"""
22
+ from duckrun.auth import get_fabric_api_token
23
+ self.token = get_fabric_api_token()
24
+ if not self.token:
25
+ raise Exception("Failed to get Fabric API token")
26
+
27
+ def _get_headers(self):
28
+ return {
29
+ "Authorization": f"Bearer {self.token}",
30
+ "Content-Type": "application/json"
31
+ }
32
+
33
+ def get(self, endpoint: str):
34
+ url = f"{self.base_url}{endpoint}"
35
+ response = requests.get(url, headers=self._get_headers())
36
+ response.raise_for_status()
37
+ return response
38
+
39
+ def post(self, endpoint: str, json: dict = None):
40
+ url = f"{self.base_url}{endpoint}"
41
+ response = requests.post(url, headers=self._get_headers(), json=json)
42
+ response.raise_for_status()
43
+ return response
44
+
45
+
46
+ def get_workspace_id(workspace_name, client):
47
+ """Get workspace ID by name"""
48
+ response = client.get("/v1/workspaces")
49
+ workspaces = response.json().get('value', [])
50
+
51
+ workspace_match = next((ws for ws in workspaces if ws.get('displayName') == workspace_name), None)
52
+ if not workspace_match:
53
+ raise ValueError(f"Workspace '{workspace_name}' not found")
54
+
55
+ workspace_id = workspace_match['id']
56
+ print(f"✓ Found workspace: {workspace_name}")
57
+ return workspace_id
58
+
59
+
60
+ def get_lakehouse_id(lakehouse_name, workspace_id, client):
61
+ """Get lakehouse ID by name"""
62
+ response = client.get(f"/v1/workspaces/{workspace_id}/lakehouses")
63
+ items = response.json().get('value', [])
64
+
65
+ lakehouse_match = next((item for item in items if item.get('displayName') == lakehouse_name), None)
66
+ if not lakehouse_match:
67
+ raise ValueError(f"Lakehouse '{lakehouse_name}' not found")
68
+
69
+ lakehouse_id = lakehouse_match['id']
70
+ print(f"✓ Found lakehouse: {lakehouse_name}")
71
+ return lakehouse_id
72
+
73
+
74
+ def get_dataset_id(dataset_name, workspace_id, client):
75
+ """Get dataset ID by name"""
76
+ response = client.get(f"/v1/workspaces/{workspace_id}/semanticModels")
77
+ items = response.json().get('value', [])
78
+
79
+ dataset_match = next((item for item in items if item.get('displayName') == dataset_name), None)
80
+ if not dataset_match:
81
+ raise ValueError(f"Dataset '{dataset_name}' not found")
82
+
83
+ return dataset_match['id']
84
+
85
+
86
+ def check_dataset_exists(dataset_name, workspace_id, client):
87
+ """Check if dataset already exists"""
88
+ try:
89
+ get_dataset_id(dataset_name, workspace_id, client)
90
+ print(f"⚠️ Dataset '{dataset_name}' already exists")
91
+ return True
92
+ except:
93
+ print(f"✓ Dataset name '{dataset_name}' is available")
94
+ return False
95
+
96
+
97
+ def refresh_dataset(dataset_name, workspace_id, client):
98
+ """Refresh a dataset and monitor progress"""
99
+ dataset_id = get_dataset_id(dataset_name, workspace_id, client)
100
+
101
+ payload = {
102
+ "type": "full",
103
+ "commitMode": "transactional",
104
+ "maxParallelism": 10,
105
+ "retryCount": 2,
106
+ "objects": []
107
+ }
108
+
109
+ response = client.post(
110
+ f"/v1/workspaces/{workspace_id}/semanticModels/{dataset_id}/refreshes",
111
+ json=payload
112
+ )
113
+
114
+ if response.status_code in [200, 202]:
115
+ print(f"✓ Refresh initiated")
116
+
117
+ refresh_id = response.json().get('id')
118
+ if refresh_id:
119
+ print(" Monitoring refresh progress...")
120
+ max_attempts = 60
121
+ for attempt in range(max_attempts):
122
+ time.sleep(5)
123
+
124
+ status_response = client.get(
125
+ f"/v1/workspaces/{workspace_id}/semanticModels/{dataset_id}/refreshes/{refresh_id}"
126
+ )
127
+ status = status_response.json().get('status')
128
+
129
+ if status == 'Completed':
130
+ print(f"✓ Refresh completed successfully")
131
+ return
132
+ elif status == 'Failed':
133
+ error = status_response.json().get('error', {})
134
+ raise Exception(f"Refresh failed: {error.get('message', 'Unknown error')}")
135
+ elif status == 'Cancelled':
136
+ raise Exception("Refresh was cancelled")
137
+
138
+ if attempt % 6 == 0:
139
+ print(f" Status: {status}...")
140
+
141
+ raise Exception(f"Refresh timed out")
142
+
143
+
144
+ def download_bim_from_github(url):
145
+ """Download BIM file from URL"""
146
+ print(f"Downloading BIM file...")
147
+ response = requests.get(url)
148
+ response.raise_for_status()
149
+ bim_content = response.json()
150
+ print(f"✓ BIM file downloaded")
151
+ print(f" - Tables: {len(bim_content.get('model', {}).get('tables', []))}")
152
+ print(f" - Relationships: {len(bim_content.get('model', {}).get('relationships', []))}")
153
+ return bim_content
154
+
155
+
156
+ def update_bim_for_directlake(bim_content, workspace_id, lakehouse_id, schema_name):
157
+ """Update BIM file for DirectLake mode"""
158
+
159
+ new_url = f"https://onelake.dfs.fabric.microsoft.com/{workspace_id}/{lakehouse_id}"
160
+ expression_name = None
161
+
162
+ # Update or create DirectLake expression
163
+ if 'model' in bim_content and 'expressions' in bim_content['model']:
164
+ for expr in bim_content['model']['expressions']:
165
+ if 'DirectLake' in expr['name'] or expr.get('kind') == 'm':
166
+ expression_name = expr['name']
167
+ expr['expression'] = [
168
+ "let",
169
+ f" Source = AzureStorage.DataLake(\"{new_url}\", [HierarchicalNavigation=true])",
170
+ "in",
171
+ " Source"
172
+ ]
173
+ break
174
+
175
+ if not expression_name:
176
+ expression_name = f"DirectLake - {schema_name}"
177
+ if 'expressions' not in bim_content['model']:
178
+ bim_content['model']['expressions'] = []
179
+
180
+ bim_content['model']['expressions'].append({
181
+ "name": expression_name,
182
+ "kind": "m",
183
+ "expression": [
184
+ "let",
185
+ f" Source = AzureStorage.DataLake(\"{new_url}\", [HierarchicalNavigation=true])",
186
+ "in",
187
+ " Source"
188
+ ],
189
+ "lineageTag": f"directlake-{schema_name}-source"
190
+ })
191
+
192
+ # Update table partitions for DirectLake
193
+ if 'tables' in bim_content['model']:
194
+ for table in bim_content['model']['tables']:
195
+ if 'partitions' in table:
196
+ for partition in table['partitions']:
197
+ if 'source' in partition:
198
+ partition['mode'] = 'directLake'
199
+ partition['source'] = {
200
+ "type": "entity",
201
+ "entityName": partition['source'].get('entityName', table['name']),
202
+ "expressionSource": expression_name,
203
+ "schemaName": schema_name
204
+ }
205
+
206
+ print(f"✓ Updated BIM for DirectLake")
207
+ print(f" - OneLake URL: {new_url}")
208
+ print(f" - Schema: {schema_name}")
209
+
210
+ return bim_content
211
+
212
+
213
+ def create_dataset_from_bim(dataset_name, bim_content, workspace_id, client):
214
+ """Create semantic model from BIM using Fabric REST API"""
215
+ # Convert to base64
216
+ bim_json = json.dumps(bim_content, indent=2)
217
+ bim_base64 = base64.b64encode(bim_json.encode('utf-8')).decode('utf-8')
218
+
219
+ pbism_content = {"version": "1.0"}
220
+ pbism_json = json.dumps(pbism_content)
221
+ pbism_base64 = base64.b64encode(pbism_json.encode('utf-8')).decode('utf-8')
222
+
223
+ payload = {
224
+ "displayName": dataset_name,
225
+ "definition": {
226
+ "parts": [
227
+ {
228
+ "path": "model.bim",
229
+ "payload": bim_base64,
230
+ "payloadType": "InlineBase64"
231
+ },
232
+ {
233
+ "path": "definition.pbism",
234
+ "payload": pbism_base64,
235
+ "payloadType": "InlineBase64"
236
+ }
237
+ ]
238
+ }
239
+ }
240
+
241
+ response = client.post(
242
+ f"/v1/workspaces/{workspace_id}/semanticModels",
243
+ json=payload
244
+ )
245
+
246
+ print(f"✓ Semantic model created")
247
+
248
+ # Handle long-running operation
249
+ if response.status_code == 202:
250
+ operation_id = response.headers.get('x-ms-operation-id')
251
+ print(f" Waiting for operation to complete...")
252
+
253
+ max_attempts = 30
254
+ for attempt in range(max_attempts):
255
+ time.sleep(2)
256
+ status_response = client.get(f"/v1/operations/{operation_id}")
257
+ status = status_response.json().get('status')
258
+
259
+ if status == 'Succeeded':
260
+ print(f"✓ Operation completed")
261
+ break
262
+ elif status == 'Failed':
263
+ error = status_response.json().get('error', {})
264
+ raise Exception(f"Operation failed: {error.get('message')}")
265
+ elif attempt == max_attempts - 1:
266
+ raise Exception(f"Operation timed out")
267
+
268
+
269
+ def deploy_semantic_model(workspace_name, lakehouse_name, schema_name, dataset_name,
270
+ bim_url, wait_seconds=5):
271
+ """
272
+ Deploy a semantic model using DirectLake mode.
273
+
274
+ Args:
275
+ workspace_name: Name of the target workspace
276
+ lakehouse_name: Name of the lakehouse
277
+ schema_name: Schema name (e.g., 'dbo', 'staging')
278
+ dataset_name: Name for the semantic model
279
+ bim_url: URL to the BIM file
280
+ wait_seconds: Seconds to wait before refresh (default: 5)
281
+
282
+ Returns:
283
+ 1 for success, 0 for failure
284
+
285
+ Examples:
286
+ dr = Duckrun.connect("My Workspace/My Lakehouse.lakehouse/dbo")
287
+ dr.deploy("https://raw.githubusercontent.com/.../model.bim")
288
+ """
289
+ print("=" * 70)
290
+ print("Semantic Model Deployment (DirectLake)")
291
+ print("=" * 70)
292
+
293
+ client = FabricRestClient()
294
+
295
+ try:
296
+ # Step 1: Get workspace ID
297
+ print("\n[Step 1/6] Getting workspace information...")
298
+ workspace_id = get_workspace_id(workspace_name, client)
299
+
300
+ # Step 2: Check if dataset exists
301
+ print(f"\n[Step 2/6] Checking if dataset '{dataset_name}' exists...")
302
+ dataset_exists = check_dataset_exists(dataset_name, workspace_id, client)
303
+
304
+ if dataset_exists:
305
+ print(f"\n✓ Dataset exists - refreshing...")
306
+
307
+ if wait_seconds > 0:
308
+ print(f" Waiting {wait_seconds} seconds...")
309
+ time.sleep(wait_seconds)
310
+
311
+ print("\n[Step 6/6] Refreshing semantic model...")
312
+ refresh_dataset(dataset_name, workspace_id, client)
313
+
314
+ print("\n" + "=" * 70)
315
+ print("🎉 Refresh Completed!")
316
+ print("=" * 70)
317
+ print(f"Dataset: {dataset_name}")
318
+ print("=" * 70)
319
+ return 1
320
+
321
+ # Step 3: Get lakehouse ID
322
+ print(f"\n[Step 3/6] Finding lakehouse...")
323
+ lakehouse_id = get_lakehouse_id(lakehouse_name, workspace_id, client)
324
+
325
+ # Step 4: Download and update BIM
326
+ print("\n[Step 4/6] Downloading and configuring BIM file...")
327
+ bim_content = download_bim_from_github(bim_url)
328
+
329
+ modified_bim = update_bim_for_directlake(bim_content, workspace_id, lakehouse_id, schema_name)
330
+ modified_bim['name'] = dataset_name
331
+ modified_bim['id'] = dataset_name
332
+
333
+ # Step 5: Deploy
334
+ print("\n[Step 5/6] Deploying semantic model...")
335
+ create_dataset_from_bim(dataset_name, modified_bim, workspace_id, client)
336
+
337
+ if wait_seconds > 0:
338
+ print(f" Waiting {wait_seconds} seconds for permissions...")
339
+ time.sleep(wait_seconds)
340
+
341
+ # Step 6: Refresh
342
+ print("\n[Step 6/6] Refreshing semantic model...")
343
+ refresh_dataset(dataset_name, workspace_id, client)
344
+
345
+ print("\n" + "=" * 70)
346
+ print("🎉 Deployment Completed!")
347
+ print("=" * 70)
348
+ print(f"Dataset: {dataset_name}")
349
+ print(f"Workspace: {workspace_name}")
350
+ print(f"Lakehouse: {lakehouse_name}")
351
+ print(f"Schema: {schema_name}")
352
+ print("=" * 70)
353
+
354
+ return 1
355
+
356
+ except Exception as e:
357
+ print("\n" + "=" * 70)
358
+ print("❌ Deployment Failed")
359
+ print("=" * 70)
360
+ print(f"Error: {str(e)}")
361
+ print("\n💡 Troubleshooting:")
362
+ print(f" - Verify workspace '{workspace_name}' exists")
363
+ print(f" - Verify lakehouse '{lakehouse_name}' exists")
364
+ print(f" - Ensure tables exist in '{schema_name}' schema")
365
+ print(f" - Check tables are in Delta format")
366
+ print("=" * 70)
367
+ return 0
@@ -147,7 +147,20 @@ def get_stats(duckrun_instance, source: str):
147
147
 
148
148
  try:
149
149
  dt = DeltaTable(table_path)
150
- xx = dt.get_add_actions(flatten=True).to_pydict()
150
+ add_actions = dt.get_add_actions(flatten=True)
151
+
152
+ # Convert to dict - compatible with both old and new deltalake versions
153
+ # Try to_pydict() first (old versions), fall back to to_pylist() (new versions)
154
+ try:
155
+ xx = add_actions.to_pydict()
156
+ except AttributeError:
157
+ # New version with arro3: use to_pylist() and convert to dict of lists
158
+ records = add_actions.to_pylist()
159
+ if records:
160
+ # Convert list of dicts to dict of lists
161
+ xx = {key: [record[key] for record in records] for key in records[0].keys()}
162
+ else:
163
+ xx = {}
151
164
 
152
165
  # Check if VORDER exists
153
166
  vorder = 'tags.VORDER' in xx.keys()
@@ -1,18 +1,36 @@
1
1
  """
2
2
  Delta Lake writer functionality for duckrun - Spark-style write API
3
3
  """
4
- from deltalake import DeltaTable, write_deltalake
4
+ from deltalake import DeltaTable, write_deltalake, __version__ as deltalake_version
5
5
 
6
6
 
7
7
  # Row Group configuration for optimal Delta Lake performance
8
8
  RG = 8_000_000
9
9
 
10
+ # Check deltalake version once at module load
11
+ # Version 0.18.x and 0.19.x support engine parameter and row group optimization
12
+ # Version 0.20+ removed these features (rust only, no row groups)
13
+ _DELTALAKE_VERSION = tuple(map(int, deltalake_version.split('.')[:2]))
14
+ _IS_OLD_DELTALAKE = _DELTALAKE_VERSION < (0, 20)
15
+
10
16
 
11
17
  def _build_write_deltalake_args(path, df, mode, schema_mode=None, partition_by=None):
12
18
  """
13
- Build arguments for write_deltalake based on requirements:
14
- - If schema_mode='merge': use rust engine (no row group params)
15
- - Otherwise: use pyarrow engine with row group optimization (if supported)
19
+ Build arguments for write_deltalake based on requirements and version:
20
+
21
+ deltalake 0.18.2 - 0.19.x:
22
+ - Has 'engine' parameter (defaults to 'pyarrow')
23
+ - Has max_rows_per_file/max_rows_per_group/min_rows_per_group for optimization
24
+ - When mergeSchema=True: must set schema_mode='merge' + engine='rust', NO row group params
25
+ - When mergeSchema=False: use row group params, DON'T set engine (pyarrow is default)
26
+
27
+ deltalake 0.20+:
28
+ - Does NOT have 'engine' parameter (everything is rust, pyarrow deprecated)
29
+ - Does NOT have max_rows_per_file (row group optimization removed)
30
+ - When mergeSchema=True: must set schema_mode='merge'
31
+ - When mergeSchema=False: just write normally (no special params)
32
+
33
+ Uses version detection for simpler logic.
16
34
  """
17
35
  args = {
18
36
  'table_or_uri': path,
@@ -24,23 +42,24 @@ def _build_write_deltalake_args(path, df, mode, schema_mode=None, partition_by=N
24
42
  if partition_by:
25
43
  args['partition_by'] = partition_by
26
44
 
27
- # Engine selection based on schema_mode
28
45
  if schema_mode == 'merge':
29
- # Use rust engine for schema merging (no row group params supported)
46
+ # Schema merging mode - must explicitly set schema_mode='merge'
30
47
  args['schema_mode'] = 'merge'
31
- args['engine'] = 'rust'
32
- else:
33
- # Try to use pyarrow engine with row group optimization
34
- # Check if row group parameters are supported by inspecting function signature
35
- import inspect
36
- sig = inspect.signature(write_deltalake)
37
48
 
38
- if 'max_rows_per_file' in sig.parameters:
39
- # Older deltalake version - use row group optimization
49
+ if _IS_OLD_DELTALAKE:
50
+ # deltalake 0.18.2-0.19.x: must also set engine='rust' for schema merging
51
+ # Do NOT use row group params (they conflict with rust engine)
52
+ args['engine'] = 'rust'
53
+ # For version 0.20+: just schema_mode='merge' is enough, rust is default
54
+ else:
55
+ # Normal write mode (no schema merging)
56
+ if _IS_OLD_DELTALAKE:
57
+ # deltalake 0.18.2-0.19.x: use row group optimization
58
+ # DON'T set engine parameter - pyarrow is the default and works with row groups
40
59
  args['max_rows_per_file'] = RG
41
60
  args['max_rows_per_group'] = RG
42
61
  args['min_rows_per_group'] = RG
43
- # For newer versions, just use default parameters
62
+ # For version 0.20+: no optimization available (rust by default, no row group params supported)
44
63
 
45
64
  return args
46
65
 
@@ -113,7 +132,18 @@ class DeltaWriter:
113
132
  partition_by=self._partition_by
114
133
  )
115
134
 
116
- engine_info = f" (engine=rust, schema_mode=merge)" if self._schema_mode == 'merge' else " (engine=pyarrow)"
135
+ # Prepare info message based on version and settings
136
+ if self._schema_mode == 'merge':
137
+ if _IS_OLD_DELTALAKE:
138
+ engine_info = " (engine=rust, schema_mode=merge)"
139
+ else:
140
+ engine_info = " (schema_mode=merge, rust by default)"
141
+ else:
142
+ if _IS_OLD_DELTALAKE:
143
+ engine_info = " (engine=pyarrow, optimized row groups)"
144
+ else:
145
+ engine_info = " (engine=rust by default)"
146
+
117
147
  partition_info = f" partitioned by {self._partition_by}" if self._partition_by else ""
118
148
  print(f"Writing to Delta table: {schema}.{table} (mode={self._mode}){engine_info}{partition_info}")
119
149
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: duckrun
3
- Version: 0.2.9.dev0
3
+ Version: 0.2.9.dev1
4
4
  Summary: Lakehouse task runner powered by DuckDB for Microsoft Fabric
5
5
  Author: mim
6
6
  License: MIT
@@ -7,6 +7,7 @@ duckrun/core.py
7
7
  duckrun/files.py
8
8
  duckrun/lakehouse.py
9
9
  duckrun/runner.py
10
+ duckrun/semantic_model.py
10
11
  duckrun/stats.py
11
12
  duckrun/writer.py
12
13
  duckrun.egg-info/PKG-INFO
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "duckrun"
7
- version = "0.2.9.dev0"
7
+ version = "0.2.9.dev1"
8
8
  description = "Lakehouse task runner powered by DuckDB for Microsoft Fabric"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
File without changes
File without changes
File without changes