Project

General

Profile

1 11 aaronmk
# Database access
2
3 1869 aaronmk
import copy
4 11 aaronmk
import re
5 865 aaronmk
import warnings
6 11 aaronmk
7 300 aaronmk
import exc
8 1909 aaronmk
import dicts
9 1893 aaronmk
import iters
10 1960 aaronmk
import lists
11 1889 aaronmk
from Proxy import Proxy
12 1872 aaronmk
import rand
13 2217 aaronmk
import sql_gen
14 862 aaronmk
import strings
15 131 aaronmk
import util
16 11 aaronmk
17 832 aaronmk
##### Exceptions
18
19 2804 aaronmk
def get_cur_query(cur, input_query=None):
20 2168 aaronmk
    raw_query = None
21
    if hasattr(cur, 'query'): raw_query = cur.query
22
    elif hasattr(cur, '_last_executed'): raw_query = cur._last_executed
23 2170 aaronmk
24
    if raw_query != None: return raw_query
25 2804 aaronmk
    else: return '[input] '+strings.ustr(input_query)
26 14 aaronmk
27 2170 aaronmk
def _add_cursor_info(e, *args, **kw_args):
28
    '''For params, see get_cur_query()'''
29 2771 aaronmk
    exc.add_msg(e, 'query: '+strings.ustr(get_cur_query(*args, **kw_args)))
30 135 aaronmk
31 300 aaronmk
class DbException(exc.ExceptionWithCause):
32 14 aaronmk
    def __init__(self, msg, cause=None, cur=None):
33 2145 aaronmk
        exc.ExceptionWithCause.__init__(self, msg, cause, cause_newline=True)
34 14 aaronmk
        if cur != None: _add_cursor_info(self, cur)
35
36 2143 aaronmk
class ExceptionWithName(DbException):
37
    def __init__(self, name, cause=None):
38 2484 aaronmk
        DbException.__init__(self, 'for name: '+strings.as_tt(str(name)), cause)
39 2143 aaronmk
        self.name = name
40 360 aaronmk
41 3109 aaronmk
class ExceptionWithValue(DbException):
42
    def __init__(self, value, cause=None):
43
        DbException.__init__(self, 'for value: '+strings.as_tt(repr(value)),
44
            cause)
45 2240 aaronmk
        self.value = value
46
47 2945 aaronmk
class ExceptionWithNameType(DbException):
48
    def __init__(self, type_, name, cause=None):
49
        DbException.__init__(self, 'for type: '+strings.as_tt(str(type_))
50
            +'; name: '+strings.as_tt(name), cause)
51
        self.type = type_
52
        self.name = name
53
54 2306 aaronmk
class ConstraintException(DbException):
55
    def __init__(self, name, cols, cause=None):
56 2484 aaronmk
        DbException.__init__(self, 'Violated '+strings.as_tt(name)
57
            +' constraint on columns: '+strings.as_tt(', '.join(cols)), cause)
58 2306 aaronmk
        self.name = name
59 468 aaronmk
        self.cols = cols
60 11 aaronmk
61 2523 aaronmk
class MissingCastException(DbException):
62
    def __init__(self, type_, col, cause=None):
63
        DbException.__init__(self, 'Missing cast to type '+strings.as_tt(type_)
64
            +' on column: '+strings.as_tt(col), cause)
65
        self.type = type_
66
        self.col = col
67
68 2143 aaronmk
class NameException(DbException): pass
69
70 2306 aaronmk
class DuplicateKeyException(ConstraintException): pass
71 13 aaronmk
72 2306 aaronmk
class NullValueException(ConstraintException): pass
73 13 aaronmk
74 3109 aaronmk
class InvalidValueException(ExceptionWithValue): pass
75 2239 aaronmk
76 2945 aaronmk
class DuplicateException(ExceptionWithNameType): pass
77 2143 aaronmk
78 89 aaronmk
class EmptyRowException(DbException): pass
79
80 865 aaronmk
##### Warnings
81
82
class DbWarning(UserWarning): pass
83
84 1930 aaronmk
##### Result retrieval
85
86
def col_names(cur): return (col[0] for col in cur.description)
87
88
def rows(cur): return iter(lambda: cur.fetchone(), None)
89
90
def consume_rows(cur):
91
    '''Used to fetch all rows so result will be cached'''
92
    iters.consume_iter(rows(cur))
93
94
def next_row(cur): return rows(cur).next()
95
96
def row(cur):
97
    row_ = next_row(cur)
98
    consume_rows(cur)
99
    return row_
100
101
def next_value(cur): return next_row(cur)[0]
102
103
def value(cur): return row(cur)[0]
104
105
def values(cur): return iters.func_iter(lambda: next_value(cur))
106
107
def value_or_none(cur):
108
    try: return value(cur)
109
    except StopIteration: return None
110
111 2762 aaronmk
##### Escaping
112 2101 aaronmk
113 2573 aaronmk
def esc_name_by_module(module, name):
114
    if module == 'psycopg2' or module == None: quote = '"'
115 2101 aaronmk
    elif module == 'MySQLdb': quote = '`'
116
    else: raise NotImplementedError("Can't escape name for "+module+' database')
117 2500 aaronmk
    return sql_gen.esc_name(name, quote)
118 2101 aaronmk
119
def esc_name_by_engine(engine, name, **kw_args):
120
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
121
122
def esc_name(db, name, **kw_args):
123
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
124
125
def qual_name(db, schema, table):
126
    def esc_name_(name): return esc_name(db, name)
127
    table = esc_name_(table)
128
    if schema != None: return esc_name_(schema)+'.'+table
129
    else: return table
130
131 1869 aaronmk
##### Database connections
132 1849 aaronmk
133 2097 aaronmk
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
134 1926 aaronmk
135 1869 aaronmk
db_engines = {
136
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
137
    'PostgreSQL': ('psycopg2', {}),
138
}
139
140
DatabaseErrors_set = set([DbException])
141
DatabaseErrors = tuple(DatabaseErrors_set)
142
143
def _add_module(module):
144
    DatabaseErrors_set.add(module.DatabaseError)
145
    global DatabaseErrors
146
    DatabaseErrors = tuple(DatabaseErrors_set)
147
148
def db_config_str(db_config):
149
    return db_config['engine']+' database '+db_config['database']
150
151 2448 aaronmk
log_debug_none = lambda msg, level=2: None
152 1901 aaronmk
153 1849 aaronmk
class DbConn:
154 2923 aaronmk
    def __init__(self, db_config, autocommit=True, caching=True,
155 3183 aaronmk
        log_debug=log_debug_none, debug_temp=False, src=None):
156 2915 aaronmk
        '''
157
        @param debug_temp Whether temporary objects should instead be permanent.
158
            This assists in debugging the internal objects used by the program.
159 3183 aaronmk
        @param src In autocommit mode, will be included in a comment in every
160
            query, to help identify the data source in pg_stat_activity.
161 2915 aaronmk
        '''
162 1869 aaronmk
        self.db_config = db_config
163 2190 aaronmk
        self.autocommit = autocommit
164
        self.caching = caching
165 1901 aaronmk
        self.log_debug = log_debug
166 2193 aaronmk
        self.debug = log_debug != log_debug_none
167 2915 aaronmk
        self.debug_temp = debug_temp
168 3183 aaronmk
        self.src = src
169 3074 aaronmk
        self.autoanalyze = False
170 1869 aaronmk
171 3124 aaronmk
        self._savepoint = 0
172 3120 aaronmk
        self._reset()
173 1869 aaronmk
174
    def __getattr__(self, name):
175
        if name == '__dict__': raise Exception('getting __dict__')
176
        if name == 'db': return self._db()
177
        else: raise AttributeError()
178
179
    def __getstate__(self):
180
        state = copy.copy(self.__dict__) # shallow copy
181 1915 aaronmk
        state['log_debug'] = None # don't pickle the debug callback
