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 unesc_name(name, quote='"'):
48
    removed_ref = [False]
49
    name = strings.remove_prefix(quote, name, removed_ref)
50
    if removed_ref[0]:
51
        name = strings.remove_suffix(quote, name, removed_ref)
52
        assert removed_ref[0]
53
        name = name.replace(quote+quote, quote)
54
    return name
55

    
56
def clean_name(name): return name.replace('"', '').replace('`', '')
57

    
58
def esc_comment(comment): return '/*'+comment.replace('*/', '* /')+'*/'
59

    
60
def lstrip(str_):
61
    '''Also removes comments.'''
62
    if str_.startswith('/*'): comment, sep, str_ = str_.partition('*/')
63
    return str_.lstrip()
64

    
65
##### General SQL code objects
66

    
67
class MockDb:
68
    def esc_value(self, value): return strings.repr_no_u(value)
69
    
70
    def esc_name(self, name): return esc_name(name)
71
    
72
    def col_info(self, col):
73
        return TypedCol(col.name, '<type>', CustomCode('<default>'), True)
74

    
75
mockDb = MockDb()
76

    
77
class BasicObject(objects.BasicObject):
78
    def __str__(self): return clean_name(strings.repr_no_u(self))
79

    
80
##### Unparameterized code objects
81

    
82
class Code(BasicObject):
83
    def __init__(self): pass
84
    
85
    def to_str(self, db): raise NotImplementedError()
86
    
87
    def __repr__(self): return self.to_str(mockDb)
88

    
89
class CustomCode(Code):
90
    def __init__(self, str_):
91
        Code.__init__(self)
92
        
93
        self.str_ = str_
94
    
95
    def to_str(self, db): return self.str_
96

    
97
def as_Code(value, db=None):
98
    '''
99
    @param db If set, runs db.std_code() on the value.
100
    '''
101
    if util.is_str(value):
102
        if db != None: value = db.std_code(value)
103
        return CustomCode(value)
104
    else: return Literal(value)
105

    
106
class Expr(Code):
107
    def __init__(self, expr):
108
        Code.__init__(self)
109
        
110
        self.expr = expr
111
    
112
    def to_str(self, db): return '('+self.expr.to_str(db)+')'
113

    
114
##### Names
115

    
116
class Name(Code):
117
    def __init__(self, name):
118
        Code.__init__(self)
119
        
120
        name = truncate(name)
121
        
122
        self.name = name
123
    
124
    def to_str(self, db): return db.esc_name(self.name)
125

    
126
def as_Name(value):
127
    if isinstance(value, Code): return value
128
    else: return Name(value)
129

    
130
##### Literal values
131

    
132
class Literal(Code):
133
    def __init__(self, value):
134
        Code.__init__(self)
135
        
136
        self.value = value
137
    
138
    def to_str(self, db): return db.esc_value(self.value)
139

    
140
def as_Value(value):
141
    if isinstance(value, Code): return value
142
    else: return Literal(value)
143

    
144
def is_literal(value): return isinstance(value, Literal)
145

    
146
def is_null(value): return is_literal(value) and value.value == None
147

    
148
##### Derived elements
149

    
150
src_self = object() # tells Col that it is its own source column
151

    
152
class Derived(Code):
153
    def __init__(self, srcs):
154
        '''An element which was derived from some other element(s).
155
        @param srcs See self.set_srcs()
156
        '''
157
        Code.__init__(self)
158
        
159
        self.set_srcs(srcs)
160
    
161
    def set_srcs(self, srcs, overwrite=True):
162
        '''
163
        @param srcs (self_type...)|src_self The element(s) this is derived from
164
        '''
165
        if not overwrite and self.srcs != (): return # already set
166
        
167
        if srcs == src_self: srcs = (self,)
168
        srcs = tuple(srcs) # make Col hashable
169
        self.srcs = srcs
170
    
171
    def _compare_on(self):
172
        compare_on = self.__dict__.copy()
173
        del compare_on['srcs'] # ignore
174
        return compare_on
175

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

    
178
##### Tables
179

    
180
class Table(Derived):
181
    def __init__(self, name, schema=None, srcs=(), is_temp=False):
182
        '''
183
        @param schema str|None (for no schema)
184
        @param srcs (Table...)|src_self See Derived.set_srcs()
185
        '''
