Project

General

Profile

1
# SQL code generation
2

    
3
import copy
4
import operator
5
from ordereddict import OrderedDict
6
import re
7
import UserDict
8
import warnings
9

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

    
18
##### Names
19

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

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

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

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

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

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

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

    
51
##### General SQL code objects
52

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

    
61
mockDb = MockDb()
62

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

    
68
##### Unparameterized code objects
69

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

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

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

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

    
94
##### Names
95

    
96
class Name(Code):
97
    def __init__(self, name):
98
        name = truncate(name)
99
        
100
        self.name = name
101
    
102
    def to_str(self, db): return db.esc_name(self.name)
103

    
104
def as_Name(value):
105
    if isinstance(value, Code): return value
106
    else: return Name(value)
107

    
108
##### Literal values
109

    
110
class Literal(Code):
111
    def __init__(self, value): self.value = value
112
    
113
    def to_str(self, db): return db.esc_value(self.value)
114

    
115
def as_Value(value):
116
    if isinstance(value, Code): return value
117
    else: return Literal(value)
118

    
119
def is_null(value): return isinstance(value, Literal) and value.value == None
120

    
121
##### Derived elements
122

    
123
src_self = object() # tells Col that it is its own source column
124

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

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

    
149
##### Tables
150

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

    
179
def is_underlying_table(table):
180
    return isinstance(table, Table) and table.to_Table() is table
181

    
182
class NoUnderlyingTableException(Exception): pass
183

    
184
def underlying_table(table):
185
    table = remove_table_rename(table)
186
    if not is_underlying_table(table): raise NoUnderlyingTableException
187
    return table
188

    
189
def as_Table(table, schema=None):
190
    if table == None or isinstance(table, Code): return table
191
    else: return Table(table, schema)
192

    
193
def suffixed_table(table, suffix):
194
    table = copy.copy(table) # don't modify input!
195
    table.name = concat(table.name, suffix)
196
    return table
197

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

    
220
def remove_table_rename(table):
221
    if isinstance(table, NamedTable): table = table.code
222
    return table
223

    
224
##### Columns
225

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

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

    
256
def index_col(col):
257
    if not is_table_col(col): return None
258
    
259
    table = col.table
260
    try: name = table.index_cols[col.name]
261
    except KeyError: return None
262
    else: return Col(name, table, col.srcs)
263

    
264
def is_temp_col(col): return is_table_col(col) and col.table.is_temp
265

    
266
def as_Col(col, table=None, name=None):
267
    '''
268
    @param name If not None, any non-Col input will be renamed using NamedCol.
269
    '''
270
    if name != None:
271
        col = as_Value(col)
272
        if not isinstance(col, Col): col = NamedCol(name, col)
273
    
274
    if isinstance(col, Code): return col
275
    else: return Col(col, table)
276

    
277
def with_table(col, table):
278
    if isinstance(col, NamedCol): pass # doesn't take a table
279
    elif isinstance(col, FunctionCall):
280
        col = copy.deepcopy(col) # don't modify input!
281
        col.args[0].table = table
282
    else:
283
        col = copy.copy(col) # don't modify input!
284
        col.table = table
285
    return col
286

    
287
def with_default_table(col, table):
288
    col = as_Col(col)
289
    if col.table == None: col = with_table(col, table)
290
    return col
291

    
292
def set_cols_table(table, cols):
293
    table = as_Table(table)
294
    
295
    for i, col in enumerate(cols):
296
        col = cols[i] = as_Col(col)
297
        col.table = table
298

    
299
def to_name_only_col(col, check_table=None):
300
    col = as_Col(col)
301
    if not is_table_col(col): return col
302
    
303
    if check_table != None:
304
        table = col.table
305
        assert table == None or table == check_table
306
    return Col(col.name)
307

    
308
def suffixed_col(col, suffix):
309
    return Col(concat(col.name, suffix), col.table, col.srcs)
310

    
311
class NamedCol(Col):
312
    def __init__(self, name, code):
313
        Col.__init__(self, name)
314
        
315
        code = as_Value(code)
316
        
317
        self.code = code
318
    
319
    def to_str(self, db):
320
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
321
    
322
    def to_Col(self): return Col(self.name)
323

    
324
def remove_col_rename(col):
325
    if isinstance(col, NamedCol): col = col.code
326
    return col
327

    
328
def underlying_col(col):
329
    col = remove_col_rename(col)
330
    if not isinstance(col, Col): raise NoUnderlyingTableException
331
    
332
    return Col(col.name, underlying_table(col.table), col.srcs)
333

    
334
def wrap(wrap_func, value):
335
    '''Wraps a value, propagating any column renaming to the returned value.'''
336
    if isinstance(value, NamedCol):
337
        return NamedCol(value.name, wrap_func(value.code))
338
    else: return wrap_func(value)
339

    
340
class ColDict(dicts.DictProxy):
341
    '''A dict that automatically makes inserted entries Col objects'''
342
    
