Project

General

Profile

1
# SQL code generation
2

    
3
import copy
4
import operator
5
import re
6
import UserDict
7
import warnings
8

    
9
import dicts
10
import exc
11
import iters
12
import lists
13
import objects
14
import strings
15
import util
16

    
17
##### Names
18

    
19
identifier_max_len = 63 # works for both PostgreSQL and MySQL
20

    
21
def concat(str_, suffix):
22
    '''Preserves version so that it won't be truncated off the string, leading
23
    to collisions.'''
24
    # Preserve version
25
    match = re.match(r'^(.*?)((?:(?:#\d+)?\)?)*(?:\.\w+)?(?:::[\w ]+)*)$', str_)
26
    if match:
27
        str_, old_suffix = match.groups()
28
        suffix = old_suffix+suffix
29
    
30
    return strings.concat(str_, suffix, identifier_max_len)
31

    
32
def truncate(str_): return concat(str_, '')
33

    
34
def is_safe_name(name):
35
    '''A name is safe *and unambiguous* if it:
36
    * contains only *lowercase* word (\w) characters
37
    * doesn't start with a digit
38
    * contains "_", so that it's not a keyword
39
    '''
40
    return re.match(r'^(?=.*_)(?!\d)[^\WA-Z]+$', name)
41

    
42
def esc_name(name, quote='"'):
43
    return quote + name.replace(quote, quote+quote) + quote
44
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
45

    
46
def clean_name(name): return name.replace('"', '').replace('`', '')
47

    
48
def esc_comment(comment): return '/*'+comment.replace('*/', '* /')+'*/'
49

    
50
##### General SQL code objects
51

    
52
class MockDb:
53
    def esc_value(self, value): return strings.repr_no_u(value)
54
    
55
    def esc_name(self, name): return esc_name(name)
56
    
57
    def col_info(self, col):
58
        return TypedCol(col.name, '<type>', CustomCode('<default>'), True)
59

    
60
mockDb = MockDb()
61

    
62
class BasicObject(objects.BasicObject):
63
    def __init__(self, value): self.value = value
64
    
65
    def __str__(self): return clean_name(strings.repr_no_u(self))
66

    
67
##### Unparameterized code objects
68

    
69
class Code(BasicObject):
70
    def to_str(self, db): raise NotImplementedError()
71
    
72
    def __repr__(self): return self.to_str(mockDb)
73

    
74
class CustomCode(Code):
75
    def __init__(self, str_): self.str_ = str_
76
    
77
    def to_str(self, db): return self.str_
78

    
79
def as_Code(value, db=None):
80
    '''
81
    @param db If set, runs db.std_code() on the value.
82
    '''
83
    if util.is_str(value):
84
        if db != None: value = db.std_code(value)
85
        return CustomCode(value)
86
    else: return Literal(value)
87

    
88
class Expr(Code):
89
    def __init__(self, expr): self.expr = expr
90
    
91
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
92

    
93
##### Names
94

    
95
class Name(Code):
96
    def __init__(self, name): self.name = name
97
    
98
    def to_str(self, db): return db.esc_name(self.name)
99

    
100
def as_Name(value):
101
    if isinstance(value, Code): return value
102
    else: return Name(value)
103

    
104
##### Literal values
105

    
106
class Literal(Code):
107
    def __init__(self, value): self.value = value
108
    
109
    def to_str(self, db): return db.esc_value(self.value)
110

    
111
def as_Value(value):
112
    if isinstance(value, Code): return value
113
    else: return Literal(value)
114

    
115
def is_null(value): return isinstance(value, Literal) and value.value == None
116

    
117
##### Derived elements
118

    
119
src_self = object() # tells Col that it is its own source column
120

    
121
class Derived(Code):
122
    def __init__(self, srcs):
123
        '''An element which was derived from some other element(s).
124
        @param srcs See self.set_srcs()
125
        '''
126
        self.set_srcs(srcs)
127
    
128
    def set_srcs(self, srcs, overwrite=True):
129
        '''
130
        @param srcs (self_type...)|src_self The element(s) this is derived from
131
        '''
132
        if not overwrite and self.srcs != (): return # already set
133
        
134
        if srcs == src_self: srcs = (self,)
135
        srcs = tuple(srcs) # make Col hashable
136
        self.srcs = srcs
137
    
138
    def _compare_on(self):
139
        compare_on = self.__dict__.copy()
140
        del compare_on['srcs'] # ignore
141
        return compare_on
142

    
143
def cols_srcs(cols): return lists.uniqify(iters.flatten((v.srcs for v in cols)))
144

    
145
##### Tables
146

    
147
class Table(Derived):
148
    def __init__(self, name, schema=None, srcs=(), is_temp=False):
