Project

General

Profile

1
# Database import/export
2

    
3
import copy
4
import operator
5
import warnings
6

    
7
import exc
8
import dicts
9
import sql
10
import sql_gen
11
import strings
12
import util
13

    
14
##### Exceptions
15

    
16
# Can't use built-in SyntaxError because it stringifies to only the first line
17
class SyntaxError(Exception): pass
18

    
19
##### Data cleanup
20

    
21
null_strs = ['', r'\N', 'NULL', 'UNKNOWN']
22

    
23
def cleanup_table(db, table, cols):
24
    table = sql_gen.as_Table(table)
25
    cols = [sql_gen.as_Col(c, table) for c in cols]
26
    cols = filter(lambda c: sql_gen.is_text_col(db, c), cols)
27
    
28
    expr = 'trim(both from %s)'
29
    for null in null_strs: expr = 'nullif('+expr+', '+db.esc_value(null)+')'
30
    changes = [(v, sql_gen.CustomCode(expr % v.to_str(db))) for v in cols]
31
    
32
    sql.update(db, table, changes, in_place=True)
33

    
34
##### Error tracking
35

    
36
def track_data_error(db, errors_table, cols, value, error_code, error):
37
    '''
38
    @param errors_table If None, does nothing.
39
    '''
40
    if errors_table == None or cols == (): return
41
    
42
    for col in cols:
43
        try:
44
            sql.insert(db, errors_table, dict(column=col.name, value=value,
45
                error_code=error_code, error=error), recover=True,
46
                cacheable=True, log_level=4)
47
        except sql.DuplicateKeyException: pass
48

    
49
class ExcToErrorsTable(sql_gen.ExcToWarning):
50
    '''Handles an exception by saving it or converting it to a warning.'''
51
    def __init__(self, return_, srcs, errors_table, value=None):
52
        '''
53
        @param return_ See sql_gen.ExcToWarning
54
        @param srcs The column names for the errors table
55
        @param errors_table None|sql_gen.Table
56
        @param value The value (or an expression for it) that caused the error
57
        @pre The invalid value must be in a local variable "value" of type text.
58
        '''
59
        sql_gen.ExcToWarning.__init__(self, return_)
60
        
61
        value = sql_gen.as_Code(value)
62
        
63
        self.srcs = srcs
64
        self.errors_table = errors_table
65
        self.value = value
66
    
67
    def to_str(self, db):
68
        if not self.srcs or self.errors_table == None:
69
            return sql_gen.ExcToWarning.to_str(self, db)
70
        
71
        errors_table_cols = map(sql_gen.Col,
72
            ['column', 'value', 'error_code', 'error'])
73
        col_names_query = sql.mk_select(db, sql_gen.NamedValues('c', None,
74
            [[c.name] for c in self.srcs]), order_by=None)
75
        insert_query = sql.mk_insert_select(db, self.errors_table,
76
            errors_table_cols,
77
            sql_gen.Values(errors_table_cols).to_str(db))+';\n'
78
        return '''\
79
-- Save error in errors table.
80
DECLARE
81
    error_code text := SQLSTATE;
82
    error text := SQLERRM;
83
    value text := '''+self.value.to_str(db)+''';
84
    "column" text;
85
BEGIN
86
    -- Insert the value and error for *each* source column.
87
'''+strings.indent(sql_gen.RowExcIgnore(None, col_names_query, insert_query,
88
    row_var=errors_table_cols[0]).to_str(db))+'''
89
END;
90

    
91
'''+self.return_.to_str(db)
92

    
93
def data_exception_handler(*args, **kw_args):
94
    '''Handles a data_exception by saving it or converting it to a warning.
95
    For params, see ExcToErrorsTable().
96
    '''
97
    return sql_gen.data_exception_handler(ExcToErrorsTable(*args, **kw_args))
98

    
99
def cast(db, type_, col, errors_table=None):
100
    '''Casts an (unrenamed) column or value.
101
    If errors_table set and col has srcs, saves errors in errors_table (using
102
    col's srcs attr as source columns). Otherwise, converts errors to warnings.
103
    @param col str|sql_gen.Col|sql_gen.Literal
104
    @param errors_table None|sql_gen.Table|str
105
    '''
