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 NameException(DbException): pass
57

    
58
class DuplicateKeyException(ConstraintException): pass
59

    
60
class NullValueException(ConstraintException): pass
61

    
62
class FunctionValueException(ExceptionWithNameValue): pass
63

    
64
class DuplicateTableException(ExceptionWithName): pass
65

    
66
class DuplicateFunctionException(ExceptionWithName): pass
67

    
68
class EmptyRowException(DbException): pass
69

    
70
##### Warnings
71

    
72
class DbWarning(UserWarning): pass
73

    
74
##### Result retrieval
75

    
76
def col_names(cur): return (col[0] for col in cur.description)
77

    
78
def rows(cur): return iter(lambda: cur.fetchone(), None)
79

    
80
def consume_rows(cur):
81
    '''Used to fetch all rows so result will be cached'''
82
    iters.consume_iter(rows(cur))
83

    
84
def next_row(cur): return rows(cur).next()
85

    
86
def row(cur):
87
    row_ = next_row(cur)
88
    consume_rows(cur)
89
    return row_
90

    
91
def next_value(cur): return next_row(cur)[0]
92

    
93
def value(cur): return row(cur)[0]
94

    
95
def values(cur): return iters.func_iter(lambda: next_value(cur))
96

    
97
def value_or_none(cur):
98
    try: return value(cur)
99
    except StopIteration: return None
100

    
101
##### Input validation
102

    
103
def clean_name(name): return name.replace('"', '')
104

    
105
def check_name(name):
106
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
107
        +'" may contain only alphanumeric characters and _')
108

    
109
def esc_name_by_module(module, name, ignore_case=False):
110
    if module == 'psycopg2' or module == None:
111
        if ignore_case:
112
            # Don't enclose in quotes because this disables case-insensitivity
113
            check_name(name)
114
            return name
115
        else: quote = '"'
116
    elif module == 'MySQLdb': quote = '`'
117
    else: raise NotImplementedError("Can't escape name for "+module+' database')
118
    return quote + name.replace(quote, quote+quote) + quote
119
        # doubling an embedded quote escapes it in both PostgreSQL and MySQL
120

    
121
def esc_name_by_engine(engine, name, **kw_args):
122
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
123

    
124
def esc_name(db, name, **kw_args):
125
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
126

    
127
def qual_name(db, schema, table):
128
    def esc_name_(name): return esc_name(db, name)
129
    table = esc_name_(table)
130
    if schema != None: return esc_name_(schema)+'.'+table
131
    else: return table
132

    
133
##### Database connections
134

    
135
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
136

    
137
db_engines = {
138
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
139
    'PostgreSQL': ('psycopg2', {}),
140
}
141

    
142
DatabaseErrors_set = set([DbException])
143
DatabaseErrors = tuple(DatabaseErrors_set)
144

    
145
def _add_module(module):
146
    DatabaseErrors_set.add(module.DatabaseError)
147
    global DatabaseErrors
148
    DatabaseErrors = tuple(DatabaseErrors_set)
149

    
150
def db_config_str(db_config):
151
    return db_config['engine']+' database '+db_config['database']
152

    
153
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
154

    
155
log_debug_none = lambda msg, level=2: None
156

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

    
337
connect = DbConn
338

    
339
##### Querying
340

    
341
def run_raw_query(db, *args, **kw_args):
342
    '''For params, see DbConn.run_query()'''
343
    return db.run_query(*args, **kw_args)
344

    
345
def mogrify(db, query, params):
346
    module = util.root_module(db.db)
347
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
348
    else: raise NotImplementedError("Can't mogrify query for "+module+
349
        ' database')
350

    
351
##### Recoverable querying
352

    
353
def with_savepoint(db, func): return db.with_savepoint(func)
354

    
355
def run_query(db, query, params=None, recover=None, cacheable=False,
356
    log_level=2, log_ignore_excs=None, **kw_args):
357
    '''For params, see run_raw_query()'''
358
    if recover == None: recover = False
359
    if log_ignore_excs == None: log_ignore_excs = ()
360
    log_ignore_excs = tuple(log_ignore_excs)
361
    
362
    debug_msg_ref = [None]
363
    try:
364
        try:
365
            def run(): return run_raw_query(db, query, params, cacheable,
366
                log_level, debug_msg_ref, **kw_args)
367
            if recover and not db.is_cached(query, params):
368
                return with_savepoint(db, run)
369
            else: return run() # don't need savepoint if cached
370
        except Exception, e:
371
            if not recover: raise # need savepoint to run index_cols()
372
            msg = exc.str_(e)
373
            
374
            match = re.search(r'duplicate key value violates unique constraint '
375
                r'"((_?[^\W_]+)_.+?)"', msg)
376
            if match:
377
                constraint, table = match.groups()
378
                try: cols = index_cols(db, table, constraint)
379
                except NotImplementedError: raise e
380
                else: raise DuplicateKeyException(constraint, cols, e)
381
            
382
            match = re.search(r'null value in column "(.+?)" violates not-null'
383
                r' constraint', msg)
384
            if match: raise NullValueException('NOT NULL', [match.group(1)], e)
385
            
386
            match = re.search(r'\b(?:invalid input (?:syntax|value)\b.*?'
387
                r'|date/time field value out of range): "(.+?)"\n'
388
                r'(?:(?s).*?)\bfunction "(.+?)".*?\bat assignment', msg)
389
            if match:
390
                value, name = match.groups()
391
                raise FunctionValueException(name, strings.to_unicode(value), e)
392
            
393
            match = re.search(r'relation "(.+?)" already exists', msg)
394
            if match: raise DuplicateTableException(match.group(1), e)
395
            
396
            match = re.search(r'function "(.+?)" already exists', msg)
397
            if match: raise DuplicateFunctionException(match.group(1), e)
398
            
399
            raise # no specific exception raised
400
    except log_ignore_excs:
401
        log_level += 2
402
        raise
403
    finally:
404
        if debug_msg_ref[0] != None: db.log_debug(debug_msg_ref[0], log_level)
405

    
406
##### Basic queries
407

    
408
def next_version(name):
409
    '''Prepends the version # so it won't be removed if the name is truncated'''
410
    version = 1 # first existing name was version 0
411
    match = re.match(r'^#(\d+)-(.*)$', name)
412
    if match:
413
        version = int(match.group(1))+1
414
        name = match.group(2)
415
    return '#'+str(version)+'-'+name
416

    
417
def run_query_into(db, query, params, into=None, *args, **kw_args):
418
    '''Outputs a query to a temp table.
419
    For params, see run_query().
420
    '''
421
    if into == None: return run_query(db, query, params, *args, **kw_args)
422
    else: # place rows in temp table
423
        assert isinstance(into, sql_gen.Table)
424
        
425
        kw_args['recover'] = True
426
        kw_args.setdefault('log_ignore_excs', (DuplicateTableException,))
427
        
428
        temp = not db.autocommit # tables are permanent in autocommit mode
429
        # "temporary tables cannot specify a schema name", so remove schema
430
        if temp: into.schema = None
431
        
432
        while True:
433
            try:
434
                create_query = 'CREATE'
435
                if temp: create_query += ' TEMP'
436
                create_query += ' TABLE '+into.to_str(db)+' AS\n'+query
437
                
438
                return run_query(db, create_query, params, *args, **kw_args)
439
                    # CREATE TABLE AS sets rowcount to # rows in query
440
            except DuplicateTableException, e:
441
                into.name = next_version(into.name)
442
                # try again with next version of name
443

    
444
order_by_pkey = object() # tells mk_select() to order by the pkey
445

    
446
distinct_on_all = object() # tells mk_select() to SELECT DISTINCT ON all columns
447

    
448
def mk_select(db, tables, fields=None, conds=None, distinct_on=[], limit=None,
449
    start=None, order_by=order_by_pkey, default_table=None):
450
    '''
451
    @param tables The single table to select from, or a list of tables to join
452
        together, with tables after the first being sql_gen.Join objects
453
    @param fields Use None to select all fields in the table
454
    @param conds WHERE conditions: [(compare_left_side, compare_right_side),...]
455
        * container can be any iterable type
456
        * compare_left_side: sql_gen.Code|str (for col name)
457
        * compare_right_side: sql_gen.ValueCond|literal value
458
    @param distinct_on The columns to SELECT DISTINCT ON, or distinct_on_all to
459
        use all columns
460
    @return tuple(query, params)
461
    '''