149
        '''
150
        @param schema str|None (for no schema)
151
        @param srcs (Table...)|src_self See Derived.set_srcs()
152
        '''
153
        Derived.__init__(self, srcs)
154
        
155
        name = truncate(name)
156
        
157
        self.name = name
158
        self.schema = schema
159
        self.is_temp = is_temp
160
        self.index_cols = {}
161
    
162
    def to_str(self, db):
163
        str_ = ''
164
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
165
        str_ += db.esc_name(self.name)
166
        return str_
167
    
168
    def to_Table(self): return self
169
    
170
    def _compare_on(self):
171
        compare_on = Derived._compare_on(self)
172
        del compare_on['index_cols'] # ignore
173
        return compare_on
174

    
175
def is_underlying_table(table):
176
    return isinstance(table, Table) and table.to_Table() is table
177

    
178
class NoUnderlyingTableException(Exception): pass
179

    
180
def underlying_table(table):
181
    table = remove_table_rename(table)
182
    if not is_underlying_table(table): raise NoUnderlyingTableException
183
    return table
184

    
185
def as_Table(table, schema=None):
186
    if table == None or isinstance(table, Code): return table
187
    else: return Table(table, schema)
188

    
189
def suffixed_table(table, suffix): return Table(table.name+suffix, table.schema)
190

    
191
class NamedTable(Table):
192
    def __init__(self, name, code, cols=None):
193
        Table.__init__(self, name)
194
        
195
        code = as_Table(code)
196
        if not isinstance(code, (Table, FunctionCall, Expr)): code = Expr(code)
197
        if cols != None: cols = [to_name_only_col(c).to_Col() for c in cols]
198
        
199
        self.code = code
200
        self.cols = cols
201
    
202
    def to_str(self, db):
203
        str_ = self.code.to_str(db)
204
        if str_.find('\n') >= 0: whitespace = '\n'
205
        else: whitespace = ' '
206
        str_ += whitespace+'AS '+Table.to_str(self, db)
207
        if self.cols != None:
208
            str_ += ' ('+(', '.join((c.to_str(db) for c in self.cols)))+')'
209
        return str_
210
    
211
    def to_Table(self): return Table(self.name)
212

    
213
def remove_table_rename(table):
214
    if isinstance(table, NamedTable): table = table.code
215
    return table
216

    
217
##### Columns
218

    
219
class Col(Derived):
220
    def __init__(self, name, table=None, srcs=()):
221
        '''
222
        @param table Table|None (for no table)
223
        @param srcs (Col...)|src_self See Derived.set_srcs()
224
        '''
225
        Derived.__init__(self, srcs)
226
        
227
        name = truncate(name)
228
        if util.is_str(table): table = Table(table)
229
        assert table == None or isinstance(table, Table)
230
        
231
        self.name = name
232
        self.table = table
233
    
234
    def to_str(self, db, for_str=False):
235
        str_ = db.esc_name(self.name)
236
        if for_str: str_ = clean_name(str_)
237
        if self.table != None:
238
            table = self.table.to_Table()
239
            if for_str: str_ = concat(str(table), '.'+str_)
240
            else: str_ = table.to_str(db)+'.'+str_
241
        return str_
242
    
243
    def __str__(self): return self.to_str(mockDb, for_str=True)
244
    
245
    def to_Col(self): return self
246

    
247
def is_table_col(col): return isinstance(col, Col) and col.table != None
248

    
249
def index_col(col):
250
    if not is_table_col(col): return None
251
    return col.table.index_cols.get(col.name, None)
252

    
253
def is_temp_col(col): return is_table_col(col) and col.table.is_temp
254

    
255
def as_Col(col, table=None, name=None):
256
    '''
257
    @param name If not None, any non-Col input will be renamed using NamedCol.
258
    '''
259
    if name != None:
260
        col = as_Value(col)
261
        if not isinstance(col, Col): col = NamedCol(name, col)
262
    
263
    if isinstance(col, Code): return col
264
    else: return Col(col, table)
265

    
266
def with_default_table(col, table, overwrite=False):
267
    col = as_Col(col)
268
    if not isinstance(col, NamedCol) and (overwrite or col.table == None):
269
        col = copy.copy(col) # don't modify input!
270
        col.table = table
271
    return col
272

    
273
def set_cols_table(table, cols):
274
    table = as_Table(table)
275
    
276
    for i, col in enumerate(cols):
277
        col = cols[i] = as_Col(col)
278
        col.table = table
279

    
280
def to_name_only_col(col, check_table=None):
281
    col = as_Col(col)