182 1869 aaronmk
        state['_DbConn__db'] = None # don't pickle the connection
183
        return state
184
185 3118 aaronmk
    def clear_cache(self): self.query_results = {}
186
187 3120 aaronmk
    def _reset(self):
188 3118 aaronmk
        self.clear_cache()
189 3124 aaronmk
        assert self._savepoint == 0
190 3118 aaronmk
        self._notices_seen = set()
191
        self.__db = None
192
193 2165 aaronmk
    def connected(self): return self.__db != None
194
195 3116 aaronmk
    def close(self):
196 3119 aaronmk
        if not self.connected(): return
197
198 3135 aaronmk
        # Record that the automatic transaction is now closed
199 3136 aaronmk
        self._savepoint -= 1
200 3135 aaronmk
201 3119 aaronmk
        self.db.close()
202 3120 aaronmk
        self._reset()
203 3116 aaronmk
204 3125 aaronmk
    def reconnect(self):
205
        # Do not do this in test mode as it would roll back everything
206
        if self.autocommit: self.close()
207
        # Connection will be reopened automatically on first query
208
209 1869 aaronmk
    def _db(self):
210
        if self.__db == None:
211
            # Process db_config
212
            db_config = self.db_config.copy() # don't modify input!
213 2097 aaronmk
            schemas = db_config.pop('schemas', None)
214 1869 aaronmk
            module_name, mappings = db_engines[db_config.pop('engine')]
215
            module = __import__(module_name)
216
            _add_module(module)
217
            for orig, new in mappings.iteritems():
218
                try: util.rename_key(db_config, orig, new)
219
                except KeyError: pass
220
221
            # Connect
222
            self.__db = module.connect(**db_config)
223
224 3161 aaronmk
            # Record that a transaction is already open
225
            self._savepoint += 1
226
227 1869 aaronmk
            # Configure connection
228 2906 aaronmk
            if hasattr(self.db, 'set_isolation_level'):
229
                import psycopg2.extensions
230
                self.db.set_isolation_level(
231
                    psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED)
232 2101 aaronmk
            if schemas != None:
233 2893 aaronmk
                search_path = [self.esc_name(s) for s in schemas.split(',')]
234
                search_path.append(value(run_query(self, 'SHOW search_path',
235
                    log_level=4)))
236
                run_query(self, 'SET search_path TO '+(','.join(search_path)),
237
                    log_level=3)
238 1869 aaronmk
239
        return self.__db
240 1889 aaronmk
241 1891 aaronmk
    class DbCursor(Proxy):
242 1927 aaronmk
        def __init__(self, outer):
243 1891 aaronmk
            Proxy.__init__(self, outer.db.cursor())
244 2191 aaronmk
            self.outer = outer
245 1927 aaronmk
            self.query_results = outer.query_results
246 1894 aaronmk
            self.query_lookup = None
247 1891 aaronmk
            self.result = []
248 1889 aaronmk
249 2802 aaronmk
        def execute(self, query):
250 2764 aaronmk
            self._is_insert = query.startswith('INSERT')
251 2797 aaronmk
            self.query_lookup = query
252 2148 aaronmk
            try:
253 3162 aaronmk
                try: cur = self.inner.execute(query)
254 2802 aaronmk
                finally: self.query = get_cur_query(self.inner, query)
255 1904 aaronmk
            except Exception, e:
256
                self.result = e # cache the exception as the result
257
                self._cache_result()
258
                raise
259 3004 aaronmk
260
            # Always cache certain queries
261 3183 aaronmk
            query = sql_gen.lstrip(query)
262 3004 aaronmk
            if query.startswith('CREATE') or query.startswith('ALTER'):
263 3007 aaronmk
                # structural changes
264 3040 aaronmk
                # Rest of query must be unique in the face of name collisions,
265
                # so don't cache ADD COLUMN unless it has distinguishing comment
266
                if query.find('ADD COLUMN') < 0 or query.endswith('*/'):
267 3007 aaronmk
                    self._cache_result()
268 3004 aaronmk
            elif self.rowcount == 0 and query.startswith('SELECT'): # empty
269 2800 aaronmk
                consume_rows(self) # fetch all rows so result will be cached
270 3004 aaronmk
271 2762 aaronmk
            return cur
272 1894 aaronmk
273 1891 aaronmk
        def fetchone(self):
274
            row = self.inner.fetchone()
275 1899 aaronmk
            if row != None: self.result.append(row)
276
            # otherwise, fetched all rows
277 1904 aaronmk
            else: self._cache_result()
278
            return row
279
280
        def _cache_result(self):
281 2948 aaronmk
            # For inserts that return a result set, don't cache result set since
282
            # inserts are not idempotent. Other non-SELECT queries don't have
283
            # their result set read, so only exceptions will be cached (an
284
            # invalid query will always be invalid).
285 1930 aaronmk
            if self.query_results != None and (not self._is_insert
286 1906 aaronmk
                or isinstance(self.result, Exception)):
287
288 1894 aaronmk
                assert self.query_lookup != None
289 1916 aaronmk
                self.query_results[self.query_lookup] = self.CacheCursor(
290
                    util.dict_subset(dicts.AttrsDictView(self),
291
                    ['query', 'result', 'rowcount', 'description']))
292 1906 aaronmk
293 1916 aaronmk
        class CacheCursor:
294
            def __init__(self, cached_result): self.__dict__ = cached_result
295
296 1927 aaronmk
            def execute(self, *args, **kw_args):
297 1916 aaronmk
                if isinstance(self.result, Exception): raise self.result
298
                # otherwise, result is a rows list
299
                self.iter = iter(self.result)
300
301
            def fetchone(self):
302
                try: return self.iter.next()
303
                except StopIteration: return None
304 1891 aaronmk
305 2212 aaronmk
    def esc_value(self, value):
306 2663 aaronmk
        try: str_ = self.mogrify('%s', [value])
307
        except NotImplementedError, e:
308
            module = util.root_module(self.db)
309
            if module == 'MySQLdb':
310
                import _mysql
311
                str_ = _mysql.escape_string(value)
312
            else: raise e
313 2374 aaronmk
        return strings.to_unicode(str_)
314 2212 aaronmk
315 2347 aaronmk
    def esc_name(self, name): return esc_name(self, name) # calls global func
316
317 2814 aaronmk
    def std_code(self, str_):
318
        '''Standardizes SQL code.
319
        * Ensures that string literals are prefixed by `E`
320
        '''
321
        if str_.startswith("'"): str_ = 'E'+str_
322
        return str_
323
324 2665 aaronmk
    def can_mogrify(self):
325 2663 aaronmk
        module = util.root_module(self.db)
326 2665 aaronmk
        return module == 'psycopg2'
327 2663 aaronmk
328 2665 aaronmk
    def mogrify(self, query, params=None):
329
        if self.can_mogrify(): return self.db.cursor().mogrify(query, params)
330
        else: raise NotImplementedError("Can't mogrify query")
331
332 2671 aaronmk
    def print_notices(self):
333 2725 aaronmk
        if hasattr(self.db, 'notices'):
334
            for msg in self.db.notices:
335
                if msg not in self._notices_seen:
336
                    self._notices_seen.add(msg)
337
                    self.log_debug(msg, level=2)
338 2671 aaronmk
339 2793 aaronmk
    def run_query(self, query, cacheable=False, log_level=2,
340 2464 aaronmk
        debug_msg_ref=None):
341 2445 aaronmk
        '''
342 2464 aaronmk
        @param log_ignore_excs The log_level will be increased by 2 if the query
343
            throws one of these exceptions.
344 2664 aaronmk
        @param debug_msg_ref If specified, the log message will be returned in
345
            this instead of being output. This allows you to filter log messages
346
            depending on the result of the query.
347 2445 aaronmk
        '''
348 2167 aaronmk
        assert query != None
349
350 3183 aaronmk
        if self.autocommit and self.src != None:
351
            query = sql_gen.esc_comment(self.src)+' '+query
