-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathclient.py
More file actions
258 lines (211 loc) · 8.62 KB
/
client.py
File metadata and controls
258 lines (211 loc) · 8.62 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
from __future__ import annotations
from typing import Any, Dict, Optional, Union, List, Iterable
from azure.core.credentials import TokenCredential
from .auth import AuthManager
from .config import DataverseConfig
from .odata import ODataClient
class DataverseClient:
"""High-level client for Dataverse operations.
This client exposes a simple, stable surface for:
- OData CRUD: create, get, update, delete records
- SQL (read-only): execute T-SQL via Dataverse Custom API (no ODBC/TDS driver)
- Table metadata: create, inspect, and delete simple custom tables
The client owns authentication (Azure Identity) and configuration, and delegates
requests to an internal OData client responsible for HTTP calls and URL shaping.
Parameters
----------
base_url : str
Your Dataverse environment URL, for example:
``"https://<org>.crm.dynamics.com"``. A trailing slash is ignored.
credential : azure.core.credentials.TokenCredential | None, optional
Any Azure Identity credential. If omitted, the SDK uses
``DefaultAzureCredential`` internally.
config : DataverseConfig | None, optional
Optional configuration (language code, SQL API name, HTTP timeouts/retries).
Raises
------
ValueError
If ``base_url`` is missing or empty after trimming.
"""
def __init__(
self,
base_url: str,
credential: Optional[TokenCredential] = None,
config: Optional[DataverseConfig] = None,
) -> None:
self.auth = AuthManager(credential)
self._base_url = (base_url or "").rstrip("/")
if not self._base_url:
raise ValueError("base_url is required.")
self._config = config or DataverseConfig.from_env()
self._odata: Optional[ODataClient] = None
def _get_odata(self) -> ODataClient:
"""Get or create the internal OData client instance.
Returns
-------
ODataClient
The lazily-initialized low-level client used to perform requests.
"""
if self._odata is None:
self._odata = ODataClient(self.auth, self._base_url, self._config)
return self._odata
# CRUD
def create(self, entity: str, record_data: Union[Dict[str, Any], List[Dict[str, Any]]]) -> Union[Dict[str, Any], List[str]]:
"""Create one or more records.
Behaviour:
- Single: returns the created record (dict) using Prefer: return=representation.
- Multiple: uses bound CreateMultiple action and returns list[str] of created record IDs.
Parameters
----------
entity : str
Entity set name (plural logical name), e.g., ``"accounts"``.
record_data : dict | list[dict]
Single record payload or list of records for multi-create.
Returns
-------
dict | list[str]
Dict for single create, list of GUID strings for multi-create.
Raises
------
requests.exceptions.HTTPError
If the request fails.
TypeError
If ``record_data`` is not a dict or list of dict.
"""
return self._get_odata().create(entity, record_data)
def update(self, entity: str, record_id: str, record_data: dict) -> dict:
"""Update a record and return its full representation.
Parameters
----------
entity : str
Entity set name (plural logical name).
record_id : str
The record GUID (with or without parentheses).
record_data : dict
Field-value pairs to update.
Returns
-------
dict
The updated record payload.
"""
return self._get_odata().update(entity, record_id, record_data)
def delete(self, entity: str, record_id: str) -> None:
"""Delete a record by ID.
Parameters
----------
entity : str
Entity set name (plural logical name).
record_id : str
The record GUID (with or without parentheses).
"""
self._get_odata().delete(entity, record_id)
def get(self, entity: str, record_id: str) -> dict:
"""Fetch a record by ID.
Parameters
----------
entity : str
Entity set name (plural logical name).
record_id : str
The record GUID (with or without parentheses).
Returns
-------
dict
The record JSON payload.
"""
return self._get_odata().get(entity, record_id)
def get_multiple(
self,
entity: str,
select: Optional[List[str]] = None,
filter: Optional[str] = None,
orderby: Optional[List[str]] = None,
top: Optional[int] = None,
expand: Optional[List[str]] = None,
page_size: Optional[int] = None,
) -> Iterable[List[Dict[str, Any]]]:
"""Fetch multiple records page-by-page as a generator.
Yields a list of records per page, following @odata.nextLink until exhausted.
Parameters mirror standard OData query options.
"""
return self._get_odata().get_multiple(
entity,
select=select,
filter=filter,
orderby=orderby,
top=top,
expand=expand,
page_size=page_size,
)
# SQL via Custom API
def query_sql(self, tsql: str):
"""Execute a read-only SQL query via the configured Custom API.
Parameters
----------
tsql : str
A SELECT-only T-SQL statement (e.g., ``"SELECT TOP 3 * FROM account"``).
Returns
-------
list[dict]
Rows as a list of dictionaries.
"""
return self._get_odata().query_sql(tsql)
# Table metadata helpers
def get_table_info(self, tablename: str) -> Optional[Dict[str, Any]]:
"""Get basic metadata for a custom table if it exists.
Parameters
----------
tablename : str
Friendly name (e.g., ``"SampleItem"``) or full schema name
(e.g., ``"new_SampleItem"``).
Returns
-------
dict | None
Dict with keys like ``entity_schema``, ``entity_logical_name``,
``entity_set_name``, and ``metadata_id``; ``None`` if not found.
"""
return self._get_odata().get_table_info(tablename)
def create_table(self, tablename: str, schema: Dict[str, Union[str, Dict[str, Any]]]) -> Dict[str, Any]:
"""Create a simple custom table.
Parameters
----------
tablename : str
Friendly name (``"SampleItem"``) or a full schema name (``"new_SampleItem"``).
schema : dict[str, str | dict]
Column definitions mapping logical names to types or lookup configurations.
For standard columns, use string type names:
``"name": "string", "count": "int", "price": "decimal"``
Supported types: ``string``, ``int``, ``decimal``, ``float``, ``datetime``, ``bool``.
For lookup fields, use a dictionary with configuration options:
``"project": {"lookup": "new_project", "display_name": "Project", "cascade_delete": "Cascade"}``
Lookup field options:
- ``lookup``: Target table (required)
- ``display_name``: Display name for the field (optional)
- ``description``: Description for the field (optional)
- ``required_level``: "None", "Recommended", or "ApplicationRequired" (default: "None")
- ``relationship_name``: Custom name for the relationship (optional)
- ``relationship_behavior``: "UseLabel", "UseCollectionName", "DoNotDisplay" (default: "UseLabel")
- ``cascade_delete``: "Cascade", "RemoveLink", "Restrict" (default: "RemoveLink")
Returns
-------
dict
Metadata summary including ``entity_schema``, ``entity_set_name``,
``entity_logical_name``, ``metadata_id``, and ``columns_created``.
"""
return self._get_odata().create_table(tablename, schema)
def delete_table(self, tablename: str) -> None:
"""Delete a custom table by name.
Parameters
----------
tablename : str
Friendly name (``"SampleItem"``) or a full schema name (``"new_SampleItem"``).
"""
self._get_odata().delete_table(tablename)
def list_tables(self) -> list[str]:
"""List all custom tables in the Dataverse environment.
Returns
-------
list[str]
A list of table names.
"""
return self._get_odata().list_tables()
__all__ = ["DataverseClient"]