Project

General

Profile

1
# Database access
2

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

    
8
import exc
9
import dicts
10
import iters
11
import lists
12
from Proxy import Proxy
13
import rand
14
import sql_gen
15
import strings
16
import util
17

    
18
##### Exceptions
19

    
20
def get_cur_query(cur, input_query=None, input_params=None):
21
    raw_query = None
22
    if hasattr(cur, 'query'): raw_query = cur.query
23
    elif hasattr(cur, '_last_executed'): raw_query = cur._last_executed
24
    
25
    if raw_query != None: return raw_query
26
    else: return '[input] '+strings.ustr(input_query)+' % '+repr(input_params)
27

    
28
def _add_cursor_info(e, *args, **kw_args):
29
    '''For params, see get_cur_query()'''
30
    exc.add_msg(e, 'query: '+str(get_cur_query(*args, **kw_args)))
31

    
32
class DbException(exc.ExceptionWithCause):
33
    def __init__(self, msg, cause=None, cur=None):
34
        exc.ExceptionWithCause.__init__(self, msg, cause, cause_newline=True)
35
        if cur != None: _add_cursor_info(self, cur)
36

    
37
class ExceptionWithName(DbException):
38
    def __init__(self, name, cause=None):
39
        DbException.__init__(self, 'for name: '+strings.as_tt(str(name)), cause)
40
        self.name = name
41

    
42
class ExceptionWithNameValue(DbException):
43
    def __init__(self, name, value, cause=None):
44
        DbException.__init__(self, 'for name: '+strings.as_tt(str(name))
45
            +'; value: '+strings.as_tt(repr(value)), cause)
46
        self.name = name
47
        self.value = value
48

    
49
class ConstraintException(DbException):
50
    def __init__(self, name, cols, cause=None):
51
        DbException.__init__(self, 'Violated '+strings.as_tt(name)
52
            +' constraint on columns: '+strings.as_tt(', '.join(cols)), cause)
53
        self.name = name
54
        self.cols = cols
55

    
56
class MissingCastException(DbException):
57
    def __init__(self, type_, col, cause=None):
58
        DbException.__init__(self, 'Missing cast to type '+strings.as_tt(type_)
59
            +' on column: '+strings.as_tt(col), cause)
60
        self.type = type_
61
        self.col = col
62

    
63
class NameException(DbException): pass
64

    
65
class DuplicateKeyException(ConstraintException): pass
66

    
67
class NullValueException(ConstraintException): pass
68

    
69
class FunctionValueException(ExceptionWithNameValue): pass
70

    
71
class DuplicateTableException(ExceptionWithName): pass
72

    
73
class DuplicateFunctionException(ExceptionWithName): pass
74

    
75
class EmptyRowException(DbException): pass
76

    
77
##### Warnings
78

    
79
class DbWarning(UserWarning): pass
80

    
81
##### Result retrieval
82

    
83
def col_names(cur): return (col[0] for col in cur.description)
84

    
85
def rows(cur): return iter(lambda: cur.fetchone(), None)
86

    
87
def consume_rows(cur):
88
    '''Used to fetch all rows so result will be cached'''
89
    iters.consume_iter(rows(cur))
90

    
91
def next_row(cur): return rows(cur).next()
92

    
93
def row(cur):
94
    row_ = next_row(cur)
95
    consume_rows(cur)
96
    return row_
97

    
98
def next_value(cur): return next_row(cur)[0]
99

    
100
def value(cur): return row(cur)[0]
101

    
102
def values(cur): return iters.func_iter(lambda: next_value(cur))
103

    
104
def value_or_none(cur):
105
    try: return value(cur)
106
    except StopIteration: return None
107

    
108
##### Input validation
109

    
110
def esc_name_by_module(module, name):
111
    if module == 'psycopg2' or module == None: quote = '"'
112
    elif module == 'MySQLdb': quote = '`'
113
    else: raise NotImplementedError("Can't escape name for "+module+' database')
114
    return sql_gen.esc_name(name, quote)
115

    
116
def esc_name_by_engine(engine, name, **kw_args):
117
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
118

    
119
def esc_name(db, name, **kw_args):
120
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
121

    
122
def qual_name(db, schema, table):
123
    def esc_name_(name): return esc_name(db, name)
124
    table = esc_name_(table)
125
    if schema != None: return esc_name_(schema)+'.'+table
126
    else: return table
127

    
128
##### Database connections
129

    
130
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
131

    
132
db_engines = {
133
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
134
    'PostgreSQL': ('psycopg2', {}),
135
}
136

    
137
DatabaseErrors_set = set([DbException])
138
DatabaseErrors = tuple(DatabaseErrors_set)
139

    
140
def _add_module(module):
141
    DatabaseErrors_set.add(module.DatabaseError)
142
    global DatabaseErrors
143
    DatabaseErrors = tuple(DatabaseErrors_set)
144

    
145
def db_config_str(db_config):
146
    return db_config['engine']+' database '+db_config['database']
147

    
148
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
149

    
150
log_debug_none = lambda msg, level=2: None
151

    
152
class DbConn:
153
    def __init__(self, db_config, serializable=True, autocommit=False,
154
        caching=True, log_debug=log_debug_none):
155
        self.db_config = db_config
156
        self.serializable = serializable
157
        self.autocommit = autocommit
158
        self.caching = caching
159
        self.log_debug = log_debug
160
        self.debug = log_debug != log_debug_none
161
        
162
        self.__db = None
163
        self.query_results = {}
164
        self._savepoint = 0
165
        self._notices_seen = set()
166
    
167
    def __getattr__(self, name):
168
        if name == '__dict__': raise Exception('getting __dict__')
169
        if name == 'db': return self._db()
170
        else: raise AttributeError()
171
    
172
    def __getstate__(self):
173
        state = copy.copy(self.__dict__) # shallow copy
174
        state['log_debug'] = None # don't pickle the debug callback
175
        state['_DbConn__db'] = None # don't pickle the connection
176
        return state
177
    
178
    def connected(self): return self.__db != None
179
    
180
    def _db(self):
181
        if self.__db == None:
182
            # Process db_config
183
            db_config = self.db_config.copy() # don't modify input!