352
353 2047 aaronmk
        if not self.caching: cacheable = False
354 1903 aaronmk
        used_cache = False
355 2664 aaronmk
356
        def log_msg(query):
357
            if used_cache: cache_status = 'cache hit'
358
            elif cacheable: cache_status = 'cache miss'
359
            else: cache_status = 'non-cacheable'
360
            return 'DB query: '+cache_status+':\n'+strings.as_code(query, 'SQL')
361
362 1903 aaronmk
        try:
363 1927 aaronmk
            # Get cursor
364
            if cacheable:
365
                try:
366 2797 aaronmk
                    cur = self.query_results[query]
367 1927 aaronmk
                    used_cache = True
368
                except KeyError: cur = self.DbCursor(self)
369
            else: cur = self.db.cursor()
370
371 2664 aaronmk
            # Log query
372
            if self.debug and debug_msg_ref == None: # log before running
373
                self.log_debug(log_msg(query), log_level)
374
375 1927 aaronmk
            # Run query
376 3162 aaronmk
            try:
377
                cur.execute(query)
378
                self.do_autocommit()
379
            except Exception, e:
380
                _add_cursor_info(e, self, query)
381
                raise
382 1903 aaronmk
        finally:
383 2671 aaronmk
            self.print_notices()
384 2664 aaronmk
            if self.debug and debug_msg_ref != None: # return after running
385 2793 aaronmk
                debug_msg_ref[0] = log_msg(str(get_cur_query(cur, query)))
386 1903 aaronmk
387
        return cur
388 1914 aaronmk
389 2797 aaronmk
    def is_cached(self, query): return query in self.query_results
390 2139 aaronmk
391 2907 aaronmk
    def with_autocommit(self, func):
392 2801 aaronmk
        import psycopg2.extensions
393
394
        prev_isolation_level = self.db.isolation_level
