Skip to content

Semantic Models

bind_semantic_model_to_gateway(workspace, semantic_model, gateway, *, datasource_ids=None)

Binds the specified dataset from the specified workspace to the specified gateway, optionally with a given set of data source IDs. If you don't supply a specific data source ID, the dataset will be bound to the first matching data source in the gateway.

Parameters:

Name Type Description Default
workspace str

The workspace name or ID.

required
semantic_model str

The semantic model name or ID.

required
gateway str

The gateway name or ID.

required
datasource_ids list[str]

List of data source IDs to bind. If not provided, the first matching data source will be used.

None

Returns:

Type Description
None

None

Examples:

bind_semantic_model_to_gateway(
    workspace="AdventureWorks",
    semantic_model="SalesAnalysis",
    gateway="my_gateway",
    datasource_ids=["id1", "id2", "id3"]
)
Source code in src/pyfabricops/helpers/semantic_models.py
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
def bind_semantic_model_to_gateway(
    workspace: str,
    semantic_model: str,
    gateway: str,
    *,
    datasource_ids: list[str] = None,
) -> None:
    """
    Binds the specified dataset from the specified workspace to the specified gateway, optionally with a given set of data source IDs. If you don't supply a specific data source ID, the dataset will be bound to the first matching data source in the gateway.

    Args:
        workspace (str): The workspace name or ID.
        semantic_model (str): The semantic model name or ID.
        gateway (str): The gateway name or ID.
        datasource_ids (list[str], optional): List of data source IDs to bind. If not provided, the first matching data source will be used.

    Returns:
        None

    Examples:
        ```python
        bind_semantic_model_to_gateway(
            workspace="AdventureWorks",
            semantic_model="SalesAnalysis",
            gateway="my_gateway",
            datasource_ids=["id1", "id2", "id3"]
        )
        ```
    """
    workspace_id = resolve_workspace(workspace)
    if not workspace_id:
        logger.error(f'Workspace "{workspace}" not found.')
        return None

    semantic_model_id = resolve_semantic_model(workspace_id, semantic_model)
    if not semantic_model_id:
        logger.error(
            f'Semantic model "{semantic_model}" not found in workspace "{workspace}".'
        )
        return None

    gateway_id = resolve_gateway(gateway)
    if not gateway_id:
        logger.error(f'Gateway "{gateway}" not found.')
        return None

    payload = {'gatewayObjectId': gateway}
    if datasource_ids:
        payload['datasourceObjectIds'] = datasource_ids

    response = _base_api(
        endpoint=f'/groups/{workspace}/datasets/{semantic_model_id}/Default.BindToGateway',
        method='post',
        payload=payload,
        audience='powerbi',
    )

    if response.status_code == 200:
        logger.success(
            f'Successfully bound semantic model "{semantic_model}" to gateway "{gateway}".'
        )
        return None
    else:
        logger.error(
            f'Failed to bind semantic model "{semantic_model}" to gateway "{gateway}".'
        )
        return None

deploy_all_semantic_models(workspace, path, start_path=None)

Deploy all semantic models to workspace.

Parameters:

Name Type Description Default
workspace str

The name or ID of the workspace.

required
path str

The path to the semantic models.

required
start_path Optional[str]

The starting path for folder creation.

None
Source code in src/pyfabricops/helpers/semantic_models.py
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
def deploy_all_semantic_models(
    workspace: str,
    path: str,
    start_path: Optional[str] = None,
) -> None:
    """
    Deploy all semantic models to workspace.

    Args:
        workspace (str): The name or ID of the workspace.
        path (str): The path to the semantic models.
        start_path (Optional[str]): The starting path for folder creation.
    """
    workspace_id = resolve_workspace(workspace)
    if workspace_id is None:
        return None

    semantic_models_paths = list_paths_of_type(path, 'SemanticModel')

    for path_ in semantic_models_paths:

        display_name = extract_display_name_from_platform(path_)
        if display_name is None:
            return None

        semantic_model_id = resolve_semantic_model(workspace_id, display_name)

        folder_path_string = extract_middle_path(path_, start_path=start_path)
        folder_id = create_folders_from_path_string(
            workspace_id, folder_path_string
        )

        item_definition = pack_item_definition(path_)

        if semantic_model_id is None:
            create_semantic_model(
                workspace_id,
                display_name=display_name,
                item_definition=item_definition,
                folder=folder_id,
                df=False,
            )

        else:
            update_semantic_model_definition(
                workspace_id,
                semantic_model_id,
                item_definition=item_definition,
                df=False,
            )

    logger.success(
        f'All semantic models were deployed to workspace "{workspace}" successfully.'
    )
    return None