106
    col = sql_gen.as_Col(col)
107
    
108
    # Don't convert exceptions to warnings for user-supplied constants
109
    if isinstance(col, sql_gen.Literal): return sql_gen.Cast(type_, col)
110
    
111
    assert not isinstance(col, sql_gen.NamedCol)
112
    
113
    function_name = strings.first_word(type_)
114
    srcs = col.srcs
115
    save_errors = errors_table != None and srcs
116
    if save_errors: # function will be unique for the given srcs
117
        function_name = strings.ustr(sql_gen.FunctionCall(function_name,
118
            *map(sql_gen.to_name_only_col, srcs)))
119
    function = db.TempFunction(function_name)
120
    
121
    # Create function definition
122
    modifiers = 'STRICT'
123
    if not save_errors: modifiers = 'IMMUTABLE '+modifiers
124
    value_param = sql_gen.FunctionParam('value', 'text')
125
    handler = data_exception_handler('RETURN NULL;\n', srcs, errors_table,
126
        value_param.name)
127
    body = sql_gen.CustomCode(handler.to_str(db, '''\
128
/* The explicit cast to the return type is needed to make the cast happen
129
inside the try block. (Implicit casts to the return type happen at the end
130
of the function, outside any block.) */
131
RETURN value::'''+type_+''';
132
'''))
133
    body.lang='plpgsql'
134
    sql.define_func(db, sql_gen.FunctionDef(function, type_, body,
135
        [value_param], modifiers))
136
    
137
    return sql_gen.FunctionCall(function, col)
138

    
139
def func_wrapper_exception_handler(db, return_, args, errors_table):
140
    '''Handles a function call's data_exceptions.
141
    Supports PL/Python functions.
142
    @param return_ See data_exception_handler()
143
    @param args [arg...] Function call's args
144
    @param errors_table See data_exception_handler()
145
    '''
146
    args = filter(sql_gen.has_srcs, args)
147
    
148
    srcs = sql_gen.cross_join_srcs(args)
149
    value = sql_gen.merge_not_null(db, ',', args)
150
    return sql_gen.NestedExcHandler(
151
        data_exception_handler(return_, srcs, errors_table, value)
152
        , sql_gen.plpythonu_error_handler
153
        )
154

    
155
def cast_temp_col(db, type_, col, errors_table=None):
156
    '''Like cast(), but creates a new column with the cast values if the input
157
    is a column.
158
    @return The new column or cast value
159
    '''
160
    def cast_(col): return cast(db, type_, col, errors_table)
161
    
162
    try: col = sql_gen.underlying_col(col)
163
    except sql_gen.NoUnderlyingTableException: return sql_gen.wrap(cast_, col)
164
    
165
    table = col.table
166
    new_col = sql_gen.suffixed_col(col, '::'+strings.first_word(type_))
167
    expr = cast_(col)
168
    
169
    # Add column
170
    new_typed_col = sql_gen.TypedCol(new_col.name, type_)
171
    sql.add_col(db, table, new_typed_col, comment=strings.urepr(col)+'::'+type_)
172
    new_col.name = new_typed_col.name # propagate any renaming
173
    
174
    sql.update(db, table, [(new_col, expr)], in_place=True, recover=True)
175
    
176
    return new_col
177

    
178
def errors_table(db, table, if_exists=True):
179
    '''
180
    @param if_exists If set, returns None if the errors table doesn't exist
181
    @return None|sql_gen.Table
182
    '''
183
    table = sql_gen.as_Table(table)
184
    if table.srcs != (): table = table.srcs[0]
185
    
186
    errors_table = sql_gen.suffixed_table(table, '.errors')
187
    if if_exists and not sql.table_exists(db, errors_table): return None
188
    return errors_table
189

    
190
def mk_errors_table(db, table):
191
    errors_table_ = errors_table(db, table, if_exists=False)
192
    if sql.table_exists(db, errors_table_): return
193
    
194
    typed_cols = [
195
        sql_gen.TypedCol('column', 'text', nullable=False),
196
        sql_gen.TypedCol('value', 'text'),
197
        sql_gen.TypedCol('error_code', 'character varying(5)', nullable=False),
198
        sql_gen.TypedCol('error', 'text', nullable=False),
199
        ]
