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
##### General SQL code objects
49

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

    
58
mockDb = MockDb()
59

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

    
65
##### Unparameterized code objects
66

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

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

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

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

    
91
##### Literal values
92

    
93
class Literal(Code):
94
    def __init__(self, value): self.value = value
95
    
96
    def to_str(self, db): return db.esc_value(self.value)
97

    
98
def as_Value(value):
99
    if isinstance(value, Code): return value
100
    else: return Literal(value)
101

    
102
def is_null(value): return isinstance(value, Literal) and value.value == None
103

    
104
##### Derived elements
105

    
106
src_self = object() # tells Col that it is its own source column
107

    
108
class Derived(Code):
109
    def __init__(self, srcs):
110
        '''An element which was derived from some other element(s).
111
        @param srcs See self.set_srcs()
112
        '''
113
        self.set_srcs(srcs)
114
    
115
    def set_srcs(self, srcs, overwrite=True):
116
        '''
117
        @param srcs (self_type...)|src_self The element(s) this is derived from
118
        '''
119
        if not overwrite and self.srcs != (): return # already set
120
        
121
        if srcs == src_self: srcs = (self,)
122
        srcs = tuple(srcs) # make Col hashable
123
        self.srcs = srcs
124
    
125
    def _compare_on(self):
126
        compare_on = self.__dict__.copy()
127
        del compare_on['srcs'] # ignore
128
        return compare_on
129

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

    
132
##### Tables
133

    
134
class Table(Derived):
135
    def __init__(self, name, schema=None, srcs=(), is_temp=False):
136
        '''
137
        @param schema str|None (for no schema)
138
        @param srcs (Table...)|src_self See Derived.set_srcs()
139
        '''
140
        Derived.__init__(self, srcs)
141
        
142
        name = truncate(name)
143
        
144
        self.name = name
145
        self.schema = schema
146
        self.is_temp = is_temp
147
        self.index_cols = {}
148
    
149
    def to_str(self, db):
150
        str_ = ''
151
        if self.schema != None: str_ += db.esc_name(self.schema)+'.'
152
        str_ += db.esc_name(self.name)
153
        return str_
154
    
155
    def to_Table(self): return self
156
    
157
    def _compare_on(self):
158
        compare_on = Derived._compare_on(self)
159
        del compare_on['index_cols'] # ignore
160
        return compare_on
161

    
162
def is_underlying_table(table):
163
    return isinstance(table, Table) and table.to_Table() is table
164

    
165
class NoUnderlyingTableException(Exception): pass
166

    
167
def underlying_table(table):
168
    table = remove_table_rename(table)
169
    if not is_underlying_table(table): raise NoUnderlyingTableException
170
    return table
171

    
172
def as_Table(table, schema=None):
173
    if table == None or isinstance(table, Code): return table
174
    else: return Table(table, schema)
175

    
176
def suffixed_table(table, suffix): return Table(table.name+suffix, table.schema)
177

    
178
class NamedTable(Table):
179
    def __init__(self, name, code, cols=None):
180
        Table.__init__(self, name)
181
        
182
        code = as_Table(code)
183
        if not isinstance(code, (Table, FunctionCall, Expr)): code = Expr(code)
184
        if cols != None: cols = [to_name_only_col(c).to_Col() for c in cols]
185
        
186
        self.code = code
187
        self.cols = cols
188
    
189
    def to_str(self, db):
190
        str_ = self.code.to_str(db)
191
        if str_.find('\n') >= 0: whitespace = '\n'
192
        else: whitespace = ' '
193
        str_ += whitespace+'AS '+Table.to_str(self, db)
194
        if self.cols != None:
195
            str_ += ' ('+(', '.join((c.to_str(db) for c in self.cols)))+')'
196
        return str_
197
    
198
    def to_Table(self): return Table(self.name)
199

    
200
def remove_table_rename(table):
201
    if isinstance(table, NamedTable): table = table.code
202
    return table
203

    
204
##### Columns
205

    
206
class Col(Derived):
207
    def __init__(self, name, table=None, srcs=()):
208
        '''
209
        @param table Table|None (for no table)
210
        @param srcs (Col...)|src_self See Derived.set_srcs()
211
        '''
212
        Derived.__init__(self, srcs)
213
        
214
        name = truncate(name)
215
        if util.is_str(table): table = Table(table)
216
        assert table == None or isinstance(table, Table)
217
        
218
        self.name = name
219
        self.table = table
220
    
221
    def to_str(self, db, for_str=False):
222
        str_ = db.esc_name(self.name)
223
        if for_str: str_ = clean_name(str_)
224
        if self.table != None:
225
            table = self.table.to_Table()
226
            if for_str: str_ = concat(str(table), '.'+str_)
227
            else: str_ = table.to_str(db)+'.'+str_
228
        return str_
229
    
230
    def __str__(self): return self.to_str(mockDb, for_str=True)
231
    
232
    def to_Col(self): return self
233

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

    
236
def index_col(col):
237
    if not is_table_col(col): return None
238
    return col.table.index_cols.get(col.name, None)