deploy_semantic_model(workspace, path, start_path=None, description=None, df=True)

Deploy a semantic model to workspace.

Parameters:

Name Type Description Default
workspace str

The name or ID of the workspace.

required
path str

The path to the semantic model.

required
start_path Optional[str]

The starting path for folder creation.

None
description Optional[str]

Description for the semantic model.

None
df Optional[bool]

If True, returns a DataFrame, otherwise returns a dictionary.

True

Returns:

Type Description
Union[DataFrame, Dict[str, Any], None]

The deployed semantic model or None if deployment fails.

Source code in src/pyfabricops/helpers/semantic_models.py
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
@df
def deploy_semantic_model(
    workspace: str,
    path: str,
    start_path: Optional[str] = None,
    description: Optional[str] = None,
    df: Optional[bool] = True,
) -> Union[DataFrame, Dict[str, Any], None]:
    """
    Deploy a semantic model to workspace.

    Args:
        workspace (str): The name or ID of the workspace.
        path (str): The path to the semantic model.
        start_path (Optional[str]): The starting path for folder creation.
        description (Optional[str]): Description for the semantic model.
        df (Optional[bool]): If True, returns a DataFrame, otherwise returns a dictionary.

    Returns:
        (Union[DataFrame, Dict[str, Any], None]): The deployed semantic model or None if deployment fails.
    """
    workspace_id = resolve_workspace(workspace)
    if workspace_id is None:
        return None

    display_name = extract_display_name_from_platform(path)
    if display_name is None:
        return None

    semantic_model_id = resolve_semantic_model(workspace_id, display_name)

    folder_path_string = extract_middle_path(path, start_path=start_path)
    folder_id = create_folders_from_path_string(
        workspace_id, folder_path_string
    )

    item_definition = pack_item_definition(path)

    if semantic_model_id is None:
        return create_semantic_model(
            workspace_id,
            display_name=display_name,
            item_definition=item_definition,
            description=description,
            folder=folder_id,
            df=False,
        )

    else:
        return update_semantic_model_definition(
            workspace_id,
            semantic_model_id,
            item_definition=item_definition,
            df=False,
        )

execute_queries(workspace, semantic_model, query, *, include_nulls=True, impersonated_user_name=None, df=True)

Execute DAX queries against a semantic model.

Parameters:

Name Type Description Default
workspace str

The workspace name or ID.

required
semantic_model str

The semantic model name or ID.

required
query str

The DAX query to execute.

required
df bool

Whether to return the results as a DataFrame.

True

Returns:

Type Description
Union[DataFrame, List[Dict[str, Any]], None]

Union[DataFrame, List[Dict[str, Any]], None]: The details of the refresh operation or None if not found.

Source code in src/pyfabricops/helpers/semantic_models.py
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
def execute_queries(
    workspace: str,
    semantic_model: str,
    query: str,
    *,
    include_nulls: bool = True,
    impersonated_user_name: Optional[str] = None,
    df: Optional[bool] = True,
) -> Union[DataFrame, List[Dict[str, Any]], None]:
    """
    Execute DAX queries against a semantic model.

    Args:
        workspace (str): The workspace name or ID.
        semantic_model (str): The semantic model name or ID.
        query (str): The DAX query to execute.
        df (bool, optional): Whether to return the results as a DataFrame.

    Returns:
        Union[DataFrame, List[Dict[str, Any]], None]: The details of the refresh operation or None if not found.
    """
    workspace_id = resolve_workspace(workspace)
    if not workspace_id:
        logger.error(f'Workspace "{workspace}" not found.')
        return None

    semantic_model_id = resolve_semantic_model(workspace_id, semantic_model)
    if not semantic_model_id:
        logger.error(
            f'Semantic model "{semantic_model}" not found in workspace "{workspace}".'
        )
        return None

    payload = {
        'queries': [{'query': query}],
        'serializerSettings': {'includeNulls': include_nulls},
    }

    if impersonated_user_name:
        payload['impersonatedUserName'] = impersonated_user_name

    response = api_request(
        endpoint=f'/groups/{workspace_id}/datasets/{semantic_model_id}/executeQueries',
        method='POST',
        audience='powerbi',
        payload=payload,
    )
    return response

export_all_semantic_models(workspace, path)

Export a semantic model to path.

Parameters:

Name Type Description Default
workspace str

The name or ID of the workspace.

required
path Union[str, Path]

The path to export to.