184
            schemas = db_config.pop('schemas', None)
185
            module_name, mappings = db_engines[db_config.pop('engine')]
186
            module = __import__(module_name)
187
            _add_module(module)
188
            for orig, new in mappings.iteritems():
189
                try: util.rename_key(db_config, orig, new)
190
                except KeyError: pass
191
            
192
            # Connect
193
            self.__db = module.connect(**db_config)
194
            
195
            # Configure connection
196
            if self.serializable and not self.autocommit: self.run_query(
197
                'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE', log_level=4)
198
            if schemas != None:
199
                schemas_ = ''.join((esc_name(self, s)+', '
200
                    for s in schemas.split(',')))
201
                self.run_query("SELECT set_config('search_path', \
202
%s || current_setting('search_path'), false)", [schemas_], log_level=3)
203
        
204
        return self.__db
205
    
206
    class DbCursor(Proxy):
207
        def __init__(self, outer):
208
            Proxy.__init__(self, outer.db.cursor())
209
            self.outer = outer
210
            self.query_results = outer.query_results
211
            self.query_lookup = None
212
            self.result = []
213
        
214
        def execute(self, query, params=None):
215
            self._is_insert = query.upper().find('INSERT') >= 0
216
            self.query_lookup = _query_lookup(query, params)
217
            try:
218
                try:
219
                    return_value = self.inner.execute(query, params)
220
                    self.outer.do_autocommit()
221
                finally: self.query = get_cur_query(self.inner, query, params)
222
            except Exception, e:
223
                _add_cursor_info(e, self, query, params)
224
                self.result = e # cache the exception as the result
225
                self._cache_result()
226
                raise
227
            # Fetch all rows so result will be cached
228
            if self.rowcount == 0 and not self._is_insert: consume_rows(self)
229
            return return_value
230
        
231
        def fetchone(self):
232
            row = self.inner.fetchone()
233
            if row != None: self.result.append(row)
234
            # otherwise, fetched all rows
235
            else: self._cache_result()
236
            return row
237
        
238
        def _cache_result(self):
239
            # For inserts, only cache exceptions since inserts are not
240
            # idempotent, but an invalid insert will always be invalid
241
            if self.query_results != None and (not self._is_insert
242
                or isinstance(self.result, Exception)):
243
                
244
                assert self.query_lookup != None
245
                self.query_results[self.query_lookup] = self.CacheCursor(
246
                    util.dict_subset(dicts.AttrsDictView(self),
247
                    ['query', 'result', 'rowcount', 'description']))
248
        
249
        class CacheCursor:
250
            def __init__(self, cached_result): self.__dict__ = cached_result
251
            
252
            def execute(self, *args, **kw_args):
253
                if isinstance(self.result, Exception): raise self.result
254
                # otherwise, result is a rows list
255
                self.iter = iter(self.result)
256
            
257
            def fetchone(self):
258
                try: return self.iter.next()
259
                except StopIteration: return None
260
    
261
    def esc_value(self, value):
262
        try: str_ = self.mogrify('%s', [value])
263
        except NotImplementedError, e:
264
            module = util.root_module(self.db)
265
            if module == 'MySQLdb':
266
                import _mysql
267
                str_ = _mysql.escape_string(value)
268
            else: raise e
269
        return strings.to_unicode(str_)
270
    
271
    def esc_name(self, name): return esc_name(self, name) # calls global func
272
    
273
    def can_mogrify(self):
274
        module = util.root_module(self.db)
275
        return module == 'psycopg2'
276
    
277
    def mogrify(self, query, params=None):
278
        if self.can_mogrify(): return self.db.cursor().mogrify(query, params)
279
        else: raise NotImplementedError("Can't mogrify query")
280
    
281
    def print_notices(self):
282
        for msg in self.db.notices:
283
            if msg not in self._notices_seen:
284
                self._notices_seen.add(msg)
285
                self.log_debug(msg, level=2)
286
    
287
    def run_query(self, query, params=None, cacheable=False, log_level=2,
288
        debug_msg_ref=None):
289
        '''
290
        @param log_ignore_excs The log_level will be increased by 2 if the query
291
            throws one of these exceptions.
292
        @param debug_msg_ref If specified, the log message will be returned in
293
            this instead of being output. This allows you to filter log messages
294
            depending on the result of the query.
295
        '''
296
        assert query != None
297
        
298
        if not self.caching: cacheable = False
299
        used_cache = False
300
        
301
        def log_msg(query):
302
            if used_cache: cache_status = 'cache hit'
303
            elif cacheable: cache_status = 'cache miss'
304
            else: cache_status = 'non-cacheable'
305
            return 'DB query: '+cache_status+':\n'+strings.as_code(query, 'SQL')
306
        
307
        try:
308
            # Get cursor
309
            if cacheable:
310
                query_lookup = _query_lookup(query, params)
311
                try:
312
                    cur = self.query_results[query_lookup]
313
                    used_cache = True
314
                except KeyError: cur = self.DbCursor(self)
315
            else: cur = self.db.cursor()
316
            
317
            # Log query
318
            if self.debug and debug_msg_ref == None: # log before running
319
                self.log_debug(log_msg(query), log_level)
320
            
321
            # Run query
322
            cur.execute(query, params)
323
        finally:
324
            self.print_notices()
325
            if self.debug and debug_msg_ref != None: # return after running
326
                debug_msg_ref[0] = log_msg(str(get_cur_query(cur, query,
327
                    params)))
328
        
329
        return cur
330
    
331
    def is_cached(self, query, params=None):
332
        return _query_lookup(query, params) in self.query_results
333
    
334
    def with_autocommit(self, func, autocommit=True):
335
        prev_autocommit = self.db.autocommit
336
        self.db.autocommit = autocommit
337
        try: return func()
338
        finally: self.db.autocommit = prev_autocommit
339
    
340
    def with_savepoint(self, func):
341
        savepoint = 'level_'+str(self._savepoint)
342
        self.run_query('SAVEPOINT '+savepoint, log_level=4)
343
        self._savepoint += 1
344
        try:
345
            try: return_val = func()
346
            finally:
347
                self._savepoint -= 1
348
                assert self._savepoint >= 0
