Project

General

Profile

1
# Database access
2

    
3
import copy
4
import re
5
import warnings
6

    
7
import exc
8
import dicts
9
import iters
10
import lists
11
from Proxy import Proxy
12
import rand
13
import sql_gen
14
import strings
15
import util
16

    
17
##### Exceptions
18

    
19
def get_cur_query(cur, input_query=None):
20
    raw_query = None
21
    if hasattr(cur, 'query'): raw_query = cur.query
22
    elif hasattr(cur, '_last_executed'): raw_query = cur._last_executed
23
    
24
    if raw_query != None: return raw_query
25
    else: return '[input] '+strings.ustr(input_query)
26

    
27
def _add_cursor_info(e, *args, **kw_args):
28
    '''For params, see get_cur_query()'''
29
    exc.add_msg(e, 'query: '+strings.ustr(get_cur_query(*args, **kw_args)))
30

    
31
class DbException(exc.ExceptionWithCause):
32
    def __init__(self, msg, cause=None, cur=None):
33
        exc.ExceptionWithCause.__init__(self, msg, cause, cause_newline=True)
34
        if cur != None: _add_cursor_info(self, cur)
35

    
36
class ExceptionWithName(DbException):
37
    def __init__(self, name, cause=None):
38
        DbException.__init__(self, 'for name: '+strings.as_tt(str(name)), cause)
39
        self.name = name
40

    
41
class ExceptionWithValue(DbException):
42
    def __init__(self, value, cause=None):
43
        DbException.__init__(self, 'for value: '+strings.as_tt(repr(value)),
44
            cause)
45
        self.value = value
46

    
47
class ExceptionWithNameType(DbException):
48
    def __init__(self, type_, name, cause=None):
49
        DbException.__init__(self, 'for type: '+strings.as_tt(str(type_))
50
            +'; name: '+strings.as_tt(name), cause)
51
        self.type = type_
52
        self.name = name
53

    
54
class ConstraintException(DbException):
55
    def __init__(self, name, cols, cause=None):
56
        DbException.__init__(self, 'Violated '+strings.as_tt(name)
57
            +' constraint on columns: '+strings.as_tt(', '.join(cols)), cause)
58
        self.name = name
59
        self.cols = cols
60

    
61
class MissingCastException(DbException):
62
    def __init__(self, type_, col, cause=None):
63
        DbException.__init__(self, 'Missing cast to type '+strings.as_tt(type_)
64
            +' on column: '+strings.as_tt(col), cause)
65
        self.type = type_
66
        self.col = col
67

    
68
class NameException(DbException): pass
69

    
70
class DuplicateKeyException(ConstraintException): pass
71

    
72
class NullValueException(ConstraintException): pass
73

    
74
class InvalidValueException(ExceptionWithValue): pass
75

    
76
class DuplicateException(ExceptionWithNameType): pass
77

    
78
class EmptyRowException(DbException): pass
79

    
80
##### Warnings
81

    
82
class DbWarning(UserWarning): pass
83

    
84
##### Result retrieval
85

    
86
def col_names(cur): return (col[0] for col in cur.description)
87

    
88
def rows(cur): return iter(lambda: cur.fetchone(), None)
89

    
90
def consume_rows(cur):
91
    '''Used to fetch all rows so result will be cached'''
92
    iters.consume_iter(rows(cur))
93

    
94
def next_row(cur): return rows(cur).next()
95

    
96
def row(cur):
97
    row_ = next_row(cur)
98
    consume_rows(cur)
99
    return row_
100

    
101
def next_value(cur): return next_row(cur)[0]
102

    
103
def value(cur): return row(cur)[0]
104

    
105
def values(cur): return iters.func_iter(lambda: next_value(cur))
106

    
107
def value_or_none(cur):
108
    try: return value(cur)
109
    except StopIteration: return None
110

    
111
##### Escaping
112

    
113
def esc_name_by_module(module, name):
114
    if module == 'psycopg2' or module == None: quote = '"'
115
    elif module == 'MySQLdb': quote = '`'
116
    else: raise NotImplementedError("Can't escape name for "+module+' database')
117
    return sql_gen.esc_name(name, quote)
118

    
119
def esc_name_by_engine(engine, name, **kw_args):
120
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
121

    
122
def esc_name(db, name, **kw_args):
123
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
124

    
125
def qual_name(db, schema, table):
126
    def esc_name_(name): return esc_name(db, name)
127
    table = esc_name_(table)
128
    if schema != None: return esc_name_(schema)+'.'+table
129
    else: return table
130

    
131
##### Database connections
132

    
133
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
134

    
135
db_engines = {
136
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
137
    'PostgreSQL': ('psycopg2', {}),
138
}
139

    
140
DatabaseErrors_set = set([DbException])
141
DatabaseErrors = tuple(DatabaseErrors_set)
142

    
143
def _add_module(module):
144
    DatabaseErrors_set.add(module.DatabaseError)
145
    global DatabaseErrors
146
    DatabaseErrors = tuple(DatabaseErrors_set)
147

    
148
def db_config_str(db_config):
149
    return db_config['engine']+' database '+db_config['database']
150

    
151
log_debug_none = lambda msg, level=2: None
152

    
153
class DbConn:
154
    def __init__(self, db_config, autocommit=True, caching=True,
155
        log_debug=log_debug_none, debug_temp=False):
156
        '''
157
        @param debug_temp Whether temporary objects should instead be permanent.
158
            This assists in debugging the internal objects used by the program.
159
        '''
160
        self.db_config = db_config
161
        self.autocommit = autocommit
162
        self.caching = caching
163
        self.log_debug = log_debug
164
        self.debug = log_debug != log_debug_none
165
        self.debug_temp = debug_temp
166
        self.autoanalyze = False
167
        
168
        self._savepoint = 0
169
        self._reset()
170
    
171
    def __getattr__(self, name):
172
        if name == '__dict__': raise Exception('getting __dict__')
173
        if name == 'db': return self._db()
174
        else: raise AttributeError()
175
    
176
    def __getstate__(self):
177
        state = copy.copy(self.__dict__) # shallow copy
178
        state['log_debug'] = None # don't pickle the debug callback
179
        state['_DbConn__db'] = None # don't pickle the connection
180
        return state
181
    
182
    def clear_cache(self): self.query_results = {}
183
    
184
    def _reset(self):
185
        self.clear_cache()
186
        assert self._savepoint == 0
187
        self._notices_seen = set()
188
        self.__db = None
189
    