required
Source code in src/pyfabricops/helpers/semantic_models.py
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
def export_all_semantic_models(
    workspace: str,
    path: Union[str, Path],
) -> None:
    """
    Export a semantic model to path.

    Args:
        workspace (str): The name or ID of the workspace.
        path (Union[str, Path]): The path to export to.
    """
    workspace_id = resolve_workspace(workspace)
    if workspace_id is None:
        return None

    items = list_valid_semantic_models(workspace_id, df=False)
    if items is None:
        return None

    for item in items:
        try:
            folder_path = resolve_folder_from_id_to_path(
                workspace_id, item['folderId']
            )
        except:
            logger.info(
                f'{item["displayName"]}.SemanticModel is not inside a folder.'
            )
            folder_path = None

        if folder_path is None:
            item_path = Path(path) / (item['displayName'] + '.SemanticModel')
        else:
            item_path = (
                Path(path)
                / folder_path
                / (item['displayName'] + '.SemanticModel')
            )
        os.makedirs(item_path, exist_ok=True)

        definition = get_semantic_model_definition(workspace_id, item['id'])
        if definition is None:
            return None

        unpack_item_definition(definition, item_path)

    logger.success(
        f'All semantic models were exported to {path} successfully.'
    )
    return None

export_semantic_model(workspace, semantic_model, path)

Export a semantic model to path.

Parameters:

Name Type Description Default
workspace str

The name or ID of the workspace.

required
semantic_model str

The name or ID of the semantic_model.

required
path Union[str, Path]

The path to export to.

required
Source code in src/pyfabricops/helpers/semantic_models.py
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
def export_semantic_model(
    workspace: str,
    semantic_model: str,
    path: Union[str, Path],
) -> None:
    """
    Export a semantic model to path.

    Args:
        workspace (str): The name or ID of the workspace.
        semantic_model (str): The name or ID of the semantic_model.
        path (Union[str, Path]): The path to export to.
    """
    workspace_id = resolve_workspace(workspace)
    if workspace_id is None:
        return None

    item = get_semantic_model(workspace_id, semantic_model, df=False)
    try:
        folder_path = resolve_folder_from_id_to_path(
            workspace_id, item['folderId']
        )
    except:
        logger.info(
            f'{item["displayName"]}.SemanticModel is not inside a folder.'
        )
        folder_path = None

    if folder_path is None:
        item_path = Path(path) / (item['displayName'] + '.SemanticModel')
    else:
        item_path = (
            Path(path) / folder_path / (item['displayName'] + '.SemanticModel')
        )
    os.makedirs(item_path, exist_ok=True)

    definition = get_semantic_model_definition(workspace_id, item['id'])
    if definition is None:
        return None

    unpack_item_definition(definition, item_path)

    logger.success(
        f'`{item["displayName"]}.SemanticModel` was exported to {item_path} successfully.'
    )
    return None

extract_tmdl_parameters_from_semantic_model(path)

Extract TMDL parameters from a specified semantic model in the local directory.

Parameters:

Name Type Description Default
path Union[str, Path]

The semantic model path.

required
Source code in src/pyfabricops/helpers/semantic_models.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def extract_tmdl_parameters_from_semantic_model(
    path: Union[str, Path]
) -> Dict[str, str]:
    """
    Extract TMDL parameters from a specified semantic model in the local directory.

    Args:
        path (Union[str, Path]): The semantic model path.
    """
    expressions_path = Path(path) / 'definition' / 'expressions.tmdl'
    if not expressions_path.exists():
        return None

    parameters = parse_tmdl_parameters(expressions_path)

    if parameters is None:
        return None

    return parameters

get_all_semantic_models_config(workspace)

Get semantic models config from a workspace.

Parameters:

Name Type Description Default
workspace str

The name or ID from the workspace.

required

Returns:

Type Description
Union[Dict[str, Any], None]

The dict config of all semantic models in the workspace

Source code in src/pyfabricops/helpers/semantic_models.py
 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
def get_all_semantic_models_config(
    workspace: str,
) -> Union[Dict[str, Any], None]:
    """
    Get semantic models config from a workspace.

    Args:
        workspace (str): The name or ID from the workspace.

    Returns:
        (Union[Dict[str, Any], None]): The dict config of all semantic models in the workspace
    """
    items = list_valid_semantic_models(workspace, df=False)

    if items is None:
        return None

    config = {}

    for item in items:

        item_data = get_semantic_model(workspace, item['id'], df=False)

        config[item['displayName']] = {
            'id': item['id'],
            'description': item.get('description', None),
            'folder_id': ''
            if item.get('folderId') is None or pd.isna(item.get('folderId'))
            else item['folderId'],
        }

    return config

get_semantic_model_config(workspace, semantic_model)

Get a specific semantic model config from a workspace.

Parameters:

Name Type Description Default
workspace str

The name or ID of the workspace.

required
semantic_model str

The name or ID of the semantic.