395 2907 aaronmk
        self.db.set_isolation_level(
396
            psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
397 2683 aaronmk
        try: return func()
398 2801 aaronmk
        finally: self.db.set_isolation_level(prev_isolation_level)
399 2683 aaronmk
400 2139 aaronmk
    def with_savepoint(self, func):
401 3137 aaronmk
        top = self._savepoint == 0
402 2171 aaronmk
        savepoint = 'level_'+str(self._savepoint)
403 3137 aaronmk
404 3160 aaronmk
        # Must happen before running queries so they don't get autocommitted
405
        self._savepoint += 1
406
407 3137 aaronmk
        if top: query = 'START TRANSACTION ISOLATION LEVEL READ COMMITTED'
408
        else: query = 'SAVEPOINT '+savepoint
409
        self.run_query(query, log_level=4)
410
        try:
411
            return func()
412
            if top: self.run_query('COMMIT', log_level=4)
413 2139 aaronmk
        except:
414 3137 aaronmk
            if top: query = 'ROLLBACK'
415
            else: query = 'ROLLBACK TO SAVEPOINT '+savepoint
416
            self.run_query(query, log_level=4)
417
418 2139 aaronmk
            raise
419 2930 aaronmk
        finally:
420
            # Always release savepoint, because after ROLLBACK TO SAVEPOINT,
421
            # "The savepoint remains valid and can be rolled back to again"
422
            # (http://www.postgresql.org/docs/8.3/static/sql-rollback-to.html).
423 3137 aaronmk
            if not top:
424
                self.run_query('RELEASE SAVEPOINT '+savepoint, log_level=4)
425 2930 aaronmk
426
            self._savepoint -= 1
427
            assert self._savepoint >= 0
428
429
            self.do_autocommit() # OK to do this after ROLLBACK TO SAVEPOINT
430 2191 aaronmk
431
    def do_autocommit(self):
432
        '''Autocommits if outside savepoint'''
433 3135 aaronmk
        assert self._savepoint >= 1
434
        if self.autocommit and self._savepoint == 1:
435 2924 aaronmk
            self.log_debug('Autocommitting', level=4)
436 2191 aaronmk
            self.db.commit()
437 2643 aaronmk
438 3155 aaronmk
    def col_info(self, col, cacheable=True):
439 2643 aaronmk
        table = sql_gen.Table('columns', 'information_schema')
440 3063 aaronmk
        type_ = sql_gen.Coalesce(sql_gen.Nullif(sql_gen.Col('data_type'),
441
            'USER-DEFINED'), sql_gen.Col('udt_name'))
442 3078 aaronmk
        cols = [type_, 'column_default',
443
            sql_gen.Cast('boolean', sql_gen.Col('is_nullable'))]
444 2643 aaronmk
445
        conds = [('table_name', col.table.name), ('column_name', col.name)]
446
        schema = col.table.schema
447
        if schema != None: conds.append(('table_schema', schema))
448
449 2819 aaronmk
        type_, default, nullable = row(select(self, table, cols, conds,
450 3150 aaronmk
            order_by='table_schema', limit=1, cacheable=cacheable, log_level=4))
451 2643 aaronmk
            # TODO: order_by search_path schema order
452 2819 aaronmk
        default = sql_gen.as_Code(default, self)
453
454
        return sql_gen.TypedCol(col.name, type_, default, nullable)
455 2917 aaronmk
456
    def TempFunction(self, name):
457
        if self.debug_temp: schema = None
458
        else: schema = 'pg_temp'
459
        return sql_gen.Function(name, schema)
460 1849 aaronmk
461 1869 aaronmk
connect = DbConn
462
463 832 aaronmk
##### Recoverable querying
464 15 aaronmk
465 2139 aaronmk
def with_savepoint(db, func): return db.with_savepoint(func)
466 11 aaronmk
467 2791 aaronmk
def run_query(db, query, recover=None, cacheable=False, log_level=2,
468
    log_ignore_excs=None, **kw_args):
469 2794 aaronmk
    '''For params, see DbConn.run_query()'''
470 830 aaronmk
    if recover == None: recover = False
471 2464 aaronmk
    if log_ignore_excs == None: log_ignore_excs = ()
472
    log_ignore_excs = tuple(log_ignore_excs)
473 830 aaronmk
474 2666 aaronmk
    debug_msg_ref = None # usually, db.run_query() logs query before running it
475
    # But if filtering with log_ignore_excs, wait until after exception parsing
476 2984 aaronmk
    if log_ignore_excs != () or not db.can_mogrify(): debug_msg_ref = [None]
477 2666 aaronmk
478 2148 aaronmk
    try:
479 2464 aaronmk
        try:
480 2794 aaronmk
            def run(): return db.run_query(query, cacheable, log_level,
481 2793 aaronmk
                debug_msg_ref, **kw_args)
482 2796 aaronmk
            if recover and not db.is_cached(query):
483 2464 aaronmk
                return with_savepoint(db, run)
484
            else: return run() # don't need savepoint if cached
485
        except Exception, e:
486 3095 aaronmk
            msg = strings.ustr(e.args[0])
487 2464 aaronmk
488 3095 aaronmk
            match = re.match(r'^duplicate key value violates unique constraint '
489 3096 aaronmk
                r'"((_?[^\W_]+(?=[._]))?.+?)"', msg)
490 2464 aaronmk
            if match:
491
                constraint, table = match.groups()
492 3025 aaronmk
                cols = []
493
                if recover: # need auto-rollback to run index_cols()
494
                    try: cols = index_cols(db, table, constraint)
495
                    except NotImplementedError: pass
496
                raise DuplicateKeyException(constraint, cols, e)
497 2464 aaronmk
498 3095 aaronmk
            match = re.match(r'^null value in column "(.+?)" violates not-null'
499 2464 aaronmk
                r' constraint', msg)
500
            if match: raise NullValueException('NOT NULL', [match.group(1)], e)
501
502 3095 aaronmk
            match = re.match(r'^(?:invalid input (?:syntax|value)\b.*?'
503 3109 aaronmk
                r'|.+? field value out of range): "(.+?)"', msg)
504 2464 aaronmk
            if match:
505 3109 aaronmk
                value, = match.groups()
506
                raise InvalidValueException(strings.to_unicode(value), e)
507 2464 aaronmk
508 3095 aaronmk
            match = re.match(r'^column "(.+?)" is of type (.+?) but expression '
509 2523 aaronmk
                r'is of type', msg)
510
            if match:
511
                col, type_ = match.groups()
512
                raise MissingCastException(type_, col, e)
513
514 3095 aaronmk
            match = re.match(r'^(\S+) "(.+?)".*? already exists', msg)
515 2945 aaronmk
            if match:
516
                type_, name = match.groups()
517
                raise DuplicateException(type_, name, e)
518 2464 aaronmk
519
            raise # no specific exception raised
520
    except log_ignore_excs:
521
        log_level += 2
522
        raise
523
    finally:
524 2666 aaronmk
        if debug_msg_ref != None and debug_msg_ref[0] != None:
525
            db.log_debug(debug_msg_ref[0], log_level)
526 830 aaronmk
527 832 aaronmk
##### Basic queries
528
529 2153 aaronmk
def next_version(name):
530 2163 aaronmk
    version = 1 # first existing name was version 0
531 2586 aaronmk
    match = re.match(r'^(.*)#(\d+)$', name)
532 2153 aaronmk
    if match:
533 2586 aaronmk
        name, version = match.groups()
534
        version = int(version)+1
535 2932 aaronmk
    return sql_gen.concat(name, '#'+str(version))
536 2153 aaronmk
537 2899 aaronmk
def lock_table(db, table, mode):
538
    table = sql_gen.as_Table(table)
539
    run_query(db, 'LOCK TABLE '+table.to_str(db)+' IN '+mode+' MODE')
540
541 2789 aaronmk
def run_query_into(db, query, into=None, add_indexes_=False, **kw_args):
542 2085 aaronmk
    '''Outputs a query to a temp table.
543
    For params, see run_query().
544
    '''
545 2789 aaronmk
    if into == None: return run_query(db, query, **kw_args)
546 2790 aaronmk
547
    assert isinstance(into, sql_gen.Table)
548
549 2992 aaronmk
    into.is_temp = True
550 3008 aaronmk
    # "temporary tables cannot specify a schema name", so remove schema
551
    into.schema = None
552 2992 aaronmk
553 2790 aaronmk
    kw_args['recover'] = True
554 2945 aaronmk
    kw_args.setdefault('log_ignore_excs', (DuplicateException,))
555 2790 aaronmk
556 2916 aaronmk
    temp = not db.debug_temp # tables are permanent in debug_temp mode
557 2790 aaronmk
558
    # Create table
559
    while True:
560
        create_query = 'CREATE'
561
        if temp: create_query += ' TEMP'
562
        create_query += ' TABLE '+into.to_str(db)+' AS\n'+query
563 2385 aaronmk
564 2790 aaronmk
        try:
565
            cur = run_query(db, create_query, **kw_args)
566
                # CREATE TABLE AS sets rowcount to # rows in query
567
            break
568 2945 aaronmk
        except DuplicateException, e:
569 2790 aaronmk
            into.name = next_version(into.name)
570
            # try again with next version of name
571
572
    if add_indexes_: add_indexes(db, into)
573 3075 aaronmk
574
    # According to the PostgreSQL doc, "The autovacuum daemon cannot access and
575
    # therefore cannot vacuum or analyze temporary tables. [...] if a temporary
576
    # table is going to be used in complex queries, it is wise to run ANALYZE on
577
    # the temporary table after it is populated."
578
    # (http://www.postgresql.org/docs/9.1/static/sql-createtable.html)
579
    # If into is not a temp table, ANALYZE is useful but not required.
580 3073 aaronmk
    analyze(db, into)
581 2790 aaronmk
582
    return cur
583 2085 aaronmk
584 2120 aaronmk
order_by_pkey = object() # tells mk_select() to order by the pkey
585
586 2199 aaronmk
distinct_on_all = object() # tells mk_select() to SELECT DISTINCT ON all columns
587
588 2233 aaronmk
def mk_select(db, tables, fields=None, conds=None, distinct_on=[], limit=None,
589 2293 aaronmk
    start=None, order_by=order_by_pkey, default_table=None):
590 1981 aaronmk
    '''
591 2121 aaronmk
    @param tables The single table to select from, or a list of tables to join
592 2280 aaronmk
        together, with tables after the first being sql_gen.Join objects
593 1981 aaronmk
    @param fields Use None to select all fields in the table
594 2377 aaronmk
    @param conds WHERE conditions: [(compare_left_side, compare_right_side),...]
595 2379 aaronmk
        * container can be any iterable type
596 2399 aaronmk
        * compare_left_side: sql_gen.Code|str (for col name)
597
        * compare_right_side: sql_gen.ValueCond|literal value
598 2199 aaronmk
    @param distinct_on The columns to SELECT DISTINCT ON, or distinct_on_all to
599
        use all columns
600 2786 aaronmk
    @return query
601 1981 aaronmk
    '''
602 2315 aaronmk
    # Parse tables param
603 2964 aaronmk
    tables = lists.mk_seq(tables)
604 2141 aaronmk
    tables = list(tables) # don't modify input! (list() copies input)
605 2315 aaronmk
    table0 = sql_gen.as_Table(tables.pop(0)) # first table is separate
606 2121 aaronmk
607 2315 aaronmk
    # Parse other params
608 2376 aaronmk
    if conds == None: conds = []
609 2650 aaronmk
    elif dicts.is_dict(conds): conds = conds.items()
610 2379 aaronmk
    conds = list(conds) # don't modify input! (list() copies input)
611 3129 aaronmk
    assert limit == None or isinstance(limit, (int, long))
612
    assert start == None or isinstance(start, (int, long))
613 2315 aaronmk
    if order_by is order_by_pkey:
614
        if distinct_on != []: order_by = None
615
        else: order_by = pkey(db, table0, recover=True)
616 865 aaronmk
617 2315 aaronmk
    query = 'SELECT'
618 2056 aaronmk
619 2315 aaronmk
    def parse_col(col): return sql_gen.as_Col(col, default_table).to_str(db)
620 2056 aaronmk
621 2200 aaronmk
    # DISTINCT ON columns
622 2233 aaronmk
    if distinct_on != []:
623 2467 aaronmk
        query += '\nDISTINCT'
624 2254 aaronmk
        if distinct_on is not distinct_on_all:
625 2200 aaronmk
            query += ' ON ('+(', '.join(map(parse_col, distinct_on)))+')'
626
627
    # Columns
628 3185 aaronmk
    if query.find('\n') >= 0: whitespace = '\n'
629
    else: whitespace = ' '
630
    if fields == None: query += whitespace+'*'
631 2765 aaronmk
    else:
632
        assert fields != []
633 3185 aaronmk
        if len(fields) > 1: whitespace = '\n'
634
        query += whitespace+('\n, '.join(map(parse_col, fields)))
635 2200 aaronmk
636
    # Main table
637 3185 aaronmk
    if query.find('\n') >= 0 or len(tables) > 0: whitespace = '\n'
638
    else: whitespace = ' '
639
    query += whitespace+'FROM '+table0.to_str(db)
640 865 aaronmk
641 2122 aaronmk
    # Add joins
642 2271 aaronmk
    left_table = table0
643 2263 aaronmk
    for join_ in tables:
644
        table = join_.table
645 2238 aaronmk
646 2343 aaronmk
        # Parse special values
647
        if join_.type_ is sql_gen.filter_out: # filter no match
648 2376 aaronmk
            conds.append((sql_gen.Col(table_not_null_col(db, table), table),
649 2853 aaronmk
                sql_gen.CompareCond(None, '~=')))
650 2343 aaronmk
651 2467 aaronmk
        query += '\n'+join_.to_str(db, left_table)
652 2122 aaronmk
653
        left_table = table
654
655 865 aaronmk
    missing = True
656 2376 aaronmk
    if conds != []:
657 2576 aaronmk
        if len(conds) == 1: whitespace = ' '
658
        else: whitespace = '\n'
659 2578 aaronmk
        query += '\n'+sql_gen.combine_conds([sql_gen.ColValueCond(l, r)
660
            .to_str(db) for l, r in conds], 'WHERE')
661 865 aaronmk
        missing = False
662 2227 aaronmk
    if order_by != None:
663 2467 aaronmk
        query += '\nORDER BY '+sql_gen.as_Col(order_by, table0).to_str(db)
664
    if limit != None: query += '\nLIMIT '+str(limit); missing = False
665 865 aaronmk
    if start != None:
666 2467 aaronmk
        if start != 0: query += '\nOFFSET '+str(start)
667 865 aaronmk
        missing = False
668
    if missing: warnings.warn(DbWarning(
669
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
670
671 2786 aaronmk
    return query
672 11 aaronmk
673 2054 aaronmk
def select(db, *args, **kw_args):
674
    '''For params, see mk_select() and run_query()'''
675
    recover = kw_args.pop('recover', None)
676
    cacheable = kw_args.pop('cacheable', True)
677 2442 aaronmk
    log_level = kw_args.pop('log_level', 2)
678 2054 aaronmk
679 2791 aaronmk
    return run_query(db, mk_select(db, *args, **kw_args), recover, cacheable,
680
        log_level=log_level)
681 2054 aaronmk
682 2788 aaronmk
def mk_insert_select(db, table, cols=None, select_query=None, returning=None,
683 3181 aaronmk
    embeddable=False, ignore=False, src=None):
684 1960 aaronmk
    '''
685
    @param returning str|None An inserted column (such as pkey) to return
686 2070 aaronmk
    @param embeddable Whether the query should be embeddable as a nested SELECT.
687 2073 aaronmk
        Warning: If you set this and cacheable=True when the query is run, the
688
        query will be fully cached, not just if it raises an exception.
689 3009 aaronmk
    @param ignore Whether to ignore duplicate keys.
690 3181 aaronmk
    @param src Will be included in the name of any created function, to help
691
        identify the data source in pg_stat_activity.
692 1960 aaronmk
    '''
693 2754 aaronmk
    table = sql_gen.remove_table_rename(sql_gen.as_Table(table))
694 2318 aaronmk
    if cols == []: cols = None # no cols (all defaults) = unknown col names
695 3010 aaronmk
    if cols != None: cols = [sql_gen.to_name_only_col(c, table) for c in cols]
696 2063 aaronmk
    if select_query == None: select_query = 'DEFAULT VALUES'
697 2327 aaronmk
    if returning != None: returning = sql_gen.as_Col(returning, table)
698 2063 aaronmk
699 2497 aaronmk
    first_line = 'INSERT INTO '+table.to_str(db)
700 2063 aaronmk
701 3009 aaronmk
    def mk_insert(select_query):
702
        query = first_line
703 3014 aaronmk
        if cols != None:
704
            query += '\n('+(', '.join((c.to_str(db) for c in cols)))+')'
705 3009 aaronmk
        query += '\n'+select_query
706
707
        if returning != None:
708
            returning_name_col = sql_gen.to_name_only_col(returning)
709
            query += '\nRETURNING '+returning_name_col.to_str(db)
710
711
        return query
712 2063 aaronmk
713 3017 aaronmk
    return_type = 'unknown'
714
    if returning != None: return_type = returning.to_str(db)+'%TYPE'
715
716 3009 aaronmk
    lang = 'sql'
717
    if ignore:
718 3017 aaronmk
        # Always return something to set the correct rowcount
719
        if returning == None: returning = sql_gen.NamedCol('NULL', None)
720
721 3009 aaronmk
        embeddable = True # must use function
722
        lang = 'plpgsql'
723 3010 aaronmk
724 3092 aaronmk
        if cols == None:
725
            row = [sql_gen.Col(sql_gen.all_cols, 'row')]
726
            row_vars = [sql_gen.Table('row')]
727
        else:
728
            row_vars = row = [sql_gen.Col(c.name, 'row') for c in cols]
729
730 3009 aaronmk
        query = '''\
731 3010 aaronmk
DECLARE
732 3014 aaronmk
    row '''+table.to_str(db)+'''%ROWTYPE;
733 3009 aaronmk
BEGIN
734 3019 aaronmk
    /* Need an EXCEPTION block for each individual row because "When an error is
735
    caught by an EXCEPTION clause, [...] all changes to persistent database
736
    state within the block are rolled back."
737
    This is unfortunate because "A block containing an EXCEPTION clause is
738
    significantly more expensive to enter and exit than a block without one."
739 3015 aaronmk
    (http://www.postgresql.org/docs/8.3/static/plpgsql-control-structures.html\
740
#PLPGSQL-ERROR-TRAPPING)
741
    */
742 3092 aaronmk
    FOR '''+(', '.join((v.to_str(db) for v in row_vars)))+''' IN
743 3034 aaronmk
'''+select_query+'''
744
    LOOP
745 3015 aaronmk
        BEGIN
746 3019 aaronmk
            RETURN QUERY
747 3014 aaronmk
'''+mk_insert(sql_gen.Values(row).to_str(db))+'''
748 3010 aaronmk
;
749 3015 aaronmk
        EXCEPTION
750 3019 aaronmk
            WHEN unique_violation THEN NULL; -- continue to next row
751 3015 aaronmk
        END;
752 3010 aaronmk
    END LOOP;
753
END;\
754 3009 aaronmk
'''
755
    else: query = mk_insert(select_query)
756
757 2070 aaronmk
    if embeddable:
758
        # Create function
759 2513 aaronmk
        function_name = sql_gen.clean_name(first_line)
760 3181 aaronmk
        if src != None: function_name = src+': '+function_name
761 2189 aaronmk
        while True:
762
            try:
763 2918 aaronmk
                function = db.TempFunction(function_name)
764 2194 aaronmk
765 2189 aaronmk
                function_query = '''\
766 2698 aaronmk
CREATE FUNCTION '''+function.to_str(db)+'''()
767 3017 aaronmk
RETURNS SETOF '''+return_type+'''
768 3009 aaronmk
LANGUAGE '''+lang+'''
769 2467 aaronmk
AS $$
770 3009 aaronmk
'''+query+'''
771 2467 aaronmk
$$;
772 2070 aaronmk
'''
773 2446 aaronmk
                run_query(db, function_query, recover=True, cacheable=True,
774 2945 aaronmk
                    log_ignore_excs=(DuplicateException,))
775 2189 aaronmk
                break # this version was successful
776 2945 aaronmk
            except DuplicateException, e:
777 2189 aaronmk
                function_name = next_version(function_name)
778
                # try again with next version of name
779 2070 aaronmk
780 2337 aaronmk
        # Return query that uses function
781 3009 aaronmk
        cols = None
782
        if returning != None: cols = [returning]
783 2698 aaronmk
        func_table = sql_gen.NamedTable('f', sql_gen.FunctionCall(function),
784 3009 aaronmk
            cols) # AS clause requires function alias
785 2787 aaronmk
        return mk_select(db, func_table, start=0, order_by=None)
786 2070 aaronmk
787 2787 aaronmk
    return query
788 2066 aaronmk
789 3074 aaronmk
def insert_select(db, table, *args, **kw_args):
790 2085 aaronmk
    '''For params, see mk_insert_select() and run_query_into()
791 2386 aaronmk
    @param into sql_gen.Table with suggested name of temp table to put RETURNING
792
        values in
793 2072 aaronmk
    '''
794 3141 aaronmk
    returning = kw_args.get('returning', None)
795
    ignore = kw_args.get('ignore', False)
796
797 2386 aaronmk
    into = kw_args.pop('into', None)
798
    if into != None: kw_args['embeddable'] = True
799 2066 aaronmk
    recover = kw_args.pop('recover', None)
800 3141 aaronmk
    if ignore: recover = True
801 2066 aaronmk
    cacheable = kw_args.pop('cacheable', True)
802 2673 aaronmk
    log_level = kw_args.pop('log_level', 2)
803 2066 aaronmk
804 3141 aaronmk
    rowcount_only = ignore and returning == None # keep NULL rows on server
805
    if rowcount_only: into = sql_gen.Table('rowcount')
806
807 3074 aaronmk
    cur = run_query_into(db, mk_insert_select(db, table, *args, **kw_args),
808
        into, recover=recover, cacheable=cacheable, log_level=log_level)
809 3141 aaronmk
    if rowcount_only: empty_temp(db, into)
810 3074 aaronmk
    autoanalyze(db, table)
811
    return cur
812 2063 aaronmk
813 2738 aaronmk
default = sql_gen.default # tells insert() to use the default value for a column
814 2066 aaronmk
815 2063 aaronmk
def insert(db, table, row, *args, **kw_args):
816 2085 aaronmk
    '''For params, see insert_select()'''
817 1960 aaronmk
    if lists.is_seq(row): cols = None
818
    else:
819
        cols = row.keys()
820
        row = row.values()
821 2738 aaronmk
    row = list(row) # ensure that "== []" works
822 1960 aaronmk
823 2738 aaronmk
    if row == []: query = None
824
    else: query = sql_gen.Values(row).to_str(db)
825 1961 aaronmk
826 2788 aaronmk
    return insert_select(db, table, cols, query, *args, **kw_args)
827 11 aaronmk
828 3152 aaronmk
def mk_update(db, table, changes=None, cond=None, in_place=False,
829 3153 aaronmk
    cacheable_=True):
830 2402 aaronmk
    '''
831
    @param changes [(col, new_value),...]
832
        * container can be any iterable type
833
        * col: sql_gen.Code|str (for col name)
834
        * new_value: sql_gen.Code|literal value
835
    @param cond sql_gen.Code WHERE condition. e.g. use sql_gen.*Cond objects.
836 3056 aaronmk
    @param in_place If set, locks the table and updates rows in place.
837
        This avoids creating dead rows in PostgreSQL.
838
        * cond must be None
839 3153 aaronmk
    @param cacheable_ Whether column structure information used to generate the
840 3152 aaronmk
        query can be cached
841 2402 aaronmk
    @return str query
842
    '''
843 3057 aaronmk
    table = sql_gen.as_Table(table)
844
    changes = [(sql_gen.to_name_only_col(c, table), sql_gen.as_Value(v))
845
        for c, v in changes]
846
847 3056 aaronmk
    if in_place:
848
        assert cond == None
849 3058 aaronmk
850 3065 aaronmk
        query = 'ALTER TABLE '+table.to_str(db)+'\n'
851
        query += ',\n'.join(('ALTER COLUMN '+c.to_str(db)+' TYPE '
852 3153 aaronmk
            +db.col_info(sql_gen.with_default_table(c, table), cacheable_).type
853 3065 aaronmk
            +'\nUSING '+v.to_str(db) for c, v in changes))
854 3058 aaronmk
    else:
855
        query = 'UPDATE '+table.to_str(db)+'\nSET\n'
856
        query += ',\n'.join((c.to_str(db)+' = '+v.to_str(db)
857
            for c, v in changes))
858
        if cond != None: query += '\nWHERE\n'+cond.to_str(db)
859 3056 aaronmk
860 2402 aaronmk
    return query
861
862 3074 aaronmk
def update(db, table, *args, **kw_args):
863 2402 aaronmk
    '''For params, see mk_update() and run_query()'''
864
    recover = kw_args.pop('recover', None)
865 3043 aaronmk
    cacheable = kw_args.pop('cacheable', False)
866 3030 aaronmk
    log_level = kw_args.pop('log_level', 2)
867 2402 aaronmk
868 3074 aaronmk
    cur = run_query(db, mk_update(db, table, *args, **kw_args), recover,
869
        cacheable, log_level=log_level)
870
    autoanalyze(db, table)
871
    return cur
872 2402 aaronmk
873 135 aaronmk
def last_insert_id(db):
874 1849 aaronmk
    module = util.root_module(db.db)
875 135 aaronmk
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
876
    elif module == 'MySQLdb': return db.insert_id()
877
    else: return None
878 13 aaronmk
879 2394 aaronmk
def mk_flatten_mapping(db, into, cols, preserve=[], as_items=False):
880 2383 aaronmk
    '''Creates a mapping from original column names (which may have collisions)
881 2415 aaronmk
    to names that will be distinct among the columns' tables.
882 2383 aaronmk
    This is meant to be used for several tables that are being joined together.
883 2415 aaronmk
    @param cols The columns to combine. Duplicates will be removed.
884
    @param into The table for the new columns.
885 2394 aaronmk
    @param preserve [sql_gen.Col...] Columns not to rename. Note that these
886
        columns will be included in the mapping even if they are not in cols.
887
        The tables of the provided Col objects will be changed to into, so make
888
        copies of them if you want to keep the original tables.
889
    @param as_items Whether to return a list of dict items instead of a dict
890 2383 aaronmk
    @return dict(orig_col=new_col, ...)
891
        * orig_col: sql_gen.Col(orig_col_name, orig_table)
892 2392 aaronmk
        * new_col: sql_gen.Col(orig_col_name, into)
893
        * All mappings use the into table so its name can easily be
894 2383 aaronmk
          changed for all columns at once
895
    '''
896 2415 aaronmk
    cols = lists.uniqify(cols)
897
898 2394 aaronmk
    items = []
899 2389 aaronmk
    for col in preserve:
900 2390 aaronmk
        orig_col = copy.copy(col)
901 2392 aaronmk
        col.table = into
902 2394 aaronmk
        items.append((orig_col, col))
903
    preserve = set(preserve)
904
    for col in cols:
905 2716 aaronmk
        if col not in preserve:
906
            items.append((col, sql_gen.Col(str(col), into, col.srcs)))
907 2394 aaronmk
908
    if not as_items: items = dict(items)
909
    return items
910 2383 aaronmk
911 2393 aaronmk
def flatten(db, into, joins, cols, limit=None, start=None, **kw_args):
912 2391 aaronmk
    '''For params, see mk_flatten_mapping()
913
    @return See return value of mk_flatten_mapping()
914
    '''
915 2394 aaronmk
    items = mk_flatten_mapping(db, into, cols, as_items=True, **kw_args)
916
    cols = [sql_gen.NamedCol(new.name, old) for old, new in items]
917 2786 aaronmk
    run_query_into(db, mk_select(db, joins, cols, limit=limit, start=start),
918 3166 aaronmk
        into=into)
919 2394 aaronmk
    return dict(items)
920 2391 aaronmk
921 3079 aaronmk
##### Database structure introspection
922 2414 aaronmk
923 3079 aaronmk
#### Tables
924
925
def tables(db, schema_like='public', table_like='%', exact=False):
926
    if exact: compare = '='
927
    else: compare = 'LIKE'
928
929
    module = util.root_module(db.db)
930
    if module == 'psycopg2':
931
        conds = [('schemaname', sql_gen.CompareCond(schema_like, compare)),
932
            ('tablename', sql_gen.CompareCond(table_like, compare))]
933
        return values(select(db, 'pg_tables', ['tablename'], conds,
934
            order_by='tablename', log_level=4))
935
    elif module == 'MySQLdb':
936
        return values(run_query(db, 'SHOW TABLES LIKE '+db.esc_value(table_like)
937
            , cacheable=True, log_level=4))
938
    else: raise NotImplementedError("Can't list tables for "+module+' database')
939
940
def table_exists(db, table):
941
    table = sql_gen.as_Table(table)
942
    return list(tables(db, table.schema, table.name, exact=True)) != []
943
944 2426 aaronmk
def table_row_count(db, table, recover=None):
945 2786 aaronmk
    return value(run_query(db, mk_select(db, table, [sql_gen.row_count],
946 2443 aaronmk
        order_by=None, start=0), recover=recover, log_level=3))
947 2426 aaronmk
948 2414 aaronmk
def table_cols(db, table, recover=None):
949
    return list(col_names(select(db, table, limit=0, order_by=None,
950 2443 aaronmk
        recover=recover, log_level=4)))
951 2414 aaronmk
952 2291 aaronmk
def pkey(db, table, recover=None):
953 832 aaronmk
    '''Assumed to be first column in table'''
954 2339 aaronmk
    return table_cols(db, table, recover)[0]
955 832 aaronmk
956 2559 aaronmk
not_null_col = 'not_null_col'
957 2340 aaronmk
958
def table_not_null_col(db, table, recover=None):
959
    '''Name assumed to be the value of not_null_col. If not found, uses pkey.'''
960
    if not_null_col in table_cols(db, table, recover): return not_null_col
961
    else: return pkey(db, table, recover)
962
963 853 aaronmk
def index_cols(db, table, index):
964
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
965
    automatically created. When you don't know whether something is a UNIQUE
966
    constraint or a UNIQUE index, use this function.'''
967 1909 aaronmk
    module = util.root_module(db.db)
968
    if module == 'psycopg2':
969
        return list(values(run_query(db, '''\
970 853 aaronmk
SELECT attname
971 866 aaronmk
FROM
972
(
973
        SELECT attnum, attname
974
        FROM pg_index
975
        JOIN pg_class index ON index.oid = indexrelid
976
        JOIN pg_class table_ ON table_.oid = indrelid
977
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
978
        WHERE
979 2782 aaronmk
            table_.relname = '''+db.esc_value(table)+'''
980
            AND index.relname = '''+db.esc_value(index)+'''
981 866 aaronmk
    UNION
982
        SELECT attnum, attname
983
        FROM
984
        (
985
            SELECT
986
                indrelid
987
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
988
                    AS indkey
989
            FROM pg_index
990
            JOIN pg_class index ON index.oid = indexrelid
991
            JOIN pg_class table_ ON table_.oid = indrelid
992
            WHERE
993 2782 aaronmk
                table_.relname = '''+db.esc_value(table)+'''
994
                AND index.relname = '''+db.esc_value(index)+'''
995 866 aaronmk
        ) s
996
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
997
) s
998 853 aaronmk
ORDER BY attnum
999 2782 aaronmk
'''
1000
            , cacheable=True, log_level=4)))
1001 1909 aaronmk
    else: raise NotImplementedError("Can't list index columns for "+module+
1002
        ' database')
1003 853 aaronmk
1004 464 aaronmk
def constraint_cols(db, table, constraint):
1005 1849 aaronmk
    module = util.root_module(db.db)
1006 464 aaronmk
    if module == 'psycopg2':
1007
        return list(values(run_query(db, '''\
1008
SELECT attname
1009
FROM pg_constraint
1010
JOIN pg_class ON pg_class.oid = conrelid
1011
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
1012
WHERE
1013 2783 aaronmk
    relname = '''+db.esc_value(table)+'''
1014
    AND conname = '''+db.esc_value(constraint)+'''
1015 464 aaronmk
ORDER BY attnum
1016 2783 aaronmk
'''
1017
            )))
1018 464 aaronmk
    else: raise NotImplementedError("Can't list constraint columns for "+module+
1019
        ' database')
1020
1021 3079 aaronmk
#### Functions
1022
1023
def function_exists(db, function):
1024
    function = sql_gen.as_Function(function)
1025
1026
    info_table = sql_gen.Table('routines', 'information_schema')
1027
    conds = [('routine_name', function.name)]
1028
    schema = function.schema
1029
    if schema != None: conds.append(('routine_schema', schema))
1030
    # Exclude trigger functions, since they cannot be called directly
1031
    conds.append(('data_type', sql_gen.CompareCond('trigger', '!=')))
1032
1033
    return list(values(select(db, info_table, ['routine_name'], conds,
1034
        order_by='routine_schema', limit=1, log_level=4))) != []
1035
        # TODO: order_by search_path schema order
1036
1037
##### Structural changes
1038
1039
#### Columns
1040
1041
def add_col(db, table, col, comment=None, **kw_args):
1042
    '''
1043
    @param col TypedCol Name may be versioned, so be sure to propagate any
1044
        renaming back to any source column for the TypedCol.
1045
    @param comment None|str SQL comment used to distinguish columns of the same
1046
        name from each other when they contain different data, to allow the
1047
        ADD COLUMN query to be cached. If not set, query will not be cached.
1048
    '''
1049
    assert isinstance(col, sql_gen.TypedCol)
1050
1051
    while True:
1052
        str_ = 'ALTER TABLE '+table.to_str(db)+' ADD COLUMN '+col.to_str(db)
1053
        if comment != None: str_ += ' '+sql_gen.esc_comment(comment)
1054
1055
        try:
1056
            run_query(db, str_, recover=True, cacheable=True, **kw_args)
1057
            break
1058
        except DuplicateException:
1059
            col.name = next_version(col.name)
1060
            # try again with next version of name
1061
1062
def add_not_null(db, col):
1063
    table = col.table
1064
    col = sql_gen.to_name_only_col(col)
1065
    run_query(db, 'ALTER TABLE '+table.to_str(db)+' ALTER COLUMN '
1066
        +col.to_str(db)+' SET NOT NULL', cacheable=True, log_level=3)
1067
1068 2096 aaronmk
row_num_col = '_row_num'
1069
1070 3079 aaronmk
row_num_typed_col = sql_gen.TypedCol(row_num_col, 'serial', nullable=False,
1071
    constraints='PRIMARY KEY')
1072
1073
def add_row_num(db, table):
1074
    '''Adds a row number column to a table. Its name is in row_num_col. It will
1075
    be the primary key.'''
1076
    add_col(db, table, row_num_typed_col, log_level=3)
1077
1078
#### Indexes
1079
1080
def add_pkey(db, table, cols=None, recover=None):
1081
    '''Adds a primary key.
1082
    @param cols [sql_gen.Col,...] The columns in the primary key.
1083
        Defaults to the first column in the table.
1084
    @pre The table must not already have a primary key.
1085
    '''
1086
    table = sql_gen.as_Table(table)
1087
    if cols == None: cols = [pkey(db, table, recover)]
1088
    col_strs = [sql_gen.to_name_only_col(v).to_str(db) for v in cols]
1089
1090
    run_query(db, 'ALTER TABLE '+table.to_str(db)+' ADD PRIMARY KEY ('
1091
        +(', '.join(col_strs))+')', recover=True, cacheable=True, log_level=3,
1092
        log_ignore_excs=(DuplicateException,))
1093
1094 2998 aaronmk
def add_index(db, exprs, table=None, unique=False, ensure_not_null_=True):
1095 2688 aaronmk
    '''Adds an index on column(s) or expression(s) if it doesn't already exist.
1096 2538 aaronmk
    Currently, only function calls are supported as expressions.
1097 2998 aaronmk
    @param ensure_not_null_ If set, translates NULL values to sentinel values.
1098 2847 aaronmk
        This allows indexes to be used for comparisons where NULLs are equal.
1099 2538 aaronmk
    '''
1100 2964 aaronmk
    exprs = lists.mk_seq(exprs)
1101 2538 aaronmk
1102 2688 aaronmk
    # Parse exprs
1103
    old_exprs = exprs[:]
1104
    exprs = []
1105
    cols = []
1106
    for i, expr in enumerate(old_exprs):
1107 2823 aaronmk
        expr = sql_gen.as_Col(expr, table)
1108 2688 aaronmk
1109 2823 aaronmk
        # Handle nullable columns
1110 2998 aaronmk
        if ensure_not_null_:
1111 3164 aaronmk
            try: expr = sql_gen.ensure_not_null(db, expr)
1112 2860 aaronmk
            except KeyError: pass # unknown type, so just create plain index
1113 2823 aaronmk
1114 2688 aaronmk
        # Extract col
1115 3002 aaronmk
        expr = copy.deepcopy(expr) # don't modify input!
1116 2688 aaronmk
        if isinstance(expr, sql_gen.FunctionCall):
1117
            col = expr.args[0]
1118
            expr = sql_gen.Expr(expr)
1119
        else: col = expr
1120 2823 aaronmk
        assert isinstance(col, sql_gen.Col)
1121 2688 aaronmk
1122
        # Extract table
1123
        if table == None:
1124
            assert sql_gen.is_table_col(col)
1125
            table = col.table
1126
1127
        col.table = None
1128
1129
        exprs.append(expr)
1130
        cols.append(col)
1131 2408 aaronmk
1132 2688 aaronmk
    table = sql_gen.as_Table(table)
1133
1134 3005 aaronmk
    # Add index
1135 3148 aaronmk
    str_ = 'CREATE'
1136
    if unique: str_ += ' UNIQUE'
1137
    str_ += ' INDEX ON '+table.to_str(db)+' ('+(
1138
        ', '.join((v.to_str(db) for v in exprs)))+')'
1139
    run_query(db, str_, recover=True, cacheable=True, log_level=3)
1140 2408 aaronmk
1141 3083 aaronmk
already_indexed = object() # tells add_indexes() the pkey has already been added
1142
1143
def add_indexes(db, table, has_pkey=True):
1144
    '''Adds an index on all columns in a table.
1145
    @param has_pkey bool|already_indexed Whether a pkey instead of a regular
1146
        index should be added on the first column.
1147
        * If already_indexed, the pkey is assumed to have already been added
1148
    '''
1149
    cols = table_cols(db, table)
1150
    if has_pkey:
1151
        if has_pkey is not already_indexed: add_pkey(db, table)
1152
        cols = cols[1:]
1153
    for col in cols: add_index(db, col, table)
1154
1155 3079 aaronmk
#### Tables
1156 2772 aaronmk
1157 3079 aaronmk
### Maintenance
1158 2772 aaronmk
1159 3079 aaronmk
def analyze(db, table):
1160
    table = sql_gen.as_Table(table)
1161
    run_query(db, 'ANALYZE '+table.to_str(db), log_level=3)
1162 2934 aaronmk
1163 3079 aaronmk
def autoanalyze(db, table):
1164
    if db.autoanalyze: analyze(db, table)
1165 2935 aaronmk
1166 3079 aaronmk
def vacuum(db, table):
1167
    table = sql_gen.as_Table(table)
1168
    db.with_autocommit(lambda: run_query(db, 'VACUUM ANALYZE '+table.to_str(db),
1169
        log_level=3))
1170 2086 aaronmk
1171 3079 aaronmk
### Lifecycle
1172
1173 2889 aaronmk
def drop_table(db, table):
1174
    table = sql_gen.as_Table(table)
1175
    return run_query(db, 'DROP TABLE IF EXISTS '+table.to_str(db)+' CASCADE')
1176
1177 3082 aaronmk
def create_table(db, table, cols=[], has_pkey=True, col_indexes=True,
1178
    like=None):
1179 2675 aaronmk
    '''Creates a table.
1180 2681 aaronmk
    @param cols [sql_gen.TypedCol,...] The column names and types
1181
    @param has_pkey If set, the first column becomes the primary key.
1182 2760 aaronmk
    @param col_indexes bool|[ref]
1183
        * If True, indexes will be added on all non-pkey columns.
1184
        * If a list reference, [0] will be set to a function to do this.
1185
          This can be used to delay index creation until the table is populated.
1186 2675 aaronmk
    '''
1187
    table = sql_gen.as_Table(table)
1188
1189 3082 aaronmk
    if like != None:
1190
        cols = [sql_gen.CustomCode('LIKE '+like.to_str(db)+' INCLUDING ALL')
1191
            ]+cols
1192 2681 aaronmk
    if has_pkey:
1193
        cols[0] = pkey = copy.copy(cols[0]) # don't modify input!
1194 2872 aaronmk
        pkey.constraints = 'PRIMARY KEY'
1195 2681 aaronmk
1196 3085 aaronmk
    temp = table.is_temp and not db.debug_temp
1197
        # temp tables permanent in debug_temp mode
1198 2760 aaronmk
1199 3085 aaronmk
    # Create table
1200
    while True:
1201
        str_ = 'CREATE'
1202
        if temp: str_ += ' TEMP'
1203
        str_ += ' TABLE '+table.to_str(db)+' (\n'
1204
        str_ += '\n, '.join(c.to_str(db) for c in cols)
1205 3126 aaronmk
        str_ += '\n);'
1206 3085 aaronmk
1207
        try:
1208 3127 aaronmk
            run_query(db, str_, recover=True, cacheable=True, log_level=2,
1209 3085 aaronmk
                log_ignore_excs=(DuplicateException,))
1210
            break
1211
        except DuplicateException:
1212
            table.name = next_version(table.name)
1213
            # try again with next version of name
1214
1215 2760 aaronmk
    # Add indexes
1216 2773 aaronmk
    if has_pkey: has_pkey = already_indexed
1217
    def add_indexes_(): add_indexes(db, table, has_pkey)
1218
    if isinstance(col_indexes, list): col_indexes[0] = add_indexes_ # defer
1219
    elif col_indexes: add_indexes_() # add now
1220 2675 aaronmk
1221 3084 aaronmk
def copy_table_struct(db, src, dest):
1222
    '''Creates a structure-only copy of a table. (Does not copy data.)'''
1223 3085 aaronmk
    create_table(db, dest, has_pkey=False, col_indexes=False, like=src)
1224 3084 aaronmk
1225 3079 aaronmk
### Data
1226 2684 aaronmk
1227 2970 aaronmk
def truncate(db, table, schema='public', **kw_args):
1228
    '''For params, see run_query()'''
1229 2777 aaronmk
    table = sql_gen.as_Table(table, schema)
1230 2970 aaronmk
    return run_query(db, 'TRUNCATE '+table.to_str(db)+' CASCADE', **kw_args)
1231 2732 aaronmk
1232 2965 aaronmk
def empty_temp(db, tables):
1233
    tables = lists.mk_seq(tables)
1234 2971 aaronmk
    for table in tables: truncate(db, table, log_level=3)
1235 2965 aaronmk
1236 1968 aaronmk
def empty_db(db, schema='public', **kw_args):
1237
    '''For kw_args, see tables()'''
1238
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
1239 3094 aaronmk
1240
def distinct_table(db, table, distinct_on):
1241
    '''Creates a copy of a temp table which is distinct on the given columns.
1242 3099 aaronmk
    The old and new tables will both get an index on these columns, to
1243
    facilitate merge joins.
1244 3097 aaronmk
    @param distinct_on If empty, creates a table with one row. This is useful if
1245
        your distinct_on columns are all literal values.
1246 3099 aaronmk
    @return The new table.
1247 3094 aaronmk
    '''
1248 3099 aaronmk
    new_table = sql_gen.suffixed_table(table, '_distinct')
1249 3094 aaronmk
1250 3099 aaronmk
    copy_table_struct(db, table, new_table)
1251 3097 aaronmk
1252
    limit = None
1253
    if distinct_on == []: limit = 1 # one sample row
1254 3099 aaronmk
    else:
1255
        add_index(db, distinct_on, new_table, unique=True)
1256
        add_index(db, distinct_on, table) # for join optimization
1257 3097 aaronmk
1258 3099 aaronmk
    insert_select(db, new_table, None, mk_select(db, table, start=0,
1259 3097 aaronmk
        limit=limit), ignore=True)
1260 3099 aaronmk
    analyze(db, new_table)
1261 3094 aaronmk
1262 3099 aaronmk
    return new_table