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', 'nulo']
22

    
23
def cleanup_table(db, table):
24
    table = sql_gen.as_Table(table)
25
    cols = [sql_gen.as_Col(strings.ustr(c), table)
26
        for c in sql.table_cols(db, table)]
27
    cols = filter(lambda c: sql_gen.is_text_col(db, c), cols)
28
    if not cols: return
29
    
30
    expr = 'trim(both from %s)'
31
    for null in null_strs: expr = 'nullif('+expr+', '+db.esc_value(null)+')'
32
    changes = [(v, sql_gen.CustomCode(expr % v.to_str(db))) for v in cols]
33
    
34
    while True:
35
        try:
36
            sql.update(db, table, changes, in_place=True, recover=True)
37
            break # successful
38
        except sql.NullValueException, e:
39
            db.log_debug('Caught exception: '+exc.str_(e))
40
            col, = e.cols
41
            sql.drop_not_null(db, col)
42
    
43
    db.log_debug('Vacuuming and reanalyzing table', level=1.5)
44
    sql.vacuum(db, table)
45

    
46
##### Error tracking
47

    
48
def track_data_error(db, errors_table, cols, value, error_code, error):
49
    '''
50
    @param errors_table If None, does nothing.
51
    '''
52
    if errors_table == None or cols == (): return
53
    
54
    for col in cols:
55
        try:
56
            sql.insert(db, errors_table, dict(column=col.name, value=value,
57
                error_code=error_code, error=error), recover=True,
58
                cacheable=True, log_level=4)
59
        except sql.DuplicateKeyException: pass
60

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

    
103
'''+self.return_.to_str(db)
104

    
105
def data_exception_handler(*args, **kw_args):
106
    '''Handles a data_exception by saving it or converting it to a warning.
107
    For params, see ExcToErrorsTable().
108
    '''
109
    return sql_gen.data_exception_handler(ExcToErrorsTable(*args, **kw_args))
110

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

    
151
def func_wrapper_exception_handler(db, return_, args, errors_table):
152
    '''Handles a function call's data_exceptions.
153
    Supports PL/Python functions.
154
    @param return_ See data_exception_handler()
155
    @param args [arg...] Function call's args
156
    @param errors_table See data_exception_handler()
157
    '''
158
    args = filter(sql_gen.has_srcs, args)
159
    
160
    srcs = sql_gen.cross_join_srcs(args)
161
    value = sql_gen.merge_not_null(db, ',', args)
162
    return sql_gen.NestedExcHandler(
163
        data_exception_handler(return_, srcs, errors_table, value)
164
        , sql_gen.plpythonu_error_handler
165
        )
166

    
167
def cast_temp_col(db, type_, col, errors_table=None):
168
    '''Like cast(), but creates a new column with the cast values if the input
169
    is a column.
170
    @return The new column or cast value
171
    '''
172
    def cast_(col): return cast(db, type_, col, errors_table)
173
    
174
    try: col = sql_gen.underlying_col(col)
175
    except sql_gen.NoUnderlyingTableException: return sql_gen.wrap(cast_, col)
176
    
177
    table = col.table
178
    new_col = sql_gen.suffixed_col(col, '::'+strings.first_word(type_))
179
    expr = cast_(col)
180
    
181
    # Add column
182
    new_typed_col = sql_gen.TypedCol(new_col.name, type_)
183
    sql.add_col(db, table, new_typed_col, comment=strings.urepr(col)+'::'+type_)
184
    new_col.name = new_typed_col.name # propagate any renaming
185
    
186
    sql.update(db, table, [(new_col, expr)], in_place=True, recover=True)
187
    
188
    return new_col
189

    
190
def errors_table(db, table, if_exists=True):
191
    '''
192
    @param if_exists If set, returns None if the errors table doesn't exist
193
    @return None|sql_gen.Table
194
    '''
195
    table = sql_gen.as_Table(table)
196
    if table.srcs != (): table = table.srcs[0]
197
    
198
    errors_table = sql_gen.suffixed_table(table, '.errors')
199
    if if_exists and not sql.table_exists(db, errors_table): return None
200
    return errors_table
201

    
202
def mk_errors_table(db, table):
203
    errors_table_ = errors_table(db, table, if_exists=False)
204
    if sql.table_exists(db, errors_table_, cacheable=False): return
205
    
206
    typed_cols = [
207
        sql_gen.TypedCol('column', 'text', nullable=False),
208
        sql_gen.TypedCol('value', 'text'),
209
        sql_gen.TypedCol('error_code', 'character varying(5)', nullable=False),
210
        sql_gen.TypedCol('error', 'text', nullable=False),
211
        ]
212
    sql.create_table(db, errors_table_, typed_cols, has_pkey=False)
213
    index_cols = ['column', 'value', 'error_code', 'error']
214
    sql.add_index(db, index_cols, errors_table_, unique=True)
215

    
216
##### Import
217

    
218
def put(db, table, row, pkey_=None, row_ct_ref=None):
219
    '''Recovers from errors.
220
    Only works under PostgreSQL (uses INSERT RETURNING).
221
    '''
222
    return put_table(db, table, [], row, row_ct_ref)
223

    
224
def get(db, table, row, pkey, row_ct_ref=None, create=False):
225
    '''Recovers from errors'''
226
    try:
227
        return sql.value(sql.select(db, table, [pkey], row, limit=1,
228
            recover=True))
229
    except StopIteration:
230
        if not create: raise
231
        return put(db, table, row, pkey, row_ct_ref) # insert new row
232

    
233
def is_func_result(col):
234
    return col.table.name.find('(') >= 0 and col.name == 'result'
235

    
236
def into_table_name(out_table, in_tables0, mapping, is_func):
237
    def in_col_str(in_col):
238
        in_col = sql_gen.remove_col_rename(in_col)
239
        if isinstance(in_col, sql_gen.Col):
240
            table = in_col.table
241
            if table == in_tables0:
242
                in_col = sql_gen.to_name_only_col(in_col)
243
            elif is_func_result(in_col): in_col = table # omit col name
244
        return strings.ustr(in_col)
245
    
246
    str_ = strings.ustr(out_table)
247
    if is_func:
248
        str_ += '('
249
        
250
        try: value_in_col = mapping['value']
251
        except KeyError:
252
            str_ += ', '.join((strings.ustr(k)+'='+in_col_str(v)
253
                for k, v in mapping.iteritems()))
254
        else: str_ += in_col_str(value_in_col)
255
        
256
        str_ += ')'
257
    else:
258
        out_col = 'rank'
259
        try: in_col = mapping[out_col]
260
        except KeyError: str_ += '_pkeys'
261
        else: # has a rank column, so hierarchical
262
            str_ += '['+strings.ustr(out_col)+'='+in_col_str(in_col)+']'
263
    return str_
264

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