required

Returns:

Type Description
Union[Dict[str, Any], None]

The dict config from the semantic model

Source code in src/pyfabricops/helpers/semantic_models.py
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
def get_semantic_model_config(
    workspace: str, semantic_model: str
) -> Union[Dict[str, Any], None]:
    """
    Get a specific semantic model config from a workspace.

    Args:
        workspace (str): The name or ID of the workspace.
        semantic_model (str): The name or ID of the semantic.

    Returns:
        (Union[Dict[str, Any], None]): The dict config from the semantic model
    """
    item = semantic_model
    item_data = get_semantic_model(workspace, item, df=False)

    if item_data is None:
        return None

    else:
        config = {}
        config = config[item_data.get('displayName')] = {}

        config = {
            'id': item_data['id'],
            'description': item_data.get('description', None),
            'folder_id': ''
            if item_data.get('folderId') is None
            or pd.isna(item_data.get('folderId'))
            else item_data['folderId'],
        }

        return config

get_semantic_model_refresh_details(workspace, semantic_model, refresh_id, *, df=True)

Get the details of a specific refresh operation for a semantic model.

Parameters:

Name Type Description Default
workspace str

The workspace name or ID.

required
semantic_model str

The semantic model name or ID.

required
refresh_id str

The ID of the refresh operation.

required
df bool

Whether to return the results as a DataFrame.

True

Returns:

Type Description
Union[DataFrame, List[Dict[str, Any]], None]

Union[DataFrame, List[Dict[str, Any]], None]: The details of the refresh operation or None if not found.

Source code in src/pyfabricops/helpers/semantic_models.py
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
@df
def get_semantic_model_refresh_details(
    workspace: str,
    semantic_model: str,
    refresh_id: str,
    *,
    df: Optional[bool] = True,
) -> Union[DataFrame, List[Dict[str, Any]], None]:
    """
    Get the details of a specific refresh operation for a semantic model.

    Args:
        workspace (str): The workspace name or ID.
        semantic_model (str): The semantic model name or ID.
        refresh_id (str): The ID of the refresh operation.
        df (bool, optional): Whether to return the results as a DataFrame.

    Returns:
        Union[DataFrame, List[Dict[str, Any]], None]: The details of the refresh operation or None if not found.
    """
    workspace_id = resolve_workspace(workspace)
    if not workspace_id:
        logger.error(f'Workspace "{workspace}" not found.')
        return None

    semantic_model_id = resolve_semantic_model(workspace_id, semantic_model)
    if not semantic_model_id:
        logger.error(
            f'Semantic model "{semantic_model}" not found in workspace "{workspace}".'
        )
        return None

    response = api_request(
        endpoint=f'/groups/{workspace_id}/datasets/{semantic_model_id}/refreshes/{refresh_id}',
        audience='powerbi',
    )
    return response

get_semantic_model_refreshes(workspace, semantic_model, *, top=None, df=True)

Get the list of refresh operations for a semantic model.

Parameters:

Name Type Description Default
workspace str

The workspace name or ID.

required
semantic_model str

The semantic model name or ID.

required
top int

The maximum number of refresh operations to return.

None
df bool

Whether to return the results as a DataFrame.

True

Returns:

Type Description
Union[DataFrame, List[Dict[str, Any]], None]

Union[DataFrame, List[Dict[str, Any]], None]: The list of refresh operations or None if not found.

Source code in src/pyfabricops/helpers/semantic_models.py
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
@df
def get_semantic_model_refreshes(
    workspace: str,
    semantic_model: str,
    *,
    top: int = None,
    df: Optional[bool] = True,
) -> Union[DataFrame, List[Dict[str, Any]], None]:
    """
    Get the list of refresh operations for a semantic model.

    Args:
        workspace (str): The workspace name or ID.
        semantic_model (str): The semantic model name or ID.
        top (int, optional): The maximum number of refresh operations to return.
        df (bool, optional): Whether to return the results as a DataFrame.

    Returns:
        Union[DataFrame, List[Dict[str, Any]], None]: The list of refresh operations or None if not found.
    """
    workspace_id = resolve_workspace(workspace)
    if not workspace_id:
        logger.error(f'Workspace "{workspace}" not found.')
        return None

    semantic_model_id = resolve_semantic_model(workspace_id, semantic_model)
    if not semantic_model_id:
        logger.error(
            f'Semantic model "{semantic_model}" not found in workspace "{workspace}".'
        )
        return None

    params = {}
    if not top is None and top >= 1:
        params = {'$top': top}

    response = api_request(
        endpoint=f'/groups/{workspace_id}/datasets/{semantic_model_id}/refreshes',
        audience='powerbi',
        support_pagination=True,
        params=params,
    )
    return response

