Project

General

Profile

1
# Database import/export
2

    
3
import operator
4

    
5
import exc
6
import dicts
7
import sql
8
import sql_gen
9
import strings
10
import util
11

    
12
##### Data cleanup
13

    
14
def cleanup_table(db, table, cols):
15
    table = sql_gen.as_Table(table)
16
    cols = map(sql_gen.as_Col, cols)
17
    
18
    expr = ('nullif(nullif(trim(both from %s), '+db.esc_value('')+'), '
19
        +db.esc_value(r'\N')+')')
20
    changes = [(v, sql_gen.CustomCode(expr % v.to_str(db)))
21
        for v in cols]
22
    
23
    sql.update(db, table, changes, in_place=True)
24

    
25
##### Error tracking
26

    
27
def track_data_error(db, errors_table, cols, value, error_code, error):
28
    '''
29
    @param errors_table If None, does nothing.
30
    '''
31
    if errors_table == None or cols == (): return
32
    
33
    for col in cols:
34
        try:
35
            sql.insert(db, errors_table, dict(column=col.name, value=value,
36
                error_code=error_code, error=error), recover=True,
37
                cacheable=True, log_level=4)
38
        except sql.DuplicateKeyException: pass
39

    
40
def data_exception_handler(db, srcs=[], errors_table=None):
41
    '''Handles a data_exception by saving the error or converting it to a
42
    warning, and returning NULL.
43
    @param srcs The column names for the errors table
44
    @param errors_table None|sql_gen.Table
45
    '''
46
    save_errors = errors_table != None and srcs
47
    handler = ''
48
    if save_errors:
49
        errors_table_cols = map(sql_gen.Col,
50
            ['column', 'value', 'error_code', 'error'])
51
        handler += '''\
52
-- Save error in errors table.
53
DECLARE
54
    error_code text := SQLSTATE;
55
    error text := SQLERRM;
56
    "column" text;
57
BEGIN
58
    -- Insert the value and error for *each* source column.
59
    FOR "column" IN
60
'''+sql.mk_select(db, sql_gen.NamedValues('c', None, [[c.name] for c in srcs]),
61
    order_by=None)+'''
62
    LOOP
63
        BEGIN
64
'''+sql.mk_insert_select(db, errors_table, errors_table_cols,
65
    sql_gen.Values(errors_table_cols).to_str(db))+''';
66
        EXCEPTION
67
            WHEN unique_violation THEN NULL; -- continue to next row
68
        END;
69
    END LOOP;
70
END;
71
'''
72
    else:
73
        handler += '''\
74
RAISE WARNING '%', SQLERRM;
75
'''
76
    handler += '''\
77
RETURN NULL;
78
'''
79
    return sql_gen.ExcHandler('data_exception', handler)
80

    
81
def cast(db, type_, col, errors_table=None):
82
    '''Casts an (unrenamed) column or value.
83
    If errors_table set and col has srcs, saves errors in errors_table (using
84
    col's srcs attr as source columns). Otherwise, converts errors to warnings.
85
    @param col str|sql_gen.Col|sql_gen.Literal
86
    @param errors_table None|sql_gen.Table|str
87
    '''
88
    col = sql_gen.as_Col(col)
89
    
90
    # Don't convert exceptions to warnings for user-supplied constants
91
    if isinstance(col, sql_gen.Literal): return sql_gen.Cast(type_, col)
92
    
93
    assert not isinstance(col, sql_gen.NamedCol)
94
    
95
    function_name = strings.first_word(type_)
96
    srcs = col.srcs
97
    save_errors = (errors_table != None and isinstance(col, sql_gen.Col)
98
        and col.srcs != ())
99
    if save_errors:
100
        srcs = map(sql_gen.to_name_only_col, col.srcs)
101
        function_name = str(sql_gen.FunctionCall(function_name, *srcs))
102
    function = db.TempFunction(function_name)
103
    
104
    while True:
105
        # Create function definition