282
    if not is_table_col(col): return col
283
    
284
    if check_table != None:
285
        table = col.table
286
        assert table == None or table == check_table
287
    return Col(col.name)
288

    
289
def suffixed_col(col, suffix):
290
    return Col(concat(col.name, suffix), col.table, col.srcs)
291

    
292
class NamedCol(Col):
293
    def __init__(self, name, code):
294
        Col.__init__(self, name)
295
        
296
        code = as_Value(code)
297
        
298
        self.code = code
299
    
300
    def to_str(self, db):
301
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
302
    
303
    def to_Col(self): return Col(self.name)
304

    
305
def remove_col_rename(col):
306
    if isinstance(col, NamedCol): col = col.code
307
    return col
308

    
309
def underlying_col(col):
310
    col = remove_col_rename(col)
311
    if not isinstance(col, Col): raise NoUnderlyingTableException
312
    
313
    return Col(col.name, underlying_table(col.table), col.srcs)
314

    
315
def wrap(wrap_func, value):
316
    '''Wraps a value, propagating any column renaming to the returned value.'''
317
    if isinstance(value, NamedCol):
318
        return NamedCol(value.name, wrap_func(value.code))
319
    else: return wrap_func(value)
320

    
321
class ColDict(dicts.DictProxy):
322
    '''A dict that automatically makes inserted entries Col objects'''
323
    
324
    def __init__(self, db, keys_table, dict_={}):
325
        dicts.DictProxy.__init__(self, {})
326
        
327
        keys_table = as_Table(keys_table)
328
        
329
        self.db = db
330
        self.table = keys_table
331
        self.update(dict_) # after setting vars because __setitem__() needs them
332
    
333
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
334
    
335
    def __getitem__(self, key):
336
        return dicts.DictProxy.__getitem__(self, self._key(key))
337
    
338
    def __setitem__(self, key, value):
339
        key = self._key(key)
340
        if value == None: value = self.db.col_info(key).default
341
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
342
    
343
    def _key(self, key): return as_Col(key, self.table)
344

    
345
##### Functions
346

    
347
Function = Table
348
as_Function = as_Table
349

    
350
class InternalFunction(CustomCode): pass
351

    
352
class NamedArg(NamedCol):
353
    def __init__(self, name, value):
354
        NamedCol.__init__(self, name, value)
355
    
356
    def to_str(self, db):
357
        return Col.to_str(self, db)+' := '+self.code.to_str(db)
358

    
359
class FunctionCall(Code):
360
    def __init__(self, function, *args, **kw_args):
361
        '''
362
        @param args [Code|literal-value...] The function's arguments
363
        '''
364
        function = as_Function(function)
365
        def filter_(arg): return remove_col_rename(as_Value(arg))
366
        args = map(filter_, args)
367
        args += [NamedArg(k, filter_(v)) for k, v in kw_args.iteritems()]
368
        
369
        self.function = function
370
        self.args = args
371
    
372
    def to_str(self, db):
373
        args_str = ', '.join((v.to_str(db) for v in self.args))
374
        return self.function.to_str(db)+'('+args_str+')'
375

    
376
def wrap_in_func(function, value):
377
    '''Wraps a value inside a function call.
378
    Propagates any column renaming to the returned value.
379
    '''
380
    return wrap(lambda v: FunctionCall(function, v), value)
381

    
382
def unwrap_func_call(func_call, check_name=None):
383
    '''Unwraps any function call to its first argument.
384
    Also removes any column renaming.
385
    '''
386
    func_call = remove_col_rename(func_call)
387
    if not isinstance(func_call, FunctionCall): return func_call
388
    
389
    if check_name != None:
390
        name = func_call.function.name
391
        assert name == None or name == check_name
392
    return func_call.args[0]
393

    
394
##### Casts
395

    
396
class Cast(FunctionCall):
397
    def __init__(self, type_, value):
398
        value = as_Value(value)
399
        
400
        self.type_ = type_
401
        self.value = value
402
    
403
    def to_str(self, db):
404
        return 'CAST('+self.value.to_str(db)+' AS '+self.type_+')'
405

    
406
##### Conditions
407

    
408
class ColValueCond(Code):
409
    def __init__(self, col, value):
410
        value = as_ValueCond(value)
411
        
412
        self.col = col
413
        self.value = value
414
    
415
    def to_str(self, db): return self.value.to_str(db, self.col)
416

    
417
def combine_conds(conds, keyword=None):
418
    '''
419
    @param keyword The keyword to add before the conditions, if any
420
    '''
421
    str_ = ''
422
    if keyword != None:
423
        if conds == []: whitespace = ''