190
    def connected(self): return self.__db != None
191
    
192
    def close(self):
193
        if not self.connected(): return
194
        
195
        # Record that the automatic transaction is now closed
196
        self._savepoint -= 1
197
        
198
        self.db.close()
199
        self._reset()
200
    
201
    def reconnect(self):
202
        # Do not do this in test mode as it would roll back everything
203
        if self.autocommit: self.close()
204
        # Connection will be reopened automatically on first query
205
    
206
    def _db(self):
207
        if self.__db == None:
208
            # Process db_config
209
            db_config = self.db_config.copy() # don't modify input!
210
            schemas = db_config.pop('schemas', None)
211
            module_name, mappings = db_engines[db_config.pop('engine')]
212
            module = __import__(module_name)
213
            _add_module(module)
214
            for orig, new in mappings.iteritems():
215
                try: util.rename_key(db_config, orig, new)
216
                except KeyError: pass
217
            
218
            # Connect
219
            self.__db = module.connect(**db_config)
220
            
221
            # Record that a transaction is already open
222
            self._savepoint += 1
223
            
224
            # Configure connection
225
            if hasattr(self.db, 'set_isolation_level'):
226
                import psycopg2.extensions
227
                self.db.set_isolation_level(
228
                    psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED)
229
            if schemas != None:
230
                search_path = [self.esc_name(s) for s in schemas.split(',')]
231
                search_path.append(value(run_query(self, 'SHOW search_path',
232
                    log_level=4)))
233
                run_query(self, 'SET search_path TO '+(','.join(search_path)),
234
                    log_level=3)
235
        
236
        return self.__db
237
    
238
    class DbCursor(Proxy):
239
        def __init__(self, outer):
240
            Proxy.__init__(self, outer.db.cursor())
241
            self.outer = outer
242
            self.query_results = outer.query_results
243
            self.query_lookup = None
244
            self.result = []
245
        
246
        def execute(self, query):
247
            self._is_insert = query.startswith('INSERT')
248
            self.query_lookup = query
249
            try:
250
                try:
251
                    cur = self.inner.execute(query)
252
                    self.outer.do_autocommit()
253
                finally: self.query = get_cur_query(self.inner, query)
254
            except Exception, e:
255
                _add_cursor_info(e, self, query)
256
                self.result = e # cache the exception as the result
257
                self._cache_result()
258
                raise
259
            
260
            # Always cache certain queries
261
            if query.startswith('CREATE') or query.startswith('ALTER'):
262
                # structural changes
263
                # Rest of query must be unique in the face of name collisions,
264
                # so don't cache ADD COLUMN unless it has distinguishing comment
265
                if query.find('ADD COLUMN') < 0 or query.endswith('*/'):
266
                    self._cache_result()
267
            elif self.rowcount == 0 and query.startswith('SELECT'): # empty
268
                consume_rows(self) # fetch all rows so result will be cached
269
            
270
            return cur
271
        
272
        def fetchone(self):
273
            row = self.inner.fetchone()
274
            if row != None: self.result.append(row)
275
            # otherwise, fetched all rows
276
            else: self._cache_result()
277
            return row
278
        
279
        def _cache_result(self):
280
            # For inserts that return a result set, don't cache result set since
281
            # inserts are not idempotent. Other non-SELECT queries don't have
282
            # their result set read, so only exceptions will be cached (an
283
            # invalid query will always be invalid).
284
            if self.query_results != None and (not self._is_insert
285
                or isinstance(self.result, Exception)):
286
                
287
                assert self.query_lookup != None
288
                self.query_results[self.query_lookup] = self.CacheCursor(
289
                    util.dict_subset(dicts.AttrsDictView(self),
290
                    ['query', 'result', 'rowcount', 'description']))
291
        
292
        class CacheCursor:
293
            def __init__(self, cached_result): self.__dict__ = cached_result
294
            
295
            def execute(self, *args, **kw_args):
296
                if isinstance(self.result, Exception): raise self.result
297
                # otherwise, result is a rows list
298
                self.iter = iter(self.result)
299
            
300
            def fetchone(self):
301
                try: return self.iter.next()
302
                except StopIteration: return None
303
    
304
    def esc_value(self, value):
305
        try: str_ = self.mogrify('%s', [value])
306
        except NotImplementedError, e:
307
            module = util.root_module(self.db)
308
            if module == 'MySQLdb':
309
                import _mysql
310
                str_ = _mysql.escape_string(value)
311
            else: raise e
312
        return strings.to_unicode(str_)
313
    
314
    def esc_name(self, name): return esc_name(self, name) # calls global func
315
    
316
    def std_code(self, str_):
317
        '''Standardizes SQL code.
318
        * Ensures that string literals are prefixed by `E`
319
        '''
320
        if str_.startswith("'"): str_ = 'E'+str_
321
        return str_
322
    
323
    def can_mogrify(self):
324
        module = util.root_module(self.db)
325
        return module == 'psycopg2'
326
    
327
    def mogrify(self, query, params=None):
328
        if self.can_mogrify(): return self.db.cursor().mogrify(query, params)
329
        else: raise NotImplementedError("Can't mogrify query")
330
    
331
    def print_notices(self):
332
        if hasattr(self.db, 'notices'):
333
            for msg in self.db.notices:
334
                if msg not in self._notices_seen:
335
                    self._notices_seen.add(msg)
336
                    self.log_debug(msg, level=2)
337
    
338
    def run_query(self, query, cacheable=False, log_level=2,
339
        debug_msg_ref=None):
340
        '''
341
        @param log_ignore_excs The log_level will be increased by 2 if the query
342
            throws one of these exceptions.
343
        @param debug_msg_ref If specified, the log message will be returned in
344
            this instead of being output. This allows you to filter log messages
345
            depending on the result of the query.
346
        '''
347
        assert query != None
348
        
349
        if not self.caching: cacheable = False
350
        used_cache = False
351
        
352
        def log_msg(query):
353
            if used_cache: cache_status = 'cache hit'
354
            elif cacheable: cache_status = 'cache miss'
355
            else: cache_status = 'non-cacheable'
356
            return 'DB query: '+cache_status+':\n'+strings.as_code(query, 'SQL')
357
        
358
        try:
359
            # Get cursor
360
            if cacheable:
361
                try:
362
                    cur = self.query_results[query]
363
                    used_cache = True
364
                except KeyError: cur = self.DbCursor(self)
365
            else: cur = self.db.cursor()
366
            
367
            # Log query