239

    
240
def is_temp_col(col): return is_table_col(col) and col.table.is_temp
241

    
242
def as_Col(col, table=None, name=None):
243
    '''
244
    @param name If not None, any non-Col input will be renamed using NamedCol.
245
    '''
246
    if name != None:
247
        col = as_Value(col)
248
        if not isinstance(col, Col): col = NamedCol(name, col)
249
    
250
    if isinstance(col, Code): return col
251
    else: return Col(col, table)
252

    
253
def with_default_table(col, table, overwrite=False):
254
    col = as_Col(col)
255
    if not isinstance(col, NamedCol) and (overwrite or col.table == None):
256
        col = copy.copy(col) # don't modify input!
257
        col.table = table
258
    return col
259

    
260
def set_cols_table(table, cols):
261
    table = as_Table(table)
262
    
263
    for i, col in enumerate(cols):
264
        col = cols[i] = as_Col(col)
265
        col.table = table
266

    
267
def to_name_only_col(col, check_table=None):
268
    col = as_Col(col)
269
    if not is_table_col(col): return col
270
    
271
    if check_table != None:
272
        table = col.table
273
        assert table == None or table == check_table
274
    return Col(col.name)
275

    
276
def suffixed_col(col, suffix):
277
    return Col(concat(col.name, suffix), col.table, col.srcs)
278

    
279
class NamedCol(Col):
280
    def __init__(self, name, code):
281
        Col.__init__(self, name)
282
        
283
        code = as_Value(code)
284
        
285
        self.code = code
286
    
287
    def to_str(self, db):
288
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
289
    
290
    def to_Col(self): return Col(self.name)
291

    
292
def remove_col_rename(col):
293
    if isinstance(col, NamedCol): col = col.code
294
    return col
295

    
296
def underlying_col(col):
297
    col = remove_col_rename(col)
298
    if not isinstance(col, Col): raise NoUnderlyingTableException
299
    
300
    return Col(col.name, underlying_table(col.table), col.srcs)
301

    
302
def wrap(wrap_func, value):
303
    '''Wraps a value, propagating any column renaming to the returned value.'''
304
    if isinstance(value, NamedCol):
305
        return NamedCol(value.name, wrap_func(value.code))
306
    else: return wrap_func(value)
307

    
308
class ColDict(dicts.DictProxy):
309
    '''A dict that automatically makes inserted entries Col objects'''
310
    
311
    def __init__(self, db, keys_table, dict_={}):
312
        dicts.DictProxy.__init__(self, {})
313
        
314
        keys_table = as_Table(keys_table)
315
        
316
        self.db = db
317
        self.table = keys_table
318
        self.update(dict_) # after setting vars because __setitem__() needs them
319
    
320
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
321
    
322
    def __getitem__(self, key):
323
        return dicts.DictProxy.__getitem__(self, self._key(key))
324
    
325
    def __setitem__(self, key, value):
326
        key = self._key(key)
327
        if value == None: value = self.db.col_info(key).default
328
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
329
    
330
    def _key(self, key): return as_Col(key, self.table)
331

    
332
##### Functions
333

    
334
Function = Table
335
as_Function = as_Table
336

    
337
class InternalFunction(CustomCode): pass
338

    
339
class NamedArg(NamedCol):
340
    def __init__(self, name, value):
341
        NamedCol.__init__(self, name, value)
342
    
343
    def to_str(self, db):
344
        return Col.to_str(self, db)+' := '+self.code.to_str(db)
345

    
346
class FunctionCall(Code):
347
    def __init__(self, function, *args, **kw_args):
348
        '''
349
        @param args [Code|literal-value...] The function's arguments
350
        '''
351
        function = as_Function(function)
352
        def filter_(arg): return remove_col_rename(as_Value(arg))
353
        args = map(filter_, args)
354
        args += [NamedArg(k, filter_(v)) for k, v in kw_args.iteritems()]
355
        
356
        self.function = function
357
        self.args = args
358
    
359
    def to_str(self, db):
360
        args_str = ', '.join((v.to_str(db) for v in self.args))
361
        return self.function.to_str(db)+'('+args_str+')'
362

    
363
def wrap_in_func(function, value):
364
    '''Wraps a value inside a function call.
365
    Propagates any column renaming to the returned value.
366
    '''
367
    return wrap(lambda v: FunctionCall(function, v), value)
368

    
369
def unwrap_func_call(func_call, check_name=None):
370
    '''Unwraps any function call to its first argument.
371
    Also removes any column renaming.
372
    '''
373
    func_call = remove_col_rename(func_call)
374
    if not isinstance(func_call, FunctionCall): return func_call
375
    
376
    if check_name != None:
377
        name = func_call.function.name
378
        assert name == None or name == check_name
379
    return func_call.args[0]
380

    
381
##### Casts
382

    
383
class Cast(FunctionCall):
384
    def __init__(self, type_, value):
385
        value = as_Value(value)
386
        
387
        self.type_ = type_
388
        self.value = value
389
    
390
    def to_str(self, db):
391
        return 'CAST('+self.value.to_str(db)+' AS '+self.type_+')'