106
        query = '''\
107
CREATE FUNCTION '''+function.to_str(db)+'''(value text)
108
RETURNS '''+type_+'''
109
LANGUAGE plpgsql
110
'''
111
        if not save_errors: query += 'IMMUTABLE '
112
        query += '''\
113
STRICT
114
AS $$
115
'''
116
        query += data_exception_handler(db, srcs, errors_table).to_str(db, '''\
117
    /* The explicit cast to the return type is needed to make the cast happen
118
    inside the try block. (Implicit casts to the return type happen at the end
119
    of the function, outside any block.) */
120
    RETURN value::'''+type_+''';
121
''')
122
        query += '''\
123
$$;
124
'''
125
        
126
        # Create function
127
        try:
128
            sql.run_query(db, query, recover=True, cacheable=True,
129
                log_ignore_excs=(sql.DuplicateException,))
130
            break # successful
131
        except sql.DuplicateException:
132
            function.name = sql.next_version(function.name)
133
            # try again with next version of name
134
    
135
    return sql_gen.FunctionCall(function, col)
136

    
137
def cast_temp_col(db, type_, col, errors_table=None):
138
    '''Like cast(), but creates a new column with the cast values if the input
139
    is a column.
140
    @return The new column or cast value
141
    '''
142
    def cast_(col): return cast(db, type_, col, errors_table)
143
    
144
    try: col = sql_gen.underlying_col(col)
145
    except sql_gen.NoUnderlyingTableException: return sql_gen.wrap(cast_, col)
146
    
147
    table = col.table
148
    new_col = sql_gen.suffixed_col(col, '::'+strings.first_word(type_))
149
    expr = cast_(col)
150
    
151
    # Add column
152
    new_typed_col = sql_gen.TypedCol(new_col.name, type_)
153
    sql.add_col(db, table, new_typed_col, comment=repr(col)+'::'+type_)
154
    new_col.name = new_typed_col.name # propagate any renaming
155
    
156
    sql.update(db, table, [(new_col, expr)], in_place=True, recover=True)
157
    
158
    return new_col
159

    
160
def errors_table(db, table, if_exists=True):
161
    '''
162
    @param if_exists If set, returns None if the errors table doesn't exist
163
    @return None|sql_gen.Table
164
    '''
165
    table = sql_gen.as_Table(table)
166
    if table.srcs != (): table = table.srcs[0]
167
    
168
    errors_table = sql_gen.suffixed_table(table, '.errors')
169
    if if_exists and not sql.table_exists(db, errors_table): return None
170
    return errors_table
171

    
172
##### Import
173

    
174
def put(db, table, row, pkey_=None, row_ct_ref=None):
175
    '''Recovers from errors.
176
    Only works under PostgreSQL (uses INSERT RETURNING).
177
    '''
178
    row = sql_gen.ColDict(db, table, row)
179
    if pkey_ == None: pkey_ = sql.pkey(db, table, recover=True)
180
    
181
    try:
182
        cur = sql.insert(db, table, row, pkey_, recover=True, log_level=3.5)
183
        if row_ct_ref != None and cur.rowcount >= 0:
184
            row_ct_ref[0] += cur.rowcount
185
        return sql.value(cur)
186
    except sql.DuplicateKeyException, e:
187
        row = sql_gen.ColDict(db, table,
188
            util.dict_subset_right_join(row, e.cols))
189
        return sql.value(sql.select(db, table, [pkey_], row, recover=True,
190
            log_level=3.5))
191
    except sql.NullValueException: return None
192

    
193
def get(db, table, row, pkey, row_ct_ref=None, create=False):
194
    '''Recovers from errors'''
195
    try:
196
        return sql.value(sql.select(db, table, [pkey], row, limit=1,
197
            recover=True))
198
    except StopIteration:
199
        if not create: raise
200
        return put(db, table, row, pkey, row_ct_ref) # insert new row
201

    
202
def is_func_result(col):
203
    return col.table.name.find('(') >= 0 and col.name == 'result'
204

    
205
def into_table_name(out_table, in_tables0, mapping, is_func):
206
    def in_col_str(in_col):
207
        in_col = sql_gen.remove_col_rename(in_col)
