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 ExceptionWithName(DbException):
32
    def __init__(self, name, cause=None):
33
        DbException.__init__(self, 'name: '+str(name), cause)
34
        self.name = name
35

    
36
class ExceptionWithColumns(DbException):
37
    def __init__(self, cols, cause=None):
38
        DbException.__init__(self, '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
        
319
        run_query(db, 'DROP TABLE IF EXISTS '+into+' CASCADE', *args, **kw_args)
320
        return run_query(db, 'CREATE TEMP TABLE '+into+' AS '+query, params,
321
            *args, **kw_args) # CREATE TABLE sets rowcount to # rows in query
322

    
323
order_by_pkey = object() # tells mk_select() to order by the pkey
324

    
325
join_using = object() # tells mk_select() to join the column with USING
326

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

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

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

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

    
472
default = object() # tells insert() to use the default value for a column
473

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

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

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

    
506
##### Database structure queries
507

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

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

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

    
575
row_num_col = '_row_num'
576

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

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

    
602
##### Database management
603

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

    
608
##### Heuristic queries
609

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

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

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

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

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

    
713
##### Data cleanup
714

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