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: return_value = self.inner.execute(query, params)
197
            except Exception, e:
198
                self.result = e # cache the exception as the result
199
                self._cache_result()
200
                raise
201
            finally: self.query = get_cur_query(self.inner)
202
            # Fetch all rows so result will be cached
203
            if self.rowcount == 0 and not self._is_insert: consume_rows(self)
204
            return return_value
205
        
206
        def fetchone(self):
207
            row = self.inner.fetchone()
208
            if row != None: self.result.append(row)
209
            # otherwise, fetched all rows
210
            else: self._cache_result()
211
            return row
212
        
213
        def _cache_result(self):
214
            # For inserts, only cache exceptions since inserts are not
215
            # idempotent, but an invalid insert will always be invalid
216
            if self.query_results != None and (not self._is_insert
217
                or isinstance(self.result, Exception)):
218
                
219
                assert self.query_lookup != None
220
                self.query_results[self.query_lookup] = self.CacheCursor(
221
                    util.dict_subset(dicts.AttrsDictView(self),
222
                    ['query', 'result', 'rowcount', 'description']))
223
        
224
        class CacheCursor:
225
            def __init__(self, cached_result): self.__dict__ = cached_result
226
            
227
            def execute(self, *args, **kw_args):
228
                if isinstance(self.result, Exception): raise self.result
229
                # otherwise, result is a rows list
230
                self.iter = iter(self.result)
231
            
232
            def fetchone(self):
233
                try: return self.iter.next()
234
                except StopIteration: return None
235
    
236
    def run_query(self, query, params=None, cacheable=False):
237
        if not self.caching: cacheable = False
238
        used_cache = False
239
        try:
240
            # Get cursor
241
            if cacheable:
242
                query_lookup = _query_lookup(query, params)
243
                try:
244
                    cur = self.query_results[query_lookup]
245
                    used_cache = True
246
                except KeyError: cur = self.DbCursor(self)
247
            else: cur = self.db.cursor()
248
            
249
            # Run query
250
            try: cur.execute(query, params)
251
            except Exception, e:
252
                _add_cursor_info(e, cur)
253
                raise
254
        finally:
255
            if self.log_debug != log_debug_none: # only compute msg if needed
256
                if used_cache: cache_status = 'Cache hit'
257
                elif cacheable: cache_status = 'Cache miss'
258
                else: cache_status = 'Non-cacheable'
259
                self.log_debug(cache_status+': '
260
                    +strings.one_line(get_cur_query(cur)))
261
        
262
        return cur
263
    
264
    def is_cached(self, query, params=None):
265
        return _query_lookup(query, params) in self.query_results
266
    
267
    def with_savepoint(self, func):
268
        savepoint = 'savepoint_'+str(self._savepoint)
269
        self.run_query('SAVEPOINT '+savepoint)
270
        self._savepoint += 1
271
        try: 
272
            try: return_val = func()
273
            finally:
274
                self._savepoint -= 1
275
                assert self._savepoint >= 0
276
        except:
277
            self.run_query('ROLLBACK TO SAVEPOINT '+savepoint)
278
            raise
279
        else:
280
            self.run_query('RELEASE SAVEPOINT '+savepoint)
281
            return return_val
282

    
283
connect = DbConn
284

    
285
##### Querying
286

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

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

    
297
##### Recoverable querying
298

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

    
301
def run_query(db, query, params=None, recover=None, cacheable=False):
302
    if recover == None: recover = False
303
    
304
    def run(): return run_raw_query(db, query, params, cacheable)
305
    if recover and not db.is_cached(query, params):
306
        return with_savepoint(db, run)
307
    else: return run() # don't need savepoint if cached
308

    
309
##### Basic queries
310

    
311
def run_query_into(db, query, params, into=None, *args, **kw_args):
312
    '''Outputs a query to a temp table.
313
    For params, see run_query().
314
    '''
315
    if into == None: return run_query(db, query, params, *args, **kw_args)
316
    else: # place rows in temp table
317
        check_name(into)
318
        return run_query(db, 'CREATE TEMP TABLE '+into+' AS '+query, params,
319
            *args, **kw_args) # CREATE TABLE sets rowcount to # rows in query
320

    
321
order_by_pkey = object() # tells mk_select() to order by the pkey
322

    
323
join_using = object() # tells mk_select() to join the column with USING
324

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

    
408
def select(db, *args, **kw_args):
409
    '''For params, see mk_select() and run_query()'''
410
    recover = kw_args.pop('recover', None)
411
    cacheable = kw_args.pop('cacheable', True)