208
        if isinstance(in_col, sql_gen.Col):
209
            table = in_col.table
210
            if table == in_tables0:
211
                in_col = sql_gen.to_name_only_col(in_col)
212
            elif is_func_result(in_col): in_col = table # omit col name
213
        return str(in_col)
214
    
215
    str_ = str(out_table)
216
    if is_func:
217
        str_ += '('
218
        
219
        try: value_in_col = mapping['value']
220
        except KeyError:
221
            str_ += ', '.join((str(k)+'='+in_col_str(v)
222
                for k, v in mapping.iteritems()))
223
        else: str_ += in_col_str(value_in_col)
224
        
225
        str_ += ')'
226
    else:
227
        out_col = 'rank'
228
        try: in_col = mapping[out_col]
229
        except KeyError: str_ += '_pkeys'
230
        else: # has a rank column, so hierarchical
231
            str_ += '['+str(out_col)+'='+in_col_str(in_col)+']'
232
    return str_
233

    
234
def put_table(db, out_table, in_tables, mapping, row_ct_ref=None, into=None,
235
    default=None, is_func=False, on_error=exc.raise_):
236
    '''Recovers from errors.
237
    Only works under PostgreSQL (uses INSERT RETURNING).
238
    IMPORTANT: Must be run at the *beginning* of a transaction.
239
    @param in_tables The main input table to select from, followed by a list of
240
        tables to join with it using the main input table's pkey
241
    @param mapping dict(out_table_col=in_table_col, ...)
242
        * out_table_col: str (*not* sql_gen.Col)
243
        * in_table_col: sql_gen.Col|literal-value
244
    @param into The table to contain the output and input pkeys.
245
        Defaults to `out_table.name+'_pkeys'`.
246
    @param default The *output* column to use as the pkey for missing rows.
247
        If this output column does not exist in the mapping, uses None.
248
    @param is_func Whether out_table is the name of a SQL function, not a table
249
    @return sql_gen.Col Where the output pkeys are made available
250
    '''
251
    out_table = sql_gen.as_Table(out_table)
252
    
253
    def log_debug(msg): db.log_debug(msg, level=1.5)
254
    def col_ustr(str_):
255
        return strings.repr_no_u(sql_gen.remove_col_rename(str_))
256
    
257
    log_debug('********** New iteration **********')
258
    log_debug('Inserting these input columns into '+strings.as_tt(
259
        out_table.to_str(db))+':\n'+strings.as_table(mapping, ustr=col_ustr))
260
    
261
    is_function = sql.function_exists(db, out_table)
262
    
263
    if is_function: out_pkey = 'result'
264
    else: out_pkey = sql.pkey(db, out_table, recover=True)
265
    out_pkey_col = sql_gen.as_Col(out_pkey, out_table)
266
    
267
    in_tables_ = in_tables[:] # don't modify input!
268
    try: in_tables0 = in_tables_.pop(0) # first table is separate
269
    except IndexError: in_tables0 = None
270
    else:
271
        in_pkey = sql.pkey(db, in_tables0, recover=True)
272
        in_pkey_col = sql_gen.as_Col(in_pkey, in_tables0)
273
    
274
    # Determine if can use optimization for only literal values
275
    is_literals = not reduce(operator.or_, map(sql_gen.is_table_col,
276
        mapping.values()), False)
277
    is_literals_or_function = is_literals or is_function
278
    
279
    if in_tables0 == None: errors_table_ = None
280
    else: errors_table_ = errors_table(db, in_tables0)
281
    
282
    # Create input joins from list of input tables
283
    input_joins = [in_tables0]+[sql_gen.Join(v,
284
        {in_pkey: sql_gen.join_same_not_null}) for v in in_tables_]
285
    
286
    if mapping == {} and not is_function: # need >= one column for INSERT SELECT
287
        mapping = {out_pkey: None} # ColDict will replace with default value
288
    
289
    if not is_literals:
290
        if into == None:
291
            into = into_table_name(out_table, in_tables0, mapping, is_func)
292
        into = sql_gen.as_Table(into)
