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):
20
    if hasattr(cur, 'query'): return cur.query
21
    elif hasattr(cur, '_last_executed'): return cur._last_executed
22
    else: return None
23

    
24
def _add_cursor_info(e, cur): exc.add_msg(e, 'query: '+get_cur_query(cur))
25

    
26
class DbException(exc.ExceptionWithCause):
27
    def __init__(self, msg, cause=None, cur=None):
28
        exc.ExceptionWithCause.__init__(self, msg, cause, cause_newline=True)
29
        if cur != None: _add_cursor_info(self, cur)
30

    
31
class ExceptionWithName(DbException):
32
    def __init__(self, name, cause=None):
33
        DbException.__init__(self, 'for name: '+str(name), cause)
34
        self.name = name
35

    
36
class ExceptionWithColumns(DbException):
37
    def __init__(self, cols, cause=None):
38
        DbException.__init__(self, 'for columns: '+(', '.join(cols)), cause)
39
        self.cols = cols
40

    
41
class NameException(DbException): pass
42

    
43
class DuplicateKeyException(ExceptionWithColumns): pass
44

    
45
class NullValueException(ExceptionWithColumns): pass
46

    
47
class DuplicateTableException(ExceptionWithName): pass
48

    
49
class EmptyRowException(DbException): pass
50

    
51
##### Warnings
52

    
53
class DbWarning(UserWarning): pass
54

    
55
##### Result retrieval
56

    
57
def col_names(cur): return (col[0] for col in cur.description)
58

    
59
def rows(cur): return iter(lambda: cur.fetchone(), None)
60

    
61
def consume_rows(cur):
62
    '''Used to fetch all rows so result will be cached'''
63
    iters.consume_iter(rows(cur))
64

    
65
def next_row(cur): return rows(cur).next()
66

    
67
def row(cur):
68
    row_ = next_row(cur)
69
    consume_rows(cur)
70
    return row_
71

    
72
def next_value(cur): return next_row(cur)[0]
73

    
74
def value(cur): return row(cur)[0]
75

    
76
def values(cur): return iters.func_iter(lambda: next_value(cur))
77

    
78
def value_or_none(cur):
79
    try: return value(cur)
80
    except StopIteration: return None
81

    
82
##### Input validation
83

    
84
def clean_name(name): return re.sub(r'\W', r'', name)
85

    
86
def check_name(name):
87
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
88
        +'" may contain only alphanumeric characters and _')
89

    
90
def esc_name_by_module(module, name, ignore_case=False):
91
    if module == 'psycopg2':
92
        if ignore_case:
93
            # Don't enclose in quotes because this disables case-insensitivity
94
            check_name(name)
95
            return name
96
        else: quote = '"'
97
    elif module == 'MySQLdb': quote = '`'
98
    else: raise NotImplementedError("Can't escape name for "+module+' database')
99
    return quote + name.replace(quote, '') + quote
100

    
101
def esc_name_by_engine(engine, name, **kw_args):
102
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
103

    
104
def esc_name(db, name, **kw_args):
105
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
106

    
107
def qual_name(db, schema, table):
108
    def esc_name_(name): return esc_name(db, name)
109
    table = esc_name_(table)
110
    if schema != None: return esc_name_(schema)+'.'+table
111
    else: return table
112

    
113
##### Database connections
114

    
115
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
116

    
117
db_engines = {
118
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
119
    'PostgreSQL': ('psycopg2', {}),
120
}
121

    
122
DatabaseErrors_set = set([DbException])
123
DatabaseErrors = tuple(DatabaseErrors_set)
124

    
125
def _add_module(module):
126
    DatabaseErrors_set.add(module.DatabaseError)
127
    global DatabaseErrors
128
    DatabaseErrors = tuple(DatabaseErrors_set)
129

    
130
def db_config_str(db_config):
131
    return db_config['engine']+' database '+db_config['database']
132

    
133
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
134

    
135
log_debug_none = lambda msg: None
136

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

    
284
connect = DbConn
285

    
286
##### Querying
287

    
288
def run_raw_query(db, *args, **kw_args):
289
    '''For params, see DbConn.run_query()'''
290
    return db.run_query(*args, **kw_args)
291

    
292
def mogrify(db, query, params):
293
    module = util.root_module(db.db)
294
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
295
    else: raise NotImplementedError("Can't mogrify query for "+module+
296
        ' database')
