/
ddl.py
511 lines (389 loc) · 12.7 KB
/
ddl.py
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
345
346
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
455
456
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
500
501
502
503
504
505
506
507
508
509
510
511
import re
import ibis.expr.datatypes as dt
import ibis.expr.schema as sch
from ibis.backends.base.sql.compiler import DDL, DML
from ibis.backends.base.sql.registry import (
quote_identifier,
type_to_sql_string,
)
fully_qualified_re = re.compile(r"(.*)\.(?:`(.*)`|(.*))")
_format_aliases = {'TEXT': 'TEXTFILE'}
def _sanitize_format(format):
if format is None:
return
format = format.upper()
format = _format_aliases.get(format, format)
if format not in ('PARQUET', 'AVRO', 'TEXTFILE'):
raise ValueError(f'Invalid format: {format!r}')
return format
def is_fully_qualified(x):
return bool(fully_qualified_re.search(x))
def _is_quoted(x):
regex = re.compile(r"(?:`(.*)`|(.*))")
quoted, _ = regex.match(x).groups()
return quoted is not None
def format_schema(schema):
elements = [
_format_schema_element(name, t)
for name, t in zip(schema.names, schema.types)
]
return '({})'.format(',\n '.join(elements))
def _format_schema_element(name, t):
return '{} {}'.format(
quote_identifier(name, force=True),
type_to_sql_string(t),
)
def _format_partition_kv(k, v, type):
if type == dt.string:
value_formatted = f'"{v}"'
else:
value_formatted = str(v)
return f'{k}={value_formatted}'
def format_partition(partition, partition_schema):
tokens = []
if isinstance(partition, dict):
for name in partition_schema:
if name in partition:
tok = _format_partition_kv(
name, partition[name], partition_schema[name]
)
else:
# dynamic partitioning
tok = name
tokens.append(tok)
else:
for name, value in zip(partition_schema, partition):
tok = _format_partition_kv(name, value, partition_schema[name])
tokens.append(tok)
return 'PARTITION ({})'.format(', '.join(tokens))
def _format_properties(props):
tokens = []
for k, v in sorted(props.items()):
tokens.append(f" '{k}'='{v}'")
return '(\n{}\n)'.format(',\n'.join(tokens))
def format_tblproperties(props):
formatted_props = _format_properties(props)
return f'TBLPROPERTIES {formatted_props}'
def _serdeproperties(props):
formatted_props = _format_properties(props)
return f'SERDEPROPERTIES {formatted_props}'
class _BaseQualifiedSQLStatement:
def _get_scoped_name(self, obj_name, database):
if database:
scoped_name = f'{database}.`{obj_name}`'
else:
if not is_fully_qualified(obj_name):
if _is_quoted(obj_name):
return obj_name
else:
return f'`{obj_name}`'
else:
return obj_name
return scoped_name
class BaseDDL(DDL, _BaseQualifiedSQLStatement):
pass
class _BaseDML(DML, _BaseQualifiedSQLStatement):
pass
class _CreateDDL(BaseDDL):
def _if_exists(self):
return 'IF NOT EXISTS ' if self.can_exist else ''
class CreateTable(_CreateDDL):
"""
Parameters
----------
partition :
"""
def __init__(
self,
table_name,
database=None,
external=False,
format='parquet',
can_exist=False,
partition=None,
path=None,
tbl_properties=None,
):
self.table_name = table_name
self.database = database
self.partition = partition
self.path = path
self.external = external
self.can_exist = can_exist
self.format = _sanitize_format(format)
self.tbl_properties = tbl_properties
@property
def _prefix(self):
if self.external:
return 'CREATE EXTERNAL TABLE'
else:
return 'CREATE TABLE'
def _create_line(self):
scoped_name = self._get_scoped_name(self.table_name, self.database)
return f'{self._prefix} {self._if_exists()}{scoped_name}'
def _location(self):
return f"LOCATION '{self.path}'" if self.path else None
def _storage(self):
# By the time we're here, we have a valid format
return f'STORED AS {self.format}'
@property
def pieces(self):
yield self._create_line()
yield from filter(None, self._pieces)
def compile(self):
return '\n'.join(self.pieces)
class CTAS(CreateTable):
"""
Create Table As Select
"""
def __init__(
self,
table_name,
select,
database=None,
external=False,
format='parquet',
can_exist=False,
path=None,
partition=None,
):
super().__init__(
table_name,
database=database,
external=external,
format=format,
can_exist=can_exist,
path=path,
partition=partition,
)
self.select = select
@property
def _pieces(self):
yield self._partitioned_by()
yield self._storage()
yield self._location()
yield 'AS'
yield self.select.compile()
def _partitioned_by(self):
if self.partition is not None:
return 'PARTITIONED BY ({})'.format(
', '.join(
quote_identifier(expr.get_name())
for expr in self.partition
)
)
return None
class CreateView(CTAS):
"""Create a view"""
def __init__(self, table_name, select, database=None, can_exist=False):
super().__init__(
table_name, select, database=database, can_exist=can_exist
)
@property
def _pieces(self):
yield 'AS'
yield self.select.compile()
@property
def _prefix(self):
return 'CREATE VIEW'
class CreateTableWithSchema(CreateTable):
def __init__(self, table_name, schema, table_format=None, **kwargs):
super().__init__(table_name, **kwargs)
self.schema = schema
self.table_format = table_format
@property
def _pieces(self):
if self.partition is not None:
main_schema = self.schema
part_schema = self.partition
if not isinstance(part_schema, sch.Schema):
part_schema = sch.Schema(
part_schema, [self.schema[name] for name in part_schema]
)
to_delete = []
for name in self.partition:
if name in self.schema:
to_delete.append(name)
if len(to_delete):
main_schema = main_schema.delete(to_delete)
yield format_schema(main_schema)
yield f'PARTITIONED BY {format_schema(part_schema)}'
else:
yield format_schema(self.schema)
if self.table_format is not None:
yield '\n'.join(self.table_format.to_ddl())
else:
yield self._storage()
yield self._location()
class CreateDatabase(_CreateDDL):
def __init__(self, name, path=None, can_exist=False):
self.name = name
self.path = path
self.can_exist = can_exist
def compile(self):
name = quote_identifier(self.name)
create_decl = 'CREATE DATABASE'
create_line = f'{create_decl} {self._if_exists()}{name}'
if self.path is not None:
create_line += f"\nLOCATION '{self.path}'"
return create_line
class DropObject(BaseDDL):
def __init__(self, must_exist=True):
self.must_exist = must_exist
def compile(self):
if_exists = '' if self.must_exist else 'IF EXISTS '
object_name = self._object_name()
return f'DROP {self._object_type} {if_exists}{object_name}'
class DropDatabase(DropObject):
_object_type = 'DATABASE'
def __init__(self, name, must_exist=True):
super().__init__(must_exist=must_exist)
self.name = name
def _object_name(self):
return self.name
class DropTable(DropObject):
_object_type = 'TABLE'
def __init__(self, table_name, database=None, must_exist=True):
super().__init__(must_exist=must_exist)
self.table_name = table_name
self.database = database
def _object_name(self):
return self._get_scoped_name(self.table_name, self.database)
class DropView(DropTable):
_object_type = 'VIEW'
class TruncateTable(BaseDDL):
_object_type = 'TABLE'
def __init__(self, table_name, database=None):
self.table_name = table_name
self.database = database
def compile(self):
name = self._get_scoped_name(self.table_name, self.database)
return f'TRUNCATE TABLE {name}'
class InsertSelect(_BaseDML):
def __init__(
self,
table_name,
select_expr,
database=None,
partition=None,
partition_schema=None,
overwrite=False,
):
self.table_name = table_name
self.database = database
self.select = select_expr
self.partition = partition
self.partition_schema = partition_schema
self.overwrite = overwrite
def compile(self):
if self.overwrite:
cmd = 'INSERT OVERWRITE'
else:
cmd = 'INSERT INTO'
if self.partition is not None:
part = format_partition(self.partition, self.partition_schema)
partition = f' {part} '
else:
partition = ''
select_query = self.select.compile()
scoped_name = self._get_scoped_name(self.table_name, self.database)
return f'{cmd} {scoped_name}{partition}\n{select_query}'
class AlterTable(BaseDDL):
def __init__(
self,
table,
location=None,
format=None,
tbl_properties=None,
serde_properties=None,
):
self.table = table
self.location = location
self.format = _sanitize_format(format)
self.tbl_properties = tbl_properties
self.serde_properties = serde_properties
def _wrap_command(self, cmd):
return f'ALTER TABLE {cmd}'
def _format_properties(self, prefix=''):
tokens = []
if self.location is not None:
tokens.append(f"LOCATION '{self.location}'")
if self.format is not None:
tokens.append(f"FILEFORMAT {self.format}")
if self.tbl_properties is not None:
tokens.append(format_tblproperties(self.tbl_properties))
if self.serde_properties is not None:
tokens.append(_serdeproperties(self.serde_properties))
if len(tokens) > 0:
return '\n{}{}'.format(prefix, '\n'.join(tokens))
else:
return ''
def compile(self):
props = self._format_properties()
action = f'{self.table} SET {props}'
return self._wrap_command(action)
class DropFunction(DropObject):
def __init__(
self, name, inputs, must_exist=True, aggregate=False, database=None
):
super().__init__(must_exist=must_exist)
self.name = name
self.inputs = tuple(map(dt.dtype, inputs))
self.must_exist = must_exist
self.aggregate = aggregate
self.database = database
def _object_name(self):
return self.name
def compile(self):
tokens = ['DROP']
if self.aggregate:
tokens.append('AGGREGATE')
tokens.append('FUNCTION')
if not self.must_exist:
tokens.append('IF EXISTS')
tokens.append(self._impala_signature())
return ' '.join(tokens)
class RenameTable(AlterTable):
def __init__(
self, old_name, new_name, old_database=None, new_database=None
):
# if either database is None, the name is assumed to be fully scoped
self.old_name = old_name
self.old_database = old_database
self.new_name = new_name
self.new_database = new_database
new_qualified_name = new_name
if new_database is not None:
new_qualified_name = self._get_scoped_name(new_name, new_database)
old_qualified_name = old_name
if old_database is not None:
old_qualified_name = self._get_scoped_name(old_name, old_database)
self.old_qualified_name = old_qualified_name
self.new_qualified_name = new_qualified_name
def compile(self):
cmd = '{} RENAME TO {}'.format(
self.old_qualified_name, self.new_qualified_name
)
return self._wrap_command(cmd)
__all__ = (
'fully_qualified_re',
'is_fully_qualified',
'format_schema',
'format_partition',
'format_tblproperties',
'BaseDDL',
'CreateTable',
'CTAS',
'CreateView',
'CreateTableWithSchema',
'CreateDatabase',
'DropObject',
'DropDatabase',
'DropTable',
'DropView',
'TruncateTable',
'InsertSelect',
'AlterTable',
'DropFunction',
'RenameTable',
)