list_valid_semantic_models(workspace, df=True)

Generate a list of valid semantic_models of the workspace.

Parameters:

Name Type Description Default
workspace str

The name or ID from the workspace.

required

Returns:

Type Description
Union[Dict[str, Any], None]

The list of valids semantic_models of the workspace

Source code in src/pyfabricops/helpers/semantic_models.py
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
@df
def list_valid_semantic_models(
    workspace: str,
    df: Optional[bool] = True,
) -> Union[DataFrame, List[Dict[str, Any]], None]:
    """
    Generate a list of valid semantic_models of the workspace.

    Args:
        workspace (str): The name or ID from the workspace.

    Returns:
        (Union[Dict[str, Any], None]): The list of valids semantic_models of the workspace
    """
    workspace_id = resolve_workspace(workspace)

    # Retrivieng the list of semantic models
    items = list_semantic_models(workspace_id)
    if items is None:
        return None

    # Creating a excluded list of Staging, Lake and Warehouses default semantic models
    exclude_list = ['staging']

    lakehouses_df = list_valid_lakehouses(workspace_id)
    if lakehouses_df is not None:
        lakehouses_list = lakehouses_df['displayName'].tolist()
        exclude_list.extend(lakehouses_list)

    warehouses_df = list_valid_warehouses(workspace_id)
    if warehouses_df is not None:
        warehouses_list = warehouses_df['displayName'].tolist()
        exclude_list.extend(warehouses_list)

    # Create regex pattern to create multiple parts
    if exclude_list:
        exclude_pattern = '|'.join(exclude_list)
        filtered_items = items[
            ~items['displayName'].str.contains(
                exclude_pattern, case=False, na=False
            )
        ]
    else:
        filtered_items = items

    return filtered_items.to_dict(orient='records')

refresh_semantic_model(workspace, semantic_model, *, notify_option='NoNotification', apply_refresh_policy=None, commit_mode='Transactional', effective_date=None, max_parallelism=1, objects=None, retry_count=3, timeout='00:30:00', type='Full')

Refreshes the specified semantic model in the specified workspace.

Parameters:

Name Type Description Default
workspace str

The workspace name or ID.

required
semantic_model str

The semantic model name or ID.

required
notify_option Literal['MailOnCompletion', 'MailOnFailure', 'NoNotification']

Notification option for the refresh operation.

'NoNotification'
apply_refresh_policy bool

Whether to apply the refresh policy.

None
commit_mode Literal['PartialBatch', 'Transactional']

Commit mode for the refresh operation.

'Transactional'
effective_date str

Effective date for the refresh operation.

None
max_parallelism int

Maximum parallelism for the refresh operation.

1
objects list[dict[str, str]]

List of objects to refresh.

None
retry_count int

Number of retry attempts for the refresh operation.

3
timeout str

Timeout duration for the refresh operation.

'00:30:00'
type Literal['Automatic', 'Calculate', 'ClearValues', 'DataOnly', 'Defragment', 'Full']

Type of refresh operation.

'Full'

Returns:

Type Description
None

None

Examples:

refresh_semantic_model(
    workspace="AdventureWorks",
    semantic_model="SalesAnalysis",
    apply_refresh_policy=False,
    commit_mode="Transactional",
    effective_date="2023-01-01",
    max_parallelism=5,
    objects=[
        {
            "table": "FactSales",
            "partition": "2024"
        },
        {
            "table": "FactReturns",
            "partition": "2024"
        }
    ],
    retry_count=3,
    timeout="00:30:00",
    type="Full"
)
Source code in src/pyfabricops/helpers/semantic_models.py
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
def refresh_semantic_model(
    workspace: str,
    semantic_model: str,
    *,
    notify_option: Literal[
        'MailOnCompletion', 'MailOnFailure', 'NoNotification'
    ] = 'NoNotification',
    apply_refresh_policy: Union[bool, None] = None,
    commit_mode: Literal['PartialBatch', 'Transactional'] = 'Transactional',
    effective_date: str = None,
    max_parallelism: int = 1,
    objects: list[dict[str, str]] = None,
    retry_count: int = 3,
    timeout: str = '00:30:00',
    type: Literal[
        'Automatic',
        'Calculate',
        'ClearValues',
        'DataOnly',
        'Defragment',
        'Full',
    ] = 'Full',
) -> None:
    """
    Refreshes the specified semantic model in the specified workspace.

    Args:
        workspace (str): The workspace name or ID.
        semantic_model (str): The semantic model name or ID.
        notify_option (Literal['MailOnCompletion', 'MailOnFailure', 'NoNotification'], optional): Notification option for the refresh operation.
        apply_refresh_policy (bool, optional): Whether to apply the refresh policy.
        commit_mode (Literal['PartialBatch', 'Transactional'], optional): Commit mode for the refresh operation.
        effective_date (str, optional): Effective date for the refresh operation.
        max_parallelism (int, optional): Maximum parallelism for the refresh operation.
        objects (list[dict[str, str]], optional): List of objects to refresh.
        retry_count (int, optional): Number of retry attempts for the refresh operation.
        timeout (str, optional): Timeout duration for the refresh operation.
        type (Literal['Automatic', 'Calculate', 'ClearValues', 'DataOnly','Defragment', 'Full'], optional): Type of refresh operation.

    Returns:
        None

    Examples:
        ```python
        refresh_semantic_model(
            workspace="AdventureWorks",
            semantic_model="SalesAnalysis",
            apply_refresh_policy=False,
            commit_mode="Transactional",
            effective_date="2023-01-01",
            max_parallelism=5,
            objects=[
                {
                    "table": "FactSales",
                    "partition": "2024"
                },
                {
                    "table": "FactReturns",
                    "partition": "2024"
                }
            ],
            retry_count=3,
            timeout="00:30:00",
            type="Full"
        )
        ```
    """
    workspace_id = resolve_workspace(workspace)
    if not workspace_id:
        logger.error(f'Workspace "{workspace}" not found.')
        return None

    semantic_model_id = resolve_semantic_model(workspace_id, semantic_model)
    if not semantic_model_id:
        logger.error(
            f'Semantic model "{semantic_model}" not found in workspace "{workspace}".'
        )
        return None

    payload = {'notifyOption': notify_option}
    if apply_refresh_policy is not None:
        payload['applyRefreshPolicy'] = apply_refresh_policy
    if commit_mode:
        payload['commitMode'] = commit_mode
    if effective_date:
        payload['effectiveDate'] = effective_date
    if max_parallelism:
        payload['maxParallelism'] = max_parallelism
    if objects:
        payload['objects'] = objects
    if retry_count:
        payload['retryCount'] = retry_count
    if timeout:
        payload['timeout'] = timeout
    if type:
        payload['type'] = type

    response = _base_api(
        endpoint=f'/groups/{workspace_id}/datasets/{semantic_model_id}/refreshes',
        method='post',
        payload=payload,
        audience='powerbi',
    )

    if response.status_code == 202:
        logger.success('Refresh accepted successfully.')
    else:
        logger.error(f'Refresh failed: {response.error}')

replace_semantic_model_parameters_with_placeholders(path)

Replace parameter values with placeholders in semantic model expressions. Supports both Import and Direct Lake model syntaxes.

Parameters:

Name Type Description Default
path Union[str, Path]

The path to the semantic model.

