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)
29
        if cur != None: _add_cursor_info(self, cur)
30

    
31
class NameException(DbException): pass
32

    
33
class ExceptionWithColumns(DbException):
34
    def __init__(self, cols, cause=None):
35
        DbException.__init__(self, 'columns: ' + ', '.join(cols), cause)
36
        self.cols = cols
37

    
38
class DuplicateKeyException(ExceptionWithColumns): pass
39

    
40
class NullValueException(ExceptionWithColumns): pass
41

    
42
class EmptyRowException(DbException): pass
43

    
44
##### Warnings
45

    
46
class DbWarning(UserWarning): pass
47

    
48
##### Result retrieval
49

    
50
def col_names(cur): return (col[0] for col in cur.description)
51

    
52
def rows(cur): return iter(lambda: cur.fetchone(), None)
53

    
54
def consume_rows(cur):
55
    '''Used to fetch all rows so result will be cached'''
56
    iters.consume_iter(rows(cur))
57

    
58
def next_row(cur): return rows(cur).next()
59

    
60
def row(cur):
61
    row_ = next_row(cur)
62
    consume_rows(cur)
63
    return row_
64

    
65
def next_value(cur): return next_row(cur)[0]
66

    
67
def value(cur): return row(cur)[0]
68

    
69
def values(cur): return iters.func_iter(lambda: next_value(cur))
70

    
71
def value_or_none(cur):
72
    try: return value(cur)
73
    except StopIteration: return None
74

    
75
##### Input validation
76

    
77
def clean_name(name): return re.sub(r'\W', r'', name)
78

    
79
def check_name(name):
80
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
81
        +'" may contain only alphanumeric characters and _')
82

    
83
def esc_name_by_module(module, name, ignore_case=False):
84
    if module == 'psycopg2':
85
        if ignore_case:
86
            # Don't enclose in quotes because this disables case-insensitivity
87
            check_name(name)
88
            return name
89
        else: quote = '"'
90
    elif module == 'MySQLdb': quote = '`'
91
    else: raise NotImplementedError("Can't escape name for "+module+' database')
92
    return quote + name.replace(quote, '') + quote
93

    
94
def esc_name_by_engine(engine, name, **kw_args):
95
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
96

    
97
def esc_name(db, name, **kw_args):
98
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
99

    
100
def qual_name(db, schema, table):
101
    def esc_name_(name): return esc_name(db, name)
102
    table = esc_name_(table)
103
    if schema != None: return esc_name_(schema)+'.'+table
104
    else: return table
105

    
106
##### Database connections
107

    
108
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
109

    
110
db_engines = {
111
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
112
    'PostgreSQL': ('psycopg2', {}),
113
}
114

    
115
DatabaseErrors_set = set([DbException])
116
DatabaseErrors = tuple(DatabaseErrors_set)
117

    
118
def _add_module(module):
119
    DatabaseErrors_set.add(module.DatabaseError)
120
    global DatabaseErrors
121
    DatabaseErrors = tuple(DatabaseErrors_set)
122

    
123
def db_config_str(db_config):
124
    return db_config['engine']+' database '+db_config['database']
125

    
126
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
127

    
128
log_debug_none = lambda msg: None
129

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

    
259
connect = DbConn
260

    
261
##### Querying
262

    
263
def run_raw_query(db, *args, **kw_args):
264
    '''For params, see DbConn.run_query()'''
265
    return db.run_query(*args, **kw_args)
266

    
267
def mogrify(db, query, params):
268
    module = util.root_module(db.db)
269
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
270
    else: raise NotImplementedError("Can't mogrify query for "+module+
271
        ' database')
272

    
273
##### Recoverable querying
274

    
275
def with_savepoint(db, func):
276
    savepoint = 'savepoint_'+str(rand.rand_int()) # must be unique
277
    run_raw_query(db, 'SAVEPOINT '+savepoint)
278
    try: return_val = func()
279
    except:
280
        run_raw_query(db, 'ROLLBACK TO SAVEPOINT '+savepoint)
281
        raise
282
    else:
283
        run_raw_query(db, 'RELEASE SAVEPOINT '+savepoint)
284
        return return_val
285

    
286
def run_query(db, query, params=None, recover=None, cacheable=False):
287
    if recover == None: recover = False
288
    
289
    def run(): return run_raw_query(db, query, params, cacheable)
290
    if recover and not db.is_cached(query, params):
291
        return with_savepoint(db, run)
292
    else: return run() # don't need savepoint if cached
293

    
294
##### Basic queries
295

    
296
def run_query_into(db, query, params, into=None, *args, **kw_args):
297
    '''Outputs a query to a temp table.
298
    For params, see run_query().
299
    '''
300
    if into == None: return run_query(db, query, params, *args, **kw_args)
301
    else: # place rows in temp table
302
        check_name(into)
303
        
304
        run_query(db, 'DROP TABLE IF EXISTS '+into+' CASCADE', *args, **kw_args)
305
        return run_query(db, 'CREATE TEMP TABLE '+into+' AS '+query, params,
306
            *args, **kw_args) # CREATE TABLE sets rowcount to # rows in query
307

    
308
order_by_pkey = object() # tells mk_select() to order by the pkey
309

    
310
join_using = object() # tells mk_select() to join the column with USING
311

    
312
def mk_select(db, tables, fields=None, conds=None, limit=None, start=None,
313
    order_by=order_by_pkey, table_is_esc=False):
314
    '''
315
    @param tables The single table to select from, or a list of tables to join
316
        together: [table0, (table1, dict(right_col=left_col, ...)), ...]
317
    @param fields Use None to select all fields in the table
318
    @param table_is_esc Whether the table name has already been escaped
319
    @return tuple(query, params)
320
    '''
321
    def esc_name_(name): return esc_name(db, name)
322
    
323
    if not lists.is_seq(tables): tables = [tables]
324
    tables = tables[:] # don't modify input!
325
    table0 = tables.pop(0) # first table is separate
326
    
327
    if conds == None: conds = {}
328
    assert limit == None or type(limit) == int
329
    assert start == None or type(start) == int
330
    if order_by == order_by_pkey:
331
        order_by = pkey(db, table0, recover=True, table_is_esc=table_is_esc)
332
    if not table_is_esc: table0 = esc_name_(table0)
333
    
334
    params = []
335
    
336
    def parse_col(field):
337
        '''Parses fields'''
338
        if isinstance(field, tuple): # field is literal value
339
            value, col = field
340
            sql_ = '%s'
341
            params.append(value)
342
            if col != None: sql_ += ' AS '+esc_name_(col)
343
        else: sql_ = esc_name_(field) # field is col name
344
        return sql_
345
    def cond(entry):
346
        '''Parses conditions'''
347
        col, value = entry
348
        cond_ = esc_name_(col)+' '
349
        if value == None: cond_ += 'IS'
350
        else: cond_ += '='
351
        cond_ += ' %s'
352
        return cond_
353
    
354
    query = 'SELECT '
355
    if fields == None: query += '*'
356
    else: query += ', '.join(map(parse_col, fields))
357
    query += ' FROM '+table0
358
    
359
    # Add joins
360
    left_table = table0
361
    for table, joins in tables:
362
        if not table_is_esc: table = esc_name_(table)
363
        query += ' JOIN '+table
364
        
365
        def join(entry):
366
            '''Parses non-USING joins'''
367
            right_col, left_col = entry
368
            right_col = table+'.'+esc_name_(right_col)
369
            left_col = left_table+'.'+esc_name_(left_col)
370
            return (right_col+' = '+left_col
371
                +' OR ('+right_col+' IS NULL AND '+left_col+' IS NULL)')
372
        
373
        if reduce(operator.and_, (v == join_using for v in joins.itervalues())):
374
            # all cols w/ USING
375
            query += ' USING ('+(', '.join(joins.iterkeys()))+')'
376
        else: query += ' ON '+(' AND '.join(map(join, joins.iteritems())))
377
        
378
        left_table = table
379
    
380
    missing = True
381
    if conds != {}:
382
        query += ' WHERE '+(' AND '.join(map(cond, conds.iteritems())))
383
        params += conds.values()
384
        missing = False
385
    if order_by != None: query += ' ORDER BY '+esc_name_(order_by)
386
    if limit != None: query += ' LIMIT '+str(limit); missing = False
387
    if start != None:
388
        if start != 0: query += ' OFFSET '+str(start)
389
        missing = False
390
    if missing: warnings.warn(DbWarning(
391
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
392
    
393
    return (query, params)
394

    
395
def select(db, *args, **kw_args):
396
    '''For params, see mk_select() and run_query()'''
397
    recover = kw_args.pop('recover', None)
398
    cacheable = kw_args.pop('cacheable', True)
399
    
400
    query, params = mk_select(db, *args, **kw_args)
401
    return run_query(db, query, params, recover, cacheable)
402

    
403
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
404
    returning=None, embeddable=False, table_is_esc=False):
405
    '''
406
    @param returning str|None An inserted column (such as pkey) to return
407
    @param embeddable Whether the query should be embeddable as a nested SELECT.
408
        Warning: If you set this and cacheable=True when the query is run, the
409
        query will be fully cached, not just if it raises an exception.
410
    @param table_is_esc Whether the table name has already been escaped
411
    '''
412
    if select_query == None: select_query = 'DEFAULT VALUES'
413
    if cols == []: cols = None # no cols (all defaults) = unknown col names
414
    if not table_is_esc: check_name(table)
415
    
416
    # Build query
417
    query = 'INSERT INTO '+table
418
    if cols != None:
419
        map(check_name, cols)
420
        query += ' ('+', '.join(cols)+')'
421
    query += ' '+select_query
422
    
423
    if returning != None:
424
        check_name(returning)
425
        query += ' RETURNING '+returning
426
    
427
    if embeddable:
428
        # Create function
429
        function = 'pg_temp.'+('_'.join(map(clean_name,
430
            ['insert', table] + cols)))
431
        return_type = 'SETOF '+table+'.'+returning+'%TYPE'
432
        function_query = '''\
433
CREATE OR REPLACE FUNCTION '''+function+'''() RETURNS '''+return_type+'''
434
    LANGUAGE sql
435
    AS $$'''+mogrify(db, query, params)+''';$$;
436
'''
437
        run_query(db, function_query, cacheable=True)
438
        
439
        # Return query that uses function
440
        return mk_select(db, function+'() AS f ('+returning+')', order_by=None,
441
            table_is_esc=True) # function alias is required in AS clause
442
    
443
    return (query, params)
444

    
445
def insert_select(db, *args, **kw_args):
446
    '''For params, see mk_insert_select() and run_query_into()
447
    @param into Name of temp table to place RETURNING values in
448
    '''
449
    into = kw_args.pop('into', None)
450
    if into != None: kw_args['embeddable'] = True
451
    recover = kw_args.pop('recover', None)
452
    cacheable = kw_args.pop('cacheable', True)
453
    
454
    query, params = mk_insert_select(db, *args, **kw_args)
455
    return run_query_into(db, query, params, into, recover, cacheable)
456

    
457
default = object() # tells insert() to use the default value for a column
458

    
459
def insert(db, table, row, *args, **kw_args):
460
    '''For params, see insert_select()'''
461
    if lists.is_seq(row): cols = None
462
    else:
463
        cols = row.keys()
464
        row = row.values()
465
    row = list(row) # ensure that "!= []" works
466
    
467
    # Check for special values
468
    labels = []
469
    values = []
470
    for value in row:
471
        if value == default: labels.append('DEFAULT')
472
        else:
473
            labels.append('%s')
474
            values.append(value)
475
    
476
    # Build query
477
    if values != []: query = ' VALUES ('+(', '.join(labels))+')'
478
    else: query = None
479
    
480
    return insert_select(db, table, cols, query, values, *args, **kw_args)
481

    
482
def last_insert_id(db):
483
    module = util.root_module(db.db)
484
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
485
    elif module == 'MySQLdb': return db.insert_id()
486
    else: return None
487

    
488
def truncate(db, table, schema='public'):
489
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
490

    
491
##### Database structure queries
492

    
493
def pkey(db, table, recover=None, table_is_esc=False):
494
    '''Assumed to be first column in table'''
495
    return col_names(select(db, table, limit=0, order_by=None, recover=recover,
496
        table_is_esc=table_is_esc)).next()
497

    
498
def index_cols(db, table, index):
499
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
500
    automatically created. When you don't know whether something is a UNIQUE
501
    constraint or a UNIQUE index, use this function.'''
502
    check_name(table)
503
    check_name(index)
504
    module = util.root_module(db.db)
505
    if module == 'psycopg2':
506
        return list(values(run_query(db, '''\
507
SELECT attname
508
FROM
509
(
510
        SELECT attnum, attname
511
        FROM pg_index
512
        JOIN pg_class index ON index.oid = indexrelid
513
        JOIN pg_class table_ ON table_.oid = indrelid
514
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
515
        WHERE
516
            table_.relname = %(table)s
517
            AND index.relname = %(index)s
518
    UNION
519
        SELECT attnum, attname
520
        FROM
521
        (
522
            SELECT
523
                indrelid
524
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
525
                    AS indkey
526
            FROM pg_index
527
            JOIN pg_class index ON index.oid = indexrelid
528
            JOIN pg_class table_ ON table_.oid = indrelid
529
            WHERE
530
                table_.relname = %(table)s
531
                AND index.relname = %(index)s
532
        ) s
533
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
534
) s
535
ORDER BY attnum
536
''',
537
            {'table': table, 'index': index}, cacheable=True)))
538
    else: raise NotImplementedError("Can't list index columns for "+module+
539
        ' database')
540

    
541
def constraint_cols(db, table, constraint):
542
    check_name(table)
543
    check_name(constraint)
544
    module = util.root_module(db.db)
545
    if module == 'psycopg2':
546
        return list(values(run_query(db, '''\
547
SELECT attname
548
FROM pg_constraint
549
JOIN pg_class ON pg_class.oid = conrelid
550
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
551
WHERE
552
    relname = %(table)s
553
    AND conname = %(constraint)s
554
ORDER BY attnum
555
''',
556
            {'table': table, 'constraint': constraint})))
557
    else: raise NotImplementedError("Can't list constraint columns for "+module+
558
        ' database')
559

    
560
row_num_col = '_row_num'
561

    
562
def add_row_num(db, table):
563
    '''Adds a row number column to a table. Its name is in row_num_col. It will
564
    be the primary key.'''
565
    check_name(table)
566
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
567
        +' serial NOT NULL PRIMARY KEY')
568

    
569
def tables(db, schema='public', table_like='%'):
570
    module = util.root_module(db.db)
571
    params = {'schema': schema, 'table_like': table_like}
572
    if module == 'psycopg2':
573
        return values(run_query(db, '''\
574
SELECT tablename
575
FROM pg_tables
576
WHERE
577
    schemaname = %(schema)s
578
    AND tablename LIKE %(table_like)s
579
ORDER BY tablename
580
''',
581
            params, cacheable=True))
582
    elif module == 'MySQLdb':
583
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
584
            cacheable=True))
585
    else: raise NotImplementedError("Can't list tables for "+module+' database')
586

    
587
##### Database management
588

    
589
def empty_db(db, schema='public', **kw_args):
590
    '''For kw_args, see tables()'''
591
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
592

    
593
##### Heuristic queries
594

    
595
def with_parsed_errors(db, func):
596
    '''Translates known DB errors to typed exceptions'''
597
    try: return func()
598
    except Exception, e:
599
        msg = str(e)
600
        match = re.search(r'duplicate key value violates unique constraint '
601
            r'"(([^\W_]+)_[^"]+)"', msg)
602
        if match:
603
            constraint, table = match.groups()
604
            try: cols = index_cols(db, table, constraint)
605
            except NotImplementedError: raise e
606
            else: raise DuplicateKeyException(cols, e)
607
        match = re.search(r'null value in column "(\w+)" violates not-null '
608
            'constraint', msg)
609
        if match: raise NullValueException([match.group(1)], e)
610
        raise # no specific exception raised
611

    
612
def try_insert(db, table, row, returning=None):
613
    '''Recovers from errors'''
614
    return with_parsed_errors(db, lambda: insert(db, table, row, returning,
615
        recover=True))
616

    
617
def put(db, table, row, pkey_=None, row_ct_ref=None):
618
    '''Recovers from errors.
619
    Only works under PostgreSQL (uses INSERT RETURNING).
620
    '''
621
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
622
    
623
    try:
624
        cur = try_insert(db, table, row, pkey_)
625
        if row_ct_ref != None and cur.rowcount >= 0:
626
            row_ct_ref[0] += cur.rowcount
627
        return value(cur)
628
    except DuplicateKeyException, e:
629
        return value(select(db, table, [pkey_],
630
            util.dict_subset_right_join(row, e.cols), recover=True))
631

    
632
def get(db, table, row, pkey, row_ct_ref=None, create=False):
633
    '''Recovers from errors'''
634
    try: return value(select(db, table, [pkey], row, 1, recover=True))
635
    except StopIteration:
636
        if not create: raise
637
        return put(db, table, row, pkey, row_ct_ref) # insert new row
638

    
639
def put_table(db, out_table, in_tables, mapping, row_ct_ref=None,
640
    table_is_esc=False):
641
    '''Recovers from errors.
642
    Only works under PostgreSQL (uses INSERT RETURNING).
643
    @param in_tables The main input table to select from, followed by a list of
644
        tables to join with it using the main input table's pkey
645
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
646
        available
647
    '''
648
    out_table_clean = clean_name(out_table)
649
    pkeys = out_table_clean+'_pkeys'
650
    
651
    out_pkey = pkey(db, out_table, recover=True, table_is_esc=table_is_esc)
652
    
653
    # Join together input tables
654
    in_tables = in_tables[:] # don't modify input!
655
    in_tables0 = in_tables.pop(0) # first table is separate
656
    in_pkey = pkey(db, in_tables0, recover=True, table_is_esc=table_is_esc)
657
    joins = [in_tables0] + [(t, {in_pkey: join_using}) for t in in_tables]
658
    
659
    def mk_select_(cols):
660
        return mk_select(db, joins, cols, table_is_esc=table_is_esc)
661
    
662
    out_pkeys = out_table_clean+'_out_pkeys'
663
    def insert_():
664
        cur = insert_select(db, out_table, mapping.keys(),
665
            *mk_select_(mapping.values()), returning=out_pkey,
666
            into=out_pkeys, recover=True, table_is_esc=table_is_esc)
667
        if row_ct_ref != None and cur.rowcount >= 0:
668
            row_ct_ref[0] += cur.rowcount
669
        add_row_num(db, out_pkeys) # for joining it with in_pkeys
670
        
671
        # Get input pkeys corresponding to rows in insert
672
        in_pkeys = out_table_clean+'_in_pkeys'
673
        run_query_into(db, *mk_select_([in_pkey]), into=in_pkeys)
674
        add_row_num(db, in_pkeys) # for joining it with out_pkeys
675
        
676
        # Join together out_pkeys and in_pkeys
677
        run_query_into(db, *mk_select(db,
678
            [in_pkeys, (out_pkeys, {row_num_col: join_using})],
679
            [in_pkey, out_pkey]), into=pkeys)
680
    
681
    try:
682
        # Insert and capture output pkeys
683
        with_parsed_errors(db, insert_)
684
        
685
        return (pkeys, out_pkey)
686
    except DuplicateKeyException, e: raise
687

    
688
##### Data cleanup
689

    
690
def cleanup_table(db, table, cols, table_is_esc=False):
691
    def esc_name_(name): return esc_name(db, name)
692
    
693
    if not table_is_esc: check_name(table)
694
    cols = map(esc_name_, cols)
695
    
696
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
697
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
698
            for col in cols))),
699
        dict(null0='', null1=r'\N'))
(22-22/33)