186
        Derived.__init__(self, srcs)
187
        
188
        if util.is_str(name): name = truncate(name)
189
        
190
        self.name = name
191
        self.schema = schema
192
        self.is_temp = is_temp
193
        self.index_cols = {}
194
    
195
    def to_str(self, db):
196
        str_ = ''
197
        if self.schema != None: str_ += as_Name(self.schema).to_str(db)+'.'
198
        str_ += as_Name(self.name).to_str(db)
199
        return str_
200
    
201
    def to_Table(self): return self
202
    
203
    def _compare_on(self):
204
        compare_on = Derived._compare_on(self)
205
        del compare_on['index_cols'] # ignore
206
        return compare_on
207

    
208
def is_underlying_table(table):
209
    return isinstance(table, Table) and table.to_Table() is table
210

    
211
class NoUnderlyingTableException(Exception): pass
212

    
213
def underlying_table(table):
214
    table = remove_table_rename(table)
215
    if not is_underlying_table(table): raise NoUnderlyingTableException
216
    return table
217

    
218
def as_Table(table, schema=None):
219
    if table == None or isinstance(table, Code): return table
220
    else: return Table(table, schema)
221

    
222
def suffixed_table(table, suffix):
223
    table = copy.copy(table) # don't modify input!
224
    table.name = concat(table.name, suffix)
225
    return table
226

    
227
class NamedTable(Table):
228
    def __init__(self, name, code, cols=None):
229
        Table.__init__(self, name)
230
        
231
        code = as_Table(code)
232
        if not isinstance(code, (Table, FunctionCall, Expr)): code = Expr(code)
233
        if cols != None: cols = [to_name_only_col(c).to_Col() for c in cols]
234
        
235
        self.code = code
236
        self.cols = cols
237
    
238
    def to_str(self, db):
239
        str_ = self.code.to_str(db)
240
        if str_.find('\n') >= 0: whitespace = '\n'
241
        else: whitespace = ' '
242
        str_ += whitespace+'AS '+Table.to_str(self, db)
243
        if self.cols != None:
244
            str_ += ' ('+(', '.join((c.to_str(db) for c in self.cols)))+')'
245
        return str_
246
    
247
    def to_Table(self): return Table(self.name)
248

    
249
def remove_table_rename(table):
250
    if isinstance(table, NamedTable): table = table.code
251
    return table
252

    
253
##### Columns
254

    
255
class Col(Derived):
256
    def __init__(self, name, table=None, srcs=()):
257
        '''
258
        @param table Table|None (for no table)
259
        @param srcs (Col...)|src_self See Derived.set_srcs()
260
        '''
261
        Derived.__init__(self, srcs)
262
        
263
        if util.is_str(name): name = truncate(name)
264
        if util.is_str(table): table = Table(table)
265
        assert table == None or isinstance(table, Table)
266
        
267
        self.name = name
268
        self.table = table
269
    
270
    def to_str(self, db, for_str=False):
271
        str_ = as_Name(self.name).to_str(db)
272
        if for_str: str_ = clean_name(str_)
273
        if self.table != None:
274
            table = self.table.to_Table()
275
            if for_str: str_ = concat(str(table), '.'+str_)
276
            else: str_ = table.to_str(db)+'.'+str_
277
        return str_
278
    
279
    def __str__(self): return self.to_str(mockDb, for_str=True)
280
    
281
    def to_Col(self): return self
282

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

    
285
def index_col(col):
286
    if not is_table_col(col): return None
287
    
288
    table = col.table
289
    try: name = table.index_cols[col.name]
290
    except KeyError: return None
291
    else: return Col(name, table, col.srcs)
292

    
293
def is_temp_col(col): return is_table_col(col) and col.table.is_temp
294

    
295
def as_Col(col, table=None, name=None):
296
    '''
297
    @param name If not None, any non-Col input will be renamed using NamedCol.
298
    '''
299
    if name != None:
300
        col = as_Value(col)
301
        if not isinstance(col, Col): col = NamedCol(name, col)
302
    
303
    if isinstance(col, Code): return col
304
    else: return Col(col, table)
305

    
306
def with_table(col, table):
307
    if isinstance(col, NamedCol): pass # doesn't take a table
