geobox 2.1.0__py3-none-any.whl → 2.2.1__py3-none-any.whl

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.
Files changed (70) hide show
  1. geobox/__init__.py +61 -63
  2. geobox/aio/__init__.py +61 -63
  3. geobox/aio/api.py +491 -574
  4. geobox/aio/apikey.py +263 -263
  5. geobox/aio/attachment.py +341 -339
  6. geobox/aio/base.py +261 -262
  7. geobox/aio/basemap.py +196 -196
  8. geobox/aio/dashboard.py +340 -342
  9. geobox/aio/feature.py +35 -35
  10. geobox/aio/field.py +315 -321
  11. geobox/aio/file.py +72 -72
  12. geobox/aio/layout.py +340 -341
  13. geobox/aio/log.py +23 -23
  14. geobox/aio/map.py +1033 -1034
  15. geobox/aio/model3d.py +415 -415
  16. geobox/aio/mosaic.py +696 -696
  17. geobox/aio/plan.py +314 -314
  18. geobox/aio/query.py +693 -693
  19. geobox/aio/raster.py +88 -454
  20. geobox/aio/{analysis.py → raster_analysis.py} +153 -170
  21. geobox/aio/route.py +4 -4
  22. geobox/aio/scene.py +340 -342
  23. geobox/aio/settings.py +18 -18
  24. geobox/aio/task.py +404 -402
  25. geobox/aio/tile3d.py +337 -339
  26. geobox/aio/tileset.py +102 -103
  27. geobox/aio/usage.py +52 -51
  28. geobox/aio/user.py +506 -507
  29. geobox/aio/vector_tool.py +1968 -0
  30. geobox/aio/vectorlayer.py +316 -414
  31. geobox/aio/version.py +272 -273
  32. geobox/aio/view.py +1019 -983
  33. geobox/aio/workflow.py +340 -341
  34. geobox/api.py +14 -98
  35. geobox/apikey.py +262 -262
  36. geobox/attachment.py +336 -337
  37. geobox/base.py +384 -384
  38. geobox/basemap.py +194 -194
  39. geobox/dashboard.py +339 -341
  40. geobox/enums.py +31 -1
  41. geobox/feature.py +31 -10
  42. geobox/field.py +320 -320
  43. geobox/file.py +4 -4
  44. geobox/layout.py +339 -340
  45. geobox/log.py +4 -4
  46. geobox/map.py +1031 -1032
  47. geobox/model3d.py +410 -410
  48. geobox/mosaic.py +696 -696
  49. geobox/plan.py +313 -313
  50. geobox/query.py +691 -691
  51. geobox/raster.py +5 -368
  52. geobox/{analysis.py → raster_analysis.py} +108 -128
  53. geobox/scene.py +341 -342
  54. geobox/settings.py +194 -194
  55. geobox/task.py +399 -400
  56. geobox/tile3d.py +337 -338
  57. geobox/tileset.py +4 -4
  58. geobox/usage.py +3 -3
  59. geobox/user.py +503 -503
  60. geobox/vector_tool.py +1968 -0
  61. geobox/vectorlayer.py +5 -110
  62. geobox/version.py +272 -272
  63. geobox/view.py +981 -981
  64. geobox/workflow.py +338 -339
  65. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/METADATA +15 -1
  66. geobox-2.2.1.dist-info/RECORD +72 -0
  67. geobox-2.1.0.dist-info/RECORD +0 -70
  68. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/WHEEL +0 -0
  69. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/licenses/LICENSE +0 -0
  70. {geobox-2.1.0.dist-info → geobox-2.2.1.dist-info}/top_level.txt +0 -0