293
        
294
        # Set column sources
295
        in_cols = filter(sql_gen.is_table_col, mapping.values())
296
        for col in in_cols:
297
            if col.table == in_tables0: col.set_srcs(sql_gen.src_self)
298
        
299
        log_debug('Joining together input tables into temp table')
300
        # Place in new table so don't modify input and for speed
301
        in_table = sql_gen.Table('in')
302
        mapping = dicts.join(mapping, sql.flatten(db, in_table, input_joins,
303
            in_cols, preserve=[in_pkey_col]))
304
        input_joins = [in_table]
305
        db.log_debug('Temp table: '+strings.as_tt(in_table.to_str(db)), level=2)
306
    
307
    mapping = sql_gen.ColDict(db, out_table, mapping)
308
        # after applying dicts.join() because that returns a plain dict
309
    
310
    # Resolve default value column
311
    if default != None:
312
        try: default = mapping[default]
313
        except KeyError:
314
            db.log_debug('Default value column '
315
                +strings.as_tt(strings.repr_no_u(default))
316
                +' does not exist in mapping, falling back to None', level=2.1)
317
            default = None
318
    
319
    # Save default values for all rows since in_table may have rows deleted
320
    if is_literals: pass
321
    elif is_function: full_in_table = in_table
322
    else:
323
        full_in_table = sql_gen.suffixed_table(in_table, '_full')
324
        full_in_table_cols = [in_pkey_col]
325
        if default != None:
326
            full_in_table_cols.append(default)
327
            default = sql_gen.with_table(default, full_in_table)
328
        sql.run_query_into(db, sql.mk_select(db, in_table, full_in_table_cols,
329
            order_by=None), into=full_in_table, add_pkey_=True)
330
    
331
    if not is_literals:
332
        pkeys_names = [in_pkey, out_pkey]
333
        pkeys_cols = [in_pkey_col, out_pkey_col]
334
    
335
    pkeys_table_exists_ref = [False]
336
    def insert_into_pkeys(joins, cols, **kw_args):
337
        query = sql.mk_select(db, joins, cols, order_by=None)
338
        if pkeys_table_exists_ref[0]:
339
            sql.insert_select(db, into, pkeys_names, query, **kw_args)
340
        else:
341
            sql.run_query_into(db, query, into=into, add_pkey_=True, **kw_args)
342
            pkeys_table_exists_ref[0] = True
343
    
344
    limit_ref = [None]
345
    def mk_main_select(joins, cols):
346
        return sql.mk_select(db, joins, cols, limit=limit_ref[0], order_by=None)
347
    
348
    if is_literals: insert_in_table = None
349
    else:
350
        insert_in_table = in_table
351
        insert_in_tables = [insert_in_table]
352
    join_cols = sql_gen.ColDict(db, out_table)
353
    
354
    exc_strs = set()
355
    def log_exc(e):
356
        e_str = exc.str_(e, first_line_only=True)
357
        log_debug('Caught exception: '+e_str)
358
        assert e_str not in exc_strs # avoid infinite loops
359
        exc_strs.add(e_str)
360
    
361
    def remove_all_rows():
362
        log_debug('Ignoring all rows')
363
        limit_ref[0] = 0 # just create an empty pkeys table
364
    
365
    def ignore_cond(cond, e):
366
        out_table_cols = sql_gen.ColDict(db, out_table)
367
        out_table_cols.update(util.dict_subset_right_join({},
368
            sql.table_cols(db, out_table)))
369
        
370
        in_cols = []
371
        cond = sql.map_expr(db, cond, mapping, in_cols)
372
        cond = sql.map_expr(db, cond, out_table_cols)
373
        
374
        track_data_error(db, errors_table_, sql_gen.cols_srcs(in_cols), None,
375
            e.cause.pgcode,
376
            strings.ensure_newl(e.cause.pgerror)+'condition: '+cond)
377
        
378
        not_cond = sql_gen.NotCond(sql_gen.CustomCode(cond))
379
        log_debug('Ignoring rows where '+strings.as_tt(not_cond.to_str(db)))