308
    elif isinstance(col, FunctionCall):
309
        col = copy.deepcopy(col) # don't modify input!
310
        col.args[0].table = table
311
    else:
312
        col = copy.copy(col) # don't modify input!
313
        col.table = table
314
    return col
315

    
316
def with_default_table(col, table):
317
    col = as_Col(col)
318
    if col.table == None: col = with_table(col, table)
319
    return col
320

    
321
def set_cols_table(table, cols):
322
    table = as_Table(table)
323
    
324
    for i, col in enumerate(cols):
325
        col = cols[i] = as_Col(col)
326
        col.table = table
327

    
328
def to_name_only_col(col, check_table=None):
329
    col = as_Col(col)
330
    if not is_table_col(col): return col
331
    
332
    if check_table != None:
333
        table = col.table
334
        assert table == None or table == check_table
335
    return Col(col.name)
336

    
337
def suffixed_col(col, suffix):
338
    return Col(concat(col.name, suffix), col.table, col.srcs)
339

    
340
class NamedCol(Col):
341
    def __init__(self, name, code):
342
        Col.__init__(self, name)
343
        
344
        code = as_Value(code)
345
        
346
        self.code = code
347
    
348
    def to_str(self, db):
349
        return self.code.to_str(db)+' AS '+Col.to_str(self, db)
350
    
351
    def to_Col(self): return Col(self.name)
352

    
353
def remove_col_rename(col):
354
    if isinstance(col, NamedCol): col = col.code
355
    return col
356

    
357
def underlying_col(col):
358
    col = remove_col_rename(col)
359
    if not isinstance(col, Col): raise NoUnderlyingTableException
360
    
361
    return Col(col.name, underlying_table(col.table), col.srcs)
362

    
363
def wrap(wrap_func, value):
364
    '''Wraps a value, propagating any column renaming to the returned value.'''
365
    if isinstance(value, NamedCol):
366
        return NamedCol(value.name, wrap_func(value.code))
367
    else: return wrap_func(value)
368

    
369
class ColDict(dicts.DictProxy):
370
    '''A dict that automatically makes inserted entries Col objects'''
371
    
372
    def __init__(self, db, keys_table, dict_={}):
373
        dicts.DictProxy.__init__(self, OrderedDict())
374
        
375
        keys_table = as_Table(keys_table)
376
        
377
        self.db = db
378
        self.table = keys_table
379
        self.update(dict_) # after setting vars because __setitem__() needs them
380
    
381
    def copy(self): return ColDict(self.db, self.table, self.inner.copy())
382
    
383
    def __getitem__(self, key):
384
        return dicts.DictProxy.__getitem__(self, self._key(key))
385
    
386
    def __setitem__(self, key, value):
387
        key = self._key(key)
388
        if value == None: value = self.db.col_info(key).default
389
        dicts.DictProxy.__setitem__(self, key, as_Col(value, name=key.name))
390
    
391
    def _key(self, key): return as_Col(key, self.table)
392

    
393
##### Functions
394

    
395
Function = Table
396
as_Function = as_Table
397

    
398
class InternalFunction(CustomCode): pass
399

    
400
#### Calls
401

    
402
class NamedArg(NamedCol):
403
    def __init__(self, name, value):
404
        NamedCol.__init__(self, name, value)
405
    
406
    def to_str(self, db):
407
        return Col.to_str(self, db)+' := '+self.code.to_str(db)
408

    
409
class FunctionCall(Code):
410
    def __init__(self, function, *args, **kw_args):
411
        '''
412
        @param args [Code|literal-value...] The function's arguments
413
        '''
414
        Code.__init__(self)
415
        
416
        function = as_Function(function)
417
        def filter_(arg): return remove_col_rename(as_Value(arg))
418
        args = map(filter_, args)
419
        args += [NamedArg(k, filter_(v)) for k, v in kw_args.iteritems()]
420
        
421
        self.function = function
422
        self.args = args
423
    
424
    def to_str(self, db):
425
        args_str = ', '.join((v.to_str(db) for v in self.args))
426
        return self.function.to_str(db)+'('+args_str+')'
427

    
428
def wrap_in_func(function, value):
429
    '''Wraps a value inside a function call.
430
    Propagates any column renaming to the returned value.
431
    '''