462
    # Parse tables param
463
    if not lists.is_seq(tables): tables = [tables]
464
    tables = list(tables) # don't modify input! (list() copies input)
465
    table0 = sql_gen.as_Table(tables.pop(0)) # first table is separate
466
    
467
    # Parse other params
468
    if conds == None: conds = []
469
    elif isinstance(conds, dict): conds = conds.items()
470
    conds = list(conds) # don't modify input! (list() copies input)
471
    assert limit == None or type(limit) == int
472
    assert start == None or type(start) == int
473
    if order_by is order_by_pkey:
474
        if distinct_on != []: order_by = None
475
        else: order_by = pkey(db, table0, recover=True)
476
    
477
    query = 'SELECT'
478
    
479
    def parse_col(col): return sql_gen.as_Col(col, default_table).to_str(db)
480
    
481
    # DISTINCT ON columns
482
    if distinct_on != []:
483
        query += '\nDISTINCT'
484
        if distinct_on is not distinct_on_all:
485
            query += ' ON ('+(', '.join(map(parse_col, distinct_on)))+')'
486
    
487
    # Columns
488
    query += '\n'
489
    if fields == None: query += '*'
490
    else: query += '\n, '.join(map(parse_col, fields))
491
    
492
    # Main table
493
    query += '\nFROM '+table0.to_str(db)
494
    
495
    # Add joins
496
    left_table = table0
497
    for join_ in tables:
498
        table = join_.table
499
        
500
        # Parse special values
501
        if join_.type_ is sql_gen.filter_out: # filter no match
502
            conds.append((sql_gen.Col(table_not_null_col(db, table), table),
503
                None))
504
        
505
        query += '\n'+join_.to_str(db, left_table)
506
        
507
        left_table = table
508
    
509
    missing = True
510
    if conds != []:
511
        query += '\nWHERE\n'+('\nAND\n'.join(('('+sql_gen.ColValueCond(l, r)
512
            .to_str(db)+')' for l, r in conds)))
513
        missing = False
514
    if order_by != None:
515
        query += '\nORDER BY '+sql_gen.as_Col(order_by, table0).to_str(db)
516
    if limit != None: query += '\nLIMIT '+str(limit); missing = False
517
    if start != None:
518
        if start != 0: query += '\nOFFSET '+str(start)
519
        missing = False