412
    
413
    query, params = mk_select(db, *args, **kw_args)
414
    return run_query(db, query, params, recover, cacheable)
415

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

    
458
def insert_select(db, *args, **kw_args):
459
    '''For params, see mk_insert_select() and run_query_into()
460
    @param into Name of temp table to place RETURNING values in
461
    '''
462
    into = kw_args.pop('into', None)
463
    if into != None: kw_args['embeddable'] = True
464
    recover = kw_args.pop('recover', None)
465
    cacheable = kw_args.pop('cacheable', True)
466
    
467
    query, params = mk_insert_select(db, *args, **kw_args)
468
    return run_query_into(db, query, params, into, recover, cacheable)
469

    
470
default = object() # tells insert() to use the default value for a column
471

    
472
def insert(db, table, row, *args, **kw_args):
473
    '''For params, see insert_select()'''
474
    if lists.is_seq(row): cols = None
475
    else:
476
        cols = row.keys()
477
        row = row.values()
478
    row = list(row) # ensure that "!= []" works
479
    
480
    # Check for special values
481
    labels = []
482
    values = []
483
    for value in row:
484
        if value == default: labels.append('DEFAULT')
485
        else:
486
            labels.append('%s')
487
            values.append(value)
488
    
489
    # Build query
490
    if values != []: query = ' VALUES ('+(', '.join(labels))+')'
491
    else: query = None
492
    
493
    return insert_select(db, table, cols, query, values, *args, **kw_args)
494

    
495
def last_insert_id(db):
496
    module = util.root_module(db.db)
497
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
498
    elif module == 'MySQLdb': return db.insert_id()
499
    else: return None
500

    
501
def truncate(db, table, schema='public'):
502
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
503

    
504
##### Database structure queries
505

    
506
def pkey(db, table, recover=None, table_is_esc=False):
507
    '''Assumed to be first column in table'''
508
    return col_names(select(db, table, limit=0, order_by=None, recover=recover,
509
        table_is_esc=table_is_esc)).next()
510

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

    
554
def constraint_cols(db, table, constraint):
555
    check_name(table)
556
    check_name(constraint)
557
    module = util.root_module(db.db)
558
    if module == 'psycopg2':
559
        return list(values(run_query(db, '''\
560
SELECT attname
561
FROM pg_constraint
562
JOIN pg_class ON pg_class.oid = conrelid
563
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
564
WHERE
565
    relname = %(table)s
566
    AND conname = %(constraint)s
567
ORDER BY attnum
568
''',
569
            {'table': table, 'constraint': constraint})))
570
    else: raise NotImplementedError("Can't list constraint columns for "+module+
571
        ' database')
572

    
573
row_num_col = '_row_num'
574

    
575
def add_row_num(db, table):
576
    '''Adds a row number column to a table. Its name is in row_num_col. It will
577
    be the primary key.'''
578
    check_name(table)
579
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
580
        +' serial NOT NULL PRIMARY KEY')
581

    
582
def tables(db, schema='public', table_like='%'):
583
    module = util.root_module(db.db)
584
    params = {'schema': schema, 'table_like': table_like}
585
    if module == 'psycopg2':
586
        return values(run_query(db, '''\
587
SELECT tablename
588
FROM pg_tables
589
WHERE
590
    schemaname = %(schema)s
591
    AND tablename LIKE %(table_like)s
592
ORDER BY tablename
593
''',
594
            params, cacheable=True))
595
    elif module == 'MySQLdb':
596
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
597
            cacheable=True))
598
    else: raise NotImplementedError("Can't list tables for "+module+' database')
599

    
600
##### Database management
601

    
602
def empty_db(db, schema='public', **kw_args):
603
    '''For kw_args, see tables()'''
604
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
605

    
606
##### Heuristic queries
607

    
608
def with_parsed_errors(db, func):
609
    '''Translates known DB errors to typed exceptions'''
610
    try: return func()
611
    except Exception, e:
612
        msg = str(e)
613
        match = re.search(r'duplicate key value violates unique constraint '
614
            r'"((_?[^\W_]+)_[^"]+)"', msg)
615
        if match:
616
            constraint, table = match.groups()
617
            try: cols = index_cols(db, table, constraint)
618
            except NotImplementedError: raise e
619
            else: raise DuplicateKeyException(cols, e)
620
        match = re.search(r'null value in column "(\w+)" violates not-null '
621
            'constraint', msg)
622
        if match: raise NullValueException([match.group(1)], e)
623
        match = re.search(r'table name "(\w+)" specified more than once', msg)