200
    sql.create_table(db, errors_table_, typed_cols, has_pkey=False)
201
    index_cols = ['column', 'value', 'error_code', 'error']
202
    sql.add_index(db, index_cols, errors_table_, unique=True)
203

    
204
##### Import
205

    
206
def put(db, table, row, pkey_=None, row_ct_ref=None):
207
    '''Recovers from errors.
208
    Only works under PostgreSQL (uses INSERT RETURNING).
209
    '''
210
    return put_table(db, table, [], row, row_ct_ref)
211

    
212
def get(db, table, row, pkey, row_ct_ref=None, create=False):
213
    '''Recovers from errors'''
214
    try:
215
        return sql.value(sql.select(db, table, [pkey], row, limit=1,
216
            recover=True))
217
    except StopIteration:
218
        if not create: raise
219
        return put(db, table, row, pkey, row_ct_ref) # insert new row
220

    
221
def is_func_result(col):
222
    return col.table.name.find('(') >= 0 and col.name == 'result'
223

    
224
def into_table_name(out_table, in_tables0, mapping, is_func):
225
    def in_col_str(in_col):
226
        in_col = sql_gen.remove_col_rename(in_col)
227
        if isinstance(in_col, sql_gen.Col):
228
            table = in_col.table
229
            if table == in_tables0:
230
                in_col = sql_gen.to_name_only_col(in_col)
231
            elif is_func_result(in_col): in_col = table # omit col name
232
        return strings.ustr(in_col)
233
    
234
    str_ = str(out_table)
235
    if is_func:
236
        str_ += '('
237
        
238
        try: value_in_col = mapping['value']
239
        except KeyError:
240
            str_ += ', '.join((str(k)+'='+in_col_str(v)
241
                for k, v in mapping.iteritems()))
242
        else: str_ += in_col_str(value_in_col)
243
        
244
        str_ += ')'
245
    else:
246
        out_col = 'rank'
247
        try: in_col = mapping[out_col]
248
        except KeyError: str_ += '_pkeys'
249
        else: # has a rank column, so hierarchical
250
            str_ += '['+str(out_col)+'='+in_col_str(in_col)+']'
251
    return str_
252

    
253
def put_table(db, out_table, in_tables, mapping, row_ct_ref=None, default=None,
254
    col_defaults={}, on_error=exc.reraise):
255
    '''Recovers from errors.
256
    Only works under PostgreSQL (uses INSERT RETURNING).
257
    IMPORTANT: Must be run at the *beginning* of a transaction.
258
    @param in_tables The main input table to select from, followed by a list of
259
        tables to join with it using the main input table's pkey
260
    @param mapping dict(out_table_col=in_table_col, ...)
261
        * out_table_col: str (*not* sql_gen.Col)
262
        * in_table_col: sql_gen.Col|literal-value
263
    @param default The *output* column to use as the pkey for missing rows.
264
        If this output column does not exist in the mapping, uses None.
265
    @param col_defaults Default values for required columns.
266
    @return sql_gen.Col Where the output pkeys are made available
267
    '''
268
    import psycopg2.extensions
269
    
270
    out_table = sql_gen.as_Table(out_table)
271
    
272
    def log_debug(msg): db.log_debug(msg, level=1.5)
273
    def col_ustr(str_):
274
        return strings.repr_no_u(sql_gen.remove_col_rename(str_))
275
    
276
    log_debug('********** New iteration **********')
277
    log_debug('Inserting these input columns into '+strings.as_tt(
278
        out_table.to_str(db))+':\n'+strings.as_table(mapping, ustr=col_ustr))
279
    
280
    is_function = sql.function_exists(db, out_table)
281
    
282
    if is_function: out_pkey = 'result'
283
    else: out_pkey = sql.pkey(db, out_table, recover=True)
284
    out_pkey_col = sql_gen.as_Col(out_pkey, out_table)
285
    
286
    in_tables_ = in_tables[:] # don't modify input!
287
    try: in_tables0 = in_tables_.pop(0) # first table is separate
288
    except IndexError: in_tables0 = None
289
    else:
290
        in_pkey = sql.pkey(db, in_tables0, recover=True)
291
        in_pkey_col = sql_gen.as_Col(in_pkey, in_tables0)