343
    def __init__(self, db, keys_table, dict_={}):
344
        dicts.DictProxy.__init__(self, OrderedDict())
345
        
346
        keys_table = as_Table(keys_table)
347
        
348
        self.db = db
349
        self.table = keys_table
350
        self.update(dict_) # after setting vars because __setitem__() needs them
351
    
352
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
353
    
354
    def __getitem__(self, key):
355
        return dicts.DictProxy.__getitem__(self, self._key(key))
356
    
357
    def __setitem__(self, key, value):
358
        key = self._key(key)
359
        if value == None: value = self.db.col_info(key).default
360
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
361
    
362
    def _key(self, key): return as_Col(key, self.table)
363

    
364
##### Functions
365

    
366
Function = Table
367
as_Function = as_Table
368

    
369
class InternalFunction(CustomCode): pass
370

    
371
class NamedArg(NamedCol):
372
    def __init__(self, name, value):
373
        NamedCol.__init__(self, name, value)
374
    
375
    def to_str(self, db):
376
        return Col.to_str(self, db)+' := '+self.code.to_str(db)
377

    
378
class FunctionCall(Code):
379
    def __init__(self, function, *args, **kw_args):
380
        '''
381
        @param args [Code|literal-value...] The function's arguments
382
        '''
383
        function = as_Function(function)
384
        def filter_(arg): return remove_col_rename(as_Value(arg))
385
        args = map(filter_, args)
386
        args += [NamedArg(k, filter_(v)) for k, v in kw_args.iteritems()]
387
        
388
        self.function = function
389
        self.args = args
390
    
391
    def to_str(self, db):
392
        args_str = ', '.join((v.to_str(db) for v in self.args))
393
        return self.function.to_str(db)+'('+args_str+')'
394

    
395
def wrap_in_func(function, value):
396
    '''Wraps a value inside a function call.
397
    Propagates any column renaming to the returned value.
398
    '''
399
    return wrap(lambda v: FunctionCall(function, v), value)
400

    
401
def unwrap_func_call(func_call, check_name=None):
402
    '''Unwraps any function call to its first argument.
403
    Also removes any column renaming.
404
    '''
405
    func_call = remove_col_rename(func_call)
406
    if not isinstance(func_call, FunctionCall): return func_call
407
    
408
    if check_name != None:
409
        name = func_call.function.name
410
        assert name == None or name == check_name
411
    return func_call.args[0]
412

    
413
##### Casts
414

    
415
class Cast(FunctionCall):
416
    def __init__(self, type_, value):
417
        value = as_Value(value)
418
        
419
        self.type_ = type_
420
        self.value = value
421
    
422
    def to_str(self, db):
423
        return 'CAST('+self.value.to_str(db)+' AS '+self.type_+')'
424

    
425
##### Conditions
426

    
427
class ColValueCond(Code):
428
    def __init__(self, col, value):
429
        value = as_ValueCond(value)
430
        
431
        self.col = col
432
        self.value = value
433
    
434
    def to_str(self, db): return self.value.to_str(db, self.col)
435

    
436
def combine_conds(conds, keyword=None):
437
    '''
438
    @param keyword The keyword to add before the conditions, if any
439
    '''
440
    str_ = ''
441
    if keyword != None:
442
        if conds == []: whitespace = ''
443
        elif len(conds) == 1: whitespace = ' '
444
        else: whitespace = '\n'
445
        str_ += keyword+whitespace
446
    
447
    str_ += '\nAND '.join(conds)
448
    return str_
449

    
450
##### Condition column comparisons
451

    
452
class ValueCond(BasicObject):
453
    def __init__(self, value):
454
        value = remove_col_rename(as_Value(value))
455
        
456
        self.value = value
457
    
458
    def to_str(self, db, left_value):
459
        '''
460
        @param left_value The Code object that the condition is being applied on
461
        '''
462
        raise NotImplemented()
463
    
464
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
465

    
466
class CompareCond(ValueCond):
467
    def __init__(self, value, operator='='):
468
        '''
469
        @param operator By default, compares NULL values literally. Use '~=' or
470
            '~!=' to pass NULLs through.
471
        '''
472
        ValueCond.__init__(self, value)
473
        self.operator = operator
474
    
475
    def to_str(self, db, left_value):
476
        left_value = remove_col_rename(as_Col(left_value))
477
        
478
        right_value = self.value
479
        
480
        # Parse operator
481
        operator = self.operator
482
        passthru_null_ref = [False]
483
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
484
        neg_ref = [False]
485
        operator = strings.remove_prefix('!', operator, neg_ref)
486
        equals = operator.endswith('=') # also includes <=, >=
487
        
488
        # Handle nullable columns
489
        check_null = False
490
        if not passthru_null_ref[0]: # NULLs compare equal
491
            try: left_value = ensure_not_null(db, left_value)
492
            except ensure_not_null_excs: # fall back to alternate method
493
                check_null = equals and isinstance(right_value, Col)
