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 strings
15
import util
16

    
17
##### Exceptions
18

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

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

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

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

    
41
class ExceptionWithColumns(DbException):
42
    def __init__(self, cols, cause=None):
43
        DbException.__init__(self, 'for columns: '+(', '.join(cols)), cause)
44
        self.cols = cols
45

    
46
class NameException(DbException): pass
47

    
48
class DuplicateKeyException(ExceptionWithColumns): pass
49

    
50
class NullValueException(ExceptionWithColumns): pass
51

    
52
class DuplicateTableException(ExceptionWithName): pass
53

    
54
class DuplicateFunctionException(ExceptionWithName): pass
55

    
56
class EmptyRowException(DbException): pass
57

    
58
##### Warnings
59

    
60
class DbWarning(UserWarning): pass
61

    
62
##### Result retrieval
63

    
64
def col_names(cur): return (col[0] for col in cur.description)
65

    
66
def rows(cur): return iter(lambda: cur.fetchone(), None)
67

    
68
def consume_rows(cur):
69
    '''Used to fetch all rows so result will be cached'''
70
    iters.consume_iter(rows(cur))
71

    
72
def next_row(cur): return rows(cur).next()
73

    
74
def row(cur):
75
    row_ = next_row(cur)
76
    consume_rows(cur)
77
    return row_
78

    
79
def next_value(cur): return next_row(cur)[0]
80

    
81
def value(cur): return row(cur)[0]
82

    
83
def values(cur): return iters.func_iter(lambda: next_value(cur))
84

    
85
def value_or_none(cur):
86
    try: return value(cur)
87
    except StopIteration: return None
88

    
89
##### Input validation
90

    
91
def clean_name(name): return re.sub(r'\W', r'', name)
92

    
93
def check_name(name):
94
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
95
        +'" may contain only alphanumeric characters and _')
96

    
97
def esc_name_by_module(module, name, ignore_case=False):
98
    if module == 'psycopg2':
99
        if ignore_case:
100
            # Don't enclose in quotes because this disables case-insensitivity
101
            check_name(name)
102
            return name
103
        else: quote = '"'
104
    elif module == 'MySQLdb': quote = '`'
105
    else: raise NotImplementedError("Can't escape name for "+module+' database')
106
    return quote + name.replace(quote, '') + quote
107

    
108
def esc_name_by_engine(engine, name, **kw_args):
109
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
110

    
111
def esc_name(db, name, **kw_args):
112
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
113

    
114
def qual_name(db, schema, table):
115
    def esc_name_(name): return esc_name(db, name)
116
    table = esc_name_(table)
117
    if schema != None: return esc_name_(schema)+'.'+table
118
    else: return table
119

    
120
##### Database connections
121

    
122
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
123

    
124
db_engines = {
125
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
126
    'PostgreSQL': ('psycopg2', {}),
127
}
128

    
129
DatabaseErrors_set = set([DbException])
130
DatabaseErrors = tuple(DatabaseErrors_set)
131

    
132
def _add_module(module):
133
    DatabaseErrors_set.add(module.DatabaseError)
134
    global DatabaseErrors
135
    DatabaseErrors = tuple(DatabaseErrors_set)
136

    
137
def db_config_str(db_config):
138
    return db_config['engine']+' database '+db_config['database']
139

    
140
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
141

    
142
log_debug_none = lambda msg: None
143

    
144
class DbConn:
145
    def __init__(self, db_config, serializable=True, autocommit=False,
146
        caching=True, log_debug=log_debug_none):
147
        self.db_config = db_config
148
        self.serializable = serializable
149
        self.autocommit = autocommit
150
        self.caching = caching
151
        self.log_debug = log_debug
152
        self.debug = log_debug != log_debug_none
153
        
154
        self.__db = None
155
        self.query_results = {}
156
        self._savepoint = 0
157
    
158
    def __getattr__(self, name):
159
        if name == '__dict__': raise Exception('getting __dict__')
160
        if name == 'db': return self._db()
161
        else: raise AttributeError()
162
    
163
    def __getstate__(self):
164
        state = copy.copy(self.__dict__) # shallow copy
165
        state['log_debug'] = None # don't pickle the debug callback
166
        state['_DbConn__db'] = None # don't pickle the connection