424
        elif len(conds) == 1: whitespace = ' '
425
        else: whitespace = '\n'
426
        str_ += keyword+whitespace
427
    
428
    str_ += '\nAND '.join(conds)
429
    return str_
430

    
431
##### Condition column comparisons
432

    
433
class ValueCond(BasicObject):
434
    def __init__(self, value):
435
        value = remove_col_rename(as_Value(value))
436
        
437
        self.value = value
438
    
439
    def to_str(self, db, left_value):
440
        '''
441
        @param left_value The Code object that the condition is being applied on
442
        '''
443
        raise NotImplemented()
444
    
445
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
446

    
447
class CompareCond(ValueCond):
448
    def __init__(self, value, operator='='):
449
        '''
450
        @param operator By default, compares NULL values literally. Use '~=' or
451
            '~!=' to pass NULLs through.
452
        '''
453
        ValueCond.__init__(self, value)
454
        self.operator = operator
455
    
456
    def to_str(self, db, left_value):
457
        left_value = remove_col_rename(as_Col(left_value))
458
        
459
        right_value = self.value
460
        
461
        # Parse operator
462
        operator = self.operator
463
        passthru_null_ref = [False]
464
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
465
        neg_ref = [False]
466
        operator = strings.remove_prefix('!', operator, neg_ref)
467
        equals = operator.endswith('=') # also includes <=, >=
468
        
469
        # Handle nullable columns
470
        check_null = False
471
        if not passthru_null_ref[0]: # NULLs compare equal
472
            try: left_value = ensure_not_null(db, left_value)
473
            except ensure_not_null_excs: # fall back to alternate method
474
                check_null = equals and isinstance(right_value, Col)
475
            else:
476
                if isinstance(left_value, EnsureNotNull):
477
                    right_value = ensure_not_null(db, right_value,
478
                        left_value.type) # apply same function to both sides
479
        
480
        if equals and is_null(right_value): operator = 'IS'
481
        
482
        left = left_value.to_str(db)
483
        right = right_value.to_str(db)
484
        
485
        # Create str
486
        str_ = left+' '+operator+' '+right
487
        if check_null:
488
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
489
        if neg_ref[0]: str_ = 'NOT '+str_
490
        return str_
491

    
492
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
493
assume_literal = object()
494

    
495
def as_ValueCond(value, default_table=assume_literal):
496
    if not isinstance(value, ValueCond):
497
        if default_table is not assume_literal:
498
            value = with_default_table(value, default_table)
499
        return CompareCond(value)
500
    else: return value
501

    
502
##### Joins
503

    
504
join_same = object() # tells Join the left and right columns have the same name
505

    
506
# Tells Join the left and right columns have the same name and are never NULL
507
join_same_not_null = object()
508

    
509
filter_out = object() # tells Join to filter out rows that match the join
510

    
511
class Join(BasicObject):
512
    def __init__(self, table, mapping={}, type_=None):
513
        '''
514
        @param mapping dict(right_table_col=left_table_col, ...)
515
            * if left_table_col is join_same: left_table_col = right_table_col
516
              * Note that right_table_col must be a string
517
            * if left_table_col is join_same_not_null:
518
              left_table_col = right_table_col and both have NOT NULL constraint
519
              * Note that right_table_col must be a string
520
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
521
            * filter_out: equivalent to 'LEFT' with the query filtered by
522
              `table_pkey IS NULL` (indicating no match)
523
        '''
524
        if util.is_str(table): table = Table(table)
525
        assert type_ == None or util.is_str(type_) or type_ is filter_out
526
        
527
        self.table = table
528
        self.mapping = mapping
529
        self.type_ = type_
530
    
531
    def to_str(self, db, left_table_):
532
        def join(entry):
533
            '''Parses non-USING joins'''
534
            right_table_col, left_table_col = entry
535
            
536
            # Switch order (right_table_col is on the left in the comparison)
537
            left = right_table_col
538
            right = left_table_col
539
            left_table = self.table
540
            right_table = left_table_
541
            
542
            # Parse left side
543
            left = with_default_table(left, left_table)
544
            
545
            # Parse special values
546
            left_on_right = Col(left.name, right_table)
547
            if right is join_same: right = left_on_right
548
            elif right is join_same_not_null:
549
                right = CompareCond(left_on_right, '~=')
550
            
551
            # Parse right side
552
            right = as_ValueCond(right, right_table)
553
            
554
            return right.to_str(db, left)
555
        
556
        # Create join condition
557
        type_ = self.type_
558
        joins = self.mapping
559
        if joins == {}: join_cond = None
560
        elif type_ is not filter_out and reduce(operator.and_,
561
            (v is join_same_not_null for v in joins.itervalues())):
