Project

General

Profile

1
# Database access
2

    
3
import copy
4
import re
5
import time
6
import warnings
7

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

    
18
##### Exceptions
19

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

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

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

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

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

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

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

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

    
69
class NameException(DbException): pass
70

    
71
class DuplicateKeyException(ConstraintException): pass
72

    
73
class NullValueException(ConstraintException): pass
74

    
75
class InvalidValueException(ExceptionWithValue): pass
76

    
77
class DuplicateException(ExceptionWithNameType): pass
78

    
79
class EmptyRowException(DbException): pass
80

    
81
##### Warnings
82

    
83
class DbWarning(UserWarning): pass
84

    
85
##### Result retrieval
86

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

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

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

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

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

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

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

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

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

    
112
##### Escaping
113

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

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

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

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

    
132
##### Database connections
133

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

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

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

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

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

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

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

    
466
connect = DbConn
467

    
468
##### Recoverable querying
469

    
470
def with_savepoint(db, func): return db.with_savepoint(func)
471

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

    
528
##### Basic queries
529

    
530
def next_version(name):
531
    version = 1 # first existing name was version 0
532
    match = re.match(r'^(.*)#(\d+)$', name)
533
    if match:
534
        name, version = match.groups()
535
        version = int(version)+1
536
    return sql_gen.concat(name, '#'+str(version))
537

    
538
def lock_table(db, table, mode):
539
    table = sql_gen.as_Table(table)
540
    run_query(db, 'LOCK TABLE '+table.to_str(db)+' IN '+mode+' MODE')
541

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

    
585
order_by_pkey = object() # tells mk_select() to order by the pkey
586

    
587
distinct_on_all = object() # tells mk_select() to SELECT DISTINCT ON all columns
588

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

    
674
def select(db, *args, **kw_args):
675
    '''For params, see mk_select() and run_query()'''
676
    recover = kw_args.pop('recover', None)
677
    cacheable = kw_args.pop('cacheable', True)
678
    log_level = kw_args.pop('log_level', 2)
679
    
680
    return run_query(db, mk_select(db, *args, **kw_args), recover, cacheable,
681
        log_level=log_level)
682

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

    
790
def insert_select(db, table, *args, **kw_args):
791
    '''For params, see mk_insert_select() and run_query_into()
792
    @param into sql_gen.Table with suggested name of temp table to put RETURNING
793
        values in
794
    '''
795
    returning = kw_args.get('returning', None)
796
    ignore = kw_args.get('ignore', False)
797
    
798
    into = kw_args.pop('into', None)
799
    if into != None: kw_args['embeddable'] = True
800
    recover = kw_args.pop('recover', None)
801
    if ignore: recover = True
802
    cacheable = kw_args.pop('cacheable', True)
803
    log_level = kw_args.pop('log_level', 2)
804
    
805
    rowcount_only = ignore and returning == None # keep NULL rows on server
806
    if rowcount_only: into = sql_gen.Table('rowcount')
807
    
808
    cur = run_query_into(db, mk_insert_select(db, table, *args, **kw_args),
809
        into, recover=recover, cacheable=cacheable, log_level=log_level)
810
    if rowcount_only: empty_temp(db, into)
811
    autoanalyze(db, table)
812
    return cur
813

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

    
816
def insert(db, table, row, *args, **kw_args):
817
    '''For params, see insert_select()'''
818
    if lists.is_seq(row): cols = None
819
    else:
820
        cols = row.keys()
821
        row = row.values()
822
    row = list(row) # ensure that "== []" works
823
    
824
    if row == []: query = None
825
    else: query = sql_gen.Values(row).to_str(db)
826
    
827
    return insert_select(db, table, cols, query, *args, **kw_args)
828

    
829
def mk_update(db, table, changes=None, cond=None, in_place=False,
830
    cacheable_=True):
831
    '''
832
    @param changes [(col, new_value),...]
833
        * container can be any iterable type
834
        * col: sql_gen.Code|str (for col name)
835
        * new_value: sql_gen.Code|literal value
836
    @param cond sql_gen.Code WHERE condition. e.g. use sql_gen.*Cond objects.
837
    @param in_place If set, locks the table and updates rows in place.
838
        This avoids creating dead rows in PostgreSQL.
839
        * cond must be None
840
    @param cacheable_ Whether column structure information used to generate the
841
        query can be cached
842
    @return str query
843
    '''
844
    table = sql_gen.as_Table(table)
845
    changes = [(sql_gen.to_name_only_col(c, table), sql_gen.as_Value(v))
846
        for c, v in changes]
847
    
848
    if in_place:
849
        assert cond == None
850
        
851
        query = 'ALTER TABLE '+table.to_str(db)+'\n'