167
        return state
168
    
169
    def connected(self): return self.__db != None
170
    
171
    def _db(self):
172
        if self.__db == None:
173
            # Process db_config
174
            db_config = self.db_config.copy() # don't modify input!
175
            schemas = db_config.pop('schemas', None)
176
            module_name, mappings = db_engines[db_config.pop('engine')]
177
            module = __import__(module_name)
178
            _add_module(module)
179
            for orig, new in mappings.iteritems():
180
                try: util.rename_key(db_config, orig, new)
181
                except KeyError: pass
182
            
183
            # Connect
184
            self.__db = module.connect(**db_config)
185
            
186
            # Configure connection
187
            if self.serializable and not self.autocommit:
188
                self.db.set_session(isolation_level='SERIALIZABLE')
189
            if schemas != None:
190
                schemas_ = ''.join((esc_name(self, s)+', '
191
                    for s in schemas.split(',')))
192
                run_raw_query(self, "SELECT set_config('search_path', \
193
%s || current_setting('search_path'), false)", [schemas_])
194
        
195
        return self.__db
196
    
197
    class DbCursor(Proxy):
198
        def __init__(self, outer):
199
            Proxy.__init__(self, outer.db.cursor())
200
            self.outer = outer
201
            self.query_results = outer.query_results
202
            self.query_lookup = None
203
            self.result = []
204
        
205
        def execute(self, query, params=None):
206
            self._is_insert = query.upper().find('INSERT') >= 0
207
            self.query_lookup = _query_lookup(query, params)
208
            try:
209
                try:
210
                    return_value = self.inner.execute(query, params)
211
                    self.outer.do_autocommit()
212
                finally: self.query = get_cur_query(self.inner)
213
            except Exception, e:
214
                _add_cursor_info(e, self, query, params)
215
                self.result = e # cache the exception as the result
216
                self._cache_result()
217
                raise
218
            # Fetch all rows so result will be cached
219
            if self.rowcount == 0 and not self._is_insert: consume_rows(self)
220
            return return_value
221
        
222
        def fetchone(self):
223
            row = self.inner.fetchone()
224
            if row != None: self.result.append(row)
225
            # otherwise, fetched all rows
226
            else: self._cache_result()
227
            return row
228
        
229
        def _cache_result(self):
230
            # For inserts, only cache exceptions since inserts are not
231
            # idempotent, but an invalid insert will always be invalid
232
            if self.query_results != None and (not self._is_insert
233
                or isinstance(self.result, Exception)):
234
                
235
                assert self.query_lookup != None
236
                self.query_results[self.query_lookup] = self.CacheCursor(
237
                    util.dict_subset(dicts.AttrsDictView(self),
238
                    ['query', 'result', 'rowcount', 'description']))
239
        
240
        class CacheCursor:
241
            def __init__(self, cached_result): self.__dict__ = cached_result
242
            
243
            def execute(self, *args, **kw_args):
244
                if isinstance(self.result, Exception): raise self.result
245
                # otherwise, result is a rows list
246
                self.iter = iter(self.result)
247
            
248
            def fetchone(self):
249
                try: return self.iter.next()
250
                except StopIteration: return None
251
    
252
    def run_query(self, query, params=None, cacheable=False):
253
        '''Translates known DB errors to typed exceptions:
254
        See self.DbCursor.execute().'''
255
        assert query != None
256
        
257
        if not self.caching: cacheable = False
258
        used_cache = False
259
        try:
260
            # Get cursor
261
            if cacheable:
262
                query_lookup = _query_lookup(query, params)
263
                try:
264
                    cur = self.query_results[query_lookup]
265
                    used_cache = True
266
                except KeyError: cur = self.DbCursor(self)
267
            else: cur = self.db.cursor()
268
            
269
            # Run query
270
            cur.execute(query, params)
271
        finally:
272
            if self.debug: # only compute msg if needed
273
                if used_cache: cache_status = 'Cache hit'
274
                elif cacheable: cache_status = 'Cache miss'
275
                else: cache_status = 'Non-cacheable'
276
                self.log_debug(cache_status+': '
277
                    +strings.one_line(str(get_cur_query(cur, query, params))))
278
        
279
        return cur