368
            if self.debug and debug_msg_ref == None: # log before running
369
                self.log_debug(log_msg(query), log_level)
370
            
371
            # Run query
372
            cur.execute(query)
373
        finally:
374
            self.print_notices()
375
            if self.debug and debug_msg_ref != None: # return after running
376
                debug_msg_ref[0] = log_msg(str(get_cur_query(cur, query)))
377
        
378
        return cur
379
    
380
    def is_cached(self, query): return query in self.query_results
381
    
382
    def with_autocommit(self, func):
383
        import psycopg2.extensions
384
        
385
        prev_isolation_level = self.db.isolation_level
386
        self.db.set_isolation_level(
387
            psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
388
        try: return func()
389
        finally: self.db.set_isolation_level(prev_isolation_level)
390
    
391
    def with_savepoint(self, func):
392
        top = self._savepoint == 0
393
        savepoint = 'level_'+str(self._savepoint)
394
        
395
        # Must happen before running queries so they don't get autocommitted
396
        self._savepoint += 1
397
        
398
        if top: query = 'START TRANSACTION ISOLATION LEVEL READ COMMITTED'
399
        else: query = 'SAVEPOINT '+savepoint
400
        self.run_query(query, log_level=4)
401
        try:
402
            return func()
403
            if top: self.run_query('COMMIT', log_level=4)
404
        except:
405
            if top: query = 'ROLLBACK'
406
            else: query = 'ROLLBACK TO SAVEPOINT '+savepoint
407
            self.run_query(query, log_level=4)
408
            
409
            raise
410
        finally:
411
            # Always release savepoint, because after ROLLBACK TO SAVEPOINT,
412
            # "The savepoint remains valid and can be rolled back to again"
413
            # (http://www.postgresql.org/docs/8.3/static/sql-rollback-to.html).
414
            if not top:
415
                self.run_query('RELEASE SAVEPOINT '+savepoint, log_level=4)
416
            
417
            self._savepoint -= 1
418
            assert self._savepoint >= 0
419
            
420
            self.do_autocommit() # OK to do this after ROLLBACK TO SAVEPOINT
421
    
422
    def do_autocommit(self):
423
        '''Autocommits if outside savepoint'''
424
        assert self._savepoint >= 1
425
        if self.autocommit and self._savepoint == 1:
426
            self.log_debug('Autocommitting', level=4)
427
            self.db.commit()
428
    
429
    def col_info(self, col, cacheable=True):
430
        table = sql_gen.Table('columns', 'information_schema')
431
        type_ = sql_gen.Coalesce(sql_gen.Nullif(sql_gen.Col('data_type'),
432
            'USER-DEFINED'), sql_gen.Col('udt_name'))
433
        cols = [type_, 'column_default',
434
            sql_gen.Cast('boolean', sql_gen.Col('is_nullable'))]
435
        
436
        conds = [('table_name', col.table.name), ('column_name', col.name)]
437
        schema = col.table.schema
438
        if schema != None: conds.append(('table_schema', schema))
439
        
440
        type_, default, nullable = row(select(self, table, cols, conds,
441
            order_by='table_schema', limit=1, cacheable=cacheable, log_level=4))
442
            # TODO: order_by search_path schema order
443
        default = sql_gen.as_Code(default, self)
444
        
445
        return sql_gen.TypedCol(col.name, type_, default, nullable)
446
    
447
    def TempFunction(self, name):
448
        if self.debug_temp: schema = None
449
        else: schema = 'pg_temp'
450
        return sql_gen.Function(name, schema)
451

    
452
connect = DbConn
453

    
454
##### Recoverable querying
455

    
456
def with_savepoint(db, func): return db.with_savepoint(func)
457

    
458
def run_query(db, query, recover=None, cacheable=False, log_level=2,
459
    log_ignore_excs=None, **kw_args):
460
    '''For params, see DbConn.run_query()'''
461
    if recover == None: recover = False
462
    if log_ignore_excs == None: log_ignore_excs = ()
463
    log_ignore_excs = tuple(log_ignore_excs)
464
    
465
    debug_msg_ref = None # usually, db.run_query() logs query before running it
466
    # But if filtering with log_ignore_excs, wait until after exception parsing
467
    if log_ignore_excs != () or not db.can_mogrify(): debug_msg_ref = [None]
468
    
469
    try:
470
        try:
471
            def run(): return db.run_query(query, cacheable, log_level,
472
                debug_msg_ref, **kw_args)
473
            if recover and not db.is_cached(query):
474
                return with_savepoint(db, run)
475
            else: return run() # don't need savepoint if cached
476
        except Exception, e:
477
            msg = strings.ustr(e.args[0])
478
            
479
            match = re.match(r'^duplicate key value violates unique constraint '
480
                r'"((_?[^\W_]+(?=[._]))?.+?)"', msg)
481
            if match:
482
                constraint, table = match.groups()
483
                cols = []
484
                if recover: # need auto-rollback to run index_cols()
485
                    try: cols = index_cols(db, table, constraint)
486
                    except NotImplementedError: pass
487
                raise DuplicateKeyException(constraint, cols, e)
488
            
489
            match = re.match(r'^null value in column "(.+?)" violates not-null'
490
                r' constraint', msg)
491
            if match: raise NullValueException('NOT NULL', [match.group(1)], e)
492
            
493
            match = re.match(r'^(?:invalid input (?:syntax|value)\b.*?'
494
                r'|.+? field value out of range): "(.+?)"', msg)
495
            if match:
496
                value, = match.groups()
497
                raise InvalidValueException(strings.to_unicode(value), e)
498
            
499
            match = re.match(r'^column "(.+?)" is of type (.+?) but expression '
500
                r'is of type', msg)
501
            if match:
502
                col, type_ = match.groups()
503
                raise MissingCastException(type_, col, e)
504
            
505
            match = re.match(r'^(\S+) "(.+?)".*? already exists', msg)
506
            if match:
507
                type_, name = match.groups()
508
                raise DuplicateException(type_, name, e)
509
            
510
            raise # no specific exception raised
511
    except log_ignore_excs:
512
        log_level += 2
513
        raise
514
    finally:
515
        if debug_msg_ref != None and debug_msg_ref[0] != None:
516
            db.log_debug(debug_msg_ref[0], log_level)
517

    
518
##### Basic queries
519

    
520
def next_version(name):
521
    version = 1 # first existing name was version 0
522
    match = re.match(r'^(.*)#(\d+)$', name)
523
    if match:
524
        name, version = match.groups()
525
        version = int(version)+1
526
    return sql_gen.concat(name, '#'+str(version))
527

    
528
def lock_table(db, table, mode):
529
    table = sql_gen.as_Table(table)
530
    run_query(db, 'LOCK TABLE '+table.to_str(db)+' IN '+mode+' MODE')
531

    
532
def run_query_into(db, query, into=None, add_indexes_=False, **kw_args):
533
    '''Outputs a query to a temp table.
534
    For params, see run_query().
535
    '''
536
    if into == None: return run_query(db, query, **kw_args)
537
    
538
    assert isinstance(into, sql_gen.Table)
539
    
540
    into.is_temp = True
541
    # "temporary tables cannot specify a schema name", so remove schema
542
    into.schema = None
543
    
544
    kw_args['recover'] = True
545
    kw_args.setdefault('log_ignore_excs', (DuplicateException,))
546
    
547
    temp = not db.debug_temp # tables are permanent in debug_temp mode
548
    
549
    # Create table
550
    while True:
551
        create_query = 'CREATE'
552
        if temp: create_query += ' TEMP'
553
        create_query += ' TABLE '+into.to_str(db)+' AS\n'+query
554
        
555
        try:
556
            cur = run_query(db, create_query, **kw_args)
557
                # CREATE TABLE AS sets rowcount to # rows in query
558
            break
559
        except DuplicateException, e:
560
            into.name = next_version(into.name)
561
            # try again with next version of name
562
    
563
    if add_indexes_: add_indexes(db, into)
564
    
565
    # According to the PostgreSQL doc, "The autovacuum daemon cannot access and
566
    # therefore cannot vacuum or analyze temporary tables. [...] if a temporary
567
    # table is going to be used in complex queries, it is wise to run ANALYZE on
568
    # the temporary table after it is populated."
569
    # (http://www.postgresql.org/docs/9.1/static/sql-createtable.html)
570
    # If into is not a temp table, ANALYZE is useful but not required.
571
    analyze(db, into)
572
    
573
    return cur
574

    
575
order_by_pkey = object() # tells mk_select() to order by the pkey
576

    
577
distinct_on_all = object() # tells mk_select() to SELECT DISTINCT ON all columns
578

    
579
def mk_select(db, tables, fields=None, conds=None, distinct_on=[], limit=None,
580
    start=None, order_by=order_by_pkey, default_table=None):
581
    '''
582
    @param tables The single table to select from, or a list of tables to join
583
        together, with tables after the first being sql_gen.Join objects
584
    @param fields Use None to select all fields in the table
585
    @param conds WHERE conditions: [(compare_left_side, compare_right_side),...]
586
        * container can be any iterable type
587
        * compare_left_side: sql_gen.Code|str (for col name)
588
        * compare_right_side: sql_gen.ValueCond|literal value
589
    @param distinct_on The columns to SELECT DISTINCT ON, or distinct_on_all to
590
        use all columns
591
    @return query
592
    '''
593
    # Parse tables param
594
    tables = lists.mk_seq(tables)
595
    tables = list(tables) # don't modify input! (list() copies input)
596
    table0 = sql_gen.as_Table(tables.pop(0)) # first table is separate
597
    
598
    # Parse other params
599
    if conds == None: conds = []
600
    elif dicts.is_dict(conds): conds = conds.items()
601
    conds = list(conds) # don't modify input! (list() copies input)
602
    assert limit == None or isinstance(limit, (int, long))
603
    assert start == None or isinstance(start, (int, long))
604
    if order_by is order_by_pkey:
605
        if distinct_on != []: order_by = None
606
        else: order_by = pkey(db, table0, recover=True)
607
    
608
    query = 'SELECT'
609
    
610
    def parse_col(col): return sql_gen.as_Col(col, default_table).to_str(db)
611
    
612
    # DISTINCT ON columns
613
    if distinct_on != []:
614
        query += '\nDISTINCT'
615
        if distinct_on is not distinct_on_all:
616
            query += ' ON ('+(', '.join(map(parse_col, distinct_on)))+')'
617
    
618
    # Columns
619
    if fields == None:
620
        if query.find('\n') >= 0: whitespace = '\n'
621
        else: whitespace = ' '
622
        query += whitespace+'*'
623
    else:
624
        assert fields != []
625
        query += '\n'+('\n, '.join(map(parse_col, fields)))
626
    
627
    # Main table
628
    query += '\nFROM '+table0.to_str(db)
629
    
630
    # Add joins
631
    left_table = table0
632
    for join_ in tables:
633
        table = join_.table
634
        
635
        # Parse special values
636
        if join_.type_ is sql_gen.filter_out: # filter no match
637
            conds.append((sql_gen.Col(table_not_null_col(db, table), table),
638
                sql_gen.CompareCond(None, '~=')))
639
        
640
        query += '\n'+join_.to_str(db, left_table)
641
        
642
        left_table = table
643
    
644
    missing = True
645
    if conds != []:
646
        if len(conds) == 1: whitespace = ' '
647
        else: whitespace = '\n'
648
        query += '\n'+sql_gen.combine_conds([sql_gen.ColValueCond(l, r)
649
            .to_str(db) for l, r in conds], 'WHERE')
650
        missing = False
651
    if order_by != None:
652
        query += '\nORDER BY '+sql_gen.as_Col(order_by, table0).to_str(db)
653
    if limit != None: query += '\nLIMIT '+str(limit); missing = False
654
    if start != None:
655
        if start != 0: query += '\nOFFSET '+str(start)
656
        missing = False
657
    if missing: warnings.warn(DbWarning(
658
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
659
    
660
    return query
661

    
662
def select(db, *args, **kw_args):
663
    '''For params, see mk_select() and run_query()'''
664
    recover = kw_args.pop('recover', None)
665
    cacheable = kw_args.pop('cacheable', True)
666
    log_level = kw_args.pop('log_level', 2)
667
    
668
    return run_query(db, mk_select(db, *args, **kw_args), recover, cacheable,
669
        log_level=log_level)
670

    
671
def mk_insert_select(db, table, cols=None, select_query=None, returning=None,
672
    embeddable=False, ignore=False):
673
    '''
674
    @param returning str|None An inserted column (such as pkey) to return
675
    @param embeddable Whether the query should be embeddable as a nested SELECT.
676
        Warning: If you set this and cacheable=True when the query is run, the
677
        query will be fully cached, not just if it raises an exception.
678
    @param ignore Whether to ignore duplicate keys.
679
    '''
680
    table = sql_gen.remove_table_rename(sql_gen.as_Table(table))
681
    if cols == []: cols = None # no cols (all defaults) = unknown col names
682
    if cols != None: cols = [sql_gen.to_name_only_col(c, table) for c in cols]
683
    if select_query == None: select_query = 'DEFAULT VALUES'
684
    if returning != None: returning = sql_gen.as_Col(returning, table)
685
    
686
    first_line = 'INSERT INTO '+table.to_str(db)
687
    
688
    def mk_insert(select_query):
689
        query = first_line
690
        if cols != None:
691
            query += '\n('+(', '.join((c.to_str(db) for c in cols)))+')'
692
        query += '\n'+select_query
693
        
694
        if returning != None:
695
            returning_name_col = sql_gen.to_name_only_col(returning)
696
            query += '\nRETURNING '+returning_name_col.to_str(db)
697
        
698
        return query
699
    
700
    return_type = 'unknown'
701
    if returning != None: return_type = returning.to_str(db)+'%TYPE'
702
    
703
    lang = 'sql'
704
    if ignore:
705
        # Always return something to set the correct rowcount
706
        if returning == None: returning = sql_gen.NamedCol('NULL', None)
707
        
708
        embeddable = True # must use function
709
        lang = 'plpgsql'
710
        
711
        if cols == None:
712
            row = [sql_gen.Col(sql_gen.all_cols, 'row')]
713
            row_vars = [sql_gen.Table('row')]
714
        else:
715
            row_vars = row = [sql_gen.Col(c.name, 'row') for c in cols]
716
        
717
        query = '''\
718
DECLARE
719
    row '''+table.to_str(db)+'''%ROWTYPE;
720
BEGIN
721
    /* Need an EXCEPTION block for each individual row because "When an error is
722
    caught by an EXCEPTION clause, [...] all changes to persistent database
723
    state within the block are rolled back."
724
    This is unfortunate because "A block containing an EXCEPTION clause is
725
    significantly more expensive to enter and exit than a block without one."
726
    (http://www.postgresql.org/docs/8.3/static/plpgsql-control-structures.html\
727
#PLPGSQL-ERROR-TRAPPING)
728
    */
729
    FOR '''+(', '.join((v.to_str(db) for v in row_vars)))+''' IN
730
'''+select_query+'''
731
    LOOP
732
        BEGIN
733
            RETURN QUERY
734
'''+mk_insert(sql_gen.Values(row).to_str(db))+'''
735
;
736
        EXCEPTION
737
            WHEN unique_violation THEN NULL; -- continue to next row
738
        END;
739
    END LOOP;
740
END;\
741
'''
742
    else: query = mk_insert(select_query)
743
    
744
    if embeddable:
745
        # Create function
746
        function_name = sql_gen.clean_name(first_line)
747
        while True:
748
            try:
749
                function = db.TempFunction(function_name)
750
                
751
                function_query = '''\
752
CREATE FUNCTION '''+function.to_str(db)+'''()
753
RETURNS SETOF '''+return_type+'''
754
LANGUAGE '''+lang+'''
755
AS $$
756
'''+query+'''
757
$$;
758
'''
759
                run_query(db, function_query, recover=True, cacheable=True,
760
                    log_ignore_excs=(DuplicateException,))
761
                break # this version was successful
762
            except DuplicateException, e:
763
                function_name = next_version(function_name)
764
                # try again with next version of name
765
        
766
        # Return query that uses function
767
        cols = None
768
        if returning != None: cols = [returning]
769
        func_table = sql_gen.NamedTable('f', sql_gen.FunctionCall(function),
770
            cols) # AS clause requires function alias
771
        return mk_select(db, func_table, start=0, order_by=None)
772
    
773
    return query
774

    
775
def insert_select(db, table, *args, **kw_args):
776
    '''For params, see mk_insert_select() and run_query_into()
777
    @param into sql_gen.Table with suggested name of temp table to put RETURNING
778
        values in
779
    '''
780
    returning = kw_args.get('returning', None)
781
    ignore = kw_args.get('ignore', False)
782
    
783
    into = kw_args.pop('into', None)
784
    if into != None: kw_args['embeddable'] = True
785
    recover = kw_args.pop('recover', None)
786
    if ignore: recover = True
787
    cacheable = kw_args.pop('cacheable', True)
788
    log_level = kw_args.pop('log_level', 2)
789
    
790
    rowcount_only = ignore and returning == None # keep NULL rows on server
791
    if rowcount_only: into = sql_gen.Table('rowcount')
792
    
793
    cur = run_query_into(db, mk_insert_select(db, table, *args, **kw_args),
794
        into, recover=recover, cacheable=cacheable, log_level=log_level)
795
    if rowcount_only: empty_temp(db, into)
796
    autoanalyze(db, table)
797
    return cur
798

    
799
default = sql_gen.default # tells insert() to use the default value for a column
800

    
801
def insert(db, table, row, *args, **kw_args):
802
    '''For params, see insert_select()'''
803
    if lists.is_seq(row): cols = None
804
    else:
805
        cols = row.keys()
806
        row = row.values()
807
    row = list(row) # ensure that "== []" works
808
    
809
    if row == []: query = None
810
    else: query = sql_gen.Values(row).to_str(db)
811
    
812
    return insert_select(db, table, cols, query, *args, **kw_args)
813

    
814
def mk_update(db, table, changes=None, cond=None, in_place=False,
815
    cacheable_=True):
816
    '''
817
    @param changes [(col, new_value),...]
818
        * container can be any iterable type
819
        * col: sql_gen.Code|str (for col name)
820
        * new_value: sql_gen.Code|literal value
821
    @param cond sql_gen.Code WHERE condition. e.g. use sql_gen.*Cond objects.
822
    @param in_place If set, locks the table and updates rows in place.
823
        This avoids creating dead rows in PostgreSQL.
824
        * cond must be None
825
    @param cacheable_ Whether column structure information used to generate the
826
        query can be cached
827
    @return str query
828
    '''
829
    table = sql_gen.as_Table(table)
830
    changes = [(sql_gen.to_name_only_col(c, table), sql_gen.as_Value(v))
831
        for c, v in changes]
832
    
833
    if in_place:
834
        assert cond == None
835
        
836
        query = 'ALTER TABLE '+table.to_str(db)+'\n'
837
        query += ',\n'.join(('ALTER COLUMN '+c.to_str(db)+' TYPE '
838
            +db.col_info(sql_gen.with_default_table(c, table), cacheable_).type
839
            +'\nUSING '+v.to_str(db) for c, v in changes))
840
    else:
841
        query = 'UPDATE '+table.to_str(db)+'\nSET\n'
842
        query += ',\n'.join((c.to_str(db)+' = '+v.to_str(db)
843
            for c, v in changes))
844
        if cond != None: query += '\nWHERE\n'+cond.to_str(db)
845
    
846
    return query
847

    
848
def update(db, table, *args, **kw_args):
849
    '''For params, see mk_update() and run_query()'''
850
    recover = kw_args.pop('recover', None)
851
    cacheable = kw_args.pop('cacheable', False)
852
    log_level = kw_args.pop('log_level', 2)
853
    
854
    cur = run_query(db, mk_update(db, table, *args, **kw_args), recover,
855
        cacheable, log_level=log_level)
856
    autoanalyze(db, table)
857
    return cur
858

    
859
def last_insert_id(db):
860
    module = util.root_module(db.db)
861
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
862
    elif module == 'MySQLdb': return db.insert_id()
863
    else: return None
864

    
865
def mk_flatten_mapping(db, into, cols, preserve=[], as_items=False):
866
    '''Creates a mapping from original column names (which may have collisions)
867
    to names that will be distinct among the columns' tables.
868
    This is meant to be used for several tables that are being joined together.
869
    @param cols The columns to combine. Duplicates will be removed.
870
    @param into The table for the new columns.
871
    @param preserve [sql_gen.Col...] Columns not to rename. Note that these
872
        columns will be included in the mapping even if they are not in cols.
873
        The tables of the provided Col objects will be changed to into, so make
874
        copies of them if you want to keep the original tables.
875
    @param as_items Whether to return a list of dict items instead of a dict
876
    @return dict(orig_col=new_col, ...)
877
        * orig_col: sql_gen.Col(orig_col_name, orig_table)
878
        * new_col: sql_gen.Col(orig_col_name, into)
879
        * All mappings use the into table so its name can easily be
880
          changed for all columns at once
881
    '''
882
    cols = lists.uniqify(cols)
883
    
884
    items = []
885
    for col in preserve:
886
        orig_col = copy.copy(col)
887
        col.table = into
888
        items.append((orig_col, col))
889
    preserve = set(preserve)
890
    for col in cols:
891
        if col not in preserve:
892
            items.append((col, sql_gen.Col(str(col), into, col.srcs)))
893
    
894
    if not as_items: items = dict(items)
895
    return items
896

    
897
def flatten(db, into, joins, cols, limit=None, start=None, **kw_args):
898
    '''For params, see mk_flatten_mapping()
899
    @return See return value of mk_flatten_mapping()
900
    '''
901
    items = mk_flatten_mapping(db, into, cols, as_items=True, **kw_args)
902
    cols = [sql_gen.NamedCol(new.name, old) for old, new in items]
903
    run_query_into(db, mk_select(db, joins, cols, limit=limit, start=start),
904
        into=into, add_indexes_=True)
905
    return dict(items)
906

    
907
##### Database structure introspection
908

    
909
#### Tables
910

    
911
def tables(db, schema_like='public', table_like='%', exact=False):
912
    if exact: compare = '='
913
    else: compare = 'LIKE'
914
    
915
    module = util.root_module(db.db)
916
    if module == 'psycopg2':
917
        conds = [('schemaname', sql_gen.CompareCond(schema_like, compare)),
918
            ('tablename', sql_gen.CompareCond(table_like, compare))]
919
        return values(select(db, 'pg_tables', ['tablename'], conds,
920
            order_by='tablename', log_level=4))
921
    elif module == 'MySQLdb':
922
        return values(run_query(db, 'SHOW TABLES LIKE '+db.esc_value(table_like)
923
            , cacheable=True, log_level=4))
924
    else: raise NotImplementedError("Can't list tables for "+module+' database')
925

    
926
def table_exists(db, table):
927
    table = sql_gen.as_Table(table)
928
    return list(tables(db, table.schema, table.name, exact=True)) != []
929

    
930
def table_row_count(db, table, recover=None):
931
    return value(run_query(db, mk_select(db, table, [sql_gen.row_count],
932
        order_by=None, start=0), recover=recover, log_level=3))
933

    
934
def table_cols(db, table, recover=None):
935
    return list(col_names(select(db, table, limit=0, order_by=None,
936
        recover=recover, log_level=4)))
937

    
938
def pkey(db, table, recover=None):
939
    '''Assumed to be first column in table'''
940
    return table_cols(db, table, recover)[0]
941

    
942
not_null_col = 'not_null_col'
943

    
944
def table_not_null_col(db, table, recover=None):
945
    '''Name assumed to be the value of not_null_col. If not found, uses pkey.'''
946
    if not_null_col in table_cols(db, table, recover): return not_null_col
947
    else: return pkey(db, table, recover)
948

    
949
def index_cols(db, table, index):
950
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
951
    automatically created. When you don't know whether something is a UNIQUE
952
    constraint or a UNIQUE index, use this function.'''
953
    module = util.root_module(db.db)
954
    if module == 'psycopg2':
955
        return list(values(run_query(db, '''\
956
SELECT attname
957
FROM
958
(
959
        SELECT attnum, attname
960
        FROM pg_index
961
        JOIN pg_class index ON index.oid = indexrelid
962
        JOIN pg_class table_ ON table_.oid = indrelid
963
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
964
        WHERE
965
            table_.relname = '''+db.esc_value(table)+'''
966
            AND index.relname = '''+db.esc_value(index)+'''
967
    UNION
968
        SELECT attnum, attname
969
        FROM
970
        (
971
            SELECT
972
                indrelid
973
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
974
                    AS indkey
975
            FROM pg_index
976
            JOIN pg_class index ON index.oid = indexrelid
977
            JOIN pg_class table_ ON table_.oid = indrelid
978
            WHERE
979
                table_.relname = '''+db.esc_value(table)+'''
980
                AND index.relname = '''+db.esc_value(index)+'''
981
        ) s
982
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
983
) s
984
ORDER BY attnum
985
'''
986
            , cacheable=True, log_level=4)))
987
    else: raise NotImplementedError("Can't list index columns for "+module+
988
        ' database')
989

    
990
def constraint_cols(db, table, constraint):
991
    module = util.root_module(db.db)
992
    if module == 'psycopg2':
993
        return list(values(run_query(db, '''\
994
SELECT attname
995
FROM pg_constraint
996
JOIN pg_class ON pg_class.oid = conrelid
997
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
998
WHERE
999
    relname = '''+db.esc_value(table)+'''
1000
    AND conname = '''+db.esc_value(constraint)+'''
1001
ORDER BY attnum
1002
'''
1003
            )))
1004
    else: raise NotImplementedError("Can't list constraint columns for "+module+
1005
        ' database')
1006

    
1007
#### Functions
1008

    
1009
def function_exists(db, function):
1010
    function = sql_gen.as_Function(function)
1011
    
1012
    info_table = sql_gen.Table('routines', 'information_schema')
1013
    conds = [('routine_name', function.name)]
1014
    schema = function.schema
1015
    if schema != None: conds.append(('routine_schema', schema))
1016
    # Exclude trigger functions, since they cannot be called directly
1017
    conds.append(('data_type', sql_gen.CompareCond('trigger', '!=')))
1018
    
1019
    return list(values(select(db, info_table, ['routine_name'], conds,
1020
        order_by='routine_schema', limit=1, log_level=4))) != []
1021
        # TODO: order_by search_path schema order
1022

    
1023
##### Structural changes
1024

    
1025
#### Columns
1026

    
1027
def add_col(db, table, col, comment=None, **kw_args):
1028
    '''
1029
    @param col TypedCol Name may be versioned, so be sure to propagate any
1030
        renaming back to any source column for the TypedCol.
1031
    @param comment None|str SQL comment used to distinguish columns of the same
1032
        name from each other when they contain different data, to allow the
1033
        ADD COLUMN query to be cached. If not set, query will not be cached.
1034
    '''
1035
    assert isinstance(col, sql_gen.TypedCol)
1036
    
1037
    while True:
1038
        str_ = 'ALTER TABLE '+table.to_str(db)+' ADD COLUMN '+col.to_str(db)
1039
        if comment != None: str_ += ' '+sql_gen.esc_comment(comment)
1040
        
1041
        try:
1042
            run_query(db, str_, recover=True, cacheable=True, **kw_args)
1043
            break
1044
        except DuplicateException:
1045
            col.name = next_version(col.name)
1046
            # try again with next version of name
1047

    
1048
def add_not_null(db, col):
1049
    table = col.table
1050
    col = sql_gen.to_name_only_col(col)
1051
    run_query(db, 'ALTER TABLE '+table.to_str(db)+' ALTER COLUMN '
1052
        +col.to_str(db)+' SET NOT NULL', cacheable=True, log_level=3)
1053

    
1054
row_num_col = '_row_num'
1055

    
1056
row_num_typed_col = sql_gen.TypedCol(row_num_col, 'serial', nullable=False,
1057
    constraints='PRIMARY KEY')
1058

    
1059
def add_row_num(db, table):
1060
    '''Adds a row number column to a table. Its name is in row_num_col. It will
1061
    be the primary key.'''
1062
    add_col(db, table, row_num_typed_col, log_level=3)
1063

    
1064
#### Indexes
1065

    
1066
def add_pkey(db, table, cols=None, recover=None):
1067
    '''Adds a primary key.
1068
    @param cols [sql_gen.Col,...] The columns in the primary key.
1069
        Defaults to the first column in the table.
1070
    @pre The table must not already have a primary key.
1071
    '''
1072
    table = sql_gen.as_Table(table)
1073
    if cols == None: cols = [pkey(db, table, recover)]
1074
    col_strs = [sql_gen.to_name_only_col(v).to_str(db) for v in cols]
1075
    
1076
    run_query(db, 'ALTER TABLE '+table.to_str(db)+' ADD PRIMARY KEY ('
1077
        +(', '.join(col_strs))+')', recover=True, cacheable=True, log_level=3,
1078
        log_ignore_excs=(DuplicateException,))
1079

    
1080
def add_index(db, exprs, table=None, unique=False, ensure_not_null_=True):
1081
    '''Adds an index on column(s) or expression(s) if it doesn't already exist.
1082
    Currently, only function calls are supported as expressions.
1083
    @param ensure_not_null_ If set, translates NULL values to sentinel values.
1084
        This allows indexes to be used for comparisons where NULLs are equal.
1085
    '''
1086
    exprs = lists.mk_seq(exprs)
1087
    
1088
    # Parse exprs
1089
    old_exprs = exprs[:]
1090
    exprs = []
1091
    cols = []
1092
    for i, expr in enumerate(old_exprs):
1093
        expr = sql_gen.as_Col(expr, table)
1094
        
1095
        # Handle nullable columns
1096
        if ensure_not_null_:
1097
            try: expr = ensure_not_null(db, expr)
1098
            except KeyError: pass # unknown type, so just create plain index
1099
        
1100
        # Extract col
1101
        expr = copy.deepcopy(expr) # don't modify input!
1102
        if isinstance(expr, sql_gen.FunctionCall):
1103
            col = expr.args[0]
1104
            expr = sql_gen.Expr(expr)
1105
        else: col = expr
1106
        assert isinstance(col, sql_gen.Col)
1107
        
1108
        # Extract table
1109
        if table == None:
1110
            assert sql_gen.is_table_col(col)
1111
            table = col.table
1112
        
1113
        col.table = None
1114
        
1115
        exprs.append(expr)
1116
        cols.append(col)
1117
    
1118
    table = sql_gen.as_Table(table)
1119
    
1120
    # Add index
1121
    str_ = 'CREATE'
1122
    if unique: str_ += ' UNIQUE'
1123
    str_ += ' INDEX ON '+table.to_str(db)+' ('+(
1124
        ', '.join((v.to_str(db) for v in exprs)))+')'
1125
    run_query(db, str_, recover=True, cacheable=True, log_level=3)
1126

    
1127
def add_index_col(db, col, suffix, expr, nullable=True):
1128
    if sql_gen.index_col(col) != None: return # already has index col
1129
    
1130
    new_col = sql_gen.suffixed_col(col, suffix)
1131
    
1132
    # Add column
1133
    new_typed_col = sql_gen.TypedCol(new_col.name,
1134
        db.col_info(col, cacheable=nullable).type)
1135
        # if not nullable, col_info will be changed later by add_not_null()
1136
    add_col(db, col.table, new_typed_col, comment='src: '+repr(col),
1137
        log_level=3)
1138
    new_col.name = new_typed_col.name # propagate any renaming
1139
    
1140
    update(db, col.table, [(new_col, expr)], in_place=True, cacheable_=nullable,
1141
        cacheable=True, log_level=3)
1142
    if not nullable: add_not_null(db, new_col)
1143
    add_index(db, new_col)
1144
    
1145
    col.table.index_cols[col.name] = new_col.name
1146

    
1147
# Controls when ensure_not_null() will use index columns
1148
not_null_index_cols_min_rows = 0 # rows; initially always use index columns
1149

    
1150
def ensure_not_null(db, col):
1151
    '''For params, see sql_gen.ensure_not_null()'''
1152
    expr = sql_gen.ensure_not_null(db, col)
1153
    
1154
    # If a nullable column in a temp table, add separate index column instead.
1155
    # Note that for small datasources, this adds 6-25% to the total import time.
1156
    if (sql_gen.is_temp_col(col) and isinstance(expr, sql_gen.EnsureNotNull)
1157
        and table_row_count(db, col.table) >= not_null_index_cols_min_rows):
1158
        add_index_col(db, col, '::NOT NULL', expr, nullable=False)
1159
        expr = sql_gen.index_col(col)
1160
    
1161
    return expr
1162

    
1163
already_indexed = object() # tells add_indexes() the pkey has already been added
1164

    
1165
def add_indexes(db, table, has_pkey=True):
1166
    '''Adds an index on all columns in a table.
1167
    @param has_pkey bool|already_indexed Whether a pkey instead of a regular
1168
        index should be added on the first column.
1169
        * If already_indexed, the pkey is assumed to have already been added
1170
    '''
1171
    cols = table_cols(db, table)
1172
    if has_pkey:
1173
        if has_pkey is not already_indexed: add_pkey(db, table)
1174
        cols = cols[1:]
1175
    for col in cols: add_index(db, col, table)
1176

    
1177
#### Tables
1178

    
1179
### Maintenance
1180

    
1181
def analyze(db, table):
1182
    table = sql_gen.as_Table(table)
1183
    run_query(db, 'ANALYZE '+table.to_str(db), log_level=3)
1184

    
1185
def autoanalyze(db, table):
1186
    if db.autoanalyze: analyze(db, table)
1187

    
1188
def vacuum(db, table):
1189
    table = sql_gen.as_Table(table)
1190
    db.with_autocommit(lambda: run_query(db, 'VACUUM ANALYZE '+table.to_str(db),
1191
        log_level=3))
1192

    
1193
### Lifecycle
1194

    
1195
def drop_table(db, table):
1196
    table = sql_gen.as_Table(table)
1197
    return run_query(db, 'DROP TABLE IF EXISTS '+table.to_str(db)+' CASCADE')
1198

    
1199
def create_table(db, table, cols=[], has_pkey=True, col_indexes=True,
1200
    like=None):
1201
    '''Creates a table.
1202
    @param cols [sql_gen.TypedCol,...] The column names and types
1203
    @param has_pkey If set, the first column becomes the primary key.
1204
    @param col_indexes bool|[ref]
1205
        * If True, indexes will be added on all non-pkey columns.
1206
        * If a list reference, [0] will be set to a function to do this.
1207
          This can be used to delay index creation until the table is populated.
1208
    '''
1209
    table = sql_gen.as_Table(table)
1210
    
1211
    if like != None:
1212
        cols = [sql_gen.CustomCode('LIKE '+like.to_str(db)+' INCLUDING ALL')
1213
            ]+cols
1214
    if has_pkey:
1215
        cols[0] = pkey = copy.copy(cols[0]) # don't modify input!
1216
        pkey.constraints = 'PRIMARY KEY'
1217
    
1218
    temp = table.is_temp and not db.debug_temp
1219
        # temp tables permanent in debug_temp mode
1220
    
1221
    # Create table
1222
    while True:
1223
        str_ = 'CREATE'
1224
        if temp: str_ += ' TEMP'
1225
        str_ += ' TABLE '+table.to_str(db)+' (\n'
1226
        str_ += '\n, '.join(c.to_str(db) for c in cols)
1227
        str_ += '\n);'
1228
        
1229
        try:
1230
            run_query(db, str_, recover=True, cacheable=True, log_level=2,
1231
                log_ignore_excs=(DuplicateException,))
1232
            break
1233
        except DuplicateException:
1234
            table.name = next_version(table.name)
1235
            # try again with next version of name
1236
    
1237
    # Add indexes
1238
    if has_pkey: has_pkey = already_indexed
1239
    def add_indexes_(): add_indexes(db, table, has_pkey)
1240
    if isinstance(col_indexes, list): col_indexes[0] = add_indexes_ # defer
1241
    elif col_indexes: add_indexes_() # add now
1242

    
1243
def copy_table_struct(db, src, dest):
1244
    '''Creates a structure-only copy of a table. (Does not copy data.)'''
1245
    create_table(db, dest, has_pkey=False, col_indexes=False, like=src)
1246

    
1247
### Data
1248

    
1249
def truncate(db, table, schema='public', **kw_args):
1250
    '''For params, see run_query()'''
1251
    table = sql_gen.as_Table(table, schema)
1252
    return run_query(db, 'TRUNCATE '+table.to_str(db)+' CASCADE', **kw_args)
1253

    
1254
def empty_temp(db, tables):
1255
    tables = lists.mk_seq(tables)
1256
    for table in tables: truncate(db, table, log_level=3)
1257

    
1258
def empty_db(db, schema='public', **kw_args):
1259
    '''For kw_args, see tables()'''
1260
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
1261

    
1262
def distinct_table(db, table, distinct_on):
1263
    '''Creates a copy of a temp table which is distinct on the given columns.
1264
    The old and new tables will both get an index on these columns, to
1265
    facilitate merge joins.
1266
    @param distinct_on If empty, creates a table with one row. This is useful if
1267
        your distinct_on columns are all literal values.
1268
    @return The new table.
1269
    '''
1270
    new_table = sql_gen.suffixed_table(table, '_distinct')
1271
    
1272
    copy_table_struct(db, table, new_table)
1273
    
1274
    limit = None
1275
    if distinct_on == []: limit = 1 # one sample row
1276
    else:
1277
        add_index(db, distinct_on, new_table, unique=True)
1278
        add_index(db, distinct_on, table) # for join optimization
1279
    
1280
    insert_select(db, new_table, None, mk_select(db, table, start=0,
1281
        limit=limit), ignore=True)
1282
    analyze(db, new_table)
1283
    
1284
    return new_table
(24-24/37)