852
        query += ',\n'.join(('ALTER COLUMN '+c.to_str(db)+' TYPE '
853
            +db.col_info(sql_gen.with_default_table(c, table), cacheable_).type
854
            +'\nUSING '+v.to_str(db) for c, v in changes))
855
    else:
856
        query = 'UPDATE '+table.to_str(db)+'\nSET\n'
857
        query += ',\n'.join((c.to_str(db)+' = '+v.to_str(db)
858
            for c, v in changes))
859
        if cond != None: query += '\nWHERE\n'+cond.to_str(db)
860
    
861
    return query
862

    
863
def update(db, table, *args, **kw_args):
864
    '''For params, see mk_update() and run_query()'''
865
    recover = kw_args.pop('recover', None)
866
    cacheable = kw_args.pop('cacheable', False)
867
    log_level = kw_args.pop('log_level', 2)
868
    
869
    cur = run_query(db, mk_update(db, table, *args, **kw_args), recover,
870
        cacheable, log_level=log_level)
871
    autoanalyze(db, table)
872
    return cur
873

    
874
def last_insert_id(db):
875
    module = util.root_module(db.db)
876
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
877
    elif module == 'MySQLdb': return db.insert_id()
878
    else: return None
879

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

    
912
def flatten(db, into, joins, cols, limit=None, start=None, **kw_args):
913
    '''For params, see mk_flatten_mapping()
914
    @return See return value of mk_flatten_mapping()
915
    '''
916
    items = mk_flatten_mapping(db, into, cols, as_items=True, **kw_args)
917
    cols = [sql_gen.NamedCol(new.name, old) for old, new in items]
918
    run_query_into(db, mk_select(db, joins, cols, limit=limit, start=start),
919
        into=into)
920
    return dict(items)
921

    
922
##### Database structure introspection
923

    
924
#### Tables
925

    
926
def tables(db, schema_like='public', table_like='%', exact=False):
927
    if exact: compare = '='
928
    else: compare = 'LIKE'
929
    
930
    module = util.root_module(db.db)
931
    if module == 'psycopg2':
932
        conds = [('schemaname', sql_gen.CompareCond(schema_like, compare)),
933
            ('tablename', sql_gen.CompareCond(table_like, compare))]
934
        return values(select(db, 'pg_tables', ['tablename'], conds,
935
            order_by='tablename', log_level=4))
936
    elif module == 'MySQLdb':
937
        return values(run_query(db, 'SHOW TABLES LIKE '+db.esc_value(table_like)
938
            , cacheable=True, log_level=4))
939
    else: raise NotImplementedError("Can't list tables for "+module+' database')
940

    
941
def table_exists(db, table):
942
    table = sql_gen.as_Table(table)
943
    return list(tables(db, table.schema, table.name, exact=True)) != []
944

    
945
def table_row_count(db, table, recover=None):
946
    return value(run_query(db, mk_select(db, table, [sql_gen.row_count],
947
        order_by=None, start=0), recover=recover, log_level=3))
948

    
949
def table_cols(db, table, recover=None):
950
    return list(col_names(select(db, table, limit=0, order_by=None,
951
        recover=recover, log_level=4)))
952

    
953
def pkey(db, table, recover=None):
954
    '''Assumed to be first column in table'''
955
    return table_cols(db, table, recover)[0]
956

    
957
not_null_col = 'not_null_col'
958

    
959
def table_not_null_col(db, table, recover=None):
960
    '''Name assumed to be the value of not_null_col. If not found, uses pkey.'''
961
    if not_null_col in table_cols(db, table, recover): return not_null_col
962
    else: return pkey(db, table, recover)
963

    
964
def index_cols(db, table, index):
965
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
966
    automatically created. When you don't know whether something is a UNIQUE
967
    constraint or a UNIQUE index, use this function.'''
968
    module = util.root_module(db.db)
969
    if module == 'psycopg2':
970
        return list(values(run_query(db, '''\
971
SELECT attname
972
FROM
973
(
974
        SELECT attnum, attname
975
        FROM pg_index
976
        JOIN pg_class index ON index.oid = indexrelid
977
        JOIN pg_class table_ ON table_.oid = indrelid
978
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
979
        WHERE
980
            table_.relname = '''+db.esc_value(table)+'''
981
            AND index.relname = '''+db.esc_value(index)+'''
982
    UNION
983
        SELECT attnum, attname
984
        FROM
985
        (
986
            SELECT
987
                indrelid
988
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
989
                    AS indkey
990
            FROM pg_index
991
            JOIN pg_class index ON index.oid = indexrelid
992
            JOIN pg_class table_ ON table_.oid = indrelid
993
            WHERE
994
                table_.relname = '''+db.esc_value(table)+'''
995
                AND index.relname = '''+db.esc_value(index)+'''
996
        ) s
997
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
998
) s
999
ORDER BY attnum
1000
'''
1001
            , cacheable=True, log_level=4)))
1002
    else: raise NotImplementedError("Can't list index columns for "+module+
1003
        ' database')
1004

    
1005
def constraint_cols(db, table, constraint):
1006
    module = util.root_module(db.db)
1007
    if module == 'psycopg2':
1008
        return list(values(run_query(db, '''\