380
        sql.delete(db, insert_in_table, not_cond)
381
    
382
    not_null_cols = set()
383
    def ignore(in_col, value, e):
384
        in_col = sql_gen.with_table(in_col, insert_in_table)
385
        
386
        track_data_error(db, errors_table_, in_col.srcs, value,
387
            e.cause.pgcode, e.cause.pgerror)
388
        log_debug('Ignoring rows with '+strings.as_tt(repr(in_col))+' = '
389
            +strings.as_tt(repr(value)))
390
        
391
        sql.add_index(db, in_col, insert_in_table) # enable fast filtering
392
        if value != None and in_col not in not_null_cols:
393
            # Try just mapping the value to NULL
394
            sql.update(db, insert_in_table, [(in_col, None)],
395
                sql_gen.ColValueCond(in_col, value))
396
        else:
397
            sql.delete(db, insert_in_table, sql_gen.ColValueCond(in_col, value))
398
            if value == None: not_null_cols.add(in_col)
399
    
400
    if not is_literals:
401
        def insert_pkeys_table(which):
402
            return sql_gen.Table(sql_gen.concat(in_table.name,
403
                '_insert_'+which+'_pkeys'))
404
        insert_out_pkeys = insert_pkeys_table('out')
405
        insert_in_pkeys = insert_pkeys_table('in')
406
    
407
    # Do inserts and selects
408
    while True:
409
        if limit_ref[0] == 0: # special case
410
            if is_literals: return None
411
            log_debug('Creating an empty pkeys table')
412
            cur = sql.run_query_into(db, sql.mk_select(db, out_table,
413
                [out_pkey], order_by=None, limit=0), into=insert_out_pkeys)
414
            break # don't do main case
415
        
416
        has_joins = join_cols != {}
417
        
418
        log_debug('Trying to insert new rows')
419
        
420
        # Prepare to insert new rows
421
        if is_function:
422
            log_debug('Calling function on input rows')
423
            args = dict(((k.name, v) for k, v in mapping.iteritems()))
424
            func_call = sql_gen.NamedCol(out_pkey,
425
                sql_gen.FunctionCall(out_table, **args))
426
        else:
427
            insert_args = dict(recover=True, cacheable=False)
428
            if has_joins:
429
                insert_args.update(dict(ignore=True))
430
            else:
431
                insert_args.update(dict(returning=out_pkey))
432
                if not is_literals:
433
                    insert_args.update(dict(into=insert_out_pkeys))
434
            main_select = mk_main_select([insert_in_table], [sql_gen.with_table(
435
                c, insert_in_table) for c in mapping.values()])
436
        
437
        try:
438
            cur = None
439
            if is_function:
440
                if is_literals: cur = sql.select(db, fields=[func_call])
441
                else:
442
                    insert_into_pkeys(input_joins, [in_pkey_col, func_call],
443
                        recover=True)
444
            else:
445
                cur = sql.insert_select(db, out_table, mapping.keys(),
446
                    main_select, **insert_args)
447
            break # insert successful
448
        except sql.MissingCastException, e:
449
            log_exc(e)
450
            
451
            out_col = e.col
452
            type_ = e.type
453
            
454
            log_debug('Casting '+strings.as_tt(out_col)+' input to '
455
                +strings.as_tt(type_))
456
            in_col = mapping[out_col]
457
            while True:
458
                try:
459
                    mapping[out_col] = cast_temp_col(db, type_, in_col,
460
                        errors_table_)
461
                    break # cast successful
462
                except sql.InvalidValueException, e:
463
                    log_exc(e)
464
                    
465
                    ignore(in_col, e.value, e)
466
        except sql.DuplicateKeyException, e:
467
            log_exc(e)
468
            
469
            # Different rows violating different unique constraints not
470
            # supported
471
            assert not join_cols
472
            
473
            join_cols.update(util.dict_subset_right_join(mapping, e.cols))
474
            log_debug('Ignoring existing rows, comparing on these columns:\n'
475
                +strings.as_inline_table(join_cols, ustr=col_ustr))