292
    
293
    # Determine if can use optimization for only literal values
294
    is_literals = not reduce(operator.or_, map(sql_gen.is_table_col,
295
        mapping.values()), False)
296
    is_literals_or_function = is_literals or is_function
297
    
298
    if in_tables0 == None: errors_table_ = None
299
    else: errors_table_ = errors_table(db, in_tables0)
300
    
301
    # Create input joins from list of input tables
302
    input_joins = [in_tables0]+[sql_gen.Join(v,
303
        {in_pkey: sql_gen.join_same_not_null}) for v in in_tables_]
304
    
305
    if mapping == {} and not is_function: # need >= one column for INSERT SELECT
306
        mapping = {out_pkey: None} # ColDict will replace with default value
307
    
308
    if not is_literals:
309
        into = sql_gen.as_Table(into_table_name(out_table, in_tables0, mapping,
310
            is_function))
311
        
312
        # Set column sources
313
        in_cols = filter(sql_gen.is_table_col, mapping.values())
314
        for col in in_cols:
315
            if col.table == in_tables0: col.set_srcs(sql_gen.src_self)
316
        
317
        log_debug('Joining together input tables into temp table')
318
        # Place in new table so don't modify input and for speed
319
        in_table = sql_gen.Table('in')
320
        mapping = dicts.join(mapping, sql.flatten(db, in_table, input_joins,
321
            in_cols, preserve=[in_pkey_col]))
322
        input_joins = [in_table]
323
        db.log_debug('Temp table: '+strings.as_tt(in_table.to_str(db)), level=2)
324
    
325
    # Wrap mapping in a sql_gen.ColDict.
326
    # sql_gen.ColDict sanitizes both keys and values passed into it.
327
    # Do after applying dicts.join() because that returns a plain dict.
328
    mapping = sql_gen.ColDict(db, out_table, mapping)
329
    
330
    # Resolve default value column
331
    if default != None:
332
        try: default = mapping[default]
333
        except KeyError:
334
            db.log_debug('Default value column '
335
                +strings.as_tt(strings.repr_no_u(default))
336
                +' does not exist in mapping, falling back to None', level=2.1)
337
            default = None
338
    
339
    # Save default values for all rows since in_table may have rows deleted
340
    if is_literals: pass
341
    elif is_function: full_in_table = in_table
342
    else:
343
        full_in_table = sql_gen.suffixed_table(in_table, '_full')
344
        full_in_table_cols = [in_pkey_col]
345
        if default != None:
346
            full_in_table_cols.append(default)
347
            default = sql_gen.with_table(default, full_in_table)
348
        sql.run_query_into(db, sql.mk_select(db, in_table, full_in_table_cols,
349
            order_by=None), into=full_in_table, add_pkey_=True)
350
    
351
    if not is_literals:
352
        pkeys_names = [in_pkey, out_pkey]
353
        pkeys_cols = [in_pkey_col, out_pkey_col]
354
    
355
    pkeys_table_exists_ref = [False]
356
    def insert_into_pkeys(joins, cols=None, limit=None, **kw_args):
357
        query = sql.mk_select(db, joins, cols, order_by=None, limit=limit)
358
        if pkeys_table_exists_ref[0]:
359
            sql.insert_select(db, into, pkeys_names, query, **kw_args)
360
        else:
361
            sql.run_query_into(db, query, into=into, add_pkey_=True, **kw_args)
362
            pkeys_table_exists_ref[0] = True
363
    
364
    limit_ref = [None]
365
    def mk_main_select(joins, cols):
366
        return sql.mk_select(db, joins, cols, limit=limit_ref[0], order_by=None)
367
    
368
    if is_literals: insert_in_table = None
369
    else:
370
        insert_in_table = in_table
371
        insert_in_tables = [insert_in_table]
372
    join_cols = sql_gen.ColDict(db, out_table)
373
    
374
    exc_strs = set()
375
    def log_exc(e):
376
        e_str = exc.str_(e, first_line_only=True)
377
        log_debug('Caught exception: '+e_str)
378
        if e_str in exc_strs: # avoid infinite loops
379
            log_debug('Exception already seen, handler broken')
380
            on_error(e)
381
            remove_all_rows()