349
        except:
350
            self.run_query('ROLLBACK TO SAVEPOINT '+savepoint, log_level=4)
351
            raise
352
        else:
353
            self.run_query('RELEASE SAVEPOINT '+savepoint, log_level=4)
354
            self.do_autocommit()
355
            return return_val
356
    
357
    def do_autocommit(self):
358
        '''Autocommits if outside savepoint'''
359
        assert self._savepoint >= 0
360
        if self.autocommit and self._savepoint == 0:
361
            self.log_debug('Autocommitting')
362
            self.db.commit()
363
    
364
    def col_default(self, col):
365
        table = sql_gen.Table('columns', 'information_schema')
366
        
367
        conds = [('table_name', col.table.name), ('column_name', col.name)]
368
        schema = col.table.schema
369
        if schema != None: conds.append(('table_schema', schema))
370
        
371
        return sql_gen.as_Code(value(select(self, table, ['column_default'],
372
            conds, order_by='table_schema', limit=1, log_level=3)))
373
            # TODO: order_by search_path schema order
374

    
375
connect = DbConn
376

    
377
##### Querying
378

    
379
def run_raw_query(db, *args, **kw_args):
380
    '''For params, see DbConn.run_query()'''
381
    return db.run_query(*args, **kw_args)
382

    
383
def mogrify(db, query, params):
384
    module = util.root_module(db.db)
385
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
386
    else: raise NotImplementedError("Can't mogrify query for "+module+
387
        ' database')
388

    
389
##### Recoverable querying
390

    
391
def with_savepoint(db, func): return db.with_savepoint(func)
392

    
393
def run_query(db, query, params=None, recover=None, cacheable=False,
394
    log_level=2, log_ignore_excs=None, **kw_args):
395
    '''For params, see run_raw_query()'''
396
    if recover == None: recover = False
397
    if log_ignore_excs == None: log_ignore_excs = ()
398
    log_ignore_excs = tuple(log_ignore_excs)
399
    
400
    debug_msg_ref = None # usually, db.run_query() logs query before running it
401
    # But if filtering with log_ignore_excs, wait until after exception parsing
402
    if log_ignore_excs != () or not db.can_mogrify(): debug_msg_ref = [None] 
403
    
404
    try:
405
        try:
406
            def run(): return run_raw_query(db, query, params, cacheable,
407
                log_level, debug_msg_ref, **kw_args)
408
            if recover and not db.is_cached(query, params):
409
                return with_savepoint(db, run)
410
            else: return run() # don't need savepoint if cached
411
        except Exception, e:
412
            if not recover: raise # need savepoint to run index_cols()
413
            msg = exc.str_(e)
414
            
415
            match = re.search(r'duplicate key value violates unique constraint '
416
                r'"((_?[^\W_]+)_.+?)"', msg)
417
            if match:
418
                constraint, table = match.groups()
419
                try: cols = index_cols(db, table, constraint)
420
                except NotImplementedError: raise e
421
                else: raise DuplicateKeyException(constraint, cols, e)
422
            
423
            match = re.search(r'null value in column "(.+?)" violates not-null'
424
                r' constraint', msg)
425
            if match: raise NullValueException('NOT NULL', [match.group(1)], e)
426
            
427
            match = re.search(r'\b(?:invalid input (?:syntax|value)\b.*?'
428
                r'|date/time field value out of range): "(.+?)"\n'
429
                r'(?:(?s).*?)\bfunction "(.+?)"', msg)
430
            if match:
431
                value, name = match.groups()
432
                raise FunctionValueException(name, strings.to_unicode(value), e)
433
            
434
            match = re.search(r'column "(.+?)" is of type (.+?) but expression '
435
                r'is of type', msg)
436
            if match:
437
                col, type_ = match.groups()
438
                raise MissingCastException(type_, col, e)
439
            
440
            match = re.search(r'relation "(.+?)" already exists', msg)
441
            if match: raise DuplicateTableException(match.group(1), e)
442
            
443
            match = re.search(r'function "(.+?)" already exists', msg)
444
            if match: raise DuplicateFunctionException(match.group(1), e)
445
            
446
            raise # no specific exception raised
447
    except log_ignore_excs:
448
        log_level += 2
449
        raise
450
    finally:
451
        if debug_msg_ref != None and debug_msg_ref[0] != None:
452
            db.log_debug(debug_msg_ref[0], log_level)
453

    
454
##### Basic queries
455

    
456
def next_version(name):
457
    version = 1 # first existing name was version 0
458
    match = re.match(r'^(.*)#(\d+)$', name)
459
    if match:
460
        name, version = match.groups()
461
        version = int(version)+1
462
    return sql_gen.add_suffix(name, '#'+str(version))
463

    
464
def run_query_into(db, query, params, into=None, *args, **kw_args):
465
    '''Outputs a query to a temp table.
466
    For params, see run_query().
467
    '''
468
    if into == None: return run_query(db, query, params, *args, **kw_args)
469
    else: # place rows in temp table
470
        assert isinstance(into, sql_gen.Table)
471
        
472
        kw_args['recover'] = True
473
        kw_args.setdefault('log_ignore_excs', (DuplicateTableException,))
474
        
475
        temp = not db.autocommit # tables are permanent in autocommit mode
476
        # "temporary tables cannot specify a schema name", so remove schema
477
        if temp: into.schema = None
478
        
479
        while True:
480
            try:
481
                create_query = 'CREATE'
482
                if temp: create_query += ' TEMP'
483
                create_query += ' TABLE '+into.to_str(db)+' AS\n'+query
484
                
485
                return run_query(db, create_query, params, *args, **kw_args)
486
                    # CREATE TABLE AS sets rowcount to # rows in query
487
            except DuplicateTableException, e:
488
                into.name = next_version(into.name)
489
                # try again with next version of name
490

    
491
order_by_pkey = object() # tells mk_select() to order by the pkey
492

    
493
distinct_on_all = object() # tells mk_select() to SELECT DISTINCT ON all columns
494

    
495
def mk_select(db, tables, fields=None, conds=None, distinct_on=[], limit=None,
496
    start=None, order_by=order_by_pkey, default_table=None):