geobox/aio/query.py CHANGED
@@ -1,693 +1,693 @@
1
- from urllib.parse import urljoin
2
- from typing import Dict, List, TYPE_CHECKING, Union
3
-
4
- from ..utils import clean_data
5
- from .base import AsyncBase
6
- from .task import Task
7
- from ..enums import QueryResultType, QueryGeometryType, QueryParamType
8
-
9
- if TYPE_CHECKING:
10
- from . import AsyncGeoboxClient
11
- from .user import User
12
- from ..api import GeoboxClient as SyncGeoboxClient
13
- from ..query import Query as SyncQuery
14
-
15
-
16
- class Query(AsyncBase):
17
-
18
- BASE_ENDPOINT: str = 'queries/'
19
-
20
- def __init__(self,
21
- api: 'AsyncGeoboxClient',
22
- uuid: str = None,
23
- data: Dict = {}):
24
- """
25
- Constructs all the necessary attributes for the Query object.
26
-
27
- Args:
28
- api (AsyncGeoboxClient): The API instance.
29
- uuid (str): The UUID of the query.
30
- data (dict, optional): The data of the query.
31
- """
32
- self.result = {}
33
- self._system_query = False
34
- super().__init__(api, uuid=uuid, data=data)
35
-
36
-
37
- def _check_access(self) -> None:
38
- """
39
- Check if the query is a system query.
40
-
41
- Returns:
42
- None
43
-
44
- Raises:
45
- PermissionError: If the query is a read-only system query.
46
- """
47
- if self._system_query:
48
- raise PermissionError("Cannot modify system queries - they are read-only")
49
-
50
-
51
- @property
52
- def sql(self) -> str:
53
- """
54
- Get the SQL of the query.
55
-
56
- Returns:
57
- str: The SQL of the query.
58
-
59
- Example:
60
- >>> from geobox.aio import AsyncGeoboxClient
61
- >>> from geobox.aio.query import Query
62
- >>> async with AsyncGeoboxClient() as client:
63
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
64
- >>> query.sql
65
- 'SELECT * FROM some_layer'
66
- """
67
- return self.data['sql']
68
-
69
-
70
- @sql.setter
71
- def sql(self, value: str) -> None:
72
- """
73
- Set the SQL of the query.
74
-
75
- Args:
76
- value (str): The SQL of the query.
77
-
78
- Returns:
79
- None
80
-
81
- Example:
82
- >>> from geobox.aio import AsyncGeoboxClient
83
- >>> from geobox.aio.query import Query
84
- >>> async with AsyncGeoboxClient() as client:
85
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
86
- >>> query.sql = 'SELECT * FROM some_layer'
87
- >>> await query.save()
88
- """
89
- self.data['sql'] = value
90
-
91
-
92
- @property
93
- def params(self) -> List[Dict]:
94
- """
95
- Get the parameters of the query.
96
-
97
- Returns:
98
- List[Dict]: The parameters of the query.
99
-
100
- Example:
101
- >>> from geobox.aio import AsyncGeoboxClient
102
- >>> from geobox.aio.query import Query
103
- >>> async with AsyncGeoboxClient() as client:
104
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
105
- >>> query.params
106
- [{'name': 'layer', 'value': '12345678-1234-5678-1234-567812345678', 'type': 'Layer'}]
107
- """
108
- if not isinstance(self.data.get('params'), list):
109
- self.data['params'] = []
110
-
111
- return self.data['params']
112
-
113
-
114
- @params.setter
115
- def params(self, value: Dict) -> None:
116
- """
117
- Set the parameters of the query.
118
-
119
- Args:
120
- value (Dict): The parameters of the query.
121
-
122
- Returns:
123
- None
124
-
125
- Example:
126
- >>> from geobox.aio import AsyncGeoboxClient
127
- >>> from geobox.aio.query import Query
128
- >>> async with AsyncGeoboxClient() as client:
129
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
130
- >>> query.params = [{'name': 'layer', 'value': '12345678-1234-5678-1234-567812345678', 'type': 'Layer'}]
131
- >>> await query.save()
132
- """
133
- if not isinstance(self.data.get('params'), list):
134
- self.data['params'] = []
135
-
136
- self.data['params'] = value
137
-
138
-
139
- @classmethod
140
- async def get_queries(cls, api: 'AsyncGeoboxClient', **kwargs) -> Union[List['Query'], int]:
141
- """
142
- [async] Get Queries
143
-
144
- Args:
145
- api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
146
-
147
- Keyword Args:
148
- q (str): query filter based on OGC CQL standard. e.g. "field1 LIKE '%GIS%' AND created_at > '2021-01-01'"
149
- search (str): search term for keyword-based searching among search_fields or all textual fields if search_fields does not have value. NOTE: if q param is defined this param will be ignored.
150
- search_fields (str): comma separated list of fields for searching
151
- order_by (str): comma separated list of fields for sorting results [field1 A|D, field2 A|D, …]. e.g. name A, type D. NOTE: "A" denotes ascending order and "D" denotes descending order.
152
- return_count (bool): Whether to return total count. default is False.
153
- skip (int): Number of queries to skip. default is 0.
154
- limit(int): Maximum number of queries to return. default is 10.
155
- user_id (int): Specific user. privileges required.
156
- shared (bool): Whether to return shared queries. default is False.
157
-
158
- Returns:
159
- List[Query] | int: list of queries or the number of queries.
160
-
161
- Example:
162
- >>> from geobox.aio import AsyncGeoboxClient
163
- >>> from geobox.aio.query import Query
164
- >>> async with AsyncGeoboxClient() as client:
165
- >>> queries = await Query.get_queries(client)
166
- or
167
- >>> queries = await client.get_queries()
168
- """
169
- params = {
170
- 'f': 'json',
171
- 'q': kwargs.get('q'),
172
- 'search': kwargs.get('search'),
173
- 'search_field': kwargs.get('search_field'),
174
- 'order_by': kwargs.get('order_by'),
175
- 'return_count': kwargs.get('return_count', False),
176
- 'skip': kwargs.get('skip', 0),
177
- 'limit': kwargs.get('limit', 10),
178
- 'user_id': kwargs.get('user_id'),
179
- 'shared': kwargs.get('shared', False)
180
- }
181
- return await super()._get_list(api, cls.BASE_ENDPOINT, params, factory_func=lambda api, item: Query(api, item['uuid'], item))
182
-
183
-
184
- @classmethod
185
- async def create_query(cls, api: 'AsyncGeoboxClient', name: str, display_name: str = None, description:str = None, sql: str = None, params: List = None) -> 'Query':
186
- """
187
- [async] Creates a new query.
188
-
189
- Args:
190
- api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
191
- name (str): The name of the query.
192
- display_name (str, optional): The display name of the query.
193
- description (str, optional): The description of the query.
194
- sql (str, optional): The SQL statement for the query.
195
- params (list, optional): The parameters for the SQL statement.
196
-
197
- Returns:
198
- Query: The created query instance.
199
-
200
- Example:
201
- >>> from geobox.aio import AsyncGeoboxClient
202
- >>> from geobox.aio.query import Query
203
- >>> async with AsyncGeoboxClient() as client:
204
- >>> query = await Query.create_query(client, name='query_name', display_name='Query Name', sql='SELECT * FROM some_layer')
205
- or
206
- >>> query = await client.create_query(name='query_name', display_name='Query Name', sql='SELECT * FROM some_layer')
207
- """
208
- data = {
209
- "name": name,
210
- "display_name": display_name,
211
- "description": description,
212
- "sql": sql,
213
- "params": params
214
- }
215
- return await super()._create(api, cls.BASE_ENDPOINT, data, factory_func=lambda api, item: Query(api, item['uuid'], item))
216
-
217
-
218
- @classmethod
219
- async def get_query(cls, api: 'AsyncGeoboxClient', uuid: str, user_id: int = None) -> 'Query':
220
- """
221
- [async] Retrieves a query by its UUID.
222
-
223
- Args:
224
- api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
225
- uuid (str): The UUID of the query.
226
- user_id (int, optional): specific user ID. privileges required.
227
-
228
- Returns:
229
- Query: The retrieved query instance.
230
-
231
- Example:
232
- >>> from geobox.aio import AsyncGeoboxClient
233
- >>> from geobox.aio.query import Query
234
- >>> async with AsyncGeoboxClient() as client:
235
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
236
- or
237
- >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
238
- """
239
- params = {
240
- 'f': 'json',
241
- 'user_id': user_id
242
- }
243
- return await super()._get_detail(api, cls.BASE_ENDPOINT, uuid, params, factory_func=lambda api, item: Query(api, item['uuid'], item))
244
-
245
-
246
- @classmethod
247
- async def get_query_by_name(cls, api: 'AsyncGeoboxClient', name: str, user_id: int = None) -> Union['Query', None]:
248
- """
249
- [async] Get a query by name
250
-
251
- Args:
252
- api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
253
- name (str): the name of the query to get
254
- user_id (int, optional): specific user. privileges required.
255
-
256
- Returns:
257
- Query | None: returns the query if a query matches the given name, else None
258
-
259
- Example:
260
- >>> from geobox.aio import AsyncGeoboxClient
261
- >>> from geobox.aio.query import Query
262
- >>> async with AsyncGeoboxClient() as client:
263
- >>> query = await Query.get_query_by_name(client, name='test')
264
- or
265
- >>> query = await client.get_query_by_name(name='test')
266
- """
267
- queries = await cls.get_queries(api, q=f"name = '{name}'", user_id=user_id)
268
- if queries and queries[0].name == name:
269
- return queries[0]
270
- else:
271
- return None
272
-
273
-
274
- @classmethod
275
- async def get_system_queries(cls, api: 'AsyncGeoboxClient', **kwargs) -> List['Query']:
276
- """
277
- [async] Returns the system queries as a list of Query objects.
278
-
279
- Args:
280
- api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
281
-
282
- Keyword Args:
283
- q (str): query filter based on OGC CQL standard. e.g. "field1 LIKE '%GIS%' AND created_at > '2021-01-01'".
284
- search (str): search term for keyword-based searching among search_fields or all textual fields if search_fields does not have value. NOTE: if q param is defined this param will be ignored.
285
- search_fields (str): comma separated list of fields for searching.
286
- order_by (str): comma separated list of fields for sorting results [field1 A|D, field2 A|D, …]. e.g. name A, type D. NOTE: "A" denotes ascending order and "D" denotes descending order.
287
- return_count (bool): whether to return the total count of queries. default is False.
288
- skip (int): number of queries to skip. minimum is 0. default is 0.
289
- limit (int): number of queries to return. minimum is 1. default is 100.
290
- user_id (int): specific user. privileges required.
291
- shared (bool): whether to return shared queries. default is False.
292
-
293
- Returns:
294
- List[Query]: list of system queries.
295
-
296
- Example:
297
- >>> from geobox.aio import AsyncGeoboxClient
298
- >>> from geobox.aio.query import Query
299
- >>> async with AsyncGeoboxClient() as client:
300
- >>> queries = await Query.get_system_queries(client)
301
- or
302
- >>> queries = await client.get_system_queries()
303
- """
304
- params = {
305
- 'f': 'json',
306
- 'q': kwargs.get('q'),
307
- 'search': kwargs.get('search'),
308
- 'search_fields': kwargs.get('search_fields'),
309
- 'order_by': kwargs.get('order_by'),
310
- 'return_count': kwargs.get('return_count', False),
311
- 'skip': kwargs.get('skip', 0),
312
- 'limit': kwargs.get('limit', 100),
313
- 'user_id': kwargs.get('user_id'),
314
- 'shared': kwargs.get('shared', False)
315
- }
316
- endpoint = urljoin(cls.BASE_ENDPOINT, 'systemQueries/')
317
- def factory_func(api, item):
318
- query = Query(api, item['uuid'], item)
319
- query._system_query = True
320
- return query
321
-
322
- return await super()._get_list(api, endpoint, params, factory_func=factory_func)
323
-
324
-
325
- def add_param(self, name: str, value: str, type: 'QueryParamType', default_value: str = None, Domain: Dict = None) -> None:
326
- """
327
- Add a parameter to the query parameters.
328
-
329
- Args:
330
- name (str): The name of the parameter.
331
- value (str): The value of the parameter.
332
- type (str): The type of the parameter (default: 'Layer').
333
- default_value (str, optional): The default value for the parameter.
334
- Domain (Dict, optional): Domain information for the parameter.
335
-
336
- Returns:
337
- None
338
-
339
- Raises:
340
- PermissionError: If the query is a read-only system query.
341
-
342
- Example:
343
- >>> from geobox.aio import AsyncGeoboxClient
344
- >>> from geobox.aio.query import Query
345
- >>> async with AsyncGeoboxClient() as client:
346
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
347
- or
348
- >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
349
- >>> query.add_param(name='param_name', value='param_value', type=QueryParamType.LAYER)
350
- >>> await query.save()
351
- """
352
- self.params.append({
353
- 'name': name,
354
- 'value': value,
355
- 'type': type.value,
356
- 'default_value': default_value,
357
- 'Domain': Domain
358
- })
359
-
360
-
361
- def remove_param(self, name: str) -> None:
362
- """
363
- Remove a parameter from the query parameters by name.
364
-
365
- Args:
366
- name (str): The name of the parameter to remove.
367
-
368
- Returns:
369
- None
370
-
371
- Raises:
372
- ValueError: If the parameter is not found in query parameters.
373
- PermissionError: If the query is a read-only system query.
374
-
375
- Example:
376
- >>> from geobox.aio import AsyncGeoboxClient
377
- >>> from geobox.aio.query import Query
378
- >>> async with AsyncGeoboxClient() as client:
379
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
380
- or
381
- >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
382
- >>> query.remove_param(name='param_name')
383
- >>> await quary.save()
384
- """
385
- for i, param in enumerate(self.params):
386
- if param.get('name') == name:
387
- self.params.pop(i)
388
- return
389
-
390
- raise ValueError(f"Parameter with name '{name}' not found in query parameters")
391
-
392
-
393
- async def execute(self,
394
- f: str = "json",
395
- result_type: QueryResultType = QueryResultType.both,
396
- return_count: bool = None,
397
- out_srid: int = None,
398
- quant_factor: int = 1000000,
399
- bbox_srid: int = None,
400
- skip: int = None,
401
- limit: int = None,
402
- skip_geometry: bool = False) -> Union[Dict, int]:
403
- """
404
- [async] Executes a query with the given SQL statement and parameters.
405
-
406
- Args:
407
- f (str): the output format of the executed query. options are: json, topojson. default is json.
408
- result_type (QueryResultType, optional): The type of result to return (default is "both").
409
- return_count (bool, optional): Whether to return the count of results.
410
- out_srid (int, optional): The output spatial reference ID.
411
- quant_factor (int, optional): The quantization factor (default is 1000000).
412
- bbox_srid (int, optional): The bounding box spatial reference ID.
413
- skip (int, optional): The number of results to skip.
414
- limit (int, optional): The maximum number of results to return.
415
- skip_geometry (bool): Whether to skip the geometry part of the features or not. default is False.
416
-
417
- Returns:
418
- Dict | int: The result of the query execution or the count number of the result
419
-
420
- Example:
421
- >>> from geobox.aio import AsyncGeoboxClient
422
- >>> from geobox.aio.query import Query
423
- >>> async with AsyncGeoboxClient() as client:
424
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
425
- or
426
- >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
427
- >>> await query.execute(f='json')
428
- """
429
- if not self.sql:
430
- raise ValueError('"sql" parameter is required for this action!')
431
- if not self.params:
432
- raise ValueError('"params" parameter is required for this action!')
433
-
434
- data = clean_data({
435
- "f": f if f in ['json', 'topojson'] else None,
436
- "sql": self.sql,
437
- "params": self.params,
438
- "result_type": result_type.value,
439
- "return_count": return_count,
440
- "out_srid": out_srid,
441
- "quant_factor": quant_factor,
442
- "bbox_srid": bbox_srid,
443
- "skip": skip,
444
- "limit": limit,
445
- "skip_geometry": skip_geometry
446
- })
447
-
448
- endpoint = urljoin(self.BASE_ENDPOINT, 'exec/')
449
- self.result = await self.api.post(endpoint, data)
450
- return self.result
451
-
452
-
453
- async def update(self, **kwargs) -> Dict:
454
- """
455
- [async] Updates the query with new data.
456
-
457
- Keyword Args:
458
- name (str): The new name of the query.
459
- display_name (str): The new display name of the query.
460
- sql (str): The new SQL statement for the query.
461
- params (list): The new parameters for the SQL statement.
462
-
463
- Returns:
464
- Dict: The updated query data.
465
-
466
- Raises:
467
- PermissionError: If the query is a read-only system query.
468
-
469
- Example:
470
- >>> from geobox.aio import AsyncGeoboxClient
471
- >>> from geobox.aio.query import Query
472
- >>> async with AsyncGeoboxClient() as client:
473
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
474
- or
475
- >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
476
- >>> await query.update(name='new_name')
477
- """
478
- self._check_access()
479
-
480
- data = {
481
- "name": kwargs.get('name'),
482
- "display_name": kwargs.get('display_name'),
483
- "sql": kwargs.get('sql'),
484
- "params": kwargs.get('params')
485
- }
486
- await super()._update(self.endpoint, data)
487
-
488
-
489
- async def save(self) -> None:
490
- """
491
- [async] Save the query. Creates a new query if query uuid is None, updates existing query otherwise.
492
-
493
- Returns:
494
- None
495
-
496
- Example:
497
- >>> from geobox.aio import AsyncGeoboxClient
498
- >>> from geobox.aio.query import Query
499
- >>> async with AsyncGeoboxClient() as client:
500
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
501
- >>> await query.save()
502
- """
503
- self.params = [item for item in self.params if item.get('value')]
504
-
505
- try:
506
- if self.__getattr__('uuid'):
507
- await self.update(name=self.data['name'], display_name=self.data['display_name'], sql=self.sql, params=self.params)
508
- except AttributeError:
509
- response = await self.api.post(self.BASE_ENDPOINT, self.data)
510
- self.endpoint = urljoin(self.BASE_ENDPOINT, f'{response["uuid"]}/')
511
- self.data.update(response)
512
-
513
-
514
- async def delete(self) -> str:
515
- """
516
- [async] Deletes a query.
517
-
518
- Returns:
519
- str: The response from the API.
520
-
521
- Raises:
522
- PermissionError: If the query is a read-only system query
523
-
524
- Example:
525
- >>> from geobox.aio import AsyncGeoboxClient
526
- >>> from geobox.aio.query import Query
527
- >>> async with AsyncGeoboxClient() as client:
528
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
529
- >>> await query.delete()
530
- """
531
- self._check_access()
532
- await super().delete(self.endpoint)
533
-
534
-
535
- async def share(self, users: List['User']) -> None:
536
- """
537
- [async] Shares the query with specified users.
538
-
539
- Args:
540
- users (List[User]): The list of user objects to share the query with.
541
-
542
- Returns:
543
- None
544
-
545
- Raises:
546
- PermissionError: If the query is a read-only system query.
547
-
548
- Example:
549
- >>> from geobox.aio import AsyncGeoboxClient
550
- >>> from geobox.aio.query import Query
551
- >>> async with AsyncGeoboxClient() as client:
552
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
553
- >>> users = await client.search_users(search="John")
554
- >>> await query.share(users=users)
555
- """
556
- self._check_access()
557
- await super()._share(self.endpoint, users)
558
-
559
-
560
- async def unshare(self, users: List['User']) -> None:
561
- """
562
- [async] Unshares the query with specified users.
563
-
564
- Args:
565
- users (List[User]): The list of user objects to unshare the query with.
566
-
567
- Returns:
568
- None
569
-
570
- Raises:
571
- PermissionError: If the query is a read-only system query.
572
-
573
- Example:
574
- >>> from geobox.aio import AsyncGeoboxClient
575
- >>> from geobox.aio.query import Query
576
- >>> async with AsyncGeoboxClient() as client:
577
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
578
- >>> users = await client.search_users(search="John")
579
- >>> await query.unshare(users=users)
580
- """
581
- self._check_access()
582
- await super()._unshare(self.endpoint, users)
583
-
584
-
585
- async def get_shared_users(self, search: str = None, skip: int = 0, limit: int = 10) -> List['User']:
586
- """
587
- [async] Retrieves the list of users the query is shared with.
588
-
589
- Args:
590
- search (str, optional): the search query.
591
- skip (int, optional): The number of users to skip.
592
- limit (int, optional): The maximum number of users to retrieve.
593
-
594
- Returns:
595
- List[User]: The list of shared users.
596
-
597
- Example:
598
- >>> from geobox.aio import AsyncGeoboxClient
599
- >>> from geobox.aio.query import Query
600
- >>> async with AsyncGeoboxClient() as client:
601
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
602
- >>> users = await client.search_users(search="John")
603
- >>> await query.get_shared_users(search='John', skip=0, limit=10)
604
- """
605
- self._check_access()
606
- params = {
607
- 'search': search,
608
- 'skip': skip,
609
- 'limit': limit
610
- }
611
- return await super()._get_shared_users(self.endpoint, params)
612
-
613
-
614
- @property
615
- def thumbnail(self) -> str:
616
- """
617
- Retrieves the thumbnail URL for the query.
618
-
619
- Returns:
620
- str: The thumbnail URL.
621
-
622
- Example:
623
- >>> from geobox.aio import AsyncGeoboxClient
624
- >>> from geobox.aio.query import Query
625
- >>> async with AsyncGeoboxClient() as client:
626
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
627
- >>> query.thumbnail
628
- """
629
- return super().thumbnail()
630
-
631
-
632
- async def save_as_layer(self, layer_name: str, layer_type: 'QueryGeometryType' = None) -> Task:
633
- """
634
- [async] Saves the query as a new layer.
635
-
636
- Args:
637
- layer_name (str): The name of the new layer.
638
- layer_type (QueryGeometryType, optional): The type of the new layer.
639
-
640
- Returns:
641
- Task: The response task object.
642
-
643
- Raises:
644
- PermissionError: If the query is a read-only system query.
645
-
646
- Example:
647
- >>> from geobox.aio import AsyncGeoboxClient
648
- >>> from geobox.aio.query import Query
649
- >>> async with AsyncGeoboxClient() as client:
650
- >>> query = await Query.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
651
- >>> await query.save_as_layer(layer_name='test')
652
- """
653
- params = [{
654
- "name": item.get('name'),
655
- "type": item.get('type'),
656
- "value": item.get('default_value') if not item.get('value') else item.get('value')
657
- } for item in self.params]
658
-
659
- data = clean_data({
660
- "sql": self.sql,
661
- "params": params,
662
- "layer_name": layer_name,
663
- "layer_type": layer_type.value if layer_type else None
664
- })
665
-
666
- endpoint = urljoin(self.BASE_ENDPOINT, 'saveAsLayer/')
667
- response = await self.api.post(endpoint, data)
668
- task = await Task.get_task(self.api, response.get('task_id'))
669
- return task
670
-
671
-
672
- def to_sync(self, sync_client: 'SyncGeoboxClient') -> 'SyncQuery':
673
- """
674
- Switch to sync version of the query instance to have access to the sync methods
675
-
676
- Args:
677
- sync_client (SyncGeoboxClient): The sync version of the GeoboxClient instance for making requests.
678
-
679
- Returns:
680
- geobox.query.Query: the sync instance of the query.
681
-
682
- Example:
683
- >>> from geobox import Geoboxclient
684
- >>> from geobox.aio import AsyncGeoboxClient
685
- >>> from geobox.aio.query import Query
686
- >>> client = GeoboxClient()
687
- >>> async with AsyncGeoboxClient() as async_client:
688
- >>> query = await Query.get_query(async_client, uuid="12345678-1234-5678-1234-567812345678")
689
- >>> sync_query = query.to_sync(client)
690
- """
691
- from ..query import Query as SyncQuery
692
-
693
- return SyncQuery(api=sync_client, uuid=self.uuid, data=self.data)
1
+ from urllib.parse import urljoin
2
+ from typing import Dict, List, TYPE_CHECKING, Union
3
+
4
+ from ..utils import clean_data
5
+ from .base import AsyncBase
6
+ from .task import AsyncTask
7
+ from ..enums import QueryResultType, QueryGeometryType, QueryParamType
8
+
9
+ if TYPE_CHECKING:
10
+ from . import AsyncGeoboxClient
11
+ from .user import AsyncUser
12
+ from ..api import GeoboxClient
13
+ from ..query import Query
14
+
15
+
16
+ class AsyncQuery(AsyncBase):
17
+
18
+ BASE_ENDPOINT: str = 'queries/'
19
+
20
+ def __init__(self,
21
+ api: 'AsyncGeoboxClient',
22
+ uuid: str = None,
23
+ data: Dict = {}):
24
+ """
25
+ Constructs all the necessary attributes for the Query object.
26
+
27
+ Args:
28
+ api (AsyncGeoboxClient): The API instance.
29
+ uuid (str): The UUID of the query.
30
+ data (dict, optional): The data of the query.
31
+ """
32
+ self.result = {}
33
+ self._system_query = False
34
+ super().__init__(api, uuid=uuid, data=data)
35
+
36
+
37
+ def _check_access(self) -> None:
38
+ """
39
+ Check if the query is a system query.
40
+
41
+ Returns:
42
+ None
43
+
44
+ Raises:
45
+ PermissionError: If the query is a read-only system query.
46
+ """
47
+ if self._system_query:
48
+ raise PermissionError("Cannot modify system queries - they are read-only")
49
+
50
+
51
+ @property
52
+ def sql(self) -> str:
53
+ """
54
+ Get the SQL of the query.
55
+
56
+ Returns:
57
+ str: The SQL of the query.
58
+
59
+ Example:
60
+ >>> from geobox.aio import AsyncGeoboxClient
61
+ >>> from geobox.aio.query import AsyncQuery
62
+ >>> async with AsyncGeoboxClient() as client:
63
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
64
+ >>> query.sql
65
+ 'SELECT * FROM some_layer'
66
+ """
67
+ return self.data['sql']
68
+
69
+
70
+ @sql.setter
71
+ def sql(self, value: str) -> None:
72
+ """
73
+ Set the SQL of the query.
74
+
75
+ Args:
76
+ value (str): The SQL of the query.
77
+
78
+ Returns:
79
+ None
80
+
81
+ Example:
82
+ >>> from geobox.aio import AsyncGeoboxClient
83
+ >>> from geobox.aio.query import AsyncQuery
84
+ >>> async with AsyncGeoboxClient() as client:
85
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
86
+ >>> query.sql = 'SELECT * FROM some_layer'
87
+ >>> await query.save()
88
+ """
89
+ self.data['sql'] = value
90
+
91
+
92
+ @property
93
+ def params(self) -> List[Dict]:
94
+ """
95
+ Get the parameters of the query.
96
+
97
+ Returns:
98
+ List[Dict]: The parameters of the query.
99
+
100
+ Example:
101
+ >>> from geobox.aio import AsyncGeoboxClient
102
+ >>> from geobox.aio.query import AsyncQuery
103
+ >>> async with AsyncGeoboxClient() as client:
104
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
105
+ >>> query.params
106
+ [{'name': 'layer', 'value': '12345678-1234-5678-1234-567812345678', 'type': 'Layer'}]
107
+ """
108
+ if not isinstance(self.data.get('params'), list):
109
+ self.data['params'] = []
110
+
111
+ return self.data['params']
112
+
113
+
114
+ @params.setter
115
+ def params(self, value: Dict) -> None:
116
+ """
117
+ Set the parameters of the query.
118
+
119
+ Args:
120
+ value (Dict): The parameters of the query.
121
+
122
+ Returns:
123
+ None
124
+
125
+ Example:
126
+ >>> from geobox.aio import AsyncGeoboxClient
127
+ >>> from geobox.aio.query import AsyncQuery
128
+ >>> async with AsyncGeoboxClient() as client:
129
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
130
+ >>> query.params = [{'name': 'layer', 'value': '12345678-1234-5678-1234-567812345678', 'type': 'Layer'}]
131
+ >>> await query.save()
132
+ """
133
+ if not isinstance(self.data.get('params'), list):
134
+ self.data['params'] = []
135
+
136
+ self.data['params'] = value
137
+
138
+
139
+ @classmethod
140
+ async def get_queries(cls, api: 'AsyncGeoboxClient', **kwargs) -> Union[List['AsyncQuery'], int]:
141
+ """
142
+ [async] Get Queries
143
+
144
+ Args:
145
+ api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
146
+
147
+ Keyword Args:
148
+ q (str): query filter based on OGC CQL standard. e.g. "field1 LIKE '%GIS%' AND created_at > '2021-01-01'"
149
+ search (str): search term for keyword-based searching among search_fields or all textual fields if search_fields does not have value. NOTE: if q param is defined this param will be ignored.
150
+ search_fields (str): comma separated list of fields for searching
151
+ order_by (str): comma separated list of fields for sorting results [field1 A|D, field2 A|D, …]. e.g. name A, type D. NOTE: "A" denotes ascending order and "D" denotes descending order.
152
+ return_count (bool): Whether to return total count. default is False.
153
+ skip (int): Number of queries to skip. default is 0.
154
+ limit(int): Maximum number of queries to return. default is 10.
155
+ user_id (int): Specific user. privileges required.
156
+ shared (bool): Whether to return shared queries. default is False.
157
+
158
+ Returns:
159
+ List[AsyncQuery] | int: list of queries or the number of queries.
160
+
161
+ Example:
162
+ >>> from geobox.aio import AsyncGeoboxClient
163
+ >>> from geobox.aio.query import AsyncQuery
164
+ >>> async with AsyncGeoboxClient() as client:
165
+ >>> queries = await AsyncQuery.get_queries(client)
166
+ or
167
+ >>> queries = await client.get_queries()
168
+ """
169
+ params = {
170
+ 'f': 'json',
171
+ 'q': kwargs.get('q'),
172
+ 'search': kwargs.get('search'),
173
+ 'search_field': kwargs.get('search_field'),
174
+ 'order_by': kwargs.get('order_by'),
175
+ 'return_count': kwargs.get('return_count', False),
176
+ 'skip': kwargs.get('skip', 0),
177
+ 'limit': kwargs.get('limit', 10),
178
+ 'user_id': kwargs.get('user_id'),
179
+ 'shared': kwargs.get('shared', False)
180
+ }
181
+ return await super()._get_list(api, cls.BASE_ENDPOINT, params, factory_func=lambda api, item: AsyncQuery(api, item['uuid'], item))
182
+
183
+
184
+ @classmethod
185
+ async def create_query(cls, api: 'AsyncGeoboxClient', name: str, display_name: str = None, description:str = None, sql: str = None, params: List = None) -> 'AsyncQuery':
186
+ """
187
+ [async] Creates a new query.
188
+
189
+ Args:
190
+ api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
191
+ name (str): The name of the query.
192
+ display_name (str, optional): The display name of the query.
193
+ description (str, optional): The description of the query.
194
+ sql (str, optional): The SQL statement for the query.
195
+ params (list, optional): The parameters for the SQL statement.
196
+
197
+ Returns:
198
+ AsyncQuery: The created query instance.
199
+
200
+ Example:
201
+ >>> from geobox.aio import AsyncGeoboxClient
202
+ >>> from geobox.aio.query import AsyncQuery
203
+ >>> async with AsyncGeoboxClient() as client:
204
+ >>> query = await AsyncQuery.create_query(client, name='query_name', display_name='Query Name', sql='SELECT * FROM some_layer')
205
+ or
206
+ >>> query = await client.create_query(name='query_name', display_name='Query Name', sql='SELECT * FROM some_layer')
207
+ """
208
+ data = {
209
+ "name": name,
210
+ "display_name": display_name,
211
+ "description": description,
212
+ "sql": sql,
213
+ "params": params
214
+ }
215
+ return await super()._create(api, cls.BASE_ENDPOINT, data, factory_func=lambda api, item: AsyncQuery(api, item['uuid'], item))
216
+
217
+
218
+ @classmethod
219
+ async def get_query(cls, api: 'AsyncGeoboxClient', uuid: str, user_id: int = None) -> 'AsyncQuery':
220
+ """
221
+ [async] Retrieves a query by its UUID.
222
+
223
+ Args:
224
+ api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
225
+ uuid (str): The UUID of the query.
226
+ user_id (int, optional): specific user ID. privileges required.
227
+
228
+ Returns:
229
+ AsyncQuery: The retrieved query instance.
230
+
231
+ Example:
232
+ >>> from geobox.aio import AsyncGeoboxClient
233
+ >>> from geobox.aio.query import AsyncQuery
234
+ >>> async with AsyncGeoboxClient() as client:
235
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
236
+ or
237
+ >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
238
+ """
239
+ params = {
240
+ 'f': 'json',
241
+ 'user_id': user_id
242
+ }
243
+ return await super()._get_detail(api, cls.BASE_ENDPOINT, uuid, params, factory_func=lambda api, item: AsyncQuery(api, item['uuid'], item))
244
+
245
+
246
+ @classmethod
247
+ async def get_query_by_name(cls, api: 'AsyncGeoboxClient', name: str, user_id: int = None) -> Union['AsyncQuery', None]:
248
+ """
249
+ [async] Get a query by name
250
+
251
+ Args:
252
+ api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
253
+ name (str): the name of the query to get
254
+ user_id (int, optional): specific user. privileges required.
255
+
256
+ Returns:
257
+ AsyncQuery | None: returns the query if a query matches the given name, else None
258
+
259
+ Example:
260
+ >>> from geobox.aio import AsyncGeoboxClient
261
+ >>> from geobox.aio.query import AsyncQuery
262
+ >>> async with AsyncGeoboxClient() as client:
263
+ >>> query = await AsyncQuery.get_query_by_name(client, name='test')
264
+ or
265
+ >>> query = await client.get_query_by_name(name='test')
266
+ """
267
+ queries = await cls.get_queries(api, q=f"name = '{name}'", user_id=user_id)
268
+ if queries and queries[0].name == name:
269
+ return queries[0]
270
+ else:
271
+ return None
272
+
273
+
274
+ @classmethod
275
+ async def get_system_queries(cls, api: 'AsyncGeoboxClient', **kwargs) -> List['AsyncQuery']:
276
+ """
277
+ [async] Returns the system queries as a list of Query objects.
278
+
279
+ Args:
280
+ api (AsyncGeoboxClient): The AsyncGeoboxClient instance for making requests.
281
+
282
+ Keyword Args:
283
+ q (str): query filter based on OGC CQL standard. e.g. "field1 LIKE '%GIS%' AND created_at > '2021-01-01'".
284
+ search (str): search term for keyword-based searching among search_fields or all textual fields if search_fields does not have value. NOTE: if q param is defined this param will be ignored.
285
+ search_fields (str): comma separated list of fields for searching.
286
+ order_by (str): comma separated list of fields for sorting results [field1 A|D, field2 A|D, …]. e.g. name A, type D. NOTE: "A" denotes ascending order and "D" denotes descending order.
287
+ return_count (bool): whether to return the total count of queries. default is False.
288
+ skip (int): number of queries to skip. minimum is 0. default is 0.
289
+ limit (int): number of queries to return. minimum is 1. default is 100.
290
+ user_id (int): specific user. privileges required.
291
+ shared (bool): whether to return shared queries. default is False.
292
+
293
+ Returns:
294
+ List[AsyncQuery]: list of system queries.
295
+
296
+ Example:
297
+ >>> from geobox.aio import AsyncGeoboxClient
298
+ >>> from geobox.aio.query import AsyncQuery
299
+ >>> async with AsyncGeoboxClient() as client:
300
+ >>> queries = await AsyncQuery.get_system_queries(client)
301
+ or
302
+ >>> queries = await client.get_system_queries()
303
+ """
304
+ params = {
305
+ 'f': 'json',
306
+ 'q': kwargs.get('q'),
307
+ 'search': kwargs.get('search'),
308
+ 'search_fields': kwargs.get('search_fields'),
309
+ 'order_by': kwargs.get('order_by'),
310
+ 'return_count': kwargs.get('return_count', False),
311
+ 'skip': kwargs.get('skip', 0),
312
+ 'limit': kwargs.get('limit', 100),
313
+ 'user_id': kwargs.get('user_id'),
314
+ 'shared': kwargs.get('shared', False)
315
+ }
316
+ endpoint = urljoin(cls.BASE_ENDPOINT, 'systemQueries/')
317
+ def factory_func(api, item):
318
+ query = AsyncQuery(api, item['uuid'], item)
319
+ query._system_query = True
320
+ return query
321
+
322
+ return await super()._get_list(api, endpoint, params, factory_func=factory_func)
323
+
324
+
325
+ def add_param(self, name: str, value: str, type: 'QueryParamType', default_value: str = None, Domain: Dict = None) -> None:
326
+ """
327
+ Add a parameter to the query parameters.
328
+
329
+ Args:
330
+ name (str): The name of the parameter.
331
+ value (str): The value of the parameter.
332
+ type (str): The type of the parameter (default: 'Layer').
333
+ default_value (str, optional): The default value for the parameter.
334
+ Domain (Dict, optional): Domain information for the parameter.
335
+
336
+ Returns:
337
+ None
338
+
339
+ Raises:
340
+ PermissionError: If the query is a read-only system query.
341
+
342
+ Example:
343
+ >>> from geobox.aio import AsyncGeoboxClient
344
+ >>> from geobox.aio.query import AsyncQuery
345
+ >>> async with AsyncGeoboxClient() as client:
346
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
347
+ or
348
+ >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
349
+ >>> query.add_param(name='param_name', value='param_value', type=QueryParamType.LAYER)
350
+ >>> await query.save()
351
+ """
352
+ self.params.append({
353
+ 'name': name,
354
+ 'value': value,
355
+ 'type': type.value,
356
+ 'default_value': default_value,
357
+ 'Domain': Domain
358
+ })
359
+
360
+
361
+ def remove_param(self, name: str) -> None:
362
+ """
363
+ Remove a parameter from the query parameters by name.
364
+
365
+ Args:
366
+ name (str): The name of the parameter to remove.
367
+
368
+ Returns:
369
+ None
370
+
371
+ Raises:
372
+ ValueError: If the parameter is not found in query parameters.
373
+ PermissionError: If the query is a read-only system query.
374
+
375
+ Example:
376
+ >>> from geobox.aio import AsyncGeoboxClient
377
+ >>> from geobox.aio.query import AsyncQuery
378
+ >>> async with AsyncGeoboxClient() as client:
379
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
380
+ or
381
+ >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
382
+ >>> query.remove_param(name='param_name')
383
+ >>> await quary.save()
384
+ """
385
+ for i, param in enumerate(self.params):
386
+ if param.get('name') == name:
387
+ self.params.pop(i)
388
+ return
389
+
390
+ raise ValueError(f"Parameter with name '{name}' not found in query parameters")
391
+
392
+
393
+ async def execute(self,
394
+ f: str = "json",
395
+ result_type: QueryResultType = QueryResultType.both,
396
+ return_count: bool = None,
397
+ out_srid: int = None,
398
+ quant_factor: int = 1000000,
399
+ bbox_srid: int = None,
400
+ skip: int = None,
401
+ limit: int = None,
402
+ skip_geometry: bool = False) -> Union[Dict, int]:
403
+ """
404
+ [async] Executes a query with the given SQL statement and parameters.
405
+
406
+ Args:
407
+ f (str): the output format of the executed query. options are: json, topojson. default is json.
408
+ result_type (QueryResultType, optional): The type of result to return (default is "both").
409
+ return_count (bool, optional): Whether to return the count of results.
410
+ out_srid (int, optional): The output spatial reference ID.
411
+ quant_factor (int, optional): The quantization factor (default is 1000000).
412
+ bbox_srid (int, optional): The bounding box spatial reference ID.
413
+ skip (int, optional): The number of results to skip.
414
+ limit (int, optional): The maximum number of results to return.
415
+ skip_geometry (bool): Whether to skip the geometry part of the features or not. default is False.
416
+
417
+ Returns:
418
+ Dict | int: The result of the query execution or the count number of the result
419
+
420
+ Example:
421
+ >>> from geobox.aio import AsyncGeoboxClient
422
+ >>> from geobox.aio.query import AsyncQuery
423
+ >>> async with AsyncGeoboxClient() as client:
424
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
425
+ or
426
+ >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
427
+ >>> await query.execute(f='json')
428
+ """
429
+ if not self.sql:
430
+ raise ValueError('"sql" parameter is required for this action!')
431
+ if not self.params:
432
+ raise ValueError('"params" parameter is required for this action!')
433
+
434
+ data = clean_data({
435
+ "f": f if f in ['json', 'topojson'] else None,
436
+ "sql": self.sql,
437
+ "params": self.params,
438
+ "result_type": result_type.value,
439
+ "return_count": return_count,
440
+ "out_srid": out_srid,
441
+ "quant_factor": quant_factor,
442
+ "bbox_srid": bbox_srid,
443
+ "skip": skip,
444
+ "limit": limit,
445
+ "skip_geometry": skip_geometry
446
+ })
447
+
448
+ endpoint = urljoin(self.BASE_ENDPOINT, 'exec/')
449
+ self.result = await self.api.post(endpoint, data)
450
+ return self.result
451
+
452
+
453
+ async def update(self, **kwargs) -> Dict:
454
+ """
455
+ [async] Updates the query with new data.
456
+
457
+ Keyword Args:
458
+ name (str): The new name of the query.
459
+ display_name (str): The new display name of the query.
460
+ sql (str): The new SQL statement for the query.
461
+ params (list): The new parameters for the SQL statement.
462
+
463
+ Returns:
464
+ Dict: The updated query data.
465
+
466
+ Raises:
467
+ PermissionError: If the query is a read-only system query.
468
+
469
+ Example:
470
+ >>> from geobox.aio import AsyncGeoboxClient
471
+ >>> from geobox.aio.query import AsyncQuery
472
+ >>> async with AsyncGeoboxClient() as client:
473
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
474
+ or
475
+ >>> query = await client.get_query(uuid="12345678-1234-5678-1234-567812345678")
476
+ >>> await query.update(name='new_name')
477
+ """
478
+ self._check_access()
479
+
480
+ data = {
481
+ "name": kwargs.get('name'),
482
+ "display_name": kwargs.get('display_name'),
483
+ "sql": kwargs.get('sql'),
484
+ "params": kwargs.get('params')
485
+ }
486
+ await super()._update(self.endpoint, data)
487
+
488
+
489
+ async def save(self) -> None:
490
+ """
491
+ [async] Save the query. Creates a new query if query uuid is None, updates existing query otherwise.
492
+
493
+ Returns:
494
+ None
495
+
496
+ Example:
497
+ >>> from geobox.aio import AsyncGeoboxClient
498
+ >>> from geobox.aio.query import AsyncQuery
499
+ >>> async with AsyncGeoboxClient() as client:
500
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
501
+ >>> await query.save()
502
+ """
503
+ self.params = [item for item in self.params if item.get('value')]
504
+
505
+ try:
506
+ if self.__getattr__('uuid'):
507
+ await self.update(name=self.data['name'], display_name=self.data['display_name'], sql=self.sql, params=self.params)
508
+ except AttributeError:
509
+ response = await self.api.post(self.BASE_ENDPOINT, self.data)
510
+ self.endpoint = urljoin(self.BASE_ENDPOINT, f'{response["uuid"]}/')
511
+ self.data.update(response)
512
+
513
+
514
+ async def delete(self) -> str:
515
+ """
516
+ [async] Deletes a query.
517
+
518
+ Returns:
519
+ str: The response from the API.
520
+
521
+ Raises:
522
+ PermissionError: If the query is a read-only system query
523
+
524
+ Example:
525
+ >>> from geobox.aio import AsyncGeoboxClient
526
+ >>> from geobox.aio.query import AsyncQuery
527
+ >>> async with AsyncGeoboxClient() as client:
528
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
529
+ >>> await query.delete()
530
+ """
531
+ self._check_access()
532
+ await super()._delete(self.endpoint)
533
+
534
+
535
+ async def share(self, users: List['AsyncUser']) -> None:
536
+ """
537
+ [async] Shares the query with specified users.
538
+
539
+ Args:
540
+ users (List[AsyncUser]): The list of user objects to share the query with.
541
+
542
+ Returns:
543
+ None
544
+
545
+ Raises:
546
+ PermissionError: If the query is a read-only system query.
547
+
548
+ Example:
549
+ >>> from geobox.aio import AsyncGeoboxClient
550
+ >>> from geobox.aio.query import AsyncQuery
551
+ >>> async with AsyncGeoboxClient() as client:
552
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
553
+ >>> users = await client.search_users(search="John")
554
+ >>> await query.share(users=users)
555
+ """
556
+ self._check_access()
557
+ await super()._share(self.endpoint, users)
558
+
559
+
560
+ async def unshare(self, users: List['AsyncUser']) -> None:
561
+ """
562
+ [async] Unshares the query with specified users.
563
+
564
+ Args:
565
+ users (List[AsyncUser]): The list of user objects to unshare the query with.
566
+
567
+ Returns:
568
+ None
569
+
570
+ Raises:
571
+ PermissionError: If the query is a read-only system query.
572
+
573
+ Example:
574
+ >>> from geobox.aio import AsyncGeoboxClient
575
+ >>> from geobox.aio.query import AsyncQuery
576
+ >>> async with AsyncGeoboxClient() as client:
577
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
578
+ >>> users = await client.search_users(search="John")
579
+ >>> await query.unshare(users=users)
580
+ """
581
+ self._check_access()
582
+ await super()._unshare(self.endpoint, users)
583
+
584
+
585
+ async def get_shared_users(self, search: str = None, skip: int = 0, limit: int = 10) -> List['AsyncUser']:
586
+ """
587
+ [async] Retrieves the list of users the query is shared with.
588
+
589
+ Args:
590
+ search (str, optional): the search query.
591
+ skip (int, optional): The number of users to skip.
592
+ limit (int, optional): The maximum number of users to retrieve.
593
+
594
+ Returns:
595
+ List[AsyncUser]: The list of shared users.
596
+
597
+ Example:
598
+ >>> from geobox.aio import AsyncGeoboxClient
599
+ >>> from geobox.aio.query import AsyncQuery
600
+ >>> async with AsyncGeoboxClient() as client:
601
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
602
+ >>> users = await client.search_users(search="John")
603
+ >>> await query.get_shared_users(search='John', skip=0, limit=10)
604
+ """
605
+ self._check_access()
606
+ params = {
607
+ 'search': search,
608
+ 'skip': skip,
609
+ 'limit': limit
610
+ }
611
+ return await super()._get_shared_users(self.endpoint, params)
612
+
613
+
614
+ @property
615
+ def thumbnail(self) -> str:
616
+ """
617
+ Retrieves the thumbnail URL for the query.
618
+
619
+ Returns:
620
+ str: The thumbnail URL.
621
+
622
+ Example:
623
+ >>> from geobox.aio import AsyncGeoboxClient
624
+ >>> from geobox.aio.query import AsyncQuery
625
+ >>> async with AsyncGeoboxClient() as client:
626
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
627
+ >>> query.thumbnail
628
+ """
629
+ return super()._thumbnail()
630
+
631
+
632
+ async def save_as_layer(self, layer_name: str, layer_type: 'QueryGeometryType' = None) -> 'AsyncTask':
633
+ """
634
+ [async] Saves the query as a new layer.
635
+
636
+ Args:
637
+ layer_name (str): The name of the new layer.
638
+ layer_type (QueryGeometryType, optional): The type of the new layer.
639
+
640
+ Returns:
641
+ Task: The response task object.
642
+
643
+ Raises:
644
+ PermissionError: If the query is a read-only system query.
645
+
646
+ Example:
647
+ >>> from geobox.aio import AsyncGeoboxClient
648
+ >>> from geobox.aio.query import AsyncQuery
649
+ >>> async with AsyncGeoboxClient() as client:
650
+ >>> query = await AsyncQuery.get_query(client, uuid="12345678-1234-5678-1234-567812345678")
651
+ >>> await query.save_as_layer(layer_name='test')
652
+ """
653
+ params = [{
654
+ "name": item.get('name'),
655
+ "type": item.get('type'),
656
+ "value": item.get('default_value') if not item.get('value') else item.get('value')
657
+ } for item in self.params]
658
+
659
+ data = clean_data({
660
+ "sql": self.sql,
661
+ "params": params,
662
+ "layer_name": layer_name,
663
+ "layer_type": layer_type.value if layer_type else None
664
+ })
665
+
666
+ endpoint = urljoin(self.BASE_ENDPOINT, 'saveAsLayer/')
667
+ response = await self.api.post(endpoint, data)
668
+ task = await AsyncTask.get_task(self.api, response.get('task_id'))
669
+ return task
670
+
671
+
672
+ def to_sync(self, sync_client: 'GeoboxClient') -> 'Query':
673
+ """
674
+ Switch to sync version of the query instance to have access to the sync methods
675
+
676
+ Args:
677
+ sync_client (GeoboxClient): The sync version of the GeoboxClient instance for making requests.
678
+
679
+ Returns:
680
+ Query: the sync instance of the query.
681
+
682
+ Example:
683
+ >>> from geobox import Geoboxclient
684
+ >>> from geobox.aio import AsyncGeoboxClient
685
+ >>> from geobox.aio.query import AsyncQuery
686
+ >>> client = GeoboxClient()
687
+ >>> async with AsyncGeoboxClient() as async_client:
688
+ >>> query = await AsyncQuery.get_query(async_client, uuid="12345678-1234-5678-1234-567812345678")
689
+ >>> sync_query = query.to_sync(client)
690
+ """
691
+ from ..query import Query
692
+
693
+ return Query(api=sync_client, uuid=self.uuid, data=self.data)