382
        else: exc_strs.add(e_str)
383
    
384
    def remove_all_rows():
385
        log_debug('Ignoring all rows')
386
        limit_ref[0] = 0 # just create an empty pkeys table
387
    
388
    def ignore_cond(cond, e):
389
        if is_literals: remove_all_rows()
390
        else:
391
            out_table_cols = sql_gen.ColDict(db, out_table)
392
            out_table_cols.update(util.dict_subset_right_join({},
393
                sql.table_cols(db, out_table)))
394
            
395
            in_cols = []
396
            cond = sql.map_expr(db, cond, mapping, in_cols)
397
            cond = sql.map_expr(db, cond, out_table_cols)
398
            
399
            track_data_error(db, errors_table_, sql_gen.cols_srcs(in_cols),
400
                None, e.cause.pgcode,
401
                strings.ensure_newl(e.cause.pgerror)+'condition: '+cond)
402
            
403
            not_cond = sql_gen.NotCond(sql_gen.CustomCode(cond))
404
            log_debug('Ignoring rows where '+strings.as_tt(not_cond.to_str(db)))
405
            sql.delete(db, insert_in_table, not_cond)
406
    
407
    not_null_cols = set()
408
    def ignore(in_col, value, e):
409
        if sql_gen.is_table_col(in_col):
410
            in_col = sql_gen.with_table(in_col, insert_in_table)
411
            
412
            track_data_error(db, errors_table_, in_col.srcs, value,
413
                e.cause.pgcode, e.cause.pgerror)
414
            
415
            sql.add_index(db, in_col, insert_in_table) # enable fast filtering
416
            if value != None and in_col not in not_null_cols:
417
                log_debug('Replacing invalid value '+strings.as_tt(repr(value))
418
                    +' with NULL in column '+strings.as_tt(in_col.to_str(db)))
419
                sql.update(db, insert_in_table, [(in_col, None)],
420
                    sql_gen.ColValueCond(in_col, value))
421
            else:
422
                log_debug('Ignoring rows with '+strings.as_tt(in_col.to_str(db))
423
                    +' = '+strings.as_tt(repr(value)))
424
                sql.delete(db, insert_in_table,
425
                    sql_gen.ColValueCond(in_col, value))
426
                if value == None: not_null_cols.add(in_col)
427
        else:
428
            assert isinstance(in_col, sql_gen.NamedCol)
429
            in_value = sql_gen.remove_col_rename(in_col)
430
            assert sql_gen.is_literal(in_value)
431
            if value == in_value.value:
432
                if value != None:
433
                    log_debug('Replacing invalid literal '
434
                        +strings.as_tt(in_col.to_str(db))+' with NULL')
435
                    mapping[in_col.name] = None
436
                else:
437
                    remove_all_rows()
438
            # otherwise, all columns were being ignore()d because the specific
439
            # column couldn't be identified, and this was not the invalid column
440
    
441
    if not is_literals:
442
        def insert_pkeys_table(which):
443
            return sql_gen.Table(sql_gen.concat(in_table.name,
444
                '_insert_'+which+'_pkeys'))
445
        insert_out_pkeys = insert_pkeys_table('out')
446
        insert_in_pkeys = insert_pkeys_table('in')
447
    
448
    def mk_func_call():
449
        args = dict(((k.name, v) for k, v in mapping.iteritems()))
450
        func_call = sql_gen.NamedCol(out_pkey,
451
            sql_gen.FunctionCall(out_table, **args))
452
        return func_call, args
453
        
454
    if is_function and not is_literals:
455
        log_debug('Defining wrapper function')
456
        
457
        func_call, args = mk_func_call()
458
        
459
        # Create empty pkeys table so its row type can be used
460
        insert_into_pkeys(input_joins, [in_pkey_col, func_call], limit=0,
461
            recover=True)
462
        result_type = db.col_info(sql_gen.Col(out_pkey, into)).type
463
        
464
        ## Create error handling wrapper function
465
        
466
        wrapper = db.TempFunction(sql_gen.concat(into.name, '_wrap'))
467
        
468
        select_cols = [in_pkey_col]+args.values()
469
        row_var = copy.copy(sql_gen.row_var)
470
        row_var.set_srcs([in_table])