1009
SELECT attname
1010
FROM pg_constraint
1011
JOIN pg_class ON pg_class.oid = conrelid
1012
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
1013
WHERE
1014
    relname = '''+db.esc_value(table)+'''
1015
    AND conname = '''+db.esc_value(constraint)+'''
1016
ORDER BY attnum
1017
'''
1018
            )))
1019
    else: raise NotImplementedError("Can't list constraint columns for "+module+
1020
        ' database')
1021

    
1022
#### Functions
1023

    
1024
def function_exists(db, function):
1025
    function = sql_gen.as_Function(function)
1026
    
1027
    info_table = sql_gen.Table('routines', 'information_schema')
1028
    conds = [('routine_name', function.name)]
1029
    schema = function.schema
1030
    if schema != None: conds.append(('routine_schema', schema))
1031
    # Exclude trigger functions, since they cannot be called directly
1032
    conds.append(('data_type', sql_gen.CompareCond('trigger', '!=')))
1033
    
1034
    return list(values(select(db, info_table, ['routine_name'], conds,
1035
        order_by='routine_schema', limit=1, log_level=4))) != []
1036
        # TODO: order_by search_path schema order
1037

    
1038
##### Structural changes
1039

    
1040
#### Columns
1041

    
1042
def add_col(db, table, col, comment=None, **kw_args):
1043
    '''
1044
    @param col TypedCol Name may be versioned, so be sure to propagate any
1045
        renaming back to any source column for the TypedCol.
1046
    @param comment None|str SQL comment used to distinguish columns of the same
1047
        name from each other when they contain different data, to allow the
1048
        ADD COLUMN query to be cached. If not set, query will not be cached.
1049
    '''
1050
    assert isinstance(col, sql_gen.TypedCol)
1051
    
1052
    while True:
1053
        str_ = 'ALTER TABLE '+table.to_str(db)+' ADD COLUMN '+col.to_str(db)
1054
        if comment != None: str_ += ' '+sql_gen.esc_comment(comment)
1055
        
1056
        try:
1057
            run_query(db, str_, recover=True, cacheable=True, **kw_args)
1058
            break
1059
        except DuplicateException:
1060
            col.name = next_version(col.name)
1061
            # try again with next version of name
1062

    
1063
def add_not_null(db, col):
1064
    table = col.table
1065
    col = sql_gen.to_name_only_col(col)
1066
    run_query(db, 'ALTER TABLE '+table.to_str(db)+' ALTER COLUMN '
1067
        +col.to_str(db)+' SET NOT NULL', cacheable=True, log_level=3)
1068

    
1069
row_num_col = '_row_num'
1070

    
1071
row_num_typed_col = sql_gen.TypedCol(row_num_col, 'serial', nullable=False,
1072
    constraints='PRIMARY KEY')
1073

    
1074
def add_row_num(db, table):
1075
    '''Adds a row number column to a table. Its name is in row_num_col. It will
1076
    be the primary key.'''
1077
    add_col(db, table, row_num_typed_col, log_level=3)
1078

    
1079
#### Indexes
1080

    
1081
def add_pkey(db, table, cols=None, recover=None):
1082
    '''Adds a primary key.
1083
    @param cols [sql_gen.Col,...] The columns in the primary key.
1084
        Defaults to the first column in the table.
1085
    @pre The table must not already have a primary key.
1086
    '''
1087
    table = sql_gen.as_Table(table)
1088
    if cols == None: cols = [pkey(db, table, recover)]
1089
    col_strs = [sql_gen.to_name_only_col(v).to_str(db) for v in cols]
1090
    
1091
    run_query(db, 'ALTER TABLE '+table.to_str(db)+' ADD PRIMARY KEY ('
1092
        +(', '.join(col_strs))+')', recover=True, cacheable=True, log_level=3,
1093
        log_ignore_excs=(DuplicateException,))
1094

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

    
1142
already_indexed = object() # tells add_indexes() the pkey has already been added
1143

    
1144
def add_indexes(db, table, has_pkey=True):
1145
    '''Adds an index on all columns in a table.
1146
    @param has_pkey bool|already_indexed Whether a pkey instead of a regular
1147
        index should be added on the first column.
1148
        * If already_indexed, the pkey is assumed to have already been added
