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

    
276
connect = DbConn
277

    
278
##### Querying
279

    
280
def run_raw_query(db, *args, **kw_args):
281
    '''For params, see DbConn.run_query()'''
282
    return db.run_query(*args, **kw_args)
283

    
284
def mogrify(db, query, params):
285
    module = util.root_module(db.db)
286
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
287
    else: raise NotImplementedError("Can't mogrify query for "+module+
288
        ' database')
289

    
290
##### Recoverable querying
291

    
292
def with_savepoint(db, func): return db.with_savepoint(func)
293

    
294
def run_query(db, query, params=None, recover=None, cacheable=False):
295
    if recover == None: recover = False
296
    
297
    def run(): return run_raw_query(db, query, params, cacheable)
298
    if recover and not db.is_cached(query, params):
299
        return with_savepoint(db, run)
300
    else: return run() # don't need savepoint if cached
301

    
302
##### Basic queries
303

    
304
def run_query_into(db, query, params, into=None, *args, **kw_args):
305
    '''Outputs a query to a temp table.
306
    For params, see run_query().
307
    '''
308
    if into == None: return run_query(db, query, params, *args, **kw_args)
309
    else: # place rows in temp table
310
        check_name(into)
311
        
312
        run_query(db, 'DROP TABLE IF EXISTS '+into+' CASCADE', *args, **kw_args)
313
        return run_query(db, 'CREATE TEMP TABLE '+into+' AS '+query, params,
314
            *args, **kw_args) # CREATE TABLE sets rowcount to # rows in query
315

    
316
order_by_pkey = object() # tells mk_select() to order by the pkey
317

    
318
join_using = object() # tells mk_select() to join the column with USING
319

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

    
403
def select(db, *args, **kw_args):
404
    '''For params, see mk_select() and run_query()'''
405
    recover = kw_args.pop('recover', None)
406
    cacheable = kw_args.pop('cacheable', True)
407
    
408
    query, params = mk_select(db, *args, **kw_args)
409
    return run_query(db, query, params, recover, cacheable)
410

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

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

    
465
default = object() # tells insert() to use the default value for a column
466

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

    
490
def last_insert_id(db):
491
    module = util.root_module(db.db)
492
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
493
    elif module == 'MySQLdb': return db.insert_id()
494
    else: return None
495

    
496
def truncate(db, table, schema='public'):
497
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
498

    
499
##### Database structure queries
500

    
501
def pkey(db, table, recover=None, table_is_esc=False):
502
    '''Assumed to be first column in table'''
503
    return col_names(select(db, table, limit=0, order_by=None, recover=recover,
504
        table_is_esc=table_is_esc)).next()
505

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

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

    
568
row_num_col = '_row_num'
569

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

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

    
595
##### Database management
596

    
597
def empty_db(db, schema='public', **kw_args):
598
    '''For kw_args, see tables()'''
599
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
600

    
601
##### Heuristic queries
602

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

    
620
def try_insert(db, table, row, returning=None):
621
    '''Recovers from errors'''
622
    return with_parsed_errors(db, lambda: insert(db, table, row, returning,
623
        recover=True))
624

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

    
640
def get(db, table, row, pkey, row_ct_ref=None, create=False):
641
    '''Recovers from errors'''
642
    try: return value(select(db, table, [pkey], row, 1, recover=True))
643
    except StopIteration:
644
        if not create: raise
645
        return put(db, table, row, pkey, row_ct_ref) # insert new row
646

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

    
704
##### Data cleanup
705

    
706
def cleanup_table(db, table, cols, table_is_esc=False):
707
    def esc_name_(name): return esc_name(db, name)
708
    
709
    if not table_is_esc: check_name(table)
710
    cols = map(esc_name_, cols)
711
    
712
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
713
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
714
            for col in cols))),
715
        dict(null0='', null1=r'\N'))
(22-22/33)