520
    if missing: warnings.warn(DbWarning(
521
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
522
    
523
    return (query, [])
524

    
525
def select(db, *args, **kw_args):
526
    '''For params, see mk_select() and run_query()'''
527
    recover = kw_args.pop('recover', None)
528
    cacheable = kw_args.pop('cacheable', True)
529
    log_level = kw_args.pop('log_level', 2)
530
    
531
    query, params = mk_select(db, *args, **kw_args)
532
    return run_query(db, query, params, recover, cacheable, log_level=log_level)
533

    
534
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
535
    returning=None, embeddable=False):
536
    '''
537
    @param returning str|None An inserted column (such as pkey) to return
538
    @param embeddable Whether the query should be embeddable as a nested SELECT.
539
        Warning: If you set this and cacheable=True when the query is run, the
540
        query will be fully cached, not just if it raises an exception.
541
    '''
542
    table = sql_gen.as_Table(table)
543
    if cols == []: cols = None # no cols (all defaults) = unknown col names
544
    if cols != None: cols = [sql_gen.as_Col(v).to_str(db) for v in cols]
545
    if select_query == None: select_query = 'DEFAULT VALUES'
546
    if returning != None: returning = sql_gen.as_Col(returning, table)
547
    
548
    # Build query
549
    first_line = 'INSERT INTO '+table.to_str(db)
550
    query = first_line
551
    if cols != None: query += '\n('+', '.join(cols)+')'
552
    query += '\n'+select_query
553
    
554
    if returning != None:
555
        returning_name = copy.copy(returning)
556
        returning_name.table = None
557
        returning_name = returning_name.to_str(db)
558
        query += '\nRETURNING '+returning_name
559
    
560
    if embeddable:
561
        assert returning != None
562
        
563
        # Create function
564
        function_name = clean_name(first_line)
565
        return_type = 'SETOF '+returning.to_str(db)+'%TYPE'
566
        while True:
567
            try:
568
                func_schema = None
569
                if not db.autocommit: func_schema = 'pg_temp'
570
                function = sql_gen.Table(function_name, func_schema).to_str(db)
571
                
572
                function_query = '''\
573
CREATE FUNCTION '''+function+'''()
574
RETURNS '''+return_type+'''
575
LANGUAGE sql
576
AS $$
577
'''+mogrify(db, query, params)+''';
578
$$;
579
'''
580
                run_query(db, function_query, recover=True, cacheable=True,
581
                    log_ignore_excs=(DuplicateFunctionException,))
582
                break # this version was successful
583
            except DuplicateFunctionException, e:
584
                function_name = next_version(function_name)
585
                # try again with next version of name
586
        
587
        # Return query that uses function
588
        func_table = sql_gen.NamedTable('f', sql_gen.CustomCode(function+'()'),
589
            [returning_name]) # AS clause requires function alias
590
        return mk_select(db, func_table, start=0, order_by=None)
591
    
592
    return (query, params)
593

    
594
def insert_select(db, *args, **kw_args):
595
    '''For params, see mk_insert_select() and run_query_into()
596
    @param into sql_gen.Table with suggested name of temp table to put RETURNING
597
        values in
598
    '''
599
    into = kw_args.pop('into', None)
600
    if into != None: kw_args['embeddable'] = True
601
    recover = kw_args.pop('recover', None)
602
    cacheable = kw_args.pop('cacheable', True)
603
    
604
    query, params = mk_insert_select(db, *args, **kw_args)
605
    return run_query_into(db, query, params, into, recover=recover,
606
        cacheable=cacheable)
607

    
608
default = object() # tells insert() to use the default value for a column
609

    
610
def insert(db, table, row, *args, **kw_args):
611
    '''For params, see insert_select()'''
612
    if lists.is_seq(row): cols = None
613
    else:
614
        cols = row.keys()
615
        row = row.values()
616
    row = list(row) # ensure that "!= []" works
617
    
618
    # Check for special values
619
    labels = []
620
    values = []
621
    for value in row:
622
        if value is default: labels.append('DEFAULT')
623
        else:
624
            labels.append('%s')
625
            values.append(value)
626
    
627
    # Build query
628
    if values != []: query = 'VALUES ('+(', '.join(labels))+')'
629
    else: query = None
630
    
631
    return insert_select(db, table, cols, query, values, *args, **kw_args)
632

    
633
def mk_update(db, table, changes=None, cond=None):
634
    '''
635
    @param changes [(col, new_value),...]
636
        * container can be any iterable type
637
        * col: sql_gen.Code|str (for col name)
638
        * new_value: sql_gen.Code|literal value
639
    @param cond sql_gen.Code WHERE condition. e.g. use sql_gen.*Cond objects.
640
    @return str query
641
    '''
642
    query = 'UPDATE '+sql_gen.as_Table(table).to_str(db)+'\nSET\n'
643
    query += ',\n'.join((sql_gen.to_name_only_col(col, table).to_str(db)+' = '
644
        +sql_gen.as_Value(new_value).to_str(db) for col, new_value in changes))
645
    if cond != None: query += '\nWHERE\n'+cond.to_str(db)
646
    
647
    return query
648

    
649
def update(db, *args, **kw_args):
650
    '''For params, see mk_update() and run_query()'''
651
    recover = kw_args.pop('recover', None)
652
    
653
    return run_query(db, mk_update(db, *args, **kw_args), [], recover)
654

    
655
def last_insert_id(db):
656
    module = util.root_module(db.db)
657
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
658
    elif module == 'MySQLdb': return db.insert_id()
659
    else: return None
660

    
661
def truncate(db, table, schema='public'):
662
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
663

    
664
def mk_flatten_mapping(db, into, cols, preserve=[], as_items=False):
665
    '''Creates a mapping from original column names (which may have collisions)
666
    to names that will be distinct among the columns' tables.
667
    This is meant to be used for several tables that are being joined together.
668
    @param cols The columns to combine. Duplicates will be removed.
669
    @param into The table for the new columns.
670
    @param preserve [sql_gen.Col...] Columns not to rename. Note that these
671
        columns will be included in the mapping even if they are not in cols.
672
        The tables of the provided Col objects will be changed to into, so make
673
        copies of them if you want to keep the original tables.
674
    @param as_items Whether to return a list of dict items instead of a dict
675
    @return dict(orig_col=new_col, ...)
676
        * orig_col: sql_gen.Col(orig_col_name, orig_table)
677
        * new_col: sql_gen.Col(orig_col_name, into)
678
        * All mappings use the into table so its name can easily be
679
          changed for all columns at once
680
    '''
681
    cols = lists.uniqify(cols)
682
    
683
    items = []
684
    for col in preserve:
685
        orig_col = copy.copy(col)
686
        col.table = into
687
        items.append((orig_col, col))
688
    preserve = set(preserve)
689
    for col in cols:
690
        if col not in preserve:
691
            items.append((col, sql_gen.Col(clean_name(str(col)), into)))
692
    
693
    if not as_items: items = dict(items)
694
    return items
695

    
696
def flatten(db, into, joins, cols, limit=None, start=None, **kw_args):
697
    '''For params, see mk_flatten_mapping()
698
    @return See return value of mk_flatten_mapping()
699
    '''
700
    items = mk_flatten_mapping(db, into, cols, as_items=True, **kw_args)
701
    cols = [sql_gen.NamedCol(new.name, old) for old, new in items]
702
    run_query_into(db, *mk_select(db, joins, cols, limit=limit, start=start),
703
        into=into)
704
    return dict(items)
705

    
706
##### Database structure queries
707

    
708
def table_row_count(db, table, recover=None):
709
    return value(run_query(db, *mk_select(db, table, [sql_gen.row_count],
710
        order_by=None, start=0), recover=recover, log_level=3))
711

    
712
def table_cols(db, table, recover=None):
713
    return list(col_names(select(db, table, limit=0, order_by=None,
714
        recover=recover, log_level=4)))
715

    
716
def pkey(db, table, recover=None):
717
    '''Assumed to be first column in table'''
718
    return table_cols(db, table, recover)[0]
719

    
720
not_null_col = 'not_null'
721

    
722
def table_not_null_col(db, table, recover=None):
723
    '''Name assumed to be the value of not_null_col. If not found, uses pkey.'''
724
    if not_null_col in table_cols(db, table, recover): return not_null_col
725
    else: return pkey(db, table, recover)
726

    
727
def index_cols(db, table, index):
728
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
729
    automatically created. When you don't know whether something is a UNIQUE
730
    constraint or a UNIQUE index, use this function.'''
731
    module = util.root_module(db.db)
732
    if module == 'psycopg2':
733
        return list(values(run_query(db, '''\
734
SELECT attname
735
FROM
736
(
737
        SELECT attnum, attname
738
        FROM pg_index
739
        JOIN pg_class index ON index.oid = indexrelid
740
        JOIN pg_class table_ ON table_.oid = indrelid
741
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
742
        WHERE
743
            table_.relname = %(table)s
744
            AND index.relname = %(index)s
745
    UNION
746
        SELECT attnum, attname
747
        FROM
748
        (
749
            SELECT
750
                indrelid
751
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
752
                    AS indkey
753
            FROM pg_index
754
            JOIN pg_class index ON index.oid = indexrelid
755
            JOIN pg_class table_ ON table_.oid = indrelid
756
            WHERE
757
                table_.relname = %(table)s
758
                AND index.relname = %(index)s
759
        ) s
760
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
761
) s
762
ORDER BY attnum
763
''',
764
            {'table': table, 'index': index}, cacheable=True, log_level=4)))
765
    else: raise NotImplementedError("Can't list index columns for "+module+
766
        ' database')
767

    
768
def constraint_cols(db, table, constraint):
769
    module = util.root_module(db.db)
770
    if module == 'psycopg2':
771
        return list(values(run_query(db, '''\
772
SELECT attname
773
FROM pg_constraint
774
JOIN pg_class ON pg_class.oid = conrelid
775
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
776
WHERE
777
    relname = %(table)s
778
    AND conname = %(constraint)s
779
ORDER BY attnum
780
''',
781
            {'table': table, 'constraint': constraint})))
782
    else: raise NotImplementedError("Can't list constraint columns for "+module+
783
        ' database')
784

    
785
row_num_col = '_row_num'
786

    
787
def index_col(db, col):
788
    '''Adds an index on a column if it doesn't already exist.'''
789
    assert sql_gen.is_table_col(col)
790
    
791
    table = col.table
792
    index = sql_gen.as_Table(clean_name(str(col)))
793
    col = sql_gen.to_name_only_col(col)
794
    try: run_query(db, 'CREATE INDEX '+index.to_str(db)+' ON '+table.to_str(db)
795
        +' ('+col.to_str(db)+')', recover=True, cacheable=True, log_level=3)
796
    except DuplicateTableException: pass # index already existed
797

    
798
def index_pkey(db, table, recover=None):
799
    '''Makes the first column in a table the primary key.
800
    @pre The table must not already have a primary key.
801
    '''
802
    table = sql_gen.as_Table(table)
803
    
804
    index = sql_gen.as_Table(table.name+'_pkey')
805
    col = sql_gen.to_name_only_col(pkey(db, table, recover))
806
    run_query(db, 'ALTER TABLE '+table.to_str(db)+' ADD CONSTRAINT '
807
        +index.to_str(db)+' PRIMARY KEY('+col.to_str(db)+')', recover=recover,
808
        log_level=3)
809

    
810
def add_row_num(db, table):
811
    '''Adds a row number column to a table. Its name is in row_num_col. It will
812
    be the primary key.'''
813
    table = sql_gen.as_Table(table).to_str(db)
814
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
815
        +' serial NOT NULL PRIMARY KEY', log_level=3)