1149
    '''
1150
    cols = table_cols(db, table)
1151
    if has_pkey:
1152
        if has_pkey is not already_indexed: add_pkey(db, table)
1153
        cols = cols[1:]
1154
    for col in cols: add_index(db, col, table)
1155

    
1156
#### Tables
1157

    
1158
### Maintenance
1159

    
1160
def analyze(db, table):
1161
    table = sql_gen.as_Table(table)
1162
    run_query(db, 'ANALYZE '+table.to_str(db), log_level=3)
1163

    
1164
def autoanalyze(db, table):
1165
    if db.autoanalyze: analyze(db, table)
1166

    
1167
def vacuum(db, table):
1168
    table = sql_gen.as_Table(table)
1169
    db.with_autocommit(lambda: run_query(db, 'VACUUM ANALYZE '+table.to_str(db),
1170
        log_level=3))
1171

    
1172
### Lifecycle
1173

    
1174
def drop_table(db, table):
1175
    table = sql_gen.as_Table(table)
1176
    return run_query(db, 'DROP TABLE IF EXISTS '+table.to_str(db)+' CASCADE')
1177

    
1178
def create_table(db, table, cols=[], has_pkey=True, col_indexes=True,
1179
    like=None):
1180
    '''Creates a table.
1181
    @param cols [sql_gen.TypedCol,...] The column names and types
1182
    @param has_pkey If set, the first column becomes the primary key.
1183
    @param col_indexes bool|[ref]
1184
        * If True, indexes will be added on all non-pkey columns.
1185
        * If a list reference, [0] will be set to a function to do this.
1186
          This can be used to delay index creation until the table is populated.
1187
    '''
1188
    table = sql_gen.as_Table(table)
1189
    
1190
    if like != None:
1191
        cols = [sql_gen.CustomCode('LIKE '+like.to_str(db)+' INCLUDING ALL')
1192
            ]+cols
1193
    if has_pkey:
1194
        cols[0] = pkey = copy.copy(cols[0]) # don't modify input!
1195
        pkey.constraints = 'PRIMARY KEY'
1196
    
1197
    temp = table.is_temp and not db.debug_temp
1198
        # temp tables permanent in debug_temp mode
1199
    
1200
    # Create table
1201
    while True:
1202
        str_ = 'CREATE'
1203
        if temp: str_ += ' TEMP'
1204
        str_ += ' TABLE '+table.to_str(db)+' (\n'
1205
        str_ += '\n, '.join(c.to_str(db) for c in cols)
1206
        str_ += '\n);'
1207
        
1208
        try:
1209
            run_query(db, str_, recover=True, cacheable=True, log_level=2,
1210
                log_ignore_excs=(DuplicateException,))
1211
            break
1212
        except DuplicateException:
1213
            table.name = next_version(table.name)
1214
            # try again with next version of name
1215
    
1216
    # Add indexes
1217
    if has_pkey: has_pkey = already_indexed
1218
    def add_indexes_(): add_indexes(db, table, has_pkey)
1219
    if isinstance(col_indexes, list): col_indexes[0] = add_indexes_ # defer
1220
    elif col_indexes: add_indexes_() # add now
1221

    
1222
def copy_table_struct(db, src, dest):
1223
    '''Creates a structure-only copy of a table. (Does not copy data.)'''
1224
    create_table(db, dest, has_pkey=False, col_indexes=False, like=src)
1225

    
1226
### Data
1227

    
1228
def truncate(db, table, schema='public', **kw_args):
1229
    '''For params, see run_query()'''
1230
    table = sql_gen.as_Table(table, schema)
1231
    return run_query(db, 'TRUNCATE '+table.to_str(db)+' CASCADE', **kw_args)
1232

    
1233
def empty_temp(db, tables):
1234
    tables = lists.mk_seq(tables)
1235
    for table in tables: truncate(db, table, log_level=3)
1236

    
1237
def empty_db(db, schema='public', **kw_args):
1238
    '''For kw_args, see tables()'''
1239
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
1240

    
1241
def distinct_table(db, table, distinct_on):
1242
    '''Creates a copy of a temp table which is distinct on the given columns.
1243
    The old and new tables will both get an index on these columns, to
1244
    facilitate merge joins.
1245
    @param distinct_on If empty, creates a table with one row. This is useful if
1246
        your distinct_on columns are all literal values.
1247
    @return The new table.
1248
    '''
1249
    new_table = sql_gen.suffixed_table(table, '_distinct')
1250
    
1251
    copy_table_struct(db, table, new_table)
1252
    
1253
    limit = None
1254
    if distinct_on == []: limit = 1 # one sample row
1255
    else:
1256
        add_index(db, distinct_on, new_table, unique=True)
1257
        add_index(db, distinct_on, table) # for join optimization
1258
    
1259
    insert_select(db, new_table, None, mk_select(db, table, start=0,
1260
        limit=limit), ignore=True)
1261
    analyze(db, new_table)
1262
    
1263
    return new_table
(24-24/37)