280
    
281
    def is_cached(self, query, params=None):
282
        return _query_lookup(query, params) in self.query_results
283
    
284
    def with_savepoint(self, func):
285
        savepoint = 'level_'+str(self._savepoint)
286
        self.run_query('SAVEPOINT '+savepoint)
287
        self._savepoint += 1
288
        try: 
289
            try: return_val = func()
290
            finally:
291
                self._savepoint -= 1
292
                assert self._savepoint >= 0
293
        except:
294
            self.run_query('ROLLBACK TO SAVEPOINT '+savepoint)
295
            raise
296
        else:
297
            self.run_query('RELEASE SAVEPOINT '+savepoint)
298
            self.do_autocommit()
299
            return return_val
300
    
301
    def do_autocommit(self):
302
        '''Autocommits if outside savepoint'''
303
        assert self._savepoint >= 0
304
        if self.autocommit and self._savepoint == 0:
305
            self.log_debug('Autocommiting')
306
            self.db.commit()
307

    
308
connect = DbConn
309

    
310
##### Querying
311

    
312
def run_raw_query(db, *args, **kw_args):
313
    '''For params, see DbConn.run_query()'''
314
    return db.run_query(*args, **kw_args)
315

    
316
def mogrify(db, query, params):
317
    module = util.root_module(db.db)
318
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
319
    else: raise NotImplementedError("Can't mogrify query for "+module+
320
        ' database')
321

    
322
##### Recoverable querying
323

    
324
def with_savepoint(db, func): return db.with_savepoint(func)
325

    
326
def run_query(db, query, params=None, recover=None, cacheable=False):
327
    if recover == None: recover = False
328
    
329
    try:
330
        def run(): return run_raw_query(db, query, params, cacheable)
331
        if recover and not db.is_cached(query, params):
332
            return with_savepoint(db, run)
333
        else: return run() # don't need savepoint if cached
334
    except Exception, e:
335
        if not recover: raise # need savepoint to run index_cols()
336
        msg = str(e)
337
        match = re.search(r'duplicate key value violates unique constraint '
338
            r'"((_?[^\W_]+)_[^"]+)"', msg)
339
        if match:
340
            constraint, table = match.groups()
341
            try: cols = index_cols(db, table, constraint)
342
            except NotImplementedError: raise e
343
            else: raise DuplicateKeyException(cols, e)
344
        match = re.search(r'null value in column "(\w+)" violates not-null '
345
            'constraint', msg)
346
        if match: raise NullValueException([match.group(1)], e)
347
        match = re.search(r'relation "(\w+)" already exists', msg)
348
        if match: raise DuplicateTableException(match.group(1), e)
349
        match = re.search(r'function "(\w+)" already exists', msg)
350
        if match: raise DuplicateFunctionException(match.group(1), e)
351
        raise # no specific exception raised
352

    
353
##### Basic queries
354

    
355
def next_version(name):
356
    '''Prepends the version # so it won't be removed if the name is truncated'''
357
    version = 1 # first existing name was version 0
358
    match = re.match(r'^v(\d+)_(.*)$', name)
359
    if match:
360
        version = int(match.group(1))+1
361
        name = match.group(2)
362
    return 'v'+str(version)+'_'+name
363

    
364
def run_query_into(db, query, params, into_ref=None, *args, **kw_args):
365
    '''Outputs a query to a temp table.
366
    For params, see run_query().
367
    '''
368
    if into_ref == None: return run_query(db, query, params, *args, **kw_args)
369
    else: # place rows in temp table
370
        check_name(into_ref[0])
371
        kw_args['recover'] = True
372
        while True:
373
            try:
374
                create_query = 'CREATE'
375
                if not db.debug: create_query += ' TEMP'
376
                create_query += ' TABLE '+into_ref[0]+' AS '+query
377
                
378
                return run_query(db, create_query, params, *args, **kw_args)
379
                    # CREATE TABLE AS sets rowcount to # rows in query
380
            except DuplicateTableException, e:
381
                into_ref[0] = next_version(into_ref[0])
382
                # try again with next version of name