816

    
817
def tables(db, schema='public', table_like='%'):
818
    module = util.root_module(db.db)
819
    params = {'schema': schema, 'table_like': table_like}
820
    if module == 'psycopg2':
821
        return values(run_query(db, '''\
822
SELECT tablename
823
FROM pg_tables
824
WHERE
825
    schemaname = %(schema)s
826
    AND tablename LIKE %(table_like)s
827
ORDER BY tablename
828
''',
829
            params, cacheable=True))
830
    elif module == 'MySQLdb':
831
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
832
            cacheable=True))
833
    else: raise NotImplementedError("Can't list tables for "+module+' database')
834

    
835
##### Database management
836

    
837
def empty_db(db, schema='public', **kw_args):
838
    '''For kw_args, see tables()'''
839
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
840

    
841
##### Heuristic queries
842

    
843
def put(db, table, row, pkey_=None, row_ct_ref=None):
844
    '''Recovers from errors.
845
    Only works under PostgreSQL (uses INSERT RETURNING).
846
    '''
847
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
848
    
849
    try:
850
        cur = insert(db, table, row, pkey_, recover=True)
851
        if row_ct_ref != None and cur.rowcount >= 0:
852
            row_ct_ref[0] += cur.rowcount
853
        return value(cur)
854
    except DuplicateKeyException, e:
855
        return value(select(db, table, [pkey_],
856
            util.dict_subset_right_join(row, e.cols), recover=True))
857

    
858
def get(db, table, row, pkey, row_ct_ref=None, create=False):
859
    '''Recovers from errors'''
860
    try: return value(select(db, table, [pkey], row, limit=1, recover=True))
861
    except StopIteration:
862
        if not create: raise
863
        return put(db, table, row, pkey, row_ct_ref) # insert new row
864

    
865
def put_table(db, out_table, in_tables, mapping, row_ct_ref=None, into=None):
866
    '''Recovers from errors.
867
    Only works under PostgreSQL (uses INSERT RETURNING).
868
    @param in_tables The main input table to select from, followed by a list of
869
        tables to join with it using the main input table's pkey
870
    @param mapping dict(out_table_col=in_table_col, ...)
871
        * out_table_col: sql_gen.Col|str
872
        * in_table_col: sql_gen.Col Wrap literal values in a sql_gen.NamedCol
873
    @param into The table to contain the output and input pkeys.
874
        Defaults to `out_table.name+'-pkeys'`.
875
    @return sql_gen.Col Where the output pkeys are made available
876
    '''
877
    out_table = sql_gen.as_Table(out_table)
878
    for in_table_col in mapping.itervalues():