494
            else:
495
                if isinstance(left_value, EnsureNotNull):
496
                    right_value = ensure_not_null(db, right_value,
497
                        left_value.type) # apply same function to both sides
498
        
499
        if equals and is_null(right_value): operator = 'IS'
500
        
501
        left = left_value.to_str(db)
502
        right = right_value.to_str(db)
503
        
504
        # Create str
505
        str_ = left+' '+operator+' '+right
506
        if check_null:
507
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
508
        if neg_ref[0]: str_ = 'NOT '+str_
509
        return str_
510

    
511
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
512
assume_literal = object()
513

    
514
def as_ValueCond(value, default_table=assume_literal):
515
    if not isinstance(value, ValueCond):
516
        if default_table is not assume_literal:
517
            value = with_default_table(value, default_table)
518
        return CompareCond(value)
519
    else: return value
520

    
521
##### Joins
522

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

    
525
# Tells Join the left and right columns have the same name and are never NULL
526
join_same_not_null = object()
527

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

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

    
599
##### Value exprs
600

    
601
all_cols = CustomCode('*')
602

    
603
default = CustomCode('DEFAULT')
604

    
605
row_count = FunctionCall(InternalFunction('COUNT'), all_cols)
606

    
607
class Coalesce(FunctionCall):
608
    def __init__(self, *args):
609
        FunctionCall.__init__(self, InternalFunction('COALESCE'), *args)
610

    
611
class Nullif(FunctionCall):
612
    def __init__(self, *args):
613
        FunctionCall.__init__(self, InternalFunction('NULLIF'), *args)
614

    
615
# See <http://www.postgresql.org/docs/8.3/static/datatype-numeric.html>
616
null_sentinels = {
617
    'character varying': r'\N',
618
    'double precision': 'NaN',
619
    'integer': 2147483647,
620
    'text': r'\N',
621
    'timestamp with time zone': 'infinity'
622
}
623

    
624
class EnsureNotNull(Coalesce):
625
    def __init__(self, value, type_):
626
        Coalesce.__init__(self, as_Col(value),
627
            Cast(type_, null_sentinels[type_]))
628
        
629
        self.type = type_
630
    
631
    def to_str(self, db):
632
        col = self.args[0]
633
        index_col_ = index_col(col)
634
        if index_col_ != None: return index_col_.to_str(db)
635
        return Coalesce.to_str(self, db)
636

    
637
##### Table exprs
638

    
639
class Values(Code):
640
    def __init__(self, values):
641
        '''
642
        @param values [...]|[[...], ...] Can be one or multiple rows.
643
        '''
644
        rows = values
645
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
646
            rows = [values]
647
        for i, row in enumerate(rows):
648
            rows[i] = map(remove_col_rename, map(as_Value, row))
649
        
650
        self.rows = rows
651
    
652
    def to_str(self, db):
653
        def row_str(row):
654
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
655
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
656

    
657
def NamedValues(name, cols, values):
658
    '''
659
    @param cols None|[...]
660
    @post `cols` will be changed to Col objects with the table set to `name`.
661
    '''
662
    table = NamedTable(name, Values(values), cols)
663
    if cols != None: set_cols_table(table, cols)
664
    return table
665

    
666
##### Database structure
667

    
668
class TypedCol(Col):
669
    def __init__(self, name, type_, default=None, nullable=True,
670
        constraints=None):
671
        assert default == None or isinstance(default, Code)
672
        
673
        Col.__init__(self, name)
674
        
675
        self.type = type_
676
        self.default = default
677
        self.nullable = nullable
678
        self.constraints = constraints
679
    
680
    def to_str(self, db):
681
        str_ = Col.to_str(self, db)+' '+self.type
682
        if not self.nullable: str_ += ' NOT NULL'
683
        if self.default != None: str_ += ' DEFAULT '+self.default.to_str(db)
684
        if self.constraints != None: str_ += ' '+self.constraints
685
        return str_
686
    
687
    def to_Col(self): return Col(self.name)
688

    
689
ensure_not_null_excs = (NoUnderlyingTableException, KeyError)
690

    
691
def ensure_not_null(db, col, type_=None):
692
    '''
693
    @param col If type_ is not set, must have an underlying column.
694
    @param type_ If set, overrides the underlying column's type.
695
    @return EnsureNotNull|Col
696
    @throws ensure_not_null_excs
697
    '''
698
    nullable = True
699
    try: typed_col = db.col_info(underlying_col(col))
700
    except NoUnderlyingTableException:
701
        if type_ == None: raise
702
    else:
703
        if type_ == None: type_ = typed_col.type
704
        nullable = typed_col.nullable
705
    
706
    if nullable:
707
        try: col = EnsureNotNull(col, type_)
708
        except KeyError, e:
709
            # Warn of no null sentinel for type, even if caller catches error
710
            warnings.warn(UserWarning(exc.str_(e)))
711
            raise
712
    
713
    return col
(25-25/37)