432
    return wrap(lambda v: FunctionCall(function, v), value)
433

    
434
def unwrap_func_call(func_call, check_name=None):
435
    '''Unwraps any function call to its first argument.
436
    Also removes any column renaming.
437
    '''
438
    func_call = remove_col_rename(func_call)
439
    if not isinstance(func_call, FunctionCall): return func_call
440
    
441
    if check_name != None:
442
        name = func_call.function.name
443
        assert name == None or name == check_name
444
    return func_call.args[0]
445

    
446
#### Definitions
447

    
448
class FunctionDef(Code):
449
    def __init__(self, function, return_type, body, lang='sql'):
450
        Code.__init__(self)
451
        
452
        body = as_Code(body)
453
        
454
        self.function = function
455
        self.return_type = return_type
456
        self.body = body
457
        self.lang = lang
458
    
459
    def to_str(self, db):
460
        str_ = '''\
461
CREATE FUNCTION '''+self.function.to_str(db)+'''()
462
RETURNS SETOF '''+self.return_type+'''
463
LANGUAGE '''+self.lang+'''
464
AS $$
465
'''+self.body.to_str(db)+'''
466
$$;
467
'''
468
        return str_
469

    
470
##### Casts
471

    
472
class Cast(FunctionCall):
473
    def __init__(self, type_, value):
474
        value = as_Value(value)
475
        
476
        self.type_ = type_
477
        self.value = value
478
    
479
    def to_str(self, db):
480
        return 'CAST('+self.value.to_str(db)+' AS '+self.type_+')'
481

    
482
def cast_literal(value):
483
    if not is_literal(value): return value
484
    
485
    if util.is_str(value.value): value = Cast('text', value)
486
    return value
487

    
488
##### Conditions
489

    
490
class NotCond(Code):
491
    def __init__(self, cond):
492
        Code.__init__(self)
493
        
494
        self.cond = cond
495
    
496
    def to_str(self, db): return 'NOT '+self.cond.to_str(db)
497

    
498
class ColValueCond(Code):
499
    def __init__(self, col, value):
500
        Code.__init__(self)
501
        
502
        value = as_ValueCond(value)
503
        
504
        self.col = col
505
        self.value = value
506
    
507
    def to_str(self, db): return self.value.to_str(db, self.col)
508

    
509
def combine_conds(conds, keyword=None):
510
    '''
511
    @param keyword The keyword to add before the conditions, if any
512
    '''
513
    str_ = ''
514
    if keyword != None:
515
        if conds == []: whitespace = ''
516
        elif len(conds) == 1: whitespace = ' '
517
        else: whitespace = '\n'
518
        str_ += keyword+whitespace
519
    
520
    str_ += '\nAND '.join(conds)
521
    return str_
522

    
523
##### Condition column comparisons
524

    
525
class ValueCond(BasicObject):
526
    def __init__(self, value):
527
        value = remove_col_rename(as_Value(value))
528
        
529
        self.value = value
530
    
531
    def to_str(self, db, left_value):
532
        '''
533
        @param left_value The Code object that the condition is being applied on
534
        '''
535
        raise NotImplemented()
536
    
537
    def __repr__(self): return self.to_str(mockDb, '<left_value>')
538

    
539
class CompareCond(ValueCond):
540
    def __init__(self, value, operator='='):
541
        '''
542
        @param operator By default, compares NULL values literally. Use '~=' or
543
            '~!=' to pass NULLs through.
544
        '''
545
        ValueCond.__init__(self, value)
546
        self.operator = operator
547
    
548
    def to_str(self, db, left_value):
549
        left_value = remove_col_rename(as_Col(left_value))
550
        
551
        right_value = self.value
552
        
553
        # Parse operator
554
        operator = self.operator
555
        passthru_null_ref = [False]
556
        operator = strings.remove_prefix('~', operator, passthru_null_ref)
557
        neg_ref = [False]
558
        operator = strings.remove_prefix('!', operator, neg_ref)
559
        equals = operator.endswith('=') # also includes <=, >=
560
        
561
        # Handle nullable columns
562
        check_null = False
563
        if not passthru_null_ref[0]: # NULLs compare equal