required
Source code in src/pyfabricops/helpers/semantic_models.py
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
def replace_semantic_model_parameters_with_placeholders(
    path: Union[str, Path]
) -> None:
    """
    Replace parameter values with placeholders in semantic model expressions.
    Supports both Import and Direct Lake model syntaxes.

    Args:
        path (Union[str, Path]): The path to the semantic model.
    """
    # Read the current content of expressions.tmdl
    expressions_path = Path(path) / 'definition' / 'expressions.tmdl'

    if not expressions_path.exists():
        logger.warning(f'expressions.tmdl not found: {expressions_path}')
        return None

    try:
        with open(expressions_path, 'r', encoding='utf-8') as f:
            expressions = f.read()
    except Exception as e:
        logger.error(f'Error reading expressions.tmdl: {e}')
        return None

    semantic_model_parameters = extract_tmdl_parameters_from_semantic_model(
        path
    )
    if semantic_model_parameters is None:
        logger.warning(f'No parameters found in semantic model: {path}')
        return None

    # Replace the values with placeholders
    expressions_with_placeholders = expressions
    replacements_made = 0

    for parameter_name, actual_value in semantic_model_parameters.items():
        logger.debug(
            f'Processing parameter: {parameter_name} = "{actual_value}"'
        )

        # Pattern 1: Import model syntax - expression ParameterName = "Value"
        pattern1 = rf'(expression\s+{re.escape(parameter_name)}\s*=\s*")({re.escape(actual_value)})(")'
        replacement1 = (
            lambda m: f'{m.group(1)}#{{{parameter_name}}}#{m.group(3)}'
        )

        # Pattern 2: Direct Lake - Sql.Database("server", "database") - First parameter (server)
        pattern2 = (
            rf'(Sql\.Database\s*\(\s*")({re.escape(actual_value)})("\s*,)'
        )
        replacement2 = (
            lambda m: f'{m.group(1)}#{{{parameter_name}}}#{m.group(3)}'
        )

        # Pattern 3: Direct Lake - Sql.Database("server", "database") - Second parameter (database)
        pattern3 = rf'(Sql\.Database\s*\([^"]*"[^"]*"\s*,\s*")({re.escape(actual_value)})(")'
        replacement3 = (
            lambda m: f'{m.group(1)}#{{{parameter_name}}}#{m.group(3)}'
        )

        # Pattern 4: Generic parameter syntax - ParameterName = "Value" (without 'expression' keyword)
        pattern4 = rf'({re.escape(parameter_name)}\s*=\s*")({re.escape(actual_value)})(")'
        replacement4 = (
            lambda m: f'{m.group(1)}#{{{parameter_name}}}#{m.group(3)}'
        )

        # Pattern 5: Alternative syntax with single quotes
        pattern5 = rf"({re.escape(parameter_name)}\s*=\s*')({re.escape(actual_value)})(')"
        replacement5 = (
            lambda m: f'{m.group(1)}#{{{parameter_name}}}#{m.group(3)}'
        )

        # Pattern 6: Parameters starting with # (like #date, #datetime, etc.)
        pattern6 = rf'(expression\s+{re.escape(parameter_name)}\s*=\s*)({re.escape(actual_value)})'
        replacement6 = lambda m: f'{m.group(1)}#{{{parameter_name}}}#'

        # Try each pattern
        patterns = [
            (pattern1, replacement1, 'Import model (expression)'),
            (
                pattern2,
                replacement2,
                'Direct Lake (first parameter - server)',
            ),
            (
                pattern3,
                replacement3,
                'Direct Lake (second parameter - database)',
            ),
            (pattern4, replacement4, 'Generic parameter'),
            (pattern5, replacement5, 'Single quotes'),
            (
                pattern6,
                replacement6,
                'Hash functions (#date, #datetime, etc.)',
            ),
        ]

        pattern_found = False
        for pattern, replacement, description in patterns:
            if re.search(
                pattern,
                expressions_with_placeholders,
                re.IGNORECASE | re.DOTALL,
            ):
                old_content = expressions_with_placeholders
                expressions_with_placeholders = re.sub(
                    pattern,
                    replacement,
                    expressions_with_placeholders,
                    flags=re.IGNORECASE | re.DOTALL,
                )
                if old_content != expressions_with_placeholders:
                    logger.info(
                        f'Replaced {parameter_name} using {description} pattern'
                    )
                    replacements_made += 1
                    pattern_found = True
                    break

        if not pattern_found:
            logger.warning(
                f'No matching pattern found for parameter: {parameter_name}'
            )
            logger.debug(f'Looking for value: "{actual_value}"')

            # Log a snippet around potential matches for debugging
            if actual_value in expressions_with_placeholders:
                logger.debug(
                    f'Value found in file but no pattern matched. Context:'
                )
                lines = expressions_with_placeholders.split('\n')
                for i, line in enumerate(lines):
                    if actual_value in line:
                        start = max(0, i - 2)
                        end = min(len(lines), i + 3)
                        for j in range(start, end):
                            prefix = '>>> ' if j == i else '    '
                            logger.debug(f'{prefix}{j+1}: {lines[j]}')

    # Write back the result to file
    try:
        with open(expressions_path, 'w', encoding='utf-8') as f:
            f.write(expressions_with_placeholders)
        logger.success(
            f'Updated expressions.tmdl for: {path} ({replacements_made} replacements)'
        )
    except Exception as e:
        logger.error(f'Error writing expressions.tmdl: {e}')
    return None

replace_semantic_model_placeholders_with_parameters(path, parameters)

Replace placeholders with actual parameter values in semantic model expressions. Supports both Import and Direct Lake model syntaxes.

Parameters:

Name Type Description Default
path Union[str, Path]

The path to the semantic model.

required
parameters Dict[str, str]

A dictionary mapping parameter names to their values.