624
        if match: raise DuplicateTableException(match.group(1), e)
625
        raise # no specific exception raised
626

    
627
def try_insert(db, table, row, returning=None):
628
    '''Recovers from errors'''
629
    return with_parsed_errors(db, lambda: insert(db, table, row, returning,
630
        recover=True))
631

    
632
def put(db, table, row, pkey_=None, row_ct_ref=None):
633
    '''Recovers from errors.
634
    Only works under PostgreSQL (uses INSERT RETURNING).
635
    '''
636
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
637
    
638
    try:
639
        cur = try_insert(db, table, row, pkey_)
640
        if row_ct_ref != None and cur.rowcount >= 0:
641
            row_ct_ref[0] += cur.rowcount
642
        return value(cur)
643
    except DuplicateKeyException, e:
644
        return value(select(db, table, [pkey_],
645
            util.dict_subset_right_join(row, e.cols), recover=True))
646

    
647
def get(db, table, row, pkey, row_ct_ref=None, create=False):
648
    '''Recovers from errors'''
649
    try: return value(select(db, table, [pkey], row, 1, recover=True))
650
    except StopIteration:
651
        if not create: raise
652
        return put(db, table, row, pkey, row_ct_ref) # insert new row
653

    
654
def put_table(db, out_table, in_tables, mapping, limit=None, start=0,
655
    row_ct_ref=None, table_is_esc=False):
656
    '''Recovers from errors.
657
    Only works under PostgreSQL (uses INSERT RETURNING).
658
    @param in_tables The main input table to select from, followed by a list of
659
        tables to join with it using the main input table's pkey
660
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
661
        available
662
    '''
663
    temp_prefix = '_'.join(map(clean_name,
664
        [out_table] + list(iters.flatten(mapping.items()))))
665
    pkeys = temp_prefix+'_pkeys'
666
    
667
    # Join together input tables
668
    in_tables = in_tables[:] # don't modify input!
669
    in_tables0 = in_tables.pop(0) # first table is separate
670
    in_pkey = pkey(db, in_tables0, recover=True, table_is_esc=table_is_esc)
671
    in_joins = [in_tables0] + [(t, {in_pkey: join_using}) for t in in_tables]
672
    
673
    out_pkey = pkey(db, out_table, recover=True, table_is_esc=table_is_esc)
674
    pkeys_cols = [in_pkey, out_pkey]
675
    
676
    def mk_select_(cols):
677
        return mk_select(db, in_joins, cols, limit=limit, start=start,
678
            table_is_esc=table_is_esc)
679
    
680
    out_pkeys = temp_prefix+'_out_pkeys'
681
    def insert_():
682
        cur = insert_select(db, out_table, mapping.keys(),
683
            *mk_select_(mapping.values()), returning=out_pkey,
684
            into=out_pkeys, recover=True, table_is_esc=table_is_esc)
685
        if row_ct_ref != None and cur.rowcount >= 0:
686
            row_ct_ref[0] += cur.rowcount
687
        add_row_num(db, out_pkeys) # for joining it with in_pkeys
688
        
689
        # Get input pkeys corresponding to rows in insert
690
        in_pkeys = temp_prefix+'_in_pkeys'
691
        run_query_into(db, *mk_select_([in_pkey]), into=in_pkeys)
692
        add_row_num(db, in_pkeys) # for joining it with out_pkeys
693
        
694
        # Join together out_pkeys and in_pkeys
695
        run_query_into(db, *mk_select(db,
696
            [in_pkeys, (out_pkeys, {row_num_col: join_using})],
697
            pkeys_cols, start=0), into=pkeys)
698
    
699
    # Do inserts and selects
700
    try:
701
        # Insert and capture output pkeys
702
        with_parsed_errors(db, insert_)
703
    except DuplicateKeyException, e:
704
        join_cols = util.dict_subset_right_join(mapping, e.cols)
705
        joins = in_joins + [(out_table, join_cols)]
706
        run_query_into(db, *mk_select(db, joins, pkeys_cols,
707
            table_is_esc=table_is_esc), into=pkeys)
708
    
709
    return (pkeys, out_pkey)
710

    
711
##### Data cleanup
712

    
713
def cleanup_table(db, table, cols, table_is_esc=False):
714
    def esc_name_(name): return esc_name(db, name)
715
    
716
    if not table_is_esc: check_name(table)
717
    cols = map(esc_name_, cols)
718
    
719
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
720
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
721
            for col in cols))),
722
        dict(null0='', null1=r'\N'))
(22-22/33)