564
            try: left_value = ensure_not_null(db, left_value)
565
            except ensure_not_null_excs: # fall back to alternate method
566
                check_null = equals and isinstance(right_value, Col)
567
            else:
568
                if isinstance(left_value, EnsureNotNull):
569
                    right_value = ensure_not_null(db, right_value,
570
                        left_value.type) # apply same function to both sides
571
        
572
        if equals and is_null(right_value): operator = 'IS'
573
        
574
        left = left_value.to_str(db)
575
        right = right_value.to_str(db)
576
        
577
        # Create str
578
        str_ = left+' '+operator+' '+right
579
        if check_null:
580
            str_ = '('+str_+' OR ('+left+' IS NULL AND '+right+' IS NULL))'
581
        if neg_ref[0]: str_ = 'NOT '+str_
582
        return str_
583

    
584
# Tells as_ValueCond() to assume a non-ValueCond is a literal value
585
assume_literal = object()
586

    
587
def as_ValueCond(value, default_table=assume_literal):
588
    if not isinstance(value, ValueCond):
589
        if default_table is not assume_literal:
590
            value = with_default_table(value, default_table)
591
        return CompareCond(value)
592
    else: return value
593

    
594
##### Joins
595

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

    
598
# Tells Join the left and right columns have the same name and are never NULL
599
join_same_not_null = object()
600

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

    
603
class Join(BasicObject):
604
    def __init__(self, table, mapping={}, type_=None):
605
        '''
606
        @param mapping dict(right_table_col=left_table_col, ...)
607
            * if left_table_col is join_same: left_table_col = right_table_col
608
              * Note that right_table_col must be a string
609
            * if left_table_col is join_same_not_null:
610
              left_table_col = right_table_col and both have NOT NULL constraint
611
              * Note that right_table_col must be a string
612
        @param type_ None (for plain join)|str (e.g. 'LEFT')|filter_out
613
            * filter_out: equivalent to 'LEFT' with the query filtered by
614
              `table_pkey IS NULL` (indicating no match)
615
        '''
616
        if util.is_str(table): table = Table(table)
617
        assert type_ == None or util.is_str(type_) or type_ is filter_out
618
        
619
        self.table = table
620
        self.mapping = mapping
621
        self.type_ = type_
622
    
623
    def to_str(self, db, left_table_):
624
        def join(entry):
625
            '''Parses non-USING joins'''
626
            right_table_col, left_table_col = entry
627
            
628
            # Switch order (right_table_col is on the left in the comparison)
629
            left = right_table_col
630
            right = left_table_col
631
            left_table = self.table
632
            right_table = left_table_
633
            
634
            # Parse left side
635
            left = with_default_table(left, left_table)
636
            
637
            # Parse special values
638
            left_on_right = Col(left.name, right_table)
639
            if right is join_same: right = left_on_right
640
            elif right is join_same_not_null:
641
                right = CompareCond(left_on_right, '~=')
642
            
643
            # Parse right side
644
            right = as_ValueCond(right, right_table)
645
            
646
            return right.to_str(db, left)
647
        
648
        # Create join condition
649
        type_ = self.type_
650
        joins = self.mapping
651
        if joins == {}: join_cond = None
652
        elif type_ is not filter_out and reduce(operator.and_,
653
            (v is join_same_not_null for v in joins.itervalues())):
654
            # all cols w/ USING, so can use simpler USING syntax
655
            cols = map(to_name_only_col, joins.iterkeys())
656
            join_cond = 'USING ('+(', '.join((c.to_str(db) for c in cols)))+')'
657
        else: join_cond = combine_conds(map(join, joins.iteritems()), 'ON')
658
        
659
        if isinstance(self.table, NamedTable): whitespace = '\n'
660
        else: whitespace = ' '
661
        
662
        # Create join
663
        if type_ is filter_out: type_ = 'LEFT'
664
        str_ = ''
665
        if type_ != None: str_ += type_+' '
666
        str_ += 'JOIN'+whitespace+self.table.to_str(db)
667
        if join_cond != None: str_ += whitespace+join_cond
668
        return str_
669
    
670
    def __repr__(self): return self.to_str(mockDb, '<left_table>')