471
        in_pkey_var = sql_gen.Col(in_pkey, row_var)
472
        
473
        args = dict(((k, sql_gen.with_table(v, row_var))
474
            for k, v in args.iteritems()))
475
        func_call = sql_gen.FunctionCall(out_table, **args)
476
        
477
        def mk_return(result):
478
            return sql_gen.ReturnQuery(sql.mk_select(db,
479
                fields=[in_pkey_var, result], explain=False))
480
        exc_handler = func_wrapper_exception_handler(db,
481
            mk_return(sql_gen.Cast(result_type, None)), args.values(),
482
            errors_table_)
483
        
484
        sql.define_func(db, sql_gen.FunctionDef(wrapper, sql_gen.SetOf(into),
485
            sql_gen.RowExcIgnore(sql_gen.RowType(in_table),
486
                sql.mk_select(db, input_joins, order_by=None),
487
                mk_return(func_call), exc_handler=exc_handler)
488
            ))
489
        wrapper_table = sql_gen.FunctionCall(wrapper)
490
    
491
    # Do inserts and selects
492
    while True:
493
        has_joins = join_cols != {}
494
        
495
        # Handle unrecoverable errors in a special case
496
        if limit_ref[0] == 0:
497
            if is_literals or default == None:
498
                default = sql_gen.remove_col_rename(default)
499
                log_debug('Returning default: '+strings.as_tt(repr(default)))
500
                return default
501
            elif is_function: pass # empty pkeys table already created
502
            else:
503
                log_debug('Creating an empty output pkeys table')
504
                has_joins = False # use the no-joins case
505
                cur = sql.run_query_into(db, sql.mk_select(db, out_table,
506
                    [out_pkey], order_by=None, limit=0), into=insert_out_pkeys)
507
            
508
            break # don't do main case
509
        
510
        # Prepare to insert new rows
511
        if is_function:
512
            log_debug('Calling function on input rows')
513
            if is_literals: func_call, args = mk_func_call()
514
        else:
515
            log_debug('Trying to insert new rows')
516
            insert_args = dict(recover=True, cacheable=False)
517
            if has_joins:
518
                insert_args.update(dict(ignore=True))
519
            else:
520
                insert_args.update(dict(returning=out_pkey))
521
                if not is_literals:
522
                    insert_args.update(dict(into=insert_out_pkeys))
523
            main_select = mk_main_select([insert_in_table], [sql_gen.with_table(
524
                c, insert_in_table) for c in mapping.values()])
525
        
526
        try:
527
            cur = None
528
            if is_function:
529
                if is_literals:
530
                    cur = sql.select(db, fields=[func_call], recover=True,
531
                        cacheable=True)
532
                else: insert_into_pkeys(wrapper_table, recover=True)
533
            else:
534
                cur = sql.insert_select(db, out_table, mapping.keys(),
535
                    main_select, **insert_args)
536
            break # insert successful
537
        except sql.MissingCastException, e:
538
            log_exc(e)
539
            
540
            type_ = e.type
541
            if e.col == None: out_cols = mapping.keys()
542
            else: out_cols = [e.col]
543
            
544
            for out_col in out_cols:
545
                log_debug('Casting '+strings.as_tt(strings.repr_no_u(out_col))
546
                    +' input to '+strings.as_tt(type_))
547
                in_col = mapping[out_col]
548
                while True:
549
                    try:
550
                        mapping[out_col] = cast_temp_col(db, type_, in_col,
551
                            errors_table_)
552
                        break # cast successful
553
                    except sql.InvalidValueException, e:
554
                        log_exc(e)
555
                        
556
                        ignore(in_col, e.value, e)
557
        except sql.DuplicateKeyException, e:
558
            log_exc(e)
559
            
560
            # Different rows violating different unique constraints not
561
            # supported
562
            assert not join_cols
563
            
564
            join_cols.update(util.dict_subset_right_join(mapping, e.cols))
565
            log_debug('Ignoring existing rows, comparing on these columns:\n'
566
                +strings.as_inline_table(join_cols, ustr=col_ustr))
567
            
568
            if is_literals:
569
                return sql.value(sql.select(db, out_table, [out_pkey_col],
570
                    join_cols, order_by=None))