497
    '''
498
    @param tables The single table to select from, or a list of tables to join
499
        together, with tables after the first being sql_gen.Join objects
500
    @param fields Use None to select all fields in the table
501
    @param conds WHERE conditions: [(compare_left_side, compare_right_side),...]
502
        * container can be any iterable type
503
        * compare_left_side: sql_gen.Code|str (for col name)
504
        * compare_right_side: sql_gen.ValueCond|literal value
505
    @param distinct_on The columns to SELECT DISTINCT ON, or distinct_on_all to
506
        use all columns
507
    @return tuple(query, params)
508
    '''
509
    # Parse tables param
510
    if not lists.is_seq(tables): tables = [tables]
511
    tables = list(tables) # don't modify input! (list() copies input)
512
    table0 = sql_gen.as_Table(tables.pop(0)) # first table is separate
513
    
514
    # Parse other params
515
    if conds == None: conds = []
516
    elif dicts.is_dict(conds): conds = conds.items()
517
    conds = list(conds) # don't modify input! (list() copies input)
518
    assert limit == None or type(limit) == int
519
    assert start == None or type(start) == int
520
    if order_by is order_by_pkey:
521
        if distinct_on != []: order_by = None
522
        else: order_by = pkey(db, table0, recover=True)
523
    
524
    query = 'SELECT'
525
    
526
    def parse_col(col): return sql_gen.as_Col(col, default_table).to_str(db)
527
    
528
    # DISTINCT ON columns
529
    if distinct_on != []:
530
        query += '\nDISTINCT'
531
        if distinct_on is not distinct_on_all:
532
            query += ' ON ('+(', '.join(map(parse_col, distinct_on)))+')'
533
    
534
    # Columns
535
    query += '\n'
536
    if fields == None: query += '*'
537
    else: query += '\n, '.join(map(parse_col, fields))
538
    
539
    # Main table
540
    query += '\nFROM '+table0.to_str(db)
541
    
542
    # Add joins
543
    left_table = table0
544
    for join_ in tables:
545
        table = join_.table
546
        
547
        # Parse special values
548
        if join_.type_ is sql_gen.filter_out: # filter no match
549
            conds.append((sql_gen.Col(table_not_null_col(db, table), table),
550
                None))
551
        
552
        query += '\n'+join_.to_str(db, left_table)
553
        
554
        left_table = table
555
    
556
    missing = True
557
    if conds != []:
558
        if len(conds) == 1: whitespace = ' '
559
        else: whitespace = '\n'
560
        query += '\n'+sql_gen.combine_conds([sql_gen.ColValueCond(l, r)
561
            .to_str(db) for l, r in conds], 'WHERE')
562
        missing = False
563
    if order_by != None:
564
        query += '\nORDER BY '+sql_gen.as_Col(order_by, table0).to_str(db)
565
    if limit != None: query += '\nLIMIT '+str(limit); missing = False
566
    if start != None:
567
        if start != 0: query += '\nOFFSET '+str(start)
568
        missing = False