297

    
298
##### Recoverable querying
299

    
300
def with_savepoint(db, func): return db.with_savepoint(func)
301

    
302
def run_query(db, query, params=None, recover=None, cacheable=False):
303
    if recover == None: recover = False
304
    
305
    try:
306
        def run(): return run_raw_query(db, query, params, cacheable)
307
        if recover and not db.is_cached(query, params):
308
            return with_savepoint(db, run)
309
        else: return run() # don't need savepoint if cached
310
    except Exception, e:
311
        if not recover: raise # need savepoint to run index_cols()
312
        msg = str(e)
313
        match = re.search(r'duplicate key value violates unique constraint '
314
            r'"((_?[^\W_]+)_[^"]+)"', msg)
315
        if match:
316
            constraint, table = match.groups()
317
            try: cols = index_cols(db, table, constraint)
318
            except NotImplementedError: raise e
319
            else: raise DuplicateKeyException(cols, e)
320
        match = re.search(r'null value in column "(\w+)" violates not-null '
321
            'constraint', msg)
322
        if match: raise NullValueException([match.group(1)], e)
323
        match = re.search(r'relation "(\w+)" already exists', msg)
324
        if match: raise DuplicateTableException(match.group(1), e)
325
        raise # no specific exception raised
326

    
327
##### Basic queries
328

    
329
def next_version(name):
330
    '''Prepends the version # so it won't be removed if the name is truncated'''
331
    version = 0
332
    match = re.match(r'^v(\d+)_(.*)$', name)
333
    if match:
334
        version = int(match.group(1))+1
335
        name = match.group(2)
336
    return 'v'+str(version)+'_'+name
337

    
338
def run_query_into(db, query, params, into_ref=None, *args, **kw_args):
339
    '''Outputs a query to a temp table.
340
    For params, see run_query().
341
    '''
342
    if into_ref == None: return run_query(db, query, params, *args, **kw_args)
343
    else: # place rows in temp table
344
        check_name(into_ref[0])
345
        kw_args['recover'] = True
346
        while True:
347
            try:
348
                return run_query(db, 'CREATE TEMP TABLE '+into_ref[0]+' AS '
349
                    +query, params, *args, **kw_args)
350
                    # CREATE TABLE AS sets rowcount to # rows in query
351
            except DuplicateTableException, e:
352
                into_ref[0] = next_version(into_ref[0])
353
                # try again with next version of name
354

    
355
order_by_pkey = object() # tells mk_select() to order by the pkey
356

    
357
join_using = object() # tells mk_select() to join the column with USING
358

    
359
def mk_select(db, tables, fields=None, conds=None, limit=None, start=None,
360
    order_by=order_by_pkey, table_is_esc=False):
361
    '''
362
    @param tables The single table to select from, or a list of tables to join
363
        together: [table0, (table1, dict(right_col=left_col, ...)), ...]
364
    @param fields Use None to select all fields in the table
365
    @param table_is_esc Whether the table name has already been escaped
366
    @return tuple(query, params)
367
    '''
368
    def esc_name_(name): return esc_name(db, name)
369
    
370
    if not lists.is_seq(tables): tables = [tables]
371
    tables = list(tables) # don't modify input! (list() copies input)
372
    table0 = tables.pop(0) # first table is separate
373
    
374
    if conds == None: conds = {}
375
    assert limit == None or type(limit) == int
376
    assert start == None or type(start) == int
377
    if order_by == order_by_pkey:
378
        order_by = pkey(db, table0, recover=True, table_is_esc=table_is_esc)
379
    if not table_is_esc: table0 = esc_name_(table0)
380
    
381
    params = []
382
    
383
    def parse_col(field):
384
        '''Parses fields'''
385
        is_tuple = isinstance(field, tuple)
386
        if is_tuple and len(field) == 1: # field is literal value
387
            value, = field
388
            sql_ = '%s'
389
            params.append(value)
390
        elif is_tuple and len(field) == 2: # field is col with table
391
            table, col = field
392
            if not table_is_esc: table = esc_name_(table)
393
            sql_ = table+'.'+esc_name_(col)
394
        else: sql_ = esc_name_(field) # field is col name
395
        return sql_
396
    def cond(entry):
397
        '''Parses conditions'''
398
        col, value = entry
399
        cond_ = esc_name_(col)+' '
400
        if value == None: cond_ += 'IS'
401
        else: cond_ += '='
402
        cond_ += ' %s'
403
        return cond_