571
            
572
            # Uniquify input table to avoid internal duplicate keys
573
            insert_in_table = sql.distinct_table(db, insert_in_table,
574
                join_cols.values())
575
            insert_in_tables.append(insert_in_table)
576
        except sql.NullValueException, e:
577
            log_exc(e)
578
            
579
            out_col, = e.cols
580
            try: in_col = mapping[out_col]
581
            except KeyError, e:
582
                try: in_col = mapping[out_col] = col_defaults[out_col]
583
                except KeyError:
584
                    msg = 'Missing mapping for NOT NULL column '+out_col
585
                    log_debug(msg)
586
                    if default == None: warnings.warn(UserWarning(msg))
587
                        # not an error because sometimes the mappings include
588
                        # extra tables which aren't used by the dataset
589
                    remove_all_rows()
590
            else: ignore(in_col, None, e)
591
        except sql.CheckException, e:
592
            log_exc(e)
593
            
594
            ignore_cond(e.cond, e)
595
        except sql.InvalidValueException, e:
596
            log_exc(e)
597
            
598
            for in_col in mapping.values(): ignore(in_col, e.value, e)
599
        except psycopg2.extensions.TransactionRollbackError, e:
600
            log_exc(e)
601
            # retry
602
        except sql.DatabaseErrors, e:
603
            log_exc(e)
604
            
605
            log_debug('No handler for exception')
606
            on_error(e)
607
            remove_all_rows()
608
        # after exception handled, rerun loop with additional constraints
609
    
610
    if cur != None and row_ct_ref != None and cur.rowcount >= 0:
611
        row_ct_ref[0] += cur.rowcount
612
    
613
    if is_literals: return sql.value(cur)
614
    
615
    if is_function: pass # pkeys table already created
616
    elif has_joins:
617
        select_joins = input_joins+[sql_gen.Join(out_table, join_cols)]
618
        log_debug('Getting output table pkeys of existing/inserted rows')
619
        insert_into_pkeys(select_joins, pkeys_cols)
620
    else:
621
        sql.add_row_num(db, insert_out_pkeys) # for joining with input pkeys
622
        
623
        log_debug('Getting input table pkeys of inserted rows')
624
        # Note that mk_main_select() does not use ORDER BY. Instead, assume that
625
        # since the SELECT query is identical to the one used in INSERT SELECT,
626
        # its rows will be retrieved in the same order.
627
        sql.run_query_into(db, mk_main_select(input_joins, [in_pkey]),
628
            into=insert_in_pkeys)
629
        sql.add_row_num(db, insert_in_pkeys) # for joining with output pkeys
630
        
631
        assert sql.table_row_count(db, insert_out_pkeys) == sql.table_row_count(
632
            db, insert_in_pkeys)
633
        
634
        log_debug('Combining output and input pkeys in inserted order')
635
        pkey_joins = [insert_in_pkeys, sql_gen.Join(insert_out_pkeys,
636
            {sql.row_num_col: sql_gen.join_same_not_null})]
637
        insert_into_pkeys(pkey_joins, pkeys_names)
638
        
639
        sql.empty_temp(db, [insert_out_pkeys, insert_in_pkeys])
640
    
641
    if limit_ref[0] == 0 or not is_function: # is_function doesn't leave holes
642
        log_debug('Setting pkeys of missing rows to '
643
            +strings.as_tt(repr(default)))
644
        missing_rows_joins = [full_in_table, sql_gen.Join(into,
645
            {in_pkey: sql_gen.join_same_not_null}, sql_gen.filter_out)]
646
            # must use join_same_not_null or query will take forever
647
        insert_into_pkeys(missing_rows_joins,
648
            [sql_gen.Col(in_pkey, full_in_table),
649
            sql_gen.NamedCol(out_pkey, default)])
650
    # otherwise, there is already an entry for every row
651
    
652
    assert (sql.table_row_count(db, into)
653
        == sql.table_row_count(db, full_in_table))
654
    
655
    sql.empty_temp(db, insert_in_tables+[full_in_table])
656
    
657
    srcs = []
658
    if is_function: srcs = sql_gen.cols_srcs(in_cols)
659
    return sql_gen.Col(out_pkey, into, srcs)
(29-29/40)