569
    if missing: warnings.warn(DbWarning(
570
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
571
    
572
    return (query, [])
573

    
574
def select(db, *args, **kw_args):
575
    '''For params, see mk_select() and run_query()'''
576
    recover = kw_args.pop('recover', None)
577
    cacheable = kw_args.pop('cacheable', True)
578
    log_level = kw_args.pop('log_level', 2)
579
    
580
    query, params = mk_select(db, *args, **kw_args)
581
    return run_query(db, query, params, recover, cacheable, log_level=log_level)
582

    
583
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
584
    returning=None, embeddable=False):
585
    '''
586
    @param returning str|None An inserted column (such as pkey) to return
587
    @param embeddable Whether the query should be embeddable as a nested SELECT.
588
        Warning: If you set this and cacheable=True when the query is run, the
589
        query will be fully cached, not just if it raises an exception.
590
    '''
591
    table = sql_gen.as_Table(table)
592
    if cols == []: cols = None # no cols (all defaults) = unknown col names
593
    if cols != None:
594
        cols = [sql_gen.to_name_only_col(v, table).to_str(db) for v in cols]
595
    if select_query == None: select_query = 'DEFAULT VALUES'
596
    if returning != None: returning = sql_gen.as_Col(returning, table)
597
    
598
    # Build query
599
    first_line = 'INSERT INTO '+table.to_str(db)
600
    query = first_line
601
    if cols != None: query += '\n('+', '.join(cols)+')'
602
    query += '\n'+select_query
603
    
604
    if returning != None:
605
        returning_name = copy.copy(returning)
606
        returning_name.table = None
607
        returning_name = returning_name.to_str(db)
608
        query += '\nRETURNING '+returning_name
609
    
610
    if embeddable:
611
        assert returning != None
612
        
613
        # Create function
614
        function_name = sql_gen.clean_name(first_line)
615
        return_type = 'SETOF '+returning.to_str(db)+'%TYPE'
616
        while True:
617
            try:
618
                func_schema = None
619
                if not db.autocommit: func_schema = 'pg_temp'
620
                function = sql_gen.Table(function_name, func_schema).to_str(db)
621
                
622
                function_query = '''\
623
CREATE FUNCTION '''+function+'''()
624
RETURNS '''+return_type+'''
625
LANGUAGE sql
626
AS $$
627
'''+mogrify(db, query, params)+''';
628
$$;
629
'''
630
                run_query(db, function_query, recover=True, cacheable=True,
631
                    log_ignore_excs=(DuplicateFunctionException,))
632
                break # this version was successful
633
            except DuplicateFunctionException, e:
634
                function_name = next_version(function_name)
635
                # try again with next version of name
636
        
637
        # Return query that uses function
638
        func_table = sql_gen.NamedTable('f', sql_gen.CustomCode(function+'()'),
639
            [returning_name]) # AS clause requires function alias
640
        return mk_select(db, func_table, start=0, order_by=None)
641
    
642
    return (query, params)
643

    
644
def insert_select(db, *args, **kw_args):
645
    '''For params, see mk_insert_select() and run_query_into()
646
    @param into sql_gen.Table with suggested name of temp table to put RETURNING
647
        values in
648
    '''
649
    into = kw_args.pop('into', None)
650
    if into != None: kw_args['embeddable'] = True
651
    recover = kw_args.pop('recover', None)
652
    cacheable = kw_args.pop('cacheable', True)
653
    log_level = kw_args.pop('log_level', 2)
654
    
655
    query, params = mk_insert_select(db, *args, **kw_args)
656
    return run_query_into(db, query, params, into, recover=recover,
657
        cacheable=cacheable, log_level=log_level)
658

    
659
default = object() # tells insert() to use the default value for a column
660

    
661
def insert(db, table, row, *args, **kw_args):
662
    '''For params, see insert_select()'''
663
    if lists.is_seq(row): cols = None
664
    else:
665
        cols = row.keys()
666
        row = row.values()
667
    row = list(row) # ensure that "!= []" works
668
    
669
    # Check for special values
670
    labels = []
671
    values = []
672
    for value in row:
673
        value = sql_gen.remove_col_rename(sql_gen.as_Value(value)).value
674
        if value is default: labels.append('DEFAULT')
675
        else:
676
            labels.append('%s')
677
            values.append(value)
678
    
679
    # Build query
680
    if values != []: query = 'VALUES ('+(', '.join(labels))+')'
681
    else: query = None
682
    
683
    return insert_select(db, table, cols, query, values, *args, **kw_args)
684

    
685
def mk_update(db, table, changes=None, cond=None):
686
    '''
687
    @param changes [(col, new_value),...]
688
        * container can be any iterable type
689
        * col: sql_gen.Code|str (for col name)
690
        * new_value: sql_gen.Code|literal value
691
    @param cond sql_gen.Code WHERE condition. e.g. use sql_gen.*Cond objects.
692
    @return str query
693
    '''
694
    query = 'UPDATE '+sql_gen.as_Table(table).to_str(db)+'\nSET\n'
695
    query += ',\n'.join((sql_gen.to_name_only_col(col, table).to_str(db)+' = '
696
        +sql_gen.as_Value(new_value).to_str(db) for col, new_value in changes))
697
    if cond != None: query += '\nWHERE\n'+cond.to_str(db)
698
    
699
    return query
700

    
701
def update(db, *args, **kw_args):
702
    '''For params, see mk_update() and run_query()'''
703
    recover = kw_args.pop('recover', None)
704
    
705
    return run_query(db, mk_update(db, *args, **kw_args), [], recover)
706

    
707
def last_insert_id(db):
708
    module = util.root_module(db.db)
709
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
710
    elif module == 'MySQLdb': return db.insert_id()
711
    else: return None
712

    
713
def truncate(db, table, schema='public'):
714
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
715

    
716
def mk_flatten_mapping(db, into, cols, preserve=[], as_items=False):
717
    '''Creates a mapping from original column names (which may have collisions)
718
    to names that will be distinct among the columns' tables.
719
    This is meant to be used for several tables that are being joined together.
720
    @param cols The columns to combine. Duplicates will be removed.
721
    @param into The table for the new columns.
722
    @param preserve [sql_gen.Col...] Columns not to rename. Note that these
723
        columns will be included in the mapping even if they are not in cols.
724
        The tables of the provided Col objects will be changed to into, so make
725
        copies of them if you want to keep the original tables.
726
    @param as_items Whether to return a list of dict items instead of a dict
727
    @return dict(orig_col=new_col, ...)
728
        * orig_col: sql_gen.Col(orig_col_name, orig_table)
729
        * new_col: sql_gen.Col(orig_col_name, into)
730
        * All mappings use the into table so its name can easily be
731
          changed for all columns at once
732
    '''
733
    cols = lists.uniqify(cols)
734
    
735
    items = []
736
    for col in preserve:
737
        orig_col = copy.copy(col)
738
        col.table = into
739
        items.append((orig_col, col))
740
    preserve = set(preserve)
741
    for col in cols:
742
        if col not in preserve: items.append((col, sql_gen.Col(str(col), into)))
743
    
744
    if not as_items: items = dict(items)
745
    return items
746

    
747
def flatten(db, into, joins, cols, limit=None, start=None, **kw_args):
748
    '''For params, see mk_flatten_mapping()
749
    @return See return value of mk_flatten_mapping()
750
    '''
751
    items = mk_flatten_mapping(db, into, cols, as_items=True, **kw_args)
752
    cols = [sql_gen.NamedCol(new.name, old) for old, new in items]
753
    run_query_into(db, *mk_select(db, joins, cols, limit=limit, start=start),
754
        into=into)
755
    return dict(items)
756

    
757
##### Database structure queries
758

    
759
def table_row_count(db, table, recover=None):
760
    return value(run_query(db, *mk_select(db, table, [sql_gen.row_count],
761
        order_by=None, start=0), recover=recover, log_level=3))
762

    
763
def table_cols(db, table, recover=None):
764
    return list(col_names(select(db, table, limit=0, order_by=None,
765
        recover=recover, log_level=4)))
766

    
767
def pkey(db, table, recover=None):
768
    '''Assumed to be first column in table'''
769
    return table_cols(db, table, recover)[0]
770

    
771
not_null_col = 'not_null_col'
772

    
773
def table_not_null_col(db, table, recover=None):
774
    '''Name assumed to be the value of not_null_col. If not found, uses pkey.'''
775
    if not_null_col in table_cols(db, table, recover): return not_null_col
776
    else: return pkey(db, table, recover)
777

    
778
def index_cols(db, table, index):
779
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
780
    automatically created. When you don't know whether something is a UNIQUE
781
    constraint or a UNIQUE index, use this function.'''
782
    module = util.root_module(db.db)
783
    if module == 'psycopg2':
784
        return list(values(run_query(db, '''\
785
SELECT attname
786
FROM
787
(
788
        SELECT attnum, attname
789
        FROM pg_index
790
        JOIN pg_class index ON index.oid = indexrelid
791
        JOIN pg_class table_ ON table_.oid = indrelid
792
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
793
        WHERE
794
            table_.relname = %(table)s
795
            AND index.relname = %(index)s
796
    UNION
797
        SELECT attnum, attname
798
        FROM
799
        (
800
            SELECT
801
                indrelid
802
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
803
                    AS indkey
804
            FROM pg_index
805
            JOIN pg_class index ON index.oid = indexrelid
806
            JOIN pg_class table_ ON table_.oid = indrelid
807
            WHERE
808
                table_.relname = %(table)s
809
                AND index.relname = %(index)s
810
        ) s
811
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
812
) s
813
ORDER BY attnum
814
''',
815
            {'table': table, 'index': index}, cacheable=True, log_level=4)))
816
    else: raise NotImplementedError("Can't list index columns for "+module+
817
        ' database')
818

    
819
def constraint_cols(db, table, constraint):
820
    module = util.root_module(db.db)
821
    if module == 'psycopg2':
822
        return list(values(run_query(db, '''\
823
SELECT attname
824
FROM pg_constraint
825
JOIN pg_class ON pg_class.oid = conrelid
826
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
827
WHERE
828
    relname = %(table)s
829
    AND conname = %(constraint)s
830
ORDER BY attnum
831
''',
832
            {'table': table, 'constraint': constraint})))
833
    else: raise NotImplementedError("Can't list constraint columns for "+module+
834
        ' database')
835

    
836
row_num_col = '_row_num'
837

    
838
def add_index(db, expr):
839
    '''Adds an index on a column or expression if it doesn't already exist.
840
    Currently, only function calls are supported as expressions.
841
    '''
842
    expr = copy.deepcopy(expr) # don't modify input!
843
    
844
    # Extract col
845
    if isinstance(expr, sql_gen.FunctionCall):
846
        col = expr.args[0]
847
        expr = sql_gen.Expr(expr)
848
    else: col = expr
849
    assert sql_gen.is_table_col(col)
850
    
851
    index = sql_gen.as_Table(str(expr))
852
    table = col.table
853
    col.table = None
854
    try: run_query(db, 'CREATE INDEX '+index.to_str(db)+' ON '+table.to_str(db)
855
        +' ('+expr.to_str(db)+')', recover=True, cacheable=True, log_level=3)
856
    except DuplicateTableException: pass # index already existed
857

    
858
def add_pkey(db, table, cols=None, recover=None):
859
    '''Adds a primary key.
860
    @param cols [sql_gen.Col,...] The columns in the primary key.
861
        Defaults to the first column in the table.
862
    @pre The table must not already have a primary key.
863
    '''
864
    table = sql_gen.as_Table(table)
865
    if cols == None: cols = [pkey(db, table, recover)]
866
    col_strs = [sql_gen.to_name_only_col(v).to_str(db) for v in cols]
867
    
868
    index = sql_gen.as_Table(sql_gen.add_suffix(table.name, '_pkey'))
869
    try:
870
        run_query(db, 'ALTER TABLE '+table.to_str(db)+' ADD CONSTRAINT '
871
            +index.to_str(db)+' PRIMARY KEY ('+(', '.join(col_strs))+')',
872
            recover=True, cacheable=True, log_level=3,
873
            log_ignore_excs=(DuplicateTableException,))
874
    except DuplicateTableException, e:
875
        index.name = next_version(index.name)
876
        # try again with next version of name
877

    
878
def add_row_num(db, table):
879
    '''Adds a row number column to a table. Its name is in row_num_col. It will
880
    be the primary key.'''
881
    table = sql_gen.as_Table(table).to_str(db)
882
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
883
        +' serial NOT NULL PRIMARY KEY', log_level=3)
884

    
885
def create_table(db, table, cols, has_pkey=True):
886
    '''Creates a table.
887
    @param cols [sql_gen.TypedCol,...] The column names and types
888
    @param has_pkey If set, the first column becomes the primary key.
889
    '''
890
    table = sql_gen.as_Table(table)
891
    
892
    if has_pkey:
893
        cols[0] = pkey = copy.copy(cols[0]) # don't modify input!
894
        pkey.type += ' NOT NULL PRIMARY KEY'
895
    
896
    str_ = 'CREATE TABLE '+table.to_str(db)+' (\n'
897
    str_ += '\n, '.join(v.to_str(db) for v in cols)
898
    str_ += '\n);\n'
899
    run_query(db, str_, cacheable=True, log_level=2)
900

    
901
def vacuum(db, table):
902
    table = sql_gen.as_Table(table)
903
    db.with_autocommit(lambda: run_query(db, 'VACUUM ANALYZE '+table.to_str(db),
904
        log_level=3))
905

    
906
def tables(db, schema_like='public', table_like='%'):
907
    module = util.root_module(db.db)
908
    params = {'schema_like': schema_like, 'table_like': table_like}
909
    if module == 'psycopg2':
910
        return values(run_query(db, '''\
911
SELECT tablename
912
FROM pg_tables
913
WHERE
914
    schemaname LIKE %(schema_like)s
915
    AND tablename LIKE %(table_like)s
916
ORDER BY tablename
917
''',
918
            params, cacheable=True))
919
    elif module == 'MySQLdb':
920
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
921
            cacheable=True))
922
    else: raise NotImplementedError("Can't list tables for "+module+' database')
923

    
924
##### Database management
925

    
926
def empty_db(db, schema='public', **kw_args):
927
    '''For kw_args, see tables()'''
928
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
929

    
930
##### Heuristic queries
931

    
932
def put(db, table, row, pkey_=None, row_ct_ref=None):
933
    '''Recovers from errors.
934
    Only works under PostgreSQL (uses INSERT RETURNING).
935
    '''
936
    row = sql_gen.ColDict(db, table, row)
937
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
938
    
939
    try:
940
        cur = insert(db, table, row, pkey_, recover=True)
941
        if row_ct_ref != None and cur.rowcount >= 0:
942
            row_ct_ref[0] += cur.rowcount
943
        return value(cur)
944
    except DuplicateKeyException, e:
945
        row = sql_gen.ColDict(db, table,
946
            util.dict_subset_right_join(row, e.cols))
947
        return value(select(db, table, [pkey_], row, recover=True))
948

    
949
def get(db, table, row, pkey, row_ct_ref=None, create=False):
950
    '''Recovers from errors'''
951
    try: return value(select(db, table, [pkey], row, limit=1, recover=True))
952
    except StopIteration:
953
        if not create: raise
954
        return put(db, table, row, pkey, row_ct_ref) # insert new row
955

    
956
def is_func_result(col):
957
    return col.table.name.find('(') >= 0 and col.name == 'result'
958

    
959
def into_table_name(out_table, in_tables0, mapping, is_func):
960
    def in_col_str(in_col):
961
        in_col = sql_gen.remove_col_rename(in_col)
962
        if isinstance(in_col, sql_gen.Col):
963
            table = in_col.table
964
            if table == in_tables0:
965
                in_col = sql_gen.to_name_only_col(in_col)
966
            elif is_func_result(in_col): in_col = table # omit col name
967
        return str(in_col)
968
    
969
    str_ = str(out_table)
970
    if is_func:
971
        str_ += '('
972
        
973
        try: value_in_col = mapping['value']
974
        except KeyError:
975
            str_ += ', '.join((str(k)+'='+in_col_str(v)
976
                for k, v in mapping.iteritems()))
977
        else: str_ += in_col_str(value_in_col)
978
        
979
        str_ += ')'
980
    else: str_ += '_pkeys'
981
    return str_
982

    
983
def put_table(db, out_table, in_tables, mapping, row_ct_ref=None, into=None,
984
    default=None, is_func=False):
985
    '''Recovers from errors.
986
    Only works under PostgreSQL (uses INSERT RETURNING).
987
    @param in_tables The main input table to select from, followed by a list of
988
        tables to join with it using the main input table's pkey
989
    @param mapping dict(out_table_col=in_table_col, ...)
990
        * out_table_col: str (*not* sql_gen.Col)
991
        * in_table_col: sql_gen.Col|literal-value
992
    @param into The table to contain the output and input pkeys.
993
        Defaults to `out_table.name+'_pkeys'`.
994
    @param default The *output* column to use as the pkey for missing rows.
995
        If this output column does not exist in the mapping, uses None.
996
    @param is_func Whether out_table is the name of a SQL function, not a table
997
    @return sql_gen.Col Where the output pkeys are made available
998
    '''
999
    out_table = sql_gen.as_Table(out_table)
1000
    
1001
    def log_debug(msg): db.log_debug(msg, level=1.5)
1002
    def col_ustr(str_):
1003
        return strings.repr_no_u(sql_gen.remove_col_rename(str_))
1004
    
1005
    log_debug('********** New iteration **********')
1006
    log_debug('Inserting these input columns into '+strings.as_tt(
1007
        out_table.to_str(db))+':\n'+strings.as_table(mapping, ustr=col_ustr))
1008
    
1009
    # Create input joins from list of input tables
1010
    in_tables_ = in_tables[:] # don't modify input!
1011
    in_tables0 = in_tables_.pop(0) # first table is separate
1012
    in_pkey = pkey(db, in_tables0, recover=True)
1013
    in_pkey_col = sql_gen.as_Col(in_pkey, in_tables0)
1014
    input_joins = [in_tables0]+[sql_gen.Join(v,
1015
        {in_pkey: sql_gen.join_same_not_null}) for v in in_tables_]
1016
    
1017
    if into == None:
1018
        into = into_table_name(out_table, in_tables0, mapping, is_func)
1019
    into = sql_gen.as_Table(into)
1020
    
1021
    log_debug('Joining together input tables into temp table')
1022
    # Place in new table for speed and so don't modify input if values edited
1023
    in_table = sql_gen.Table('in')
1024
    flatten_cols = filter(sql_gen.is_table_col, mapping.values())
1025
    mapping = dicts.join(mapping, flatten(db, in_table, input_joins,
1026
        flatten_cols, preserve=[in_pkey_col], start=0))
1027
    input_joins = [in_table]
1028
    db.log_debug('Temp table: '+strings.as_tt(in_table.to_str(db)), level=2)
1029
    
1030
    mapping = sql_gen.ColDict(db, out_table, mapping)
1031
        # after applying dicts.join() because that returns a plain dict
1032
    
1033
    # Resolve default value column
1034
    try: default = mapping[default]
1035
    except KeyError:
1036
        if default != None:
1037
            db.log_debug('Default value column '
1038
                +strings.as_tt(strings.repr_no_u(default))
1039
                +' does not exist in mapping, falling back to None', level=2.1)
1040
            default = None
1041
    
1042
    out_pkey = pkey(db, out_table, recover=True)
1043
    out_pkey_col = sql_gen.as_Col(out_pkey, out_table)
1044
    
1045
    pkeys_names = [in_pkey, out_pkey]
1046
    pkeys_cols = [in_pkey_col, out_pkey_col]
1047
    
1048
    pkeys_table_exists_ref = [False]
1049
    def insert_into_pkeys(joins, cols):
1050
        query, params = mk_select(db, joins, cols, order_by=None, start=0)
1051
        if pkeys_table_exists_ref[0]:
1052
            insert_select(db, into, pkeys_names, query, params)
1053
        else:
1054
            run_query_into(db, query, params, into=into)
1055
            pkeys_table_exists_ref[0] = True
1056
    
1057
    limit_ref = [None]
1058
    conds = set()
1059
    distinct_on = []
1060
    def mk_main_select(joins, cols):
1061
        return mk_select(db, joins, cols, conds, distinct_on,
1062
            limit=limit_ref[0], start=0)
1063
    
1064
    exc_strs = set()
1065
    def log_exc(e):
1066
        e_str = exc.str_(e, first_line_only=True)
1067
        log_debug('Caught exception: '+e_str)
1068
        assert e_str not in exc_strs # avoid infinite loops
1069
        exc_strs.add(e_str)
1070
    def remove_all_rows():
1071
        log_debug('Returning NULL for all rows')
1072
        limit_ref[0] = 0 # just create an empty pkeys table
1073
    def ignore(in_col, value):
1074
        in_col_str = strings.as_tt(repr(in_col))
1075
        db.log_debug('Adding index on '+in_col_str+' to enable fast filtering',
1076
            level=2.5)
1077
        add_index(db, in_col)
1078
        log_debug('Ignoring rows with '+in_col_str+' = '
1079
            +strings.as_tt(repr(value)))
1080
    def remove_rows(in_col, value):
1081
        ignore(in_col, value)
1082
        cond = (in_col, sql_gen.CompareCond(value, '!='))
1083
        assert cond not in conds # avoid infinite loops
1084
        conds.add(cond)
1085
    def invalid2null(in_col, value):
1086
        ignore(in_col, value)
1087
        update(db, in_table, [(in_col, None)],
1088
            sql_gen.ColValueCond(in_col, value))
1089
    
1090
    def insert_pkeys_table(which):
1091
        return sql_gen.Table(sql_gen.add_suffix(in_table.name,
1092
            '_insert_'+which+'_pkeys'))
1093
    insert_out_pkeys = insert_pkeys_table('out')
1094
    insert_in_pkeys = insert_pkeys_table('in')
1095
    
1096
    # Do inserts and selects
1097
    join_cols = sql_gen.ColDict(db, out_table)
1098
    while True:
1099
        if limit_ref[0] == 0: # special case
1100
            log_debug('Creating an empty pkeys table')
1101
            cur = run_query_into(db, *mk_select(db, out_table, [out_pkey],
1102
                limit=limit_ref[0]), into=insert_out_pkeys)
1103
            break # don't do main case
1104
        
1105
        has_joins = join_cols != {}
1106
        
1107
        # Prepare to insert new rows
1108
        insert_joins = input_joins[:] # don't modify original!
1109
        insert_args = dict(recover=True, cacheable=False)
1110
        if has_joins:
1111
            distinct_on = [v.to_Col() for v in join_cols.values()]
1112
            insert_joins.append(sql_gen.Join(out_table, join_cols,
1113
                sql_gen.filter_out))
1114
        else:
1115
            insert_args.update(dict(returning=out_pkey, into=insert_out_pkeys))
1116
        main_select = mk_main_select(insert_joins, mapping.values())[0]
1117
        
1118
        log_debug('Trying to insert new rows')
1119
        try:
1120
            cur = insert_select(db, out_table, mapping.keys(), main_select,
1121
                **insert_args)
1122
            break # insert successful
1123
        except DuplicateKeyException, e:
1124
            log_exc(e)
1125
            
1126
            old_join_cols = join_cols.copy()
1127
            join_cols.update(util.dict_subset_right_join(mapping, e.cols))
1128
            log_debug('Ignoring existing rows, comparing on these columns:\n'
1129
                +strings.as_inline_table(join_cols, ustr=col_ustr))
1130
            assert join_cols != old_join_cols # avoid infinite loops
1131
        except NullValueException, e:
1132
            log_exc(e)
1133
            
1134
            out_col, = e.cols
1135
            try: in_col = mapping[out_col]
1136
            except KeyError:
1137
                log_debug('Missing mapping for NOT NULL column '+out_col)
1138
                remove_all_rows()
1139
            else: remove_rows(in_col, None)
1140
        except FunctionValueException, e:
1141
            log_exc(e)
1142
            
1143
            func_name = e.name
1144
            value = e.value
1145
            for out_col, in_col in mapping.iteritems():
1146
                invalid2null(sql_gen.unwrap_func_call(in_col, func_name), value)
1147
        except MissingCastException, e:
1148
            log_exc(e)
1149
            
1150
            out_col = e.col
1151
            mapping[out_col] = sql_gen.wrap_in_func(e.type, mapping[out_col])
1152
        except DatabaseErrors, e:
1153
            log_exc(e)
1154
            
1155
            msg = 'No handler for exception: '+exc.str_(e)
1156
            warnings.warn(DbWarning(msg))
1157
            log_debug(msg)
1158
            remove_all_rows()
1159
        # after exception handled, rerun loop with additional constraints
1160
    
1161
    if row_ct_ref != None and cur.rowcount >= 0:
1162
        row_ct_ref[0] += cur.rowcount
1163
    
1164
    if has_joins:
1165
        select_joins = input_joins+[sql_gen.Join(out_table, join_cols)]
1166
        log_debug('Getting output table pkeys of existing/inserted rows')
1167
        insert_into_pkeys(select_joins, pkeys_cols)
1168
    else:
1169
        add_row_num(db, insert_out_pkeys) # for joining with input pkeys
1170
        
1171
        log_debug('Getting input table pkeys of inserted rows')
1172
        run_query_into(db, *mk_main_select(input_joins, [in_pkey]),
1173
            into=insert_in_pkeys)
1174
        add_row_num(db, insert_in_pkeys) # for joining with output pkeys
1175
        
1176
        assert table_row_count(db, insert_out_pkeys) == table_row_count(db,
1177
            insert_in_pkeys)
1178
        
1179
        log_debug('Combining output and input pkeys in inserted order')
1180
        pkey_joins = [insert_in_pkeys, sql_gen.Join(insert_out_pkeys,
1181
            {row_num_col: sql_gen.join_same_not_null})]
1182
        insert_into_pkeys(pkey_joins, pkeys_names)
1183
    
1184
    db.log_debug('Adding pkey on pkeys table to enable fast joins', level=2.5)
1185
    add_pkey(db, into)
1186
    
1187
    log_debug('Setting pkeys of missing rows to '+strings.as_tt(repr(default)))
1188
    missing_rows_joins = input_joins+[sql_gen.Join(into,
1189
        {in_pkey: sql_gen.join_same_not_null}, sql_gen.filter_out)]
1190
        # must use join_same_not_null or query will take forever
1191
    insert_into_pkeys(missing_rows_joins,
1192
        [in_pkey_col, sql_gen.NamedCol(out_pkey, default)])
1193
    
1194
    assert table_row_count(db, into) == table_row_count(db, in_table)
1195
    
1196
    return sql_gen.Col(out_pkey, into)
1197

    
1198
##### Data cleanup
1199

    
1200
def cleanup_table(db, table, cols):
1201
    table = sql_gen.as_Table(table)
1202
    cols = map(sql_gen.as_Col, cols)
1203
    
1204
    expr = ('nullif(nullif(trim(both from %s), '+db.esc_value('')+'), '
1205
        +db.esc_value(r'\N')+')')
1206
    changes = [(v, sql_gen.CustomCode(expr % v.to_str(db)))
1207
        for v in cols]
1208
    
1209
    update(db, table, changes)
(24-24/36)