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
        def log_msg(query):
358
            if used_cache: cache_status = 'cache hit'
359
            elif cacheable: cache_status = 'cache miss'
360
            else: cache_status = 'non-cacheable'
361
            
362
            # So that the src comment is hidden when cating the file, and put
363
            # on a separate line when viewed in a text editor.
364
            query = query.replace('\t', '\r', 1)
365
            
366
            return 'DB query: '+cache_status+':\n'+strings.as_code(query, 'SQL')
367
        
368
        try:
369
            # Get cursor
370
            if cacheable:
371
                try: cur = self.query_results[query]
372
                except KeyError: cur = self.DbCursor(self)
373
                else: used_cache = True
374
            else: cur = self.db.cursor()
375
            
376
            # Run query
377
            try: cur.execute(query)
378
            except Exception, e:
379
                _add_cursor_info(e, self, query)
380
                raise
381
            else: self.do_autocommit()
382
        finally:
383
            self.print_notices()
384
            if self.debug: # log or return query
385
                msg = log_msg(str(get_cur_query(cur, query)))
386
                if debug_msg_ref != None: debug_msg_ref[0] = msg
387
                else: self.log_debug(msg, log_level)
388
        
389
        return cur
390
    
391
    def is_cached(self, query): return query in self.query_results
392
    
393
    def with_autocommit(self, func):
394
        import psycopg2.extensions
395
        
396
        prev_isolation_level = self.db.isolation_level
397
        self.db.set_isolation_level(
398
            psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
399
        try: return func()
400
        finally: self.db.set_isolation_level(prev_isolation_level)
401
    
402
    def with_savepoint(self, func):
403
        top = self._savepoint == 0
404
        savepoint = 'level_'+str(self._savepoint)
405
        
406
        # Must happen before running queries so they don't get autocommitted
407
        self._savepoint += 1
408
        
409
        if top: query = 'START TRANSACTION ISOLATION LEVEL READ COMMITTED'
410
        else: query = 'SAVEPOINT '+savepoint
411
        self.run_query(query, log_level=4)
412
        try:
413
            return func()
414
            if top: self.run_query('COMMIT', log_level=4)
415
        except:
416
            if top: query = 'ROLLBACK'
417
            else: query = 'ROLLBACK TO SAVEPOINT '+savepoint
418
            self.run_query(query, log_level=4)
419
            
420
            raise
421
        finally:
422
            # Always release savepoint, because after ROLLBACK TO SAVEPOINT,
423
            # "The savepoint remains valid and can be rolled back to again"
424
            # (http://www.postgresql.org/docs/8.3/static/sql-rollback-to.html).
425
            if not top:
426
                self.run_query('RELEASE SAVEPOINT '+savepoint, log_level=4)
427
            
428
            self._savepoint -= 1
429
            assert self._savepoint >= 0
430
            
431
            self.do_autocommit() # OK to do this after ROLLBACK TO SAVEPOINT
432
    
433
    def do_autocommit(self):
434
        '''Autocommits if outside savepoint'''
435
        assert self._savepoint >= 1
436
        if self.autocommit and self._savepoint == 1:
437
            self.log_debug('Autocommitting', level=4)
438
            self.db.commit()
439
    
440
    def col_info(self, col, cacheable=True):
441
        table = sql_gen.Table('columns', 'information_schema')
442
        type_ = sql_gen.Coalesce(sql_gen.Nullif(sql_gen.Col('data_type'),
443
            'USER-DEFINED'), sql_gen.Col('udt_name'))
444
        cols = [type_, 'column_default',
445
            sql_gen.Cast('boolean', sql_gen.Col('is_nullable'))]
446
        
447
        conds = [('table_name', col.table.name), ('column_name', col.name)]
448
        schema = col.table.schema
449
        if schema != None: conds.append(('table_schema', schema))
450
        
451
        type_, default, nullable = row(select(self, table, cols, conds,
452
            order_by='table_schema', limit=1, cacheable=cacheable, log_level=4))
453
            # TODO: order_by search_path schema order
454
        default = sql_gen.as_Code(default, self)
455
        
456
        return sql_gen.TypedCol(col.name, type_, default, nullable)
457
    
458
    def TempFunction(self, name):
459
        if self.debug_temp: schema = None
460
        else: schema = 'pg_temp'
461
        return sql_gen.Function(name, schema)
462

    
463
connect = DbConn
464

    
465
##### Recoverable querying
466

    
467
def with_savepoint(db, func): return db.with_savepoint(func)
468

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

    
525
##### Basic queries
526

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

    
535
def lock_table(db, table, mode):
536
    table = sql_gen.as_Table(table)
537
    run_query(db, 'LOCK TABLE '+table.to_str(db)+' IN '+mode+' MODE')
538

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

    
582
order_by_pkey = object() # tells mk_select() to order by the pkey
583

    
584
distinct_on_all = object() # tells mk_select() to SELECT DISTINCT ON all columns
585

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

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

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

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

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

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

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

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

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

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

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

    
919
##### Database structure introspection
920

    
921
#### Tables
922

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

    
938
def table_exists(db, table):
939
    table = sql_gen.as_Table(table)
940
    return list(tables(db, table.schema, table.name, exact=True)) != []
941

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

    
946
def table_cols(db, table, recover=None):
947
    return list(col_names(select(db, table, limit=0, order_by=None,
948
        recover=recover, log_level=4)))
949

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

    
954
not_null_col = 'not_null_col'
955

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

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

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

    
1019
#### Functions
1020

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

    
1035
##### Structural changes
1036

    
1037
#### Columns
1038

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

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

    
1066
row_num_col = '_row_num'
1067

    
1068
row_num_typed_col = sql_gen.TypedCol(row_num_col, 'serial', nullable=False,
1069
    constraints='PRIMARY KEY')
1070

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

    
1076
#### Indexes
1077

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

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

    
1139
already_indexed = object() # tells add_indexes() the pkey has already been added
1140

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

    
1153
#### Tables
1154

    
1155
### Maintenance
1156

    
1157
def analyze(db, table):
1158
    table = sql_gen.as_Table(table)
1159
    run_query(db, 'ANALYZE '+table.to_str(db), log_level=3)
1160

    
1161
def autoanalyze(db, table):
1162
    if db.autoanalyze: analyze(db, table)
1163

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

    
1169
### Lifecycle
1170

    
1171
def drop_table(db, table):
1172
    table = sql_gen.as_Table(table)
1173
    return run_query(db, 'DROP TABLE IF EXISTS '+table.to_str(db)+' CASCADE')
1174

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

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

    
1223
### Data
1224

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

    
1230
def empty_temp(db, tables):
1231
    tables = lists.mk_seq(tables)
1232
    for table in tables: truncate(db, table, log_level=3)
1233

    
1234
def empty_db(db, schema='public', **kw_args):
1235
    '''For kw_args, see tables()'''
1236
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
1237

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