required
Source code in src/pyfabricops/helpers/semantic_models.py
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
def replace_semantic_model_placeholders_with_parameters(
    path: Union[str, Path], parameters: Dict[str, str]
) -> None:
    """
    Replace placeholders with actual parameter values in semantic model expressions.
    Supports both Import and Direct Lake model syntaxes.

    Args:
        path (Union[str, Path]): The path to the semantic model.
        parameters (Dict[str, str]): A dictionary mapping parameter names to their values.
    """
    # Read the current content of expressions.tmdl
    expressions_path = Path(path) / 'definition' / 'expressions.tmdl'

    if not os.path.exists(expressions_path):
        logger.warning(f'expressions.tmdl not found: {expressions_path}')
        return None

    try:
        with open(expressions_path, 'r', encoding='utf-8') as f:
            expressions = f.read()
    except Exception as e:
        logger.error(f'Error reading expressions.tmdl: {e}')
        return None

    # Replace placeholders with actual values
    expressions_with_values = expressions
    replacements_made = 0

    for parameter_name, actual_value in parameters.items():
        logger.debug(
            f'Processing parameter: {parameter_name} = "{actual_value}"'
        )

        # Create placeholder pattern: #{ParameterName}#
        placeholder = f'#{{{parameter_name}}}#'

        # Pattern 1: Import model syntax - expression ParameterName = "#{ParameterName}#"
        pattern1 = rf'(expression\s+{re.escape(parameter_name)}\s*=\s*")({re.escape(placeholder)})(")'
        replacement1 = lambda m: f'{m.group(1)}{actual_value}{m.group(3)}'

        # Pattern 2: Direct Lake - Sql.Database("#{ServerEndpoint}#", ...) - First parameter
        pattern2 = (
            rf'(Sql\.Database\s*\(\s*")({re.escape(placeholder)})("\s*,)'
        )
        replacement2 = lambda m: f'{m.group(1)}{actual_value}{m.group(3)}'

        # Pattern 3: Direct Lake - Sql.Database(..., "#{DatabaseId}#") - Second parameter
        pattern3 = rf'(Sql\.Database\s*\([^"]*"[^"]*"\s*,\s*")({re.escape(placeholder)})(")'
        replacement3 = lambda m: f'{m.group(1)}{actual_value}{m.group(3)}'

        # Pattern 4: Generic parameter syntax - ParameterName = "#{ParameterName}#"
        pattern4 = rf'({re.escape(parameter_name)}\s*=\s*")({re.escape(placeholder)})(")'
        replacement4 = lambda m: f'{m.group(1)}{actual_value}{m.group(3)}'

        # Pattern 5: Alternative syntax with single quotes
        pattern5 = rf"({re.escape(parameter_name)}\s*=\s*')({re.escape(actual_value)})(')"
        replacement5 = lambda m: f'{m.group(1)}{actual_value}{m.group(3)}'

        # Pattern 6: Parameters starting with # (like #date, #datetime, etc.) - for placeholders
        pattern6 = rf'(expression\s+{re.escape(parameter_name)}\s*=\s*)({re.escape(placeholder)})'
        replacement6 = lambda m: f'{m.group(1)}{actual_value}'

        # Try each pattern
        patterns = [
            (pattern1, replacement1, 'Import model (expression)'),
            (
                pattern2,
                replacement2,
                'Direct Lake (first parameter - server)',
            ),
            (
                pattern3,
                replacement3,
                'Direct Lake (second parameter - database)',
            ),
            (pattern4, replacement4, 'Generic parameter'),
            (pattern5, replacement5, 'Single quotes'),
            (
                pattern6,
                replacement6,
                'Hash functions (#date, #datetime, etc.)',
            ),
        ]

        pattern_found = False
        for pattern, replacement, description in patterns:
            if re.search(
                pattern, expressions_with_values, re.IGNORECASE | re.DOTALL
            ):
                old_content = expressions_with_values
                expressions_with_values = re.sub(
                    pattern,
                    replacement,
                    expressions_with_values,
                    flags=re.IGNORECASE | re.DOTALL,
                )
                if old_content != expressions_with_values:
                    logger.info(
                        f'Replaced placeholder {parameter_name} with value using {description} pattern'
                    )
                    replacements_made += 1
                    pattern_found = True
                    break

        if not pattern_found:
            logger.warning(
                f'No matching pattern found for placeholder: {parameter_name}'
            )
            logger.debug(f'Looking for placeholder: "{placeholder}"')

            # Log a snippet around potential matches for debugging
            if placeholder in expressions_with_values:
                logger.debug(
                    f'Placeholder found in file but no pattern matched. Context:'
                )
                lines = expressions_with_values.split('\n')
                for i, line in enumerate(lines):
                    if placeholder in line:
                        start = max(0, i - 2)
                        end = min(len(lines), i + 3)
                        for j in range(start, end):
                            prefix = '>>> ' if j == i else '    '
                            logger.debug(f'{prefix}{j+1}: {lines[j]}')

    # Write back the result to file
    try:
        with open(expressions_path, 'w', encoding='utf-8') as f:
            f.write(expressions_with_values)
        logger.success(
            f'Updated expressions.tmdl for: {path} ({replacements_made} replacements)'
        )
    except Exception as e:
        logger.error(f'Error writing expressions.tmdl: {e}')

    return None