383

    
384
order_by_pkey = object() # tells mk_select() to order by the pkey
385

    
386
join_using = object() # tells mk_select() to join the column with USING
387

    
388
filter_out = object() # tells mk_select() to filter out rows that match the join
389

    
390
def mk_select(db, tables, fields=None, conds=None, limit=None, start=None,
391
    order_by=order_by_pkey, table_is_esc=False):
392
    '''
393
    @param tables The single table to select from, or a list of tables to join
394
        together: [table0, (table1, joins), ...]
395
        
396
        joins has the format: dict(right_col=left_col, ...)
397
        * if left_col is join_using, left_col is set to right_col
398
        * if left_col is filter_out, the tables are LEFT JOINed together and the
399
          query is filtered by `right_col IS NULL` (indicating no match)
400
    @param fields Use None to select all fields in the table
401
    @param table_is_esc Whether the table name has already been escaped
402
    @return tuple(query, params)
403
    '''
404
    def esc_name_(name): return esc_name(db, name)
405
    
406
    if not lists.is_seq(tables): tables = [tables]
407
    tables = list(tables) # don't modify input! (list() copies input)
408
    table0 = tables.pop(0) # first table is separate
409
    
410
    if conds == None: conds = {}
411
    assert limit == None or type(limit) == int
412
    assert start == None or type(start) == int
413
    if order_by == order_by_pkey:
414
        order_by = pkey(db, table0, recover=True, table_is_esc=table_is_esc)
415
    if not table_is_esc: table0 = esc_name_(table0)
416
    
417
    params = []
418
    
419
    def parse_col(field, default_table=None):
420
        '''Parses fields'''
421
        if field == None: field = (field,) # for None values, tuple is optional
422
        is_tuple = isinstance(field, tuple)
423
        if is_tuple and len(field) == 1: # field is literal value
424
            value, = field
425
            sql_ = '%s'
426
            params.append(value)
427
        elif is_tuple and len(field) == 2: # field is col with table
428
            table, col = field
429
            if not table_is_esc: table = esc_name_(table)
430
            sql_ = table+'.'+esc_name_(col)
431
        else:
432
            sql_ = esc_name_(field) # field is col name
433
            if default_table != None: sql_ = default_table+'.'+sql_
434
        return sql_
435
    def cond(entry):
436
        '''Parses conditions'''
437
        col, value = entry
438
        cond_ = parse_col(col)+' '
439
        if value == None: cond_ += 'IS'
440
        else: cond_ += '='
441
        cond_ += ' %s'
442
        return cond_
443
    
444
    query = 'SELECT '
445
    if fields == None: query += '*'
446
    else: query += ', '.join(map(parse_col, fields))
447
    query += ' FROM '+table0
448
    
449
    # Add joins
450
    left_table = table0
451
    for table, joins in tables:
452
        if not table_is_esc: table = esc_name_(table)
453
        
454
        left_join_ref = [False]
455
        
456
        def join(entry):
457
            '''Parses non-USING joins'''
458
            right_col, left_col = entry
459
            
460
            # Parse special values
461
            if left_col == None: left_col = (left_col,)
462
                # for None values, tuple is optional
463
            elif left_col == join_using: left_col = right_col
464
            elif left_col == filter_out:
465
                left_col = right_col
466
                left_join_ref[0] = True
467
                conds[(table, right_col)] = None # filter query by no match
468
            
469
            # Create SQL
470
            right_col = table+'.'+esc_name_(right_col)
471
            sql_ = right_col+' '
472
            if isinstance(left_col, tuple) and len(left_col) == 1:
473
                # col is literal value
474
                value, = left_col
475
                if value == None: sql_ += 'IS'
476
                else: sql_ += '='
477
                sql_ += ' %s'
478
                params.append(value)
479
            else: # col is name
480
                left_col = parse_col(left_col, left_table)
481
                sql_ += ('= '+left_col+' OR ('+right_col+' IS NULL AND '
482
                    +left_col+' IS NULL)')
483
            
484
            return sql_
485
        
486
        # Create join condition and determine join type
487
        if reduce(operator.and_, (v == join_using for v in joins.itervalues())):
488
            # all cols w/ USING, so can use simpler USING syntax
489
            join_cond = 'USING ('+(', '.join(joins.iterkeys()))+')'
490
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
491
        
492
        # Create join
493
        if left_join_ref[0]: query += ' LEFT'