404
    
405
    query = 'SELECT '
406
    if fields == None: query += '*'
407
    else: query += ', '.join(map(parse_col, fields))
408
    query += ' FROM '+table0
409
    
410
    # Add joins
411
    left_table = table0
412
    for table, joins in tables:
413
        if not table_is_esc: table = esc_name_(table)
414
        query += ' JOIN '+table
415
        
416
        def join(entry):
417
            '''Parses non-USING joins'''
418
            right_col, left_col = entry
419
            right_col = table+'.'+esc_name_(right_col)
420
            left_col = left_table+'.'+esc_name_(left_col)
421
            return (right_col+' = '+left_col
422
                +' OR ('+right_col+' IS NULL AND '+left_col+' IS NULL)')
423
        
424
        if reduce(operator.and_, (v == join_using for v in joins.itervalues())):
425
            # all cols w/ USING
426
            query += ' USING ('+(', '.join(joins.iterkeys()))+')'
427
        else: query += ' ON '+(' AND '.join(map(join, joins.iteritems())))
428
        
429
        left_table = table
430
    
431
    missing = True
432
    if conds != {}:
433
        query += ' WHERE '+(' AND '.join(map(cond, conds.iteritems())))
434
        params += conds.values()
435
        missing = False
436
    if order_by != None: query += ' ORDER BY '+esc_name_(order_by)
437
    if limit != None: query += ' LIMIT '+str(limit); missing = False
438
    if start != None:
439
        if start != 0: query += ' OFFSET '+str(start)
440
        missing = False
