Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
singlestore-labs
GitHub Repository: singlestore-labs/singlestoredb-python
Path: blob/main/singlestoredb/fusion/handlers/workspace.py
469 views
1
#!/usr/bin/env python3
2
import json
3
from typing import Any
4
from typing import Dict
5
from typing import Optional
6
7
from .. import result
8
from ..handler import SQLHandler
9
from ..result import FusionSQLResult
10
from .utils import dt_isoformat
11
from .utils import get_workspace
12
from .utils import get_workspace_group
13
from .utils import get_workspace_manager
14
15
16
class UseWorkspaceHandler(SQLHandler):
17
"""
18
USE WORKSPACE workspace [ with_database ];
19
20
# Workspace
21
workspace = { workspace_id | workspace_name | current_workspace }
22
23
# ID of workspace
24
workspace_id = ID '<workspace-id>'
25
26
# Name of workspace
27
workspace_name = '<workspace-name>'
28
29
# Current workspace
30
current_workspace = @@CURRENT
31
32
# Name of database
33
with_database = WITH DATABASE 'database-name'
34
35
Description
36
-----------
37
Change the workspace and database in the notebook.
38
39
Arguments
40
---------
41
* ``<workspace-id>``: The ID of the workspace to delete.
42
* ``<workspace-name>``: The name of the workspace to delete.
43
44
Remarks
45
-------
46
* If you want to specify a database in the current workspace,
47
the workspace name can be specified as ``@@CURRENT``.
48
* Specify the ``WITH DATABASE`` clause to select a default
49
database for the session.
50
* This command only works in a notebook session in the
51
Managed Service.
52
53
Example
54
-------
55
The following command sets the workspace to ``examplews`` and
56
select 'dbname' as the default database::
57
58
USE WORKSPACE 'examplews' WITH DATABASE 'dbname';
59
60
"""
61
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
62
from singlestoredb.notebook import portal
63
if params['workspace'].get('current_workspace'):
64
if params.get('with_database'):
65
portal.default_database = params['with_database']
66
elif params.get('with_database'):
67
if params['workspace'].get('workspace_name'):
68
portal.connection = params['workspace']['workspace_name'], \
69
params['with_database']
70
else:
71
portal.connection = params['workspace']['workspace_id'], \
72
params['with_database']
73
elif params['workspace'].get('workspace_name'):
74
portal.workspace = params['workspace']['workspace_name']
75
else:
76
portal.workspace = params['workspace']['workspace_id']
77
return None
78
79
80
UseWorkspaceHandler.register(overwrite=True)
81
82
83
class ShowRegionsHandler(SQLHandler):
84
"""
85
SHOW REGIONS [ <like> ]
86
[ <order-by> ]
87
[ <limit> ];
88
89
Description
90
-----------
91
Returns a list of all the valid regions for the user.
92
93
Arguments
94
---------
95
* ``<pattern>``: A pattern similar to SQL LIKE clause.
96
Uses ``%`` as the wildcard character.
97
98
Remarks
99
-------
100
* Use the ``LIKE`` clause to specify a pattern and return only the
101
regions that match the specified pattern.
102
* The ``LIMIT`` clause limits the number of results to the
103
specified number.
104
* Use the ``ORDER BY`` clause to sort the results by the specified
105
key. By default, the results are sorted in the ascending order.
106
107
Example
108
-------
109
The following command returns a list of all the regions in the US
110
and sorts the results in ascending order by their ``Name``::
111
112
SHOW REGIONS LIKE 'US%' ORDER BY Name;
113
114
"""
115
116
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
117
manager = get_workspace_manager()
118
119
res = FusionSQLResult()
120
res.add_field('Name', result.STRING)
121
res.add_field('ID', result.STRING)
122
res.add_field('Provider', result.STRING)
123
124
res.set_rows([(x.name, x.id, x.provider) for x in manager.regions])
125
126
if params['like']:
127
res = res.like(Name=params['like'])
128
129
return res.order_by(**params['order_by']).limit(params['limit'])
130
131
132
ShowRegionsHandler.register(overwrite=True)
133
134
135
class ShowWorkspaceGroupsHandler(SQLHandler):
136
"""
137
SHOW WORKSPACE GROUPS [ <like> ]
138
[ <extended> ] [ <order-by> ]
139
[ <limit> ];
140
141
Description
142
-----------
143
Displays information on workspace groups.
144
145
Arguments
146
---------
147
* ``<pattern>``: A pattern similar to SQL LIKE clause.
148
Uses ``%`` as the wildcard character.
149
150
Remarks
151
-------
152
* Use the ``LIKE`` clause to specify a pattern and return only the
153
workspace groups that match the specified pattern.
154
* The ``LIMIT`` clause limits the number of results to the
155
specified number.
156
* Use the ``ORDER BY`` clause to sort the results by the specified
157
key. By default, the results are sorted in the ascending order.
158
* To return more information about the workspace groups, use the
159
``EXTENDED`` clause.
160
161
Example
162
-------
163
The following command displays a list of workspace groups with names
164
that match the specified pattern::
165
166
SHOW WORKSPACE GROUPS LIKE 'Marketing%' EXTENDED ORDER BY Name;
167
168
See Also
169
--------
170
* ``SHOW WORKSPACES``
171
172
"""
173
174
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
175
manager = get_workspace_manager()
176
177
res = FusionSQLResult()
178
res.add_field('Name', result.STRING)
179
res.add_field('ID', result.STRING)
180
res.add_field('Region', result.STRING)
181
res.add_field('FirewallRanges', result.JSON)
182
183
if params['extended']:
184
res.add_field('CreatedAt', result.DATETIME)
185
res.add_field('TerminatedAt', result.DATETIME)
186
187
def fields(x: Any) -> Any:
188
return (
189
x.name, x.id, x.region.name,
190
json.dumps(x.firewall_ranges),
191
dt_isoformat(x.created_at),
192
dt_isoformat(x.terminated_at),
193
)
194
else:
195
def fields(x: Any) -> Any:
196
return (x.name, x.id, x.region.name, json.dumps(x.firewall_ranges))
197
198
res.set_rows([fields(x) for x in manager.workspace_groups])
199
200
if params['like']:
201
res = res.like(Name=params['like'])
202
203
return res.order_by(**params['order_by']).limit(params['limit'])
204
205
206
ShowWorkspaceGroupsHandler.register(overwrite=True)
207
208
209
class ShowWorkspacesHandler(SQLHandler):
210
"""
211
SHOW WORKSPACES [ in_group ]
212
[ <like> ] [ <extended> ]
213
[ <order-by> ] [ <limit> ];
214
215
# Workspace group
216
in_group = IN GROUP { group_id | group_name }
217
218
# ID of group
219
group_id = ID '<group-id>'
220
221
# Name of group
222
group_name = '<group-name>'
223
224
Description
225
-----------
226
Displays information on workspaces in a workspace group.
227
228
Arguments
229
---------
230
* ``<group_id>``: The ID of the workspace group that contains
231
the workspace.
232
* ``<group_name>``: The name of the workspace group that
233
contains the workspace.
234
* ``<pattern>``: A pattern similar to SQL LIKE clause.
235
Uses ``%`` as the wildcard character.
236
237
Remarks
238
-------
239
* The ``IN GROUP`` clause specifies the ID or the name of the
240
workspace group that contains the workspace.
241
* Use the ``LIKE`` clause to specify a pattern and return only
242
the workspaces that match the specified pattern.
243
* The ``LIMIT`` clause limits the number of results to the
244
specified number.
245
* Use the ``ORDER BY`` clause to sort the results by the
246
specified key. By default, the results are sorted in the
247
ascending order.
248
* To return more information about the workspaces, use the
249
``EXTENDED`` clause.
250
251
Example
252
-------
253
The following command displays information on all the workspaces
254
in a workspace group named **wsg1** and sorts the results by
255
workspace name in the ascending order::
256
257
SHOW WORKSPACES IN GROUP 'wsg1' EXTENDED ORDER BY Name;
258
259
See Also
260
--------
261
* ``SHOW WORKSPACE GROUPS``
262
263
"""
264
265
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
266
res = FusionSQLResult()
267
res.add_field('Name', result.STRING)
268
res.add_field('ID', result.STRING)
269
res.add_field('Size', result.STRING)
270
res.add_field('State', result.STRING)
271
272
workspace_group = get_workspace_group(params)
273
274
if params['extended']:
275
res.add_field('Endpoint', result.STRING)
276
res.add_field('CreatedAt', result.DATETIME)
277
res.add_field('TerminatedAt', result.DATETIME)
278
279
def fields(x: Any) -> Any:
280
return (
281
x.name, x.id, x.size, x.state,
282
x.endpoint, dt_isoformat(x.created_at),
283
dt_isoformat(x.terminated_at),
284
)
285
else:
286
def fields(x: Any) -> Any:
287
return (x.name, x.id, x.size, x.state)
288
289
res.set_rows([fields(x) for x in workspace_group.workspaces])
290
291
if params['like']:
292
res = res.like(Name=params['like'])
293
294
return res.order_by(**params['order_by']).limit(params['limit'])
295
296
297
ShowWorkspacesHandler.register(overwrite=True)
298
299
300
class CreateWorkspaceGroupHandler(SQLHandler):
301
"""
302
CREATE WORKSPACE GROUP [ if_not_exists ] group_name
303
IN REGION { region_id | region_name }
304
[ with_password ]
305
[ expires_at ]
306
[ with_firewall_ranges ]
307
[ with_backup_bucket_kms_key_id ]
308
[ with_data_bucket_kms_key_id ]
309
[ with_smart_dr ]
310
[ allow_all_traffic ]
311
[ with_update_window ]
312
;
313
314
# Only create workspace group if it doesn't exist already
315
if_not_exists = IF NOT EXISTS
316
317
# Name of the workspace group
318
group_name = '<group-name>'
319
320
# ID of region to create workspace group in
321
region_id = ID '<region-id>'
322
323
# Name of region to create workspace group in
324
region_name = '<region-name>'
325
326
# Admin password
327
with_password = WITH PASSWORD '<password>'
328
329
# Datetime or interval for expiration date/time of workspace group
330
expires_at = EXPIRES AT '<iso-datetime-or-interval>'
331
332
# Incoming IP ranges
333
with_firewall_ranges = WITH FIREWALL RANGES '<ip-range>',...
334
335
# Backup bucket key
336
with_backup_bucket_kms_key_id = WITH BACKUP BUCKET KMS KEY ID '<key-id>'
337
338
# Data bucket key
339
with_data_bucket_kms_key_id = WITH DATA BUCKET KMS KEY ID '<key-id>'
340
341
# Smart DR
342
with_smart_dr = WITH SMART DR
343
344
# Allow all incoming traffic
345
allow_all_traffic = ALLOW ALL TRAFFIC
346
347
# Update window
348
with_update_window = WITH UPDATE WINDOW '<day>:<hour>'
349
350
Description
351
-----------
352
Creates a workspace group.
353
354
Arguments
355
---------
356
* ``<group-name>``: The name of the workspace group.
357
* ``<region_id>`` or ``<region_name>``: The ID or the name of the region
358
in which the new workspace group is created.
359
* ``<password>``: The admin password of the workspace group.
360
The password must contain:
361
- At least 8 characters
362
- At least one uppercase character
363
- At least one lowercase character
364
- At least one number or special character
365
* ``<expiry_time>``: The timestamp of when the workspace group terminates.
366
Expiration time can be specified as a timestamp or duration.
367
* ``<ip_range>``: A list of allowed IP addresses or CIDR ranges.
368
* ``<backup_key_id>``: The KMS key ID associated with the backup bucket.
369
* ``<data_key_id>``: The KMS key ID associated with the data bucket.
370
* ``<day>:<hour>``: The day of the week (0-6) and the hour of the day
371
(0-23) when the engine updates are applied to the workspace group.
372
373
Remarks
374
-------
375
* Specify the ``IF NOT EXISTS`` clause to create a new workspace group only
376
if a workspace group with the specified name does not exist.
377
* If the ``WITH BACKUP BUCKET KMS KEY ID '<backup_key_id>'`` clause is
378
specified, Customer-Managed Encryption Keys (CMEK) encryption is enabled
379
for the data bucket of the workspace group.
380
* If the ``WITH DATA BUCKET KMS KEY ID '<data_key_id>'`` clause is specified,
381
CMEK encryption for the data bucket and Amazon Elastic Block Store (EBS)
382
volumes of the workspace group is enabled.
383
* To enable Smart Disaster Recovery (SmartDR) for the workspace group, specify
384
the WITH SMART DR clause. Refer to Smart Disaster Recovery (DR):
385
SmartDR for more information.
386
* To allow incoming traffic from any IP address, use the ``ALLOW ALL TRAFFIC``
387
clause.
388
389
Examples
390
--------
391
The following command creates a workspace group named wsg1 in the
392
US East 2 (Ohio) region::
393
394
CREATE WORKSPACE GROUP 'wsg1' IN REGION 'US East 2 (Ohio)';
395
396
The following command specifies additional workspace group configuration
397
options::
398
399
CREATE WORKSPACE GROUP 'wsg1'
400
IN REGION ID '93b61160-0000-1000-9000-977b8e2e3ee5'
401
WITH FIREWALL RANGES '0.0.0.0/0';
402
403
See Also
404
--------
405
* ``SHOW WORKSPACE GROUPS``
406
407
"""
408
409
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
410
manager = get_workspace_manager()
411
412
# Only create if one doesn't exist
413
if params['if_not_exists']:
414
try:
415
get_workspace_group(params)
416
return None
417
except (ValueError, KeyError):
418
pass
419
420
# Get region ID
421
if params['region_name']:
422
regs = [x for x in manager.regions if x.name == params['region_name']]
423
if not regs:
424
raise KeyError(f'no region found with name "{params["region_name"]}"')
425
if len(regs) > 1:
426
raise ValueError(
427
f'multiple regions found with the name "{params["region_name"]}"',
428
)
429
region_id = regs[0].id
430
else:
431
region_id = params['region_id']
432
433
with_update_window = None
434
if params['with_update_window']:
435
day, hour = params['with_update_window'].split(':', 1)
436
with_update_window = dict(day=int(day), hour=int(hour))
437
438
manager.create_workspace_group(
439
params['group_name'],
440
region=region_id,
441
admin_password=params['with_password'],
442
expires_at=params['expires_at'],
443
firewall_ranges=params['with_firewall_ranges'],
444
backup_bucket_kms_key_id=params['with_backup_bucket_kms_key_id'],
445
data_bucket_kms_key_id=params['with_data_bucket_kms_key_id'],
446
smart_dr=params['with_smart_dr'],
447
allow_all_traffic=params['allow_all_traffic'],
448
update_window=with_update_window,
449
)
450
451
return None
452
453
454
CreateWorkspaceGroupHandler.register(overwrite=True)
455
456
457
class CreateWorkspaceHandler(SQLHandler):
458
"""
459
CREATE WORKSPACE [ if_not_exists ] workspace_name
460
[ in_group ]
461
WITH SIZE size
462
[ auto_suspend ]
463
[ enable_kai ]
464
[ with_cache_config ]
465
[ wait_on_active ];
466
467
# Create workspace in workspace group
468
in_group = IN GROUP { group_id | group_name }
469
470
# Only run command if workspace doesn't already exist
471
if_not_exists = IF NOT EXISTS
472
473
# Name of the workspace
474
workspace_name = '<workspace-name>'
475
476
# ID of the group to create workspace in
477
group_id = ID '<group-id>'
478
479
# Name of the group to create workspace in
480
group_name = '<group-name>'
481
482
# Runtime size
483
size = '<size>'
484
485
# Auto-suspend
486
auto_suspend = AUTO SUSPEND AFTER suspend_after_value suspend_after_units suspend_type
487
suspend_after_value = <integer>
488
suspend_after_units = { SECONDS | MINUTES | HOURS | DAYS }
489
suspend_type = WITH TYPE { IDLE | SCHEDULED | DISABLED }
490
491
# Enable Kai
492
enable_kai = ENABLE KAI
493
494
# Cache config
495
with_cache_config = WITH CACHE CONFIG <integer>
496
497
# Wait for workspace to be active before continuing
498
wait_on_active = WAIT ON ACTIVE
499
500
Description
501
-----------
502
Creates a new workspace. Refer to
503
`Creating and Using Workspaces <https://docs.singlestore.com/cloud/getting-started-with-singlestore-helios/about-workspaces/creating-and-using-workspaces/>`_
504
for more information.
505
506
Arguments
507
---------
508
* ``<workspace_name>``: The name of the workspace.
509
* ``<group_id>`` or ``<group_name>``: The ID or name of the workspace group
510
in which the workspace is created.
511
* ``<workspace_size>``: The size of the workspace in workspace size notation,
512
for example "S-1".
513
* ``<suspend_time>``: The time (in given units) after which the workspace is
514
suspended, according to the specified auto-suspend type.
515
* ``<multiplier>``: The multiplier for the persistent cache associated with
516
the workspace.
517
518
Remarks
519
-------
520
* Use the ``IF NOT EXISTS`` clause to create a new workspace only if a workspace
521
with the specified name does not exist.
522
* If the ``WITH CACHE CONFIG <multiplier>`` clause is specified, the cache
523
configuration multiplier is enabled for the workspace. It can have the
524
following values: 1, 2, or 4.
525
* The ``WAIT ON ACTIVE`` clause indicates that the execution is paused until this
526
workspace is in ACTIVE state.
527
* Specify the ``ENABLE KAI`` clause to enable SingleStore Kai and the MongoDB®
528
API for the workspace.
529
530
Example
531
-------
532
The following command creates a workspace named **examplews** in a workspace
533
group named **wsg1**::
534
535
CREATE WORKSPACE 'examplews' IN GROUP 'wsgroup1'
536
WITH SIZE 'S-00' WAIT ON ACTIVE;
537
538
See Also
539
--------
540
* ``CREATE WORKSPACE GROUP``
541
542
""" # noqa: E501
543
544
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
545
workspace_group = get_workspace_group(params)
546
547
# Only create if one doesn't exist
548
if params['if_not_exists']:
549
try:
550
workspace_group.workspaces[params['workspace_name']]
551
return None
552
except KeyError:
553
pass
554
555
auto_suspend = None
556
if params['auto_suspend']:
557
mult = dict(
558
SECONDS=1,
559
MINUTES=60,
560
HOURS=60*60,
561
DAYS=60*60*24,
562
)
563
val = params['auto_suspend'][0]['suspend_after_value']
564
val = val * mult[params['auto_suspend'][1]['suspend_after_units'].upper()]
565
auto_suspend = dict(
566
suspend_after_seconds=val,
567
suspend_type=params['auto_suspend'][2]['suspend_type'].upper(),
568
)
569
570
workspace_group.create_workspace(
571
params['workspace_name'],
572
size=params['size'],
573
auto_suspend=auto_suspend,
574
enable_kai=params['enable_kai'],
575
cache_config=params['with_cache_config'],
576
wait_on_active=params['wait_on_active'],
577
)
578
579
return None
580
581
582
CreateWorkspaceHandler.register(overwrite=True)
583
584
585
class SuspendWorkspaceHandler(SQLHandler):
586
"""
587
SUSPEND WORKSPACE workspace
588
[ in_group ]
589
[ wait_on_suspended ];
590
591
# Workspace
592
workspace = { workspace_id | workspace_name }
593
594
# ID of workspace
595
workspace_id = ID '<workspace-id>'
596
597
# Name of workspace
598
workspace_name = '<workspace-name>'
599
600
# Workspace group
601
in_group = IN GROUP { group_id | group_name }
602
603
# ID of workspace group
604
group_id = ID '<group-id>'
605
606
# Name of workspace group
607
group_name = '<group-name>'
608
609
# Wait for workspace to be suspended before continuing
610
wait_on_suspended = WAIT ON SUSPENDED
611
612
Description
613
-----------
614
Suspends a workspace.
615
616
Refer to `Manage Workspaces <https://docs.singlestore.com/cloud/user-and-workspace-administration/manage-organizations/manage-workspaces/>`_
617
for more information.
618
619
Arguments
620
---------
621
* ``<workspace-id>``: The ID of the workspace to suspend.
622
* ``<workspace-name>``: The name of the workspace to suspend.
623
* ``<group-id>``: The ID of the workspace group that contains
624
the workspace.
625
* ``<group-name>``: The name of the workspace group that
626
contains the workspace.
627
628
Remarks
629
-------
630
* Use the ``WAIT ON SUSPENDED`` clause to pause query execution
631
until the workspace is in the ``SUSPENDED`` state.
632
633
Example
634
-------
635
The following example suspends a workspace named examplews in
636
a workspace group named **wsg1**::
637
638
SUSPEND WORKSPACE 'examplews' IN GROUP 'wsg1';
639
640
See Also
641
--------
642
* ``RESUME WORKSPACE``
643
644
""" # noqa: E501
645
646
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
647
ws = get_workspace(params)
648
ws.suspend(wait_on_suspended=params['wait_on_suspended'])
649
return None
650
651
652
SuspendWorkspaceHandler.register(overwrite=True)
653
654
655
class ResumeWorkspaceHandler(SQLHandler):
656
"""
657
RESUME WORKSPACE workspace
658
[ in_group ]
659
[ disable_auto_suspend ]
660
[ wait_on_resumed ];
661
662
# Workspace
663
workspace = { workspace_id | workspace_name }
664
665
# ID of workspace
666
workspace_id = ID '<workspace-id>'
667
668
# Name of workspace
669
workspace_name = '<workspace-name>'
670
671
# Workspace group
672
in_group = IN GROUP { group_id | group_name }
673
674
# ID of workspace group
675
group_id = ID '<group-id>'
676
677
# Name of workspace group
678
group_name = '<group-name>'
679
680
# Disable auto-suspend
681
disable_auto_suspend = DISABLE AUTO SUSPEND
682
683
# Wait for workspace to be resumed before continuing
684
wait_on_resumed = WAIT ON RESUMED
685
686
Description
687
-----------
688
Resumes a workspace.
689
690
Refer to `Manage Workspaces <https://docs.singlestore.com/cloud/user-and-workspace-administration/manage-organizations/manage-workspaces/>`_
691
for more information.
692
693
Arguments
694
---------
695
* ``<workspace-id>``: The ID of the workspace to resume.
696
* ``<workspace-name>``: The name of the workspace to resume.
697
* ``<group_id>``: The ID of the workspace group that contains
698
the workspace.
699
* ``<group_name>``: The name of the workspace group that
700
contains the workspace.
701
702
Remarks
703
-------
704
* Use the ``IN GROUP`` clause to specify the ID or name of the
705
workspace group that contains the workspace to resume.
706
* Use the ``WAIT ON RESUMED`` clause to pause query execution
707
until the workspace is in the ``RESUMED`` state.
708
* Specify the ``DISABLE AUTO SUSPEND`` clause to disable
709
auto-suspend for the resumed workspace.
710
711
Example
712
-------
713
The following example resumes a workspace with the specified ID
714
in a workspace group named **wsg1**::
715
716
RESUME WORKSPACE ID '93b61160-0000-1000-9000-977b8e2e3ee5'
717
IN GROUP 'wsg1';
718
719
""" # noqa: E501
720
721
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
722
ws = get_workspace(params)
723
ws.resume(
724
wait_on_resumed=params['wait_on_resumed'],
725
disable_auto_suspend=params['disable_auto_suspend'],
726
)
727
return None
728
729
730
ResumeWorkspaceHandler.register(overwrite=True)
731
732
733
class DropWorkspaceGroupHandler(SQLHandler):
734
"""
735
DROP WORKSPACE GROUP [ if_exists ]
736
group
737
[ wait_on_terminated ]
738
[ force ];
739
740
# Only run command if the workspace group exists
741
if_exists = IF EXISTS
742
743
# Workspace group
744
group = { group_id | group_name }
745
746
# ID of the workspace group to delete
747
group_id = ID '<group-id>'
748
749
# Name of the workspace group to delete
750
group_name = '<group-name>'
751
752
# Wait for termination to complete before continuing
753
wait_on_terminated = WAIT ON TERMINATED
754
755
# Should the workspace group be terminated even if it has workspaces?
756
force = FORCE
757
758
Description
759
-----------
760
Deletes the specified workspace group.
761
762
Arguments
763
---------
764
* ``<group_id>``: The ID of the workspace group to delete.
765
* ``<group_name>``: The name of the workspace group to delete.
766
767
Remarks
768
-------
769
* Specify the ``IF EXISTS`` clause to attempt the delete operation
770
only if a workspace group with the specified ID or name exists.
771
* Use the ``WAIT ON TERMINATED`` clause to pause query execution until
772
the workspace group is in the ``TERMINATED`` state.
773
* If the ``FORCE`` clause is specified, the workspace group is
774
terminated even if it contains workspaces.
775
776
Example
777
-------
778
The following command deletes a workspace group named **wsg1** even
779
if it contains workspaces::
780
781
DROP WORKSPACE GROUP 'wsg1' FORCE;
782
783
See Also
784
--------
785
* ``DROP WORKSPACE``
786
787
"""
788
789
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
790
try:
791
workspace_group = get_workspace_group(params)
792
if workspace_group.terminated_at is not None:
793
raise KeyError('workspace group is alread terminated')
794
workspace_group.terminate(
795
wait_on_terminated=params['wait_on_terminated'],
796
force=params['force'],
797
)
798
799
except KeyError:
800
if not params['if_exists']:
801
raise
802
803
return None
804
805
806
DropWorkspaceGroupHandler.register(overwrite=True)
807
808
809
class DropWorkspaceHandler(SQLHandler):
810
"""
811
DROP WORKSPACE [ if_exists ]
812
workspace
813
[ in_group ]
814
[ wait_on_terminated ];
815
816
# Only drop workspace if it exists
817
if_exists = IF EXISTS
818
819
# Workspace
820
workspace = { workspace_id | workspace_name }
821
822
# ID of workspace
823
workspace_id = ID '<workspace-id>'
824
825
# Name of workspace
826
workspace_name = '<workspace-name>'
827
828
# Workspace group
829
in_group = IN GROUP { group_id | group_name }
830
831
# ID of workspace group
832
group_id = ID '<group-id>'
833
834
# Name of workspace group
835
group_name = '<group-name>'
836
837
# Wait for workspace to be terminated before continuing
838
wait_on_terminated = WAIT ON TERMINATED
839
840
Description
841
-----------
842
Deletes a workspace.
843
844
Arguments
845
---------
846
* ``<workspace-id>``: The ID of the workspace to delete.
847
* ``<workspace-name>``: The name of the workspace to delete.
848
* ``<group_id>``: The ID of the workspace group that contains
849
the workspace.
850
* ``<group_name>``: The name of the workspace group that
851
contains the workspace.
852
853
Remarks
854
-------
855
* Specify the ``IF EXISTS`` clause to attempt the delete operation
856
only if a workspace with the specified ID or name exists.
857
* Use the ``IN GROUP`` clause to specify the ID or name of the workspace
858
group that contains the workspace to delete.
859
* Use the ``WAIT ON TERMINATED`` clause to pause query execution until
860
the workspace is in the ``TERMINATED`` state.
861
* All databases attached to the workspace are detached when the
862
workspace is deleted (terminated).
863
864
Example
865
-------
866
The following example deletes a workspace named **examplews** in
867
a workspace group **wsg1**::
868
869
DROP WORKSPACE IF EXISTS 'examplews' IN GROUP 'wsg1';
870
871
See Also
872
--------
873
* ``DROP WORKSPACE GROUP``
874
875
"""
876
877
def run(self, params: Dict[str, Any]) -> Optional[FusionSQLResult]:
878
try:
879
ws = get_workspace(params)
880
if ws.terminated_at is not None:
881
raise KeyError('workspace is already terminated')
882
ws.terminate(wait_on_terminated=params['wait_on_terminated'])
883
884
except KeyError:
885
if not params['if_exists']:
886
raise
887
888
return None
889
890
891
DropWorkspaceHandler.register(overwrite=True)
892
893