562
            # all cols w/ USING, so can use simpler USING syntax
563
            cols = map(to_name_only_col, joins.iterkeys())
564
            join_cond = 'USING ('+(', '.join((c.to_str(db) for c in cols)))+')'
565
        else: join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
566
        
567
        if isinstance(self.table, NamedTable): whitespace = '\n'
568
        else: whitespace = ' '
569
        
570
        # Create join
571
        if type_ is filter_out: type_ = 'LEFT'
572
        str_ = ''
573
        if type_ != None: str_ += type_+' '
574
        str_ += 'JOIN'+whitespace+self.table.to_str(db)
575
        if join_cond != None: str_ += whitespace+join_cond
576
        return str_
577
    
578
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
579

    
580
##### Value exprs
581

    
582
default = CustomCode('DEFAULT')
583

    
584
row_count = CustomCode('count(*)')
585

    
586
class Coalesce(FunctionCall):
587
    def __init__(self, *args):
588
        FunctionCall.__init__(self, InternalFunction('COALESCE'), *args)
589

    
590
class Nullif(FunctionCall):
591
    def __init__(self, *args):
592
        FunctionCall.__init__(self, InternalFunction('NULLIF'), *args)
593

    
594
# See <http://www.postgresql.org/docs/8.3/static/datatype-numeric.html>
595
null_sentinels = {
596
    'character varying': r'\N',
597
    'double precision': 'NaN',
598
    'integer': 2147483647,
599
    'text': r'\N',
600
    'timestamp with time zone': 'infinity'
601
}
602

    
603
class EnsureNotNull(Coalesce):
604
    def __init__(self, value, type_):
605
        Coalesce.__init__(self, as_Col(value),
606
            Cast(type_, null_sentinels[type_]))
607
        
608
        self.type = type_
609
    
610
    def to_str(self, db):
611
        col = self.args[0]
612
        index_col_ = index_col(col)
613
        if index_col_ != None: return index_col_.to_str(db)
614
        return Coalesce.to_str(self, db)
615

    
616
##### Table exprs
617

    
618
class Values(Code):
619
    def __init__(self, values):
620
        '''
621
        @param values [...]|[[...], ...] Can be one or multiple rows.
622
        '''
623
        rows = values
624
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
625
            rows = [values]
626
        for i, row in enumerate(rows):
627
            rows[i] = map(remove_col_rename, map(as_Value, row))
628
        
629
        self.rows = rows
630
    
631
    def to_str(self, db):
632
        def row_str(row):
633
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
634
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
635

    
636
def NamedValues(name, cols, values):
637
    '''
638
    @param cols None|[...]
639
    @post `cols` will be changed to Col objects with the table set to `name`.
640
    '''
641
    table = NamedTable(name, Values(values), cols)
642
    if cols != None: set_cols_table(table, cols)
643
    return table
644

    
645
##### Database structure
646

    
647
class TypedCol(Col):
648
    def __init__(self, name, type_, default=None, nullable=True,
649
        constraints=None):
650
        assert default == None or isinstance(default, Code)
651
        
652
        Col.__init__(self, name)
653
        
654
        self.type = type_
655
        self.default = default
656
        self.nullable = nullable
657
        self.constraints = constraints
658
    
659
    def to_str(self, db):
660
        str_ = Col.to_str(self, db)+' '+self.type
661
        if not self.nullable: str_ += ' NOT NULL'
662
        if self.default != None: str_ += ' DEFAULT '+self.default.to_str(db)
663
        if self.constraints != None: str_ += ' '+self.constraints
664
        return str_
665
    
666
    def to_Col(self): return Col(self.name)
667

    
668
ensure_not_null_excs = (NoUnderlyingTableException, KeyError)
669

    
670
def ensure_not_null(db, col, type_=None):
671
    '''
672
    @param col If type_ is not set, must have an underlying column.
673
    @param type_ If set, overrides the underlying column's type.
674
    @return EnsureNotNull|Col
675
    @throws ensure_not_null_excs
676
    '''
677
    nullable = True
678
    try: typed_col = db.col_info(underlying_col(col))
679
    except NoUnderlyingTableException:
680
        if type_ == None: raise
681
    else:
682
        if type_ == None: type_ = typed_col.type
683
        nullable = typed_col.nullable
684
    
685
    if nullable:
686
        try: col = EnsureNotNull(col, type_)
687
        except KeyError, e:
688
            # Warn of no null sentinel for type, even if caller catches error
689
            warnings.warn(UserWarning(exc.str_(e)))
690
            raise
691
    
692
    return col
(25-25/37)