494
        query += ' JOIN '+table+' '+join_cond
495
        
496
        left_table = table
497
    
498
    missing = True
499
    if conds != {}:
500
        query += ' WHERE '+(' AND '.join(map(cond, conds.iteritems())))
501
        params += conds.values()
502
        missing = False
503
    if order_by != None: query += ' ORDER BY '+parse_col(order_by, table0)
504
    if limit != None: query += ' LIMIT '+str(limit); missing = False
505
    if start != None:
506
        if start != 0: query += ' OFFSET '+str(start)
507
        missing = False
508
    if missing: warnings.warn(DbWarning(
509
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
510
    
511
    return (query, params)
512

    
513
def select(db, *args, **kw_args):
514
    '''For params, see mk_select() and run_query()'''
515
    recover = kw_args.pop('recover', None)
516
    cacheable = kw_args.pop('cacheable', True)
517
    
518
    query, params = mk_select(db, *args, **kw_args)
519
    return run_query(db, query, params, recover, cacheable)
520

    
521
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
522
    returning=None, embeddable=False, table_is_esc=False):
523
    '''
524
    @param returning str|None An inserted column (such as pkey) to return
525
    @param embeddable Whether the query should be embeddable as a nested SELECT.
526
        Warning: If you set this and cacheable=True when the query is run, the
527
        query will be fully cached, not just if it raises an exception.
528
    @param table_is_esc Whether the table name has already been escaped
529
    '''
530
    if select_query == None: select_query = 'DEFAULT VALUES'
531
    if cols == []: cols = None # no cols (all defaults) = unknown col names
532
    if not table_is_esc: check_name(table)
533
    
534
    # Build query
535
    query = 'INSERT INTO '+table
536
    if cols != None:
537
        map(check_name, cols)
538
        query += ' ('+', '.join(cols)+')'
539
    query += ' '+select_query
540
    
541
    if returning != None:
542
        check_name(returning)
543
        query += ' RETURNING '+returning
544
    
545
    if embeddable:
546
        # Create function
547
        function_name = '_'.join(map(clean_name, ['insert', table] + cols))
548
        return_type = 'SETOF '+table+'.'+returning+'%TYPE'
549
        while True:
550
            try:
551
                function = function_name
552
                if not db.debug: function = 'pg_temp.'+function
553
                
554
                function_query = '''\
555
CREATE FUNCTION '''+function+'''() RETURNS '''+return_type+'''
556
    LANGUAGE sql
557
    AS $$'''+mogrify(db, query, params)+''';$$;
558
'''
559
                run_query(db, function_query, recover=True, cacheable=True)
560
                break # this version was successful
561
            except DuplicateFunctionException, e:
562
                function_name = next_version(function_name)
563
                # try again with next version of name
564
        
565
        # Return query that uses function
566
        return mk_select(db, function+'() AS f ('+returning+')', start=0,
567
            order_by=None, table_is_esc=True)# AS clause requires function alias
568
    
569
    return (query, params)
570

    
571
def insert_select(db, *args, **kw_args):
572
    '''For params, see mk_insert_select() and run_query_into()
573
    @param into_ref List with name of temp table to place RETURNING values in
574
    '''
575
    into_ref = kw_args.pop('into_ref', None)
576
    if into_ref != None: kw_args['embeddable'] = True
577
    recover = kw_args.pop('recover', None)
578
    cacheable = kw_args.pop('cacheable', True)
579
    
580
    query, params = mk_insert_select(db, *args, **kw_args)
581
    return run_query_into(db, query, params, into_ref, recover=recover,
582
        cacheable=cacheable)
583

    
584
default = object() # tells insert() to use the default value for a column
585

    
586
def insert(db, table, row, *args, **kw_args):
587
    '''For params, see insert_select()'''
588
    if lists.is_seq(row): cols = None
589
    else:
590
        cols = row.keys()
591
        row = row.values()
592
    row = list(row) # ensure that "!= []" works
593
    
594
    # Check for special values
595
    labels = []
596
    values = []
597
    for value in row:
598
        if value == default: labels.append('DEFAULT')
599
        else:
600
            labels.append('%s')
601
            values.append(value)
602
    
603
    # Build query
604
    if values != []: query = ' VALUES ('+(', '.join(labels))+')'
605
    else: query = None
606
    
607
    return insert_select(db, table, cols, query, values, *args, **kw_args)
608

    
609
def last_insert_id(db):
610
    module = util.root_module(db.db)
611
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
612
    elif module == 'MySQLdb': return db.insert_id()
613
    else: return None
614

    
615
def truncate(db, table, schema='public'):
616
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
617

    
618
##### Database structure queries
619

    
620
def pkey(db, table, recover=None, table_is_esc=False):
621
    '''Assumed to be first column in table'''
622
    return col_names(select(db, table, limit=0, order_by=None, recover=recover,
623
        table_is_esc=table_is_esc)).next()
624

    
625
def index_cols(db, table, index):
626
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
627
    automatically created. When you don't know whether something is a UNIQUE
628
    constraint or a UNIQUE index, use this function.'''
629
    check_name(table)
630
    check_name(index)
631
    module = util.root_module(db.db)
632
    if module == 'psycopg2':
633
        return list(values(run_query(db, '''\
634
SELECT attname
635
FROM
636
(
637
        SELECT attnum, attname
638
        FROM pg_index
639
        JOIN pg_class index ON index.oid = indexrelid
640
        JOIN pg_class table_ ON table_.oid = indrelid
641
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
642
        WHERE
643
            table_.relname = %(table)s
644
            AND index.relname = %(index)s
645
    UNION
646
        SELECT attnum, attname
647
        FROM
648
        (
649
            SELECT
650
                indrelid
651
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
652
                    AS indkey
653
            FROM pg_index
654
            JOIN pg_class index ON index.oid = indexrelid
655
            JOIN pg_class table_ ON table_.oid = indrelid
656
            WHERE
657
                table_.relname = %(table)s
658
                AND index.relname = %(index)s
659
        ) s
660
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
661
) s
662
ORDER BY attnum
663
''',
664
            {'table': table, 'index': index}, cacheable=True)))
665
    else: raise NotImplementedError("Can't list index columns for "+module+
666
        ' database')
667

    
668
def constraint_cols(db, table, constraint):
669
    check_name(table)
670
    check_name(constraint)
671
    module = util.root_module(db.db)
672
    if module == 'psycopg2':
673
        return list(values(run_query(db, '''\
674
SELECT attname
675
FROM pg_constraint
676
JOIN pg_class ON pg_class.oid = conrelid
677
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
678
WHERE
679
    relname = %(table)s
680
    AND conname = %(constraint)s
681
ORDER BY attnum
682
''',
683
            {'table': table, 'constraint': constraint})))
684
    else: raise NotImplementedError("Can't list constraint columns for "+module+
685
        ' database')
686

    
687
row_num_col = '_row_num'
688

    
689
def add_row_num(db, table):
690
    '''Adds a row number column to a table. Its name is in row_num_col. It will
691
    be the primary key.'''
692
    check_name(table)
693
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
694
        +' serial NOT NULL PRIMARY KEY')
695

    
696
def tables(db, schema='public', table_like='%'):
697
    module = util.root_module(db.db)
698
    params = {'schema': schema, 'table_like': table_like}
699
    if module == 'psycopg2':
700
        return values(run_query(db, '''\
701
SELECT tablename
702
FROM pg_tables
703
WHERE
704
    schemaname = %(schema)s
705
    AND tablename LIKE %(table_like)s
706
ORDER BY tablename
707
''',
708
            params, cacheable=True))
709
    elif module == 'MySQLdb':
710
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
711
            cacheable=True))
712
    else: raise NotImplementedError("Can't list tables for "+module+' database')
713

    
714
##### Database management
715

    
716
def empty_db(db, schema='public', **kw_args):
717
    '''For kw_args, see tables()'''
718
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
719

    
720
##### Heuristic queries
721

    
722
def put(db, table, row, pkey_=None, row_ct_ref=None):
723
    '''Recovers from errors.
724
    Only works under PostgreSQL (uses INSERT RETURNING).
725
    '''
726
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
727
    
728
    try:
729
        cur = insert(db, table, row, pkey_, recover=True)
730
        if row_ct_ref != None and cur.rowcount >= 0:
731
            row_ct_ref[0] += cur.rowcount
732
        return value(cur)
733
    except DuplicateKeyException, e:
734
        return value(select(db, table, [pkey_],
735
            util.dict_subset_right_join(row, e.cols), recover=True))
736

    
737
def get(db, table, row, pkey, row_ct_ref=None, create=False):
738
    '''Recovers from errors'''
739
    try: return value(select(db, table, [pkey], row, 1, recover=True))
740
    except StopIteration:
741
        if not create: raise
742
        return put(db, table, row, pkey, row_ct_ref) # insert new row
743

    
744
def put_table(db, out_table, in_tables, mapping, limit=None, start=0,
745
    row_ct_ref=None, table_is_esc=False):
746
    '''Recovers from errors.
747
    Only works under PostgreSQL (uses INSERT RETURNING).
748
    @param in_tables The main input table to select from, followed by a list of
749
        tables to join with it using the main input table's pkey
750
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
751
        available
752
    '''
753
    temp_suffix = clean_name(out_table)
754
        # suffix, not prefix, so main name won't be removed if name is truncated
755
    pkeys_ref = ['pkeys_'+temp_suffix]
756
    
757
    # Join together input tables
758
    in_tables = in_tables[:] # don't modify input!
759
    in_tables0 = in_tables.pop(0) # first table is separate
760
    in_pkey = pkey(db, in_tables0, recover=True, table_is_esc=table_is_esc)
761
    insert_joins = [in_tables0]+[(t, {in_pkey: join_using}) for t in in_tables]
762
    
763
    out_pkey = pkey(db, out_table, recover=True, table_is_esc=table_is_esc)
764
    pkeys_cols = [in_pkey, out_pkey]
765
    
766
    def mk_select_(cols):
767
        return mk_select(db, insert_joins, cols, limit=limit, start=start,
768
            table_is_esc=table_is_esc)
769
    
770
    out_pkeys_ref = ['out_pkeys_'+temp_suffix]
771
    def insert_(pkeys_table_exists=False):
772
        '''Inserts and capture output pkeys.'''
773
        cur = insert_select(db, out_table, mapping.keys(),
774
            *mk_select_(mapping.values()), returning=out_pkey,
775
            into_ref=out_pkeys_ref, recover=True, table_is_esc=table_is_esc)
776
        if row_ct_ref != None and cur.rowcount >= 0:
777
            row_ct_ref[0] += cur.rowcount
778
            add_row_num(db, out_pkeys_ref[0]) # for joining it with input pkeys
779
        
780
        # Get input pkeys corresponding to rows in insert
781
        in_pkeys_ref = ['in_pkeys_'+temp_suffix]
782
        run_query_into(db, *mk_select_([in_pkey]), into_ref=in_pkeys_ref)
783
        add_row_num(db, in_pkeys_ref[0]) # for joining it with output pkeys
784
        
785
        # Join together output and input pkeys
786
        select_query = mk_select(db, [in_pkeys_ref[0],
787
            (out_pkeys_ref[0], {row_num_col: join_using})], pkeys_cols, start=0)
788
        if pkeys_table_exists:
789
            insert_select(db, pkeys_ref[0], pkeys_cols, *select_query)
790
        else: run_query_into(db, *select_query, into_ref=pkeys_ref)
791
    
792
    # Do inserts and selects
793
    try: insert_()
794
    except DuplicateKeyException, e:
795
        join_cols = util.dict_subset_right_join(mapping, e.cols)
796
        select_joins = insert_joins + [(out_table, join_cols)]
797
        
798
        # Get pkeys of already existing rows
799
        run_query_into(db, *mk_select(db, select_joins, pkeys_cols, start=0,
800
            table_is_esc=table_is_esc), into_ref=pkeys_ref, recover=True)
801
    
802
    return (pkeys_ref[0], out_pkey)
803

    
804
##### Data cleanup
805

    
806
def cleanup_table(db, table, cols, table_is_esc=False):
807
    def esc_name_(name): return esc_name(db, name)
808
    
809
    if not table_is_esc: check_name(table)
810
    cols = map(esc_name_, cols)
811
    
812
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
813
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
814
            for col in cols))),
815
        dict(null0='', null1=r'\N'))
(22-22/33)