879
        assert isinstance(in_table_col, sql_gen.Col)
880
    if into == None: into = out_table.name+'-pkeys'
881
    into = sql_gen.as_Table(into)
882
    
883
    def log_debug(msg): db.log_debug(msg, level=1.5)
884
    
885
    log_debug('********** New iteration **********')
886
    log_debug('Inserting these input columns into '
887
        +strings.as_tt(out_table.to_str(db))+':\n'+strings.as_table(mapping))
888
    
889
    # Create input joins from list of input tables
890
    in_tables_ = in_tables[:] # don't modify input!
891
    in_tables0 = in_tables_.pop(0) # first table is separate
892
    in_pkey = pkey(db, in_tables0, recover=True)
893
    in_pkey_col = sql_gen.as_Col(in_pkey, in_tables0)
894
    input_joins = [in_tables0]+[sql_gen.Join(v,
895
        {in_pkey: sql_gen.join_same_not_null}) for v in in_tables_]
896
    
897
    log_debug('Joining together input tables into temp table')
898
    # Place in new table for speed and so don't modify input if values edited
899
    in_table = sql_gen.Table(into.name+'-input')
900
    flatten_cols = filter(sql_gen.is_table_col, mapping.values())
901
    mapping = dicts.join(mapping, flatten(db, in_table, input_joins,
902
        flatten_cols, preserve=[in_pkey_col], start=0))
903
    input_joins = [in_table]
904
    db.log_debug('Temp table: '+strings.as_tt(in_table.to_str(db)), level=2)
905
    
906
    out_pkey = pkey(db, out_table, recover=True)
907
    out_pkey_col = sql_gen.as_Col(out_pkey, out_table)
908
    
909
    pkeys_names = [in_pkey, out_pkey]
910
    pkeys_cols = [in_pkey_col, out_pkey_col]
911
    
912
    pkeys_table_exists_ref = [False]
913
    def insert_into_pkeys(joins, cols):
914
        query, params = mk_select(db, joins, cols, order_by=None, start=0)
915
        if pkeys_table_exists_ref[0]:
916
            insert_select(db, into, pkeys_names, query, params)
917
        else:
918
            run_query_into(db, query, params, into=into)
919
            pkeys_table_exists_ref[0] = True
920
    
921
    limit_ref = [None]
922
    conds = set()
923
    distinct_on = []
924
    def mk_main_select(joins, cols):
925
        return mk_select(db, joins, cols, conds, distinct_on,
926
            limit=limit_ref[0], start=0)
927
    
928
    def log_exc(e):
929
        log_debug('Caught exception: '+exc.str_(e, first_line_only=True))
930
    def remove_all_rows():
931
        log_debug('Returning NULL for all rows')
932
        limit_ref[0] = 0 # just create an empty pkeys table
933
    def ignore(in_col, value):
934
        in_col_str = str(in_col)
935
        log_debug('Adding index on '+in_col_str+' to enable fast filtering')
936
        index_col(db, in_col)
937
        log_debug('Ignoring rows with '+in_col_str+' = '+repr(value))
938
    def remove_rows(in_col, value):
939
        ignore(in_col, value)
940
        cond = (in_col, sql_gen.CompareCond(value, '!='))
941
        assert cond not in conds # avoid infinite loops
942
        conds.add(cond)
943
    def invalid2null(in_col, value):
944
        ignore(in_col, value)
945
        update(db, in_table, [(in_col, None)],
946
            sql_gen.ColValueCond(in_col, value))
947
    
948
    # Do inserts and selects
949
    join_cols = {}
950
    insert_out_pkeys = sql_gen.Table(into.name+'-insert_out_pkeys')
951
    insert_in_pkeys = sql_gen.Table(into.name+'-insert_in_pkeys')
952
    while True:
953
        has_joins = join_cols != {}
954
        
955
        # Prepare to insert new rows
956
        insert_joins = input_joins[:] # don't modify original!
957
        insert_args = dict(recover=True, cacheable=False)
958
        if has_joins:
959
            distinct_on = [v.to_Col() for v in join_cols.values()]