671

    
672
##### Value exprs
673

    
674
all_cols = CustomCode('*')
675

    
676
default = CustomCode('DEFAULT')
677

    
678
row_count = FunctionCall(InternalFunction('COUNT'), all_cols)
679

    
680
class Coalesce(FunctionCall):
681
    def __init__(self, *args):
682
        FunctionCall.__init__(self, InternalFunction('COALESCE'), *args)
683

    
684
class Nullif(FunctionCall):
685
    def __init__(self, *args):
686
        FunctionCall.__init__(self, InternalFunction('NULLIF'), *args)
687

    
688
# See <http://www.postgresql.org/docs/8.3/static/datatype-numeric.html>
689
null_sentinels = {
690
    'character varying': r'\N',
691
    'double precision': 'NaN',
692
    'integer': 2147483647,
693
    'text': r'\N',
694
    'timestamp with time zone': 'infinity'
695
}
696

    
697
class EnsureNotNull(Coalesce):
698
    def __init__(self, value, type_):
699
        Coalesce.__init__(self, as_Col(value),
700
            Cast(type_, null_sentinels[type_]))
701
        
702
        self.type = type_
703
    
704
    def to_str(self, db):
705
        col = self.args[0]
706
        index_col_ = index_col(col)
707
        if index_col_ != None: return index_col_.to_str(db)
708
        return Coalesce.to_str(self, db)
709

    
710
##### Table exprs
711

    
712
class Values(Code):
713
    def __init__(self, values):
714
        '''
715
        @param values [...]|[[...], ...] Can be one or multiple rows.
716
        '''
717
        Code.__init__(self)
718
        
719
        rows = values
720
        if len(values) >= 1 and not lists.is_seq(values[0]): # only one row
721
            rows = [values]
722
        for i, row in enumerate(rows):
723
            rows[i] = map(remove_col_rename, map(as_Value, row))
724
        
725
        self.rows = rows
726
    
727
    def to_str(self, db):
728
        def row_str(row):
729
            return '('+(', '.join((v.to_str(db) for v in row)))+')'
730
        return 'VALUES '+(', '.join(map(row_str, self.rows)))
731

    
732
def NamedValues(name, cols, values):
733
    '''
734
    @param cols None|[...]
735
    @post `cols` will be changed to Col objects with the table set to `name`.
736
    '''
737
    table = NamedTable(name, Values(values), cols)
738
    if cols != None: set_cols_table(table, cols)
739
    return table
740

    
741
##### Database structure
742

    
743
class TypedCol(Col):
744
    def __init__(self, name, type_, default=None, nullable=True,
745
        constraints=None):
746
        assert default == None or isinstance(default, Code)
747
        
748
        Col.__init__(self, name)
749
        
750
        self.type = type_
751
        self.default = default
752
        self.nullable = nullable
753
        self.constraints = constraints
754
    
755
    def to_str(self, db):
756
        str_ = Col.to_str(self, db)+' '+self.type
757
        if not self.nullable: str_ += ' NOT NULL'
758
        if self.default != None: str_ += ' DEFAULT '+self.default.to_str(db)
759
        if self.constraints != None: str_ += ' '+self.constraints
760
        return str_
761
    
762
    def to_Col(self): return Col(self.name)
763

    
764
ensure_not_null_excs = (NoUnderlyingTableException, KeyError)
765

    
766
def ensure_not_null(db, col, type_=None):
767
    '''
768
    @param col If type_ is not set, must have an underlying column.
769
    @param type_ If set, overrides the underlying column's type.
770
    @return EnsureNotNull|Col
771
    @throws ensure_not_null_excs
772
    '''
773
    nullable = True
774
    try: typed_col = db.col_info(underlying_col(col))
775
    except NoUnderlyingTableException:
776
        col = remove_col_rename(col)
777
        if is_literal(col) and not is_null(col): nullable = False
778
        elif type_ == None: raise
779
    else:
780
        if type_ == None: type_ = typed_col.type
781
        nullable = typed_col.nullable
782
    
783
    if nullable:
784
        try: col = EnsureNotNull(col, type_)
785
        except KeyError, e:
786
            # Warn of no null sentinel for type, even if caller catches error
787
            warnings.warn(UserWarning(exc.str_(e)))
788
            raise
789
    
790
    return col
(25-25/37)