476
            
477
            if is_literals:
478
                return sql.value(sql.select(db, out_table, [out_pkey_col],
479
                    mapping, order_by=None))
480
            
481
            # Uniquify input table to avoid internal duplicate keys
482
            insert_in_table = sql.distinct_table(db, insert_in_table,
483
                join_cols.values())
484
            insert_in_tables.append(insert_in_table)
485
        except sql.NullValueException, e:
486
            log_exc(e)
487
            
488
            out_col, = e.cols
489
            try: in_col = mapping[out_col]
490
            except KeyError:
491
                msg = 'Missing mapping for NOT NULL column '+out_col
492
                log_debug(msg)
493
                if default == None: on_error(SyntaxError(msg)) # required col
494
                remove_all_rows()
495
            else: ignore(in_col, None, e)
496
        except sql.CheckException, e:
497
            log_exc(e)
498
            
499
            ignore_cond(e.cond, e)
500
        except sql.InvalidValueException, e:
501
            log_exc(e)
502
            
503
            for in_col in mapping.values(): ignore(in_col, e.value, e)
504
        except sql.DatabaseErrors, e:
505
            log_exc(e)
506
            
507
            log_debug('No handler for exception')
508
            on_error(e)
509
            remove_all_rows()
510
        # after exception handled, rerun loop with additional constraints
511
    
512
    if cur != None and row_ct_ref != None and cur.rowcount >= 0:
513
        row_ct_ref[0] += cur.rowcount
514
    
515
    if is_literals_or_function: pass # pkeys table already created
516
    elif has_joins:
517
        select_joins = input_joins+[sql_gen.Join(out_table, join_cols)]
518
        log_debug('Getting output table pkeys of existing/inserted rows')
519
        insert_into_pkeys(select_joins, pkeys_cols)
520
    else:
521
        sql.add_row_num(db, insert_out_pkeys) # for joining with input pkeys
522
        
523
        log_debug('Getting input table pkeys of inserted rows')
524
        # Note that mk_main_select() does not use ORDER BY. Instead, assume that
525
        # since the SELECT query is identical to the one used in INSERT SELECT,
526
        # its rows will be retrieved in the same order.
527
        sql.run_query_into(db, mk_main_select(input_joins, [in_pkey]),
528
            into=insert_in_pkeys)
529
        sql.add_row_num(db, insert_in_pkeys) # for joining with output pkeys
530
        
531
        assert sql.table_row_count(db, insert_out_pkeys) == sql.table_row_count(
532
            db, insert_in_pkeys)
533
        
534
        log_debug('Combining output and input pkeys in inserted order')
535
        pkey_joins = [insert_in_pkeys, sql_gen.Join(insert_out_pkeys,
536
            {sql.row_num_col: sql_gen.join_same_not_null})]
537
        insert_into_pkeys(pkey_joins, pkeys_names)
538
        
539
        sql.empty_temp(db, [insert_out_pkeys, insert_in_pkeys])
540
    
541
    if not is_literals_or_function:
542
        log_debug('Setting pkeys of missing rows to '
543
            +strings.as_tt(repr(default)))
544
        missing_rows_joins = [full_in_table, sql_gen.Join(into,
545
            {in_pkey: sql_gen.join_same_not_null}, sql_gen.filter_out)]
546
            # must use join_same_not_null or query will take forever
547
        insert_into_pkeys(missing_rows_joins,
548
            [sql_gen.Col(in_pkey, full_in_table),
549
            sql_gen.NamedCol(out_pkey, default)])
550
    # otherwise, there is already an entry for every row
551
    
552
    if is_literals: return sql.value(cur)
553
    else:
554
        assert (sql.table_row_count(db, into)
555
            == sql.table_row_count(db, full_in_table))
556
        
557
        sql.empty_temp(db, insert_in_tables+[full_in_table])
558
        
559
        srcs = []
560
        if is_func: srcs = sql_gen.cols_srcs(in_cols)
561
        return sql_gen.Col(out_pkey, into, srcs)
(26-26/37)