960
            insert_joins.append(sql_gen.Join(out_table, join_cols,
961
                sql_gen.filter_out))
962
        else:
963
            insert_args.update(dict(returning=out_pkey, into=insert_out_pkeys))
964
        
965
        log_debug('Trying to insert new rows')
966
        try:
967
            cur = insert_select(db, out_table, mapping.keys(),
968
                *mk_main_select(insert_joins, mapping.values()), **insert_args)
969
            break # insert successful
970
        except DuplicateKeyException, e:
971
            log_exc(e)
972
            
973
            old_join_cols = join_cols.copy()
974
            join_cols.update(util.dict_subset(mapping, e.cols))
975
            log_debug('Ignoring existing rows, comparing on these columns:\n'
976
                +strings.as_inline_table(join_cols))
977
            assert join_cols != old_join_cols # avoid infinite loops
978
        except NullValueException, e:
979
            log_exc(e)
980
            
981
            out_col, = e.cols
982
            try: in_col = mapping[out_col]
983
            except KeyError:
984
                log_debug('Missing mapping for NOT NULL column '+out_col)
985
                remove_all_rows()
986
            else: remove_rows(in_col, None)
987
        except FunctionValueException, e:
988
            log_exc(e)
989
            
990
            assert e.name == out_table.name
991
            out_col = 'value' # assume function param was named "value"
992
            invalid2null(mapping[out_col], e.value)
993
        except DatabaseErrors, e:
994
            log_exc(e)
995
            
996
            msg = 'No handler for exception: '+exc.str_(e, first_line_only=True)
997
            warnings.warn(DbWarning(msg))
998
            log_debug(msg)
999
            remove_all_rows()
1000
        # after exception handled, rerun loop with additional constraints
1001
    
1002
    if row_ct_ref != None and cur.rowcount >= 0:
1003
        row_ct_ref[0] += cur.rowcount
1004
    
1005
    if has_joins:
1006
        select_joins = input_joins+[sql_gen.Join(out_table, join_cols)]
1007
        log_debug('Getting output table pkeys of existing/inserted rows')
1008
        insert_into_pkeys(select_joins, pkeys_cols)
1009
    else:
1010
        add_row_num(db, insert_out_pkeys) # for joining with input pkeys
1011
        
1012
        log_debug('Getting input table pkeys of inserted rows')
1013
        run_query_into(db, *mk_main_select(input_joins, [in_pkey]),
1014
            into=insert_in_pkeys)
1015
        add_row_num(db, insert_in_pkeys) # for joining with output pkeys
1016
        
1017
        assert table_row_count(db, insert_out_pkeys) == table_row_count(db,
1018
            insert_in_pkeys)
1019
        
1020
        log_debug('Combining output and input pkeys in inserted order')
1021
        pkey_joins = [insert_in_pkeys, sql_gen.Join(insert_out_pkeys,
1022
            {row_num_col: sql_gen.join_same_not_null})]
1023
        insert_into_pkeys(pkey_joins, pkeys_names)
1024
    
1025
    db.log_debug('Adding pkey on pkeys table to enable fast joins', level=2.5)
1026
    index_pkey(db, into)
1027
    
1028
    log_debug("Setting pkeys of missing rows to NULL")
1029
    missing_rows_joins = input_joins+[sql_gen.Join(into,
1030
        {in_pkey: sql_gen.join_same_not_null}, sql_gen.filter_out)]
1031
        # must use join_same_not_null or query will take forever
1032
    insert_into_pkeys(missing_rows_joins,
1033
        [in_pkey_col, sql_gen.NamedCol(out_pkey, None)])
1034
    
1035
    assert table_row_count(db, into) == table_row_count(db, in_table)
1036
    
1037
    return sql_gen.Col(out_pkey, into)
1038

    
1039
##### Data cleanup
1040

    
1041
def cleanup_table(db, table, cols):
1042
    def esc_name_(name): return esc_name(db, name)
1043
    
1044
    table = sql_gen.as_Table(table).to_str(db)
1045
    cols = map(esc_name_, cols)
1046
    
1047
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
1048
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
1049
            for col in cols))),
1050
        dict(null0='', null1=r'\N'))
(23-23/35)