Project

General

Profile

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