441
    if missing: warnings.warn(DbWarning(
442
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
443
    
444
    return (query, params)
445

    
446
def select(db, *args, **kw_args):
447
    '''For params, see mk_select() and run_query()'''
448
    recover = kw_args.pop('recover', None)
449
    cacheable = kw_args.pop('cacheable', True)
450
    
451
    query, params = mk_select(db, *args, **kw_args)
452
    return run_query(db, query, params, recover, cacheable)
453

    
454
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
455
    returning=None, embeddable=False, table_is_esc=False):
456
    '''
457
    @param returning str|None An inserted column (such as pkey) to return
458
    @param embeddable Whether the query should be embeddable as a nested SELECT.
459
        Warning: If you set this and cacheable=True when the query is run, the
460
        query will be fully cached, not just if it raises an exception.
461
    @param table_is_esc Whether the table name has already been escaped
462
    '''
463
    if select_query == None: select_query = 'DEFAULT VALUES'
464
    if cols == []: cols = None # no cols (all defaults) = unknown col names
465
    if not table_is_esc: check_name(table)
466
    
467
    # Build query
468
    query = 'INSERT INTO '+table
469
    if cols != None:
470
        map(check_name, cols)
471
        query += ' ('+', '.join(cols)+')'
472
    query += ' '+select_query
473
    
474
    if returning != None:
475
        check_name(returning)
476
        query += ' RETURNING '+returning
477
    
478
    if embeddable:
479
        # Create function
480
        function = 'pg_temp.'+('_'.join(map(clean_name,
481
            ['insert', table] + cols)))
482
        return_type = 'SETOF '+table+'.'+returning+'%TYPE'
483
        function_query = '''\
484
CREATE OR REPLACE FUNCTION '''+function+'''() RETURNS '''+return_type+'''
485
    LANGUAGE sql
486
    AS $$'''+mogrify(db, query, params)+''';$$;
487
'''
488
        run_query(db, function_query, cacheable=True)
489
        
490
        # Return query that uses function
491
        return mk_select(db, function+'() AS f ('+returning+')', start=0,
492
            order_by=None, table_is_esc=True)# AS clause requires function alias
493
    
494
    return (query, params)
495

    
496
def insert_select(db, *args, **kw_args):
497
    '''For params, see mk_insert_select() and run_query_into()
498
    @param into_ref List with name of temp table to place RETURNING values in
499
    '''
500
    into_ref = kw_args.pop('into_ref', None)
501
    if into_ref != None: kw_args['embeddable'] = True
502
    recover = kw_args.pop('recover', None)
503
    cacheable = kw_args.pop('cacheable', True)
504
    
505
    query, params = mk_insert_select(db, *args, **kw_args)
506
    return run_query_into(db, query, params, into_ref, recover=recover,
507
        cacheable=cacheable)
508

    
509
default = object() # tells insert() to use the default value for a column
510

    
511
def insert(db, table, row, *args, **kw_args):
512
    '''For params, see insert_select()'''
513
    if lists.is_seq(row): cols = None
514
    else:
515
        cols = row.keys()
516
        row = row.values()
517
    row = list(row) # ensure that "!= []" works
518
    
519
    # Check for special values
520
    labels = []
521
    values = []
522
    for value in row:
523
        if value == default: labels.append('DEFAULT')
524
        else:
525
            labels.append('%s')
526
            values.append(value)
527
    
528
    # Build query
529
    if values != []: query = ' VALUES ('+(', '.join(labels))+')'
530
    else: query = None
531
    
532
    return insert_select(db, table, cols, query, values, *args, **kw_args)
533

    
534
def last_insert_id(db):
535
    module = util.root_module(db.db)
536
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
537
    elif module == 'MySQLdb': return db.insert_id()
538
    else: return None
539

    
540
def truncate(db, table, schema='public'):
541
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
542

    
543
##### Database structure queries
544

    
545
def pkey(db, table, recover=None, table_is_esc=False):
546
    '''Assumed to be first column in table'''
547
    return col_names(select(db, table, limit=0, order_by=None, recover=recover,
548
        table_is_esc=table_is_esc)).next()
549

    
550
def index_cols(db, table, index):
551
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
552
    automatically created. When you don't know whether something is a UNIQUE
553
    constraint or a UNIQUE index, use this function.'''
554
    check_name(table)
555
    check_name(index)
556
    module = util.root_module(db.db)
557
    if module == 'psycopg2':
558
        return list(values(run_query(db, '''\
559
SELECT attname
560
FROM
561
(
562
        SELECT attnum, attname
563
        FROM pg_index
564
        JOIN pg_class index ON index.oid = indexrelid
565
        JOIN pg_class table_ ON table_.oid = indrelid
566
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
567
        WHERE
568
            table_.relname = %(table)s
569
            AND index.relname = %(index)s
570
    UNION
571
        SELECT attnum, attname
572
        FROM
573
        (
574
            SELECT
575
                indrelid
576
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
577
                    AS indkey
578
            FROM pg_index
579
            JOIN pg_class index ON index.oid = indexrelid
580
            JOIN pg_class table_ ON table_.oid = indrelid
581
            WHERE
582
                table_.relname = %(table)s
583
                AND index.relname = %(index)s
584
        ) s
585
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
586
) s
587
ORDER BY attnum
588
''',
589
            {'table': table, 'index': index}, cacheable=True)))
590
    else: raise NotImplementedError("Can't list index columns for "+module+
591
        ' database')
592

    
593
def constraint_cols(db, table, constraint):
594
    check_name(table)
595
    check_name(constraint)
596
    module = util.root_module(db.db)
597
    if module == 'psycopg2':
598
        return list(values(run_query(db, '''\
599
SELECT attname
600
FROM pg_constraint
601
JOIN pg_class ON pg_class.oid = conrelid
602
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
603
WHERE
604
    relname = %(table)s
605
    AND conname = %(constraint)s
606
ORDER BY attnum
607
''',
608
            {'table': table, 'constraint': constraint})))
609
    else: raise NotImplementedError("Can't list constraint columns for "+module+
610
        ' database')
611

    
612
row_num_col = '_row_num'
613

    
614
def add_row_num(db, table):
615
    '''Adds a row number column to a table. Its name is in row_num_col. It will
616
    be the primary key.'''
617
    check_name(table)
618
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
619
        +' serial NOT NULL PRIMARY KEY')
620

    
621
def tables(db, schema='public', table_like='%'):
622
    module = util.root_module(db.db)
623
    params = {'schema': schema, 'table_like': table_like}
624
    if module == 'psycopg2':
625
        return values(run_query(db, '''\
626
SELECT tablename
627
FROM pg_tables
628
WHERE
629
    schemaname = %(schema)s
630
    AND tablename LIKE %(table_like)s
631
ORDER BY tablename
632
''',
633
            params, cacheable=True))
634
    elif module == 'MySQLdb':
635
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
636
            cacheable=True))
637
    else: raise NotImplementedError("Can't list tables for "+module+' database')
638

    
639
##### Database management
640

    
641
def empty_db(db, schema='public', **kw_args):
642
    '''For kw_args, see tables()'''
643
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
644

    
645
##### Heuristic queries
646

    
647
def put(db, table, row, pkey_=None, row_ct_ref=None):
648
    '''Recovers from errors.
649
    Only works under PostgreSQL (uses INSERT RETURNING).
650
    '''
651
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
652
    
653
    try:
654
        cur = insert(db, table, row, pkey_, recover=True)
655
        if row_ct_ref != None and cur.rowcount >= 0:
656
            row_ct_ref[0] += cur.rowcount
657
        return value(cur)
658
    except DuplicateKeyException, e:
659
        return value(select(db, table, [pkey_],
660
            util.dict_subset_right_join(row, e.cols), recover=True))
661

    
662
def get(db, table, row, pkey, row_ct_ref=None, create=False):
663
    '''Recovers from errors'''
664
    try: return value(select(db, table, [pkey], row, 1, recover=True))
665
    except StopIteration:
666
        if not create: raise
667
        return put(db, table, row, pkey, row_ct_ref) # insert new row
668

    
669
def put_table(db, out_table, in_tables, mapping, limit=None, start=0,
670
    row_ct_ref=None, table_is_esc=False):
671
    '''Recovers from errors.
672
    Only works under PostgreSQL (uses INSERT RETURNING).
673
    @param in_tables The main input table to select from, followed by a list of
674
        tables to join with it using the main input table's pkey
675
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
676
        available
677
    '''
678
    temp_suffix = '_'.join(map(clean_name,
679
        [out_table] + list(iters.flatten_n(mapping.items(), depth=3))))
680
        # suffix, not prefix, so main name won't be removed if name is truncated
681
    pkeys_ref = ['pkeys_'+temp_suffix]
682
    
683
    # Join together input tables
684
    in_tables = in_tables[:] # don't modify input!
685
    in_tables0 = in_tables.pop(0) # first table is separate
686
    in_pkey = pkey(db, in_tables0, recover=True, table_is_esc=table_is_esc)
687
    in_joins = [in_tables0] + [(t, {in_pkey: join_using}) for t in in_tables]
688
    
689
    out_pkey = pkey(db, out_table, recover=True, table_is_esc=table_is_esc)
690
    pkeys_cols = [in_pkey, out_pkey]
691
    
692
    def mk_select_(cols):
693
        return mk_select(db, in_joins, cols, limit=limit, start=start,
694
            table_is_esc=table_is_esc)
695
    
696
    out_pkeys_ref = ['out_pkeys_'+temp_suffix]
697
    def insert_():
698
        '''Inserts and capture output pkeys.'''
699
        cur = insert_select(db, out_table, mapping.keys(),
700
            *mk_select_(mapping.values()), returning=out_pkey,
701
            into_ref=out_pkeys_ref, recover=True, table_is_esc=table_is_esc)
702
        if row_ct_ref != None and cur.rowcount >= 0:
703
            row_ct_ref[0] += cur.rowcount
704
            add_row_num(db, out_pkeys_ref[0]) # for joining it with input pkeys
705
        
706
        # Get input pkeys corresponding to rows in insert
707
        in_pkeys_ref = ['in_pkeys_'+temp_suffix]
708
        run_query_into(db, *mk_select_([in_pkey]), into_ref=in_pkeys_ref)
709
        add_row_num(db, in_pkeys_ref[0]) # for joining it with output pkeys
710
        
711
        # Join together output and input pkeys
712
        run_query_into(db, *mk_select(db,
713
            [in_pkeys_ref[0], (out_pkeys_ref[0], {row_num_col: join_using})],
714
            pkeys_cols, start=0), into_ref=pkeys_ref)
715
    
716
    # Do inserts and selects
717
    try: insert_()
718
    except DuplicateKeyException, e:
719
        join_cols = util.dict_subset_right_join(mapping, e.cols)
720
        joins = in_joins + [(out_table, join_cols)]
721
        run_query_into(db, *mk_select(db, joins, pkeys_cols,
722
            table_is_esc=table_is_esc), into_ref=pkeys_ref, recover=True)
723
    
724
    return (pkeys_ref[0], out_pkey)
725

    
726
##### Data cleanup
727

    
728
def cleanup_table(db, table, cols, table_is_esc=False):
729
    def esc_name_(name): return esc_name(db, name)
730
    
731
    if not table_is_esc: check_name(table)
732
    cols = map(esc_name_, cols)
733
    
734
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
735
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
736
            for col in cols))),
737
        dict(null0='', null1=r'\N'))
(22-22/33)