Project

General

Profile

1 11 aaronmk
# Database access
2
3 1869 aaronmk
import copy
4 2127 aaronmk
import operator
5 11 aaronmk
import re
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 2170 aaronmk
def get_cur_query(cur, input_query=None, input_params=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
    else: return repr(input_query)+' % '+repr(input_params)
27 14 aaronmk
28 2170 aaronmk
def _add_cursor_info(e, *args, **kw_args):
29
    '''For params, see get_cur_query()'''
30
    exc.add_msg(e, 'query: '+str(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 2145 aaronmk
        DbException.__init__(self, 'for name: '+str(name), cause)
40 2143 aaronmk
        self.name = name
41 360 aaronmk
42 468 aaronmk
class ExceptionWithColumns(DbException):
43
    def __init__(self, cols, cause=None):
44 2145 aaronmk
        DbException.__init__(self, 'for columns: '+(', '.join(cols)), cause)
45 468 aaronmk
        self.cols = cols
46 11 aaronmk
47 2143 aaronmk
class NameException(DbException): pass
48
49 468 aaronmk
class DuplicateKeyException(ExceptionWithColumns): pass
50 13 aaronmk
51 468 aaronmk
class NullValueException(ExceptionWithColumns): pass
52 13 aaronmk
53 2143 aaronmk
class DuplicateTableException(ExceptionWithName): pass
54
55 2188 aaronmk
class DuplicateFunctionException(ExceptionWithName): pass
56
57 89 aaronmk
class EmptyRowException(DbException): pass
58
59 865 aaronmk
##### Warnings
60
61
class DbWarning(UserWarning): pass
62
63 1930 aaronmk
##### Result retrieval
64
65
def col_names(cur): return (col[0] for col in cur.description)
66
67
def rows(cur): return iter(lambda: cur.fetchone(), None)
68
69
def consume_rows(cur):
70
    '''Used to fetch all rows so result will be cached'''
71
    iters.consume_iter(rows(cur))
72
73
def next_row(cur): return rows(cur).next()
74
75
def row(cur):
76
    row_ = next_row(cur)
77
    consume_rows(cur)
78
    return row_
79
80
def next_value(cur): return next_row(cur)[0]
81
82
def value(cur): return row(cur)[0]
83
84
def values(cur): return iters.func_iter(lambda: next_value(cur))
85
86
def value_or_none(cur):
87
    try: return value(cur)
88
    except StopIteration: return None
89
90 2101 aaronmk
##### Input validation
91
92 2198 aaronmk
def clean_name(name): return re.sub(r'\W', r'', name).lower()
93 2101 aaronmk
94
def check_name(name):
95
    if re.search(r'\W', name) != None: raise NameException('Name "'+name
96
        +'" may contain only alphanumeric characters and _')
97
98
def esc_name_by_module(module, name, ignore_case=False):
99
    if module == 'psycopg2':
100
        if ignore_case:
101
            # Don't enclose in quotes because this disables case-insensitivity
102
            check_name(name)
103
            return name
104
        else: quote = '"'
105
    elif module == 'MySQLdb': quote = '`'
106
    else: raise NotImplementedError("Can't escape name for "+module+' database')
107
    return quote + name.replace(quote, '') + quote
108
109
def esc_name_by_engine(engine, name, **kw_args):
110
    return esc_name_by_module(db_engines[engine][0], name, **kw_args)
111
112
def esc_name(db, name, **kw_args):
113
    return esc_name_by_module(util.root_module(db.db), name, **kw_args)
114
115
def qual_name(db, schema, table):
116
    def esc_name_(name): return esc_name(db, name)
117
    table = esc_name_(table)
118
    if schema != None: return esc_name_(schema)+'.'+table
119
    else: return table
120
121 1869 aaronmk
##### Database connections
122 1849 aaronmk
123 2097 aaronmk
db_config_names = ['engine', 'host', 'user', 'password', 'database', 'schemas']
124 1926 aaronmk
125 1869 aaronmk
db_engines = {
126
    'MySQL': ('MySQLdb', {'password': 'passwd', 'database': 'db'}),
127
    'PostgreSQL': ('psycopg2', {}),
128
}
129
130
DatabaseErrors_set = set([DbException])
131
DatabaseErrors = tuple(DatabaseErrors_set)
132
133
def _add_module(module):
134
    DatabaseErrors_set.add(module.DatabaseError)
135
    global DatabaseErrors
136
    DatabaseErrors = tuple(DatabaseErrors_set)
137
138
def db_config_str(db_config):
139
    return db_config['engine']+' database '+db_config['database']
140
141 1909 aaronmk
def _query_lookup(query, params): return (query, dicts.make_hashable(params))
142 1894 aaronmk
143 1901 aaronmk
log_debug_none = lambda msg: None
144
145 1849 aaronmk
class DbConn:
146 2190 aaronmk
    def __init__(self, db_config, serializable=True, autocommit=False,
147
        caching=True, log_debug=log_debug_none):
148 1869 aaronmk
        self.db_config = db_config
149
        self.serializable = serializable
150 2190 aaronmk
        self.autocommit = autocommit
151
        self.caching = caching
152 1901 aaronmk
        self.log_debug = log_debug
153 2193 aaronmk
        self.debug = log_debug != log_debug_none
154 1869 aaronmk
155
        self.__db = None
156 1889 aaronmk
        self.query_results = {}
157 2139 aaronmk
        self._savepoint = 0
158 1869 aaronmk
159
    def __getattr__(self, name):
160
        if name == '__dict__': raise Exception('getting __dict__')
161
        if name == 'db': return self._db()
162
        else: raise AttributeError()
163
164
    def __getstate__(self):
165
        state = copy.copy(self.__dict__) # shallow copy
166 1915 aaronmk
        state['log_debug'] = None # don't pickle the debug callback
167 1869 aaronmk
        state['_DbConn__db'] = None # don't pickle the connection
168
        return state
169
170 2165 aaronmk
    def connected(self): return self.__db != None
171
172 1869 aaronmk
    def _db(self):
173
        if self.__db == None:
174
            # Process db_config
175
            db_config = self.db_config.copy() # don't modify input!
176 2097 aaronmk
            schemas = db_config.pop('schemas', None)
177 1869 aaronmk
            module_name, mappings = db_engines[db_config.pop('engine')]
178
            module = __import__(module_name)
179
            _add_module(module)
180
            for orig, new in mappings.iteritems():
181
                try: util.rename_key(db_config, orig, new)
182
                except KeyError: pass
183
184
            # Connect
185
            self.__db = module.connect(**db_config)
186
187
            # Configure connection
188 2190 aaronmk
            if self.serializable and not self.autocommit:
189
                self.db.set_session(isolation_level='SERIALIZABLE')
190 2101 aaronmk
            if schemas != None:
191
                schemas_ = ''.join((esc_name(self, s)+', '
192
                    for s in schemas.split(',')))
193
                run_raw_query(self, "SELECT set_config('search_path', \
194
%s || current_setting('search_path'), false)", [schemas_])
195 1869 aaronmk
196
        return self.__db
197 1889 aaronmk
198 1891 aaronmk
    class DbCursor(Proxy):
199 1927 aaronmk
        def __init__(self, outer):
200 1891 aaronmk
            Proxy.__init__(self, outer.db.cursor())
201 2191 aaronmk
            self.outer = outer
202 1927 aaronmk
            self.query_results = outer.query_results
203 1894 aaronmk
            self.query_lookup = None
204 1891 aaronmk
            self.result = []
205 1889 aaronmk
206 1894 aaronmk
        def execute(self, query, params=None):
207 1930 aaronmk
            self._is_insert = query.upper().find('INSERT') >= 0
208 1894 aaronmk
            self.query_lookup = _query_lookup(query, params)
209 2148 aaronmk
            try:
210 2191 aaronmk
                try:
211
                    return_value = self.inner.execute(query, params)
212
                    self.outer.do_autocommit()
213 2148 aaronmk
                finally: self.query = get_cur_query(self.inner)
214 1904 aaronmk
            except Exception, e:
215 2170 aaronmk
                _add_cursor_info(e, self, query, params)
216 1904 aaronmk
                self.result = e # cache the exception as the result
217
                self._cache_result()
218
                raise
219 1930 aaronmk
            # Fetch all rows so result will be cached
220
            if self.rowcount == 0 and not self._is_insert: consume_rows(self)
221 1894 aaronmk
            return return_value
222
223 1891 aaronmk
        def fetchone(self):
224
            row = self.inner.fetchone()
225 1899 aaronmk
            if row != None: self.result.append(row)
226
            # otherwise, fetched all rows
227 1904 aaronmk
            else: self._cache_result()
228
            return row
229
230
        def _cache_result(self):
231 1906 aaronmk
            # For inserts, only cache exceptions since inserts are not
232
            # idempotent, but an invalid insert will always be invalid
233 1930 aaronmk
            if self.query_results != None and (not self._is_insert
234 1906 aaronmk
                or isinstance(self.result, Exception)):
235
236 1894 aaronmk
                assert self.query_lookup != None
237 1916 aaronmk
                self.query_results[self.query_lookup] = self.CacheCursor(
238
                    util.dict_subset(dicts.AttrsDictView(self),
239
                    ['query', 'result', 'rowcount', 'description']))
240 1906 aaronmk
241 1916 aaronmk
        class CacheCursor:
242
            def __init__(self, cached_result): self.__dict__ = cached_result
243
244 1927 aaronmk
            def execute(self, *args, **kw_args):
245 1916 aaronmk
                if isinstance(self.result, Exception): raise self.result
246
                # otherwise, result is a rows list
247
                self.iter = iter(self.result)
248
249
            def fetchone(self):
250
                try: return self.iter.next()
251
                except StopIteration: return None
252 1891 aaronmk
253 2212 aaronmk
    def esc_value(self, value):
254 2215 aaronmk
        module = util.root_module(self.db)
255
        if module == 'psycopg2': return self.db.cursor().mogrify('%s', [value])
256 2212 aaronmk
        elif module == 'MySQLdb':
257
            import _mysql
258
            return _mysql.escape_string(value)
259
        else: raise NotImplementedError("Can't escape value for "+module
260
            +' database')
261
262 1894 aaronmk
    def run_query(self, query, params=None, cacheable=False):
263 2148 aaronmk
        '''Translates known DB errors to typed exceptions:
264
        See self.DbCursor.execute().'''
265 2167 aaronmk
        assert query != None
266
267 2047 aaronmk
        if not self.caching: cacheable = False
268 1903 aaronmk
        used_cache = False
269
        try:
270 1927 aaronmk
            # Get cursor
271
            if cacheable:
272
                query_lookup = _query_lookup(query, params)
273
                try:
274
                    cur = self.query_results[query_lookup]
275
                    used_cache = True
276
                except KeyError: cur = self.DbCursor(self)
277
            else: cur = self.db.cursor()
278
279
            # Run query
280 2148 aaronmk
            cur.execute(query, params)
281 1903 aaronmk
        finally:
282 2193 aaronmk
            if self.debug: # only compute msg if needed
283 1903 aaronmk
                if used_cache: cache_status = 'Cache hit'
284
                elif cacheable: cache_status = 'Cache miss'
285
                else: cache_status = 'Non-cacheable'
286 1927 aaronmk
                self.log_debug(cache_status+': '
287 2170 aaronmk
                    +strings.one_line(str(get_cur_query(cur, query, params))))
288 1903 aaronmk
289
        return cur
290 1914 aaronmk
291
    def is_cached(self, query, params=None):
292
        return _query_lookup(query, params) in self.query_results
293 2139 aaronmk
294
    def with_savepoint(self, func):
295 2171 aaronmk
        savepoint = 'level_'+str(self._savepoint)
296 2139 aaronmk
        self.run_query('SAVEPOINT '+savepoint)
297
        self._savepoint += 1
298
        try:
299
            try: return_val = func()
300
            finally:
301
                self._savepoint -= 1
302
                assert self._savepoint >= 0
303
        except:
304
            self.run_query('ROLLBACK TO SAVEPOINT '+savepoint)
305
            raise
306
        else:
307
            self.run_query('RELEASE SAVEPOINT '+savepoint)
308 2191 aaronmk
            self.do_autocommit()
309 2139 aaronmk
            return return_val
310 2191 aaronmk
311
    def do_autocommit(self):
312
        '''Autocommits if outside savepoint'''
313
        assert self._savepoint >= 0
314
        if self.autocommit and self._savepoint == 0:
315
            self.log_debug('Autocommiting')
316
            self.db.commit()
317 1849 aaronmk
318 1869 aaronmk
connect = DbConn
319
320 832 aaronmk
##### Querying
321
322 1894 aaronmk
def run_raw_query(db, *args, **kw_args):
323 2085 aaronmk
    '''For params, see DbConn.run_query()'''
324 1894 aaronmk
    return db.run_query(*args, **kw_args)
325 11 aaronmk
326 2068 aaronmk
def mogrify(db, query, params):
327
    module = util.root_module(db.db)
328
    if module == 'psycopg2': return db.db.cursor().mogrify(query, params)
329
    else: raise NotImplementedError("Can't mogrify query for "+module+
330
        ' database')
331
332 832 aaronmk
##### Recoverable querying
333 15 aaronmk
334 2139 aaronmk
def with_savepoint(db, func): return db.with_savepoint(func)
335 11 aaronmk
336 1894 aaronmk
def run_query(db, query, params=None, recover=None, cacheable=False):
337 830 aaronmk
    if recover == None: recover = False
338
339 2148 aaronmk
    try:
340
        def run(): return run_raw_query(db, query, params, cacheable)
341
        if recover and not db.is_cached(query, params):
342
            return with_savepoint(db, run)
343
        else: return run() # don't need savepoint if cached
344
    except Exception, e:
345
        if not recover: raise # need savepoint to run index_cols()
346
        msg = str(e)
347
        match = re.search(r'duplicate key value violates unique constraint '
348
            r'"((_?[^\W_]+)_[^"]+)"', msg)
349
        if match:
350
            constraint, table = match.groups()
351
            try: cols = index_cols(db, table, constraint)
352
            except NotImplementedError: raise e
353
            else: raise DuplicateKeyException(cols, e)
354
        match = re.search(r'null value in column "(\w+)" violates not-null '
355
            'constraint', msg)
356
        if match: raise NullValueException([match.group(1)], e)
357
        match = re.search(r'relation "(\w+)" already exists', msg)
358
        if match: raise DuplicateTableException(match.group(1), e)
359 2188 aaronmk
        match = re.search(r'function "(\w+)" already exists', msg)
360
        if match: raise DuplicateFunctionException(match.group(1), e)
361 2148 aaronmk
        raise # no specific exception raised
362 830 aaronmk
363 832 aaronmk
##### Basic queries
364
365 2153 aaronmk
def next_version(name):
366
    '''Prepends the version # so it won't be removed if the name is truncated'''
367 2163 aaronmk
    version = 1 # first existing name was version 0
368 2153 aaronmk
    match = re.match(r'^v(\d+)_(.*)$', name)
369
    if match:
370
        version = int(match.group(1))+1
371
        name = match.group(2)
372
    return 'v'+str(version)+'_'+name
373
374 2151 aaronmk
def run_query_into(db, query, params, into_ref=None, *args, **kw_args):
375 2085 aaronmk
    '''Outputs a query to a temp table.
376
    For params, see run_query().
377
    '''
378 2151 aaronmk
    if into_ref == None: return run_query(db, query, params, *args, **kw_args)
379 2085 aaronmk
    else: # place rows in temp table
380 2151 aaronmk
        check_name(into_ref[0])
381 2153 aaronmk
        kw_args['recover'] = True
382
        while True:
383
            try:
384 2194 aaronmk
                create_query = 'CREATE'
385
                if not db.debug: create_query += ' TEMP'
386
                create_query += ' TABLE '+into_ref[0]+' AS '+query
387
388
                return run_query(db, create_query, params, *args, **kw_args)
389 2153 aaronmk
                    # CREATE TABLE AS sets rowcount to # rows in query
390
            except DuplicateTableException, e:
391
                into_ref[0] = next_version(into_ref[0])
392
                # try again with next version of name
393 2085 aaronmk
394 2120 aaronmk
order_by_pkey = object() # tells mk_select() to order by the pkey
395
396 2127 aaronmk
join_using = object() # tells mk_select() to join the column with USING
397
398 2187 aaronmk
filter_out = object() # tells mk_select() to filter out rows that match the join
399 2180 aaronmk
400 2199 aaronmk
distinct_on_all = object() # tells mk_select() to SELECT DISTINCT ON all columns
401
402
def mk_select(db, tables, fields=None, conds=None, distinct_on=None, limit=None,
403
    start=None, order_by=order_by_pkey, table_is_esc=False):
404 1981 aaronmk
    '''
405 2121 aaronmk
    @param tables The single table to select from, or a list of tables to join
406 2187 aaronmk
        together: [table0, (table1, joins), ...]
407
408
        joins has the format: dict(right_col=left_col, ...)
409
        * if left_col is join_using, left_col is set to right_col
410
        * if left_col is filter_out, the tables are LEFT JOINed together and the
411
          query is filtered by `right_col IS NULL` (indicating no match)
412 1981 aaronmk
    @param fields Use None to select all fields in the table
413 2218 aaronmk
    @param conds WHERE conditions: dict(compare_left_side=compare_right_side):
414
        * compare_left_side: Code|str (for col name)
415
        * compare_right_side: ValueCond|literal value
416 2199 aaronmk
    @param distinct_on The columns to SELECT DISTINCT ON, or distinct_on_all to
417
        use all columns
418 1981 aaronmk
    @param table_is_esc Whether the table name has already been escaped
419 2054 aaronmk
    @return tuple(query, params)
420 1981 aaronmk
    '''
421 2060 aaronmk
    def esc_name_(name): return esc_name(db, name)
422 2058 aaronmk
423 2121 aaronmk
    if not lists.is_seq(tables): tables = [tables]
424 2141 aaronmk
    tables = list(tables) # don't modify input! (list() copies input)
425 2121 aaronmk
    table0 = tables.pop(0) # first table is separate
426
427 1135 aaronmk
    if conds == None: conds = {}
428 135 aaronmk
    assert limit == None or type(limit) == int
429 865 aaronmk
    assert start == None or type(start) == int
430 2120 aaronmk
    if order_by == order_by_pkey:
431 2121 aaronmk
        order_by = pkey(db, table0, recover=True, table_is_esc=table_is_esc)
432
    if not table_is_esc: table0 = esc_name_(table0)
433 865 aaronmk
434 2056 aaronmk
    params = []
435
436 2161 aaronmk
    def parse_col(field, default_table=None):
437 2056 aaronmk
        '''Parses fields'''
438 2220 aaronmk
        return sql_gen.value2sql_gen(field, default_table,
439
            table_is_esc).to_str(db)
440 11 aaronmk
    def cond(entry):
441 2056 aaronmk
        '''Parses conditions'''
442 2217 aaronmk
        left, right = entry
443
        return sql_gen.as_ValueCond(right).to_str(db, left)
444 2056 aaronmk
445 2200 aaronmk
    query = 'SELECT'
446
447
    # DISTINCT ON columns
448
    if distinct_on != None:
449
        query += ' DISTINCT'
450
        if distinct_on != distinct_on_all:
451
            query += ' ON ('+(', '.join(map(parse_col, distinct_on)))+')'
452
453
    # Columns
454
    query += ' '
455 1135 aaronmk
    if fields == None: query += '*'
456 2056 aaronmk
    else: query += ', '.join(map(parse_col, fields))
457 2200 aaronmk
458
    # Main table
459 2121 aaronmk
    query += ' FROM '+table0
460 865 aaronmk
461 2122 aaronmk
    # Add joins
462
    left_table = table0
463
    for table, joins in tables:
464
        if not table_is_esc: table = esc_name_(table)
465
466 2187 aaronmk
        left_join_ref = [False]
467
468 2122 aaronmk
        def join(entry):
469 2127 aaronmk
            '''Parses non-USING joins'''
470 2124 aaronmk
            right_col, left_col = entry
471 2173 aaronmk
472 2179 aaronmk
            # Parse special values
473 2176 aaronmk
            if left_col == None: left_col = (left_col,)
474
                # for None values, tuple is optional
475 2179 aaronmk
            elif left_col == join_using: left_col = right_col
476 2187 aaronmk
            elif left_col == filter_out:
477 2180 aaronmk
                left_col = right_col
478 2187 aaronmk
                left_join_ref[0] = True
479
                conds[(table, right_col)] = None # filter query by no match
480 2179 aaronmk
481
            # Create SQL
482 2185 aaronmk
            right_col = table+'.'+esc_name_(right_col)
483
            sql_ = right_col+' '
484 2173 aaronmk
            if isinstance(left_col, tuple) and len(left_col) == 1:
485
                # col is literal value
486
                value, = left_col
487
                if value == None: sql_ += 'IS'
488
                else: sql_ += '='
489
                sql_ += ' %s'
490
                params.append(value)
491
            else: # col is name
492
                left_col = parse_col(left_col, left_table)
493
                sql_ += ('= '+left_col+' OR ('+right_col+' IS NULL AND '
494
                    +left_col+' IS NULL)')
495
496
            return sql_
497 2122 aaronmk
498 2187 aaronmk
        # Create join condition and determine join type
499 2127 aaronmk
        if reduce(operator.and_, (v == join_using for v in joins.itervalues())):
500 2179 aaronmk
            # all cols w/ USING, so can use simpler USING syntax
501 2187 aaronmk
            join_cond = 'USING ('+(', '.join(joins.iterkeys()))+')'
502
        else: join_cond = 'ON '+(' AND '.join(map(join, joins.iteritems())))
503 2127 aaronmk
504 2187 aaronmk
        # Create join
505
        if left_join_ref[0]: query += ' LEFT'
506
        query += ' JOIN '+table+' '+join_cond
507
508 2122 aaronmk
        left_table = table
509
510 865 aaronmk
    missing = True
511 89 aaronmk
    if conds != {}:
512 2122 aaronmk
        query += ' WHERE '+(' AND '.join(map(cond, conds.iteritems())))
513 2056 aaronmk
        params += conds.values()
514 865 aaronmk
        missing = False
515 2186 aaronmk
    if order_by != None: query += ' ORDER BY '+parse_col(order_by, table0)
516 865 aaronmk
    if limit != None: query += ' LIMIT '+str(limit); missing = False
517
    if start != None:
518
        if start != 0: query += ' OFFSET '+str(start)
519
        missing = False
520
    if missing: warnings.warn(DbWarning(
521
        'SELECT statement missing a WHERE, LIMIT, or OFFSET clause: '+query))
522
523 2056 aaronmk
    return (query, params)
524 11 aaronmk
525 2054 aaronmk
def select(db, *args, **kw_args):
526
    '''For params, see mk_select() and run_query()'''
527
    recover = kw_args.pop('recover', None)
528
    cacheable = kw_args.pop('cacheable', True)
529
530
    query, params = mk_select(db, *args, **kw_args)
531
    return run_query(db, query, params, recover, cacheable)
532
533 2066 aaronmk
def mk_insert_select(db, table, cols=None, select_query=None, params=None,
534 2070 aaronmk
    returning=None, embeddable=False, table_is_esc=False):
535 1960 aaronmk
    '''
536
    @param returning str|None An inserted column (such as pkey) to return
537 2070 aaronmk
    @param embeddable Whether the query should be embeddable as a nested SELECT.
538 2073 aaronmk
        Warning: If you set this and cacheable=True when the query is run, the
539
        query will be fully cached, not just if it raises an exception.
540 1960 aaronmk
    @param table_is_esc Whether the table name has already been escaped
541
    '''
542 2063 aaronmk
    if select_query == None: select_query = 'DEFAULT VALUES'
543
    if cols == []: cols = None # no cols (all defaults) = unknown col names
544 1960 aaronmk
    if not table_is_esc: check_name(table)
545 2063 aaronmk
546
    # Build query
547
    query = 'INSERT INTO '+table
548
    if cols != None:
549
        map(check_name, cols)
550
        query += ' ('+', '.join(cols)+')'
551
    query += ' '+select_query
552
553
    if returning != None:
554
        check_name(returning)
555
        query += ' RETURNING '+returning
556
557 2070 aaronmk
    if embeddable:
558
        # Create function
559 2189 aaronmk
        function_name = '_'.join(map(clean_name, ['insert', table] + cols))
560 2070 aaronmk
        return_type = 'SETOF '+table+'.'+returning+'%TYPE'
561 2189 aaronmk
        while True:
562
            try:
563 2194 aaronmk
                function = function_name
564
                if not db.debug: function = 'pg_temp.'+function
565
566 2189 aaronmk
                function_query = '''\
567
CREATE FUNCTION '''+function+'''() RETURNS '''+return_type+'''
568 2070 aaronmk
    LANGUAGE sql
569
    AS $$'''+mogrify(db, query, params)+''';$$;
570
'''
571 2189 aaronmk
                run_query(db, function_query, recover=True, cacheable=True)
572
                break # this version was successful
573
            except DuplicateFunctionException, e:
574
                function_name = next_version(function_name)
575
                # try again with next version of name
576 2070 aaronmk
577
        # Return query that uses function
578 2134 aaronmk
        return mk_select(db, function+'() AS f ('+returning+')', start=0,
579
            order_by=None, table_is_esc=True)# AS clause requires function alias
580 2070 aaronmk
581 2066 aaronmk
    return (query, params)
582
583
def insert_select(db, *args, **kw_args):
584 2085 aaronmk
    '''For params, see mk_insert_select() and run_query_into()
585 2152 aaronmk
    @param into_ref List with name of temp table to place RETURNING values in
586 2072 aaronmk
    '''
587 2151 aaronmk
    into_ref = kw_args.pop('into_ref', None)
588
    if into_ref != None: kw_args['embeddable'] = True
589 2066 aaronmk
    recover = kw_args.pop('recover', None)
590
    cacheable = kw_args.pop('cacheable', True)
591
592
    query, params = mk_insert_select(db, *args, **kw_args)
593 2153 aaronmk
    return run_query_into(db, query, params, into_ref, recover=recover,
594
        cacheable=cacheable)
595 2063 aaronmk
596 2066 aaronmk
default = object() # tells insert() to use the default value for a column
597
598 2063 aaronmk
def insert(db, table, row, *args, **kw_args):
599 2085 aaronmk
    '''For params, see insert_select()'''
600 1960 aaronmk
    if lists.is_seq(row): cols = None
601
    else:
602
        cols = row.keys()
603
        row = row.values()
604
    row = list(row) # ensure that "!= []" works
605
606 1961 aaronmk
    # Check for special values
607
    labels = []
608
    values = []
609
    for value in row:
610
        if value == default: labels.append('DEFAULT')
611
        else:
612
            labels.append('%s')
613
            values.append(value)
614
615
    # Build query
616 2063 aaronmk
    if values != []: query = ' VALUES ('+(', '.join(labels))+')'
617
    else: query = None
618 1554 aaronmk
619 2064 aaronmk
    return insert_select(db, table, cols, query, values, *args, **kw_args)
620 11 aaronmk
621 135 aaronmk
def last_insert_id(db):
622 1849 aaronmk
    module = util.root_module(db.db)
623 135 aaronmk
    if module == 'psycopg2': return value(run_query(db, 'SELECT lastval()'))
624
    elif module == 'MySQLdb': return db.insert_id()
625
    else: return None
626 13 aaronmk
627 1968 aaronmk
def truncate(db, table, schema='public'):
628
    return run_query(db, 'TRUNCATE '+qual_name(db, schema, table)+' CASCADE')
629 832 aaronmk
630
##### Database structure queries
631
632 2084 aaronmk
def pkey(db, table, recover=None, table_is_esc=False):
633 832 aaronmk
    '''Assumed to be first column in table'''
634 2120 aaronmk
    return col_names(select(db, table, limit=0, order_by=None, recover=recover,
635 2084 aaronmk
        table_is_esc=table_is_esc)).next()
636 832 aaronmk
637 853 aaronmk
def index_cols(db, table, index):
638
    '''Can also use this for UNIQUE constraints, because a UNIQUE index is
639
    automatically created. When you don't know whether something is a UNIQUE
640
    constraint or a UNIQUE index, use this function.'''
641
    check_name(table)
642
    check_name(index)
643 1909 aaronmk
    module = util.root_module(db.db)
644
    if module == 'psycopg2':
645
        return list(values(run_query(db, '''\
646 853 aaronmk
SELECT attname
647 866 aaronmk
FROM
648
(
649
        SELECT attnum, attname
650
        FROM pg_index
651
        JOIN pg_class index ON index.oid = indexrelid
652
        JOIN pg_class table_ ON table_.oid = indrelid
653
        JOIN pg_attribute ON attrelid = indrelid AND attnum = ANY (indkey)
654
        WHERE
655
            table_.relname = %(table)s
656
            AND index.relname = %(index)s
657
    UNION
658
        SELECT attnum, attname
659
        FROM
660
        (
661
            SELECT
662
                indrelid
663
                , (regexp_matches(indexprs, E':varattno (\\\\d+)', 'g'))[1]::int
664
                    AS indkey
665
            FROM pg_index
666
            JOIN pg_class index ON index.oid = indexrelid
667
            JOIN pg_class table_ ON table_.oid = indrelid
668
            WHERE
669
                table_.relname = %(table)s
670
                AND index.relname = %(index)s
671
        ) s
672
        JOIN pg_attribute ON attrelid = indrelid AND attnum = indkey
673
) s
674 853 aaronmk
ORDER BY attnum
675
''',
676 1909 aaronmk
            {'table': table, 'index': index}, cacheable=True)))
677
    else: raise NotImplementedError("Can't list index columns for "+module+
678
        ' database')
679 853 aaronmk
680 464 aaronmk
def constraint_cols(db, table, constraint):
681
    check_name(table)
682
    check_name(constraint)
683 1849 aaronmk
    module = util.root_module(db.db)
684 464 aaronmk
    if module == 'psycopg2':
685
        return list(values(run_query(db, '''\
686
SELECT attname
687
FROM pg_constraint
688
JOIN pg_class ON pg_class.oid = conrelid
689
JOIN pg_attribute ON attrelid = conrelid AND attnum = ANY (conkey)
690
WHERE
691
    relname = %(table)s
692
    AND conname = %(constraint)s
693
ORDER BY attnum
694
''',
695
            {'table': table, 'constraint': constraint})))
696
    else: raise NotImplementedError("Can't list constraint columns for "+module+
697
        ' database')
698
699 2096 aaronmk
row_num_col = '_row_num'
700
701 2086 aaronmk
def add_row_num(db, table):
702 2117 aaronmk
    '''Adds a row number column to a table. Its name is in row_num_col. It will
703
    be the primary key.'''
704 2086 aaronmk
    check_name(table)
705 2096 aaronmk
    run_query(db, 'ALTER TABLE '+table+' ADD COLUMN '+row_num_col
706 2117 aaronmk
        +' serial NOT NULL PRIMARY KEY')
707 2086 aaronmk
708 1968 aaronmk
def tables(db, schema='public', table_like='%'):
709 1849 aaronmk
    module = util.root_module(db.db)
710 1968 aaronmk
    params = {'schema': schema, 'table_like': table_like}
711 832 aaronmk
    if module == 'psycopg2':
712 1968 aaronmk
        return values(run_query(db, '''\
713
SELECT tablename
714
FROM pg_tables
715
WHERE
716
    schemaname = %(schema)s
717
    AND tablename LIKE %(table_like)s
718
ORDER BY tablename
719
''',
720
            params, cacheable=True))
721
    elif module == 'MySQLdb':
722
        return values(run_query(db, 'SHOW TABLES LIKE %(table_like)s', params,
723
            cacheable=True))
724 832 aaronmk
    else: raise NotImplementedError("Can't list tables for "+module+' database')
725 830 aaronmk
726 833 aaronmk
##### Database management
727
728 1968 aaronmk
def empty_db(db, schema='public', **kw_args):
729
    '''For kw_args, see tables()'''
730
    for table in tables(db, schema, **kw_args): truncate(db, table, schema)
731 833 aaronmk
732 832 aaronmk
##### Heuristic queries
733
734 2104 aaronmk
def put(db, table, row, pkey_=None, row_ct_ref=None):
735 1554 aaronmk
    '''Recovers from errors.
736 2077 aaronmk
    Only works under PostgreSQL (uses INSERT RETURNING).
737
    '''
738 2104 aaronmk
    if pkey_ == None: pkey_ = pkey(db, table, recover=True)
739
740 471 aaronmk
    try:
741 2149 aaronmk
        cur = insert(db, table, row, pkey_, recover=True)
742 1554 aaronmk
        if row_ct_ref != None and cur.rowcount >= 0:
743
            row_ct_ref[0] += cur.rowcount
744
        return value(cur)
745 471 aaronmk
    except DuplicateKeyException, e:
746 2104 aaronmk
        return value(select(db, table, [pkey_],
747 1069 aaronmk
            util.dict_subset_right_join(row, e.cols), recover=True))
748 471 aaronmk
749 473 aaronmk
def get(db, table, row, pkey, row_ct_ref=None, create=False):
750 830 aaronmk
    '''Recovers from errors'''
751 2209 aaronmk
    try: return value(select(db, table, [pkey], row, limit=1, recover=True))
752 14 aaronmk
    except StopIteration:
753 40 aaronmk
        if not create: raise
754 471 aaronmk
        return put(db, table, row, pkey, row_ct_ref) # insert new row
755 2078 aaronmk
756 2134 aaronmk
def put_table(db, out_table, in_tables, mapping, limit=None, start=0,
757
    row_ct_ref=None, table_is_esc=False):
758 2078 aaronmk
    '''Recovers from errors.
759
    Only works under PostgreSQL (uses INSERT RETURNING).
760 2131 aaronmk
    @param in_tables The main input table to select from, followed by a list of
761
        tables to join with it using the main input table's pkey
762 2133 aaronmk
    @return (table, col) Where the pkeys (from INSERT RETURNING) are made
763 2078 aaronmk
        available
764
    '''
765 2162 aaronmk
    temp_suffix = clean_name(out_table)
766 2158 aaronmk
        # suffix, not prefix, so main name won't be removed if name is truncated
767
    pkeys_ref = ['pkeys_'+temp_suffix]
768 2131 aaronmk
769 2132 aaronmk
    # Join together input tables
770 2131 aaronmk
    in_tables = in_tables[:] # don't modify input!
771
    in_tables0 = in_tables.pop(0) # first table is separate
772
    in_pkey = pkey(db, in_tables0, recover=True, table_is_esc=table_is_esc)
773 2178 aaronmk
    insert_joins = [in_tables0]+[(t, {in_pkey: join_using}) for t in in_tables]
774 2131 aaronmk
775 2142 aaronmk
    out_pkey = pkey(db, out_table, recover=True, table_is_esc=table_is_esc)
776
    pkeys_cols = [in_pkey, out_pkey]
777
778 2201 aaronmk
    pkeys_table_exists_ref = [False]
779
    def run_query_into_pkeys(query, params):
780
        if pkeys_table_exists_ref[0]:
781
            insert_select(db, pkeys_ref[0], pkeys_cols, query, params)
782
        else:
783
            run_query_into(db, query, params, into_ref=pkeys_ref)
784
            pkeys_table_exists_ref[0] = True
785
786 2208 aaronmk
    conds = {}
787 2207 aaronmk
    distinct_on = None
788
    def mk_main_select(cols):
789 2208 aaronmk
        return mk_select(db, insert_joins, cols, conds, distinct_on,
790 2205 aaronmk
            order_by=None, limit=limit, start=start, table_is_esc=table_is_esc)
791 2132 aaronmk
792 2206 aaronmk
    # Do inserts and selects
793 2158 aaronmk
    out_pkeys_ref = ['out_pkeys_'+temp_suffix]
794 2206 aaronmk
    while True:
795
        try:
796
            cur = insert_select(db, out_table, mapping.keys(),
797 2207 aaronmk
                *mk_main_select(mapping.values()), returning=out_pkey,
798 2206 aaronmk
                into_ref=out_pkeys_ref, recover=True, table_is_esc=table_is_esc)
799
            if row_ct_ref != None and cur.rowcount >= 0:
800
                row_ct_ref[0] += cur.rowcount
801
                add_row_num(db, out_pkeys_ref[0]) # for joining with input pkeys
802
803
            # Get input pkeys corresponding to rows in insert
804
            in_pkeys_ref = ['in_pkeys_'+temp_suffix]
805 2207 aaronmk
            run_query_into(db, *mk_main_select([in_pkey]),
806
                into_ref=in_pkeys_ref)
807 2206 aaronmk
            add_row_num(db, in_pkeys_ref[0]) # for joining with output pkeys
808
809
            # Join together output and input pkeys
810
            run_query_into_pkeys(*mk_select(db, [in_pkeys_ref[0],
811
                (out_pkeys_ref[0], {row_num_col: join_using})], pkeys_cols,
812
                start=0))
813
814
            break # insert successful
815
        except DuplicateKeyException, e:
816
            join_cols = util.dict_subset_right_join(mapping, e.cols)
817
            select_joins = insert_joins + [(out_table, join_cols)]
818
819
            # Get pkeys of already existing rows
820
            run_query_into_pkeys(*mk_select(db, select_joins, pkeys_cols,
821
                order_by=None, start=0, table_is_esc=table_is_esc))
822
823
            # Save existing pkeys in temp table for joining on
824
            existing_pkeys_ref = ['existing_pkeys_'+temp_suffix]
825
            run_query_into(db, *mk_select(db, pkeys_ref[0], [in_pkey],
826
                order_by=None, start=0, table_is_esc=True),
827
                into_ref=existing_pkeys_ref)
828
                # need table_is_esc=True to make table name case-insensitive
829
830
            # rerun loop with additional constraints
831
            break # but until NullValueExceptions are handled, end loop here
832 2132 aaronmk
833 2154 aaronmk
    return (pkeys_ref[0], out_pkey)
834 2115 aaronmk
835
##### Data cleanup
836
837
def cleanup_table(db, table, cols, table_is_esc=False):
838
    def esc_name_(name): return esc_name(db, name)
839
840
    if not table_is_esc: check_name(table)
841
    cols = map(esc_name_, cols)
842
843
    run_query(db, 'UPDATE '+table+' SET\n'+(',\n'.join(('\n'+col
844
        +' = nullif(nullif(trim(both from '+col+"), %(null0)s), %(null1)s)"
845
            for col in cols))),
846
        dict(null0='', null1=r'\N'))