392

    
393
##### Conditions
394

    
395
class ColValueCond(Code):
396
    def __init__(self, col, value):
397
        value = as_ValueCond(value)
398
        
399
        self.col = col
400
        self.value = value
401
    
402
    def to_str(self, db): return self.value.to_str(db, self.col)
403

    
404
def combine_conds(conds, keyword=None):
405
    '''
406
    @param keyword The keyword to add before the conditions, if any
407
    '''
408
    str_ = ''
409
    if keyword != None:
410
        if conds == []: whitespace = ''
411
        elif len(conds) == 1: whitespace = ' '
412
        else: whitespace = '\n'
413
        str_ += keyword+whitespace
414
    
415
    str_ += '\nAND '.join(conds)
416
    return str_
417

    
418
##### Condition column comparisons
419

    
420
class ValueCond(BasicObject):
421
    def __init__(self, value):
422
        value = remove_col_rename(as_Value(value))
423
        
424
        self.value = value
425
    
426
    def to_str(self, db, left_value):
427
        '''
428
        @param left_value The Code object that the condition is being applied on
429
        '''
430
        raise NotImplemented()
431
    
432
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
433

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

    
479
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
480
assume_literal = object()
481

    
482
def as_ValueCond(value, default_table=assume_literal):
483
    if not isinstance(value, ValueCond):
484
        if default_table is not assume_literal:
485
            value = with_default_table(value, default_table)
486
        return CompareCond(value)
487
    else: return value
488

    
489
##### Joins
490

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

    
493
# Tells Join the left and right columns have the same name and are never NULL
494
join_same_not_null = object()
495

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

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

    
567
##### Value exprs
568

    
569
default = CustomCode('DEFAULT')
570

    
571
row_count = CustomCode('count(*)')
572

    
573
# See <http://www.postgresql.org/docs/8.3/static/datatype-numeric.html>
574
null_sentinels = {
575
    'character varying': r'\N',
576
    'double precision': 'NaN',
577
    'integer': 2147483647,
578
    'text': r'\N',
579
    'timestamp with time zone': 'infinity'
580
}
581

    
582
class EnsureNotNull(FunctionCall):
583
    def __init__(self, value, type_):
584
        FunctionCall.__init__(self, InternalFunction('COALESCE'), as_Col(value),
585
            Cast(type_, null_sentinels[type_]))
586
        
587
        self.type = type_
588
    
589
    def to_str(self, db):
590
        col = self.args[0]
591
        index_col_ = index_col(col)
592
        if index_col_ != None: return index_col_.to_str(db)
593
        return FunctionCall.to_str(self, db)
594

    
595
##### Table exprs
596

    
597
class Values(Code):
598
    def __init__(self, values):
599
        '''
600
        @param values [...]|[[...], ...] Can be one or multiple rows.
601
        '''
602
        rows = values
603
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
604
            rows = [values]
605
        for i, row in enumerate(rows):
606
            rows[i] = map(remove_col_rename, map(as_Value, row))
607
        
608
        self.rows = rows
609
    
610
    def to_str(self, db):
611
        def row_str(row):
612
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
613
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
614

    
615
def NamedValues(name, cols, values):
616
    '''
617
    @post `cols` will be changed to Col objects with the table set to `name`.
618
    '''
619
    table = NamedTable(name, Values(values), cols)
620
    set_cols_table(table, cols)
621
    return table
622

    
623
##### Database structure
624

    
625
class TypedCol(Col):
626
    def __init__(self, name, type_, default=None, nullable=True,
627
        constraints=None):
628
        assert default == None or isinstance(default, Code)
629
        
630
        Col.__init__(self, name)
631
        
632
        self.type = type_
633
        self.default = default
634
        self.nullable = nullable
635
        self.constraints = constraints
636
    
637
    def to_str(self, db):
638
        str_ = Col.to_str(self, db)+' '+self.type
639
        if not self.nullable: str_ += ' NOT NULL'
640
        if self.default != None: str_ += ' DEFAULT '+self.default.to_str(db)
641
        if self.constraints != None: str_ += ' '+self.constraints
642
        return str_
643
    
644
    def to_Col(self): return Col(self.name)
645

    
646
ensure_not_null_excs = (NoUnderlyingTableException, KeyError)
647

    
648
def ensure_not_null(db, col, type_=None):
649
    '''
650
    @param col If type_ is not set, must have an underlying column.
651
    @param type_ If set, overrides the underlying column's type.
652
    @return EnsureNotNull|Col
653
    @throws ensure_not_null_excs
654
    '''
655
    nullable = True
656
    try: typed_col = db.col_info(underlying_col(col))
657
    except NoUnderlyingTableException:
658
        if type_ == None: raise
659
    else:
660
        if type_ == None: type_ = typed_col.type
661
        nullable = typed_col.nullable
662
    
663
    if nullable:
664
        try: col = EnsureNotNull(col, type_)
665
        except KeyError, e:
666
            # Warn of no null sentinel for type, even if caller catches error
667
            warnings.warn(UserWarning(exc.str_(e)))
668
            raise
669
    
670
    return col
(25-25/36)