source: branches/4.x/pg.py @ 734

Last change on this file since 734 was 734, checked in by cito, 4 years ago

Add documentation for transaction handling methods

Also, the savepoint name is not optional.

  • Property svn:keywords set to Id
File size: 34.4 KB
Line 
1#! /usr/bin/python
2#
3# pg.py
4#
5# $Id: pg.py 734 2016-01-13 15:50:25Z cito $
6#
7
8"""PyGreSQL classic interface.
9
10This pg module implements some basic database management stuff.
11It includes the _pg module and builds on it, providing the higher
12level wrapper class named DB with additional functionality.
13This is known as the "classic" ("old style") PyGreSQL interface.
14For a DB-API 2 compliant interface use the newer pgdb module.
15
16"""
17
18# Copyright (c) 1997-2013 by D'Arcy J.M. Cain.
19#
20# Contributions made by Ch. Zwerschke and others.
21#
22# The notification handler is based on pgnotify which is
23# Copyright (c) 2001 Ng Pheng Siong. All rights reserved.
24#
25# Permission to use, copy, modify, and distribute this software and its
26# documentation for any purpose and without fee is hereby granted,
27# provided that the above copyright notice appear in all copies and that
28# both that copyright notice and this permission notice appear in
29# supporting documentation.
30
31from _pg import *
32
33import select
34import warnings
35try:
36    frozenset
37except NameError:  # Python < 2.4, unsupported
38    from sets import ImmutableSet as frozenset
39try:
40    from decimal import Decimal
41    set_decimal(Decimal)
42except ImportError:  # Python < 2.4, unsupported
43    Decimal = float
44try:
45    from collections import namedtuple
46except ImportError:  # Python < 2.6
47    namedtuple = None
48
49
50# Auxiliary functions that are independent from a DB connection:
51
52def _is_quoted(s):
53    """Check whether this string is a quoted identifier."""
54    s = s.replace('_', 'a')
55    return not s.isalnum() or s[:1].isdigit() or s != s.lower()
56
57
58def _is_unquoted(s):
59    """Check whether this string is an unquoted identifier."""
60    s = s.replace('_', 'a')
61    return s.isalnum() and not s[:1].isdigit()
62
63
64def _split_first_part(s):
65    """Split the first part of a dot separated string."""
66    s = s.lstrip()
67    if s[:1] == '"':
68        p = []
69        s = s.split('"', 3)[1:]
70        p.append(s[0])
71        while len(s) == 3 and s[1] == '':
72            p.append('"')
73            s = s[2].split('"', 2)
74            p.append(s[0])
75        p = [''.join(p)]
76        s = '"'.join(s[1:]).lstrip()
77        if s:
78            if s[:0] == '.':
79                p.append(s[1:])
80            else:
81                s = _split_first_part(s)
82                p[0] += s[0]
83                if len(s) > 1:
84                    p.append(s[1])
85    else:
86        p = s.split('.', 1)
87        s = p[0].rstrip()
88        if _is_unquoted(s):
89            s = s.lower()
90        p[0] = s
91    return p
92
93
94def _split_parts(s):
95    """Split all parts of a dot separated string."""
96    q = []
97    while s:
98        s = _split_first_part(s)
99        q.append(s[0])
100        if len(s) < 2:
101            break
102        s = s[1]
103    return q
104
105
106def _join_parts(s):
107    """Join all parts of a dot separated string."""
108    return '.'.join([_is_quoted(p) and '"%s"' % p or p for p in s])
109
110
111def _oid_key(qcl):
112    """Build oid key from qualified class name."""
113    return 'oid(%s)' % qcl
114
115
116if namedtuple:
117
118    def _namedresult(q):
119        """Get query result as named tuples."""
120        row = namedtuple('Row', q.listfields())
121        return [row(*r) for r in q.getresult()]
122
123    set_namedresult(_namedresult)
124
125
126def _db_error(msg, cls=DatabaseError):
127    """Returns DatabaseError with empty sqlstate attribute."""
128    error = cls(msg)
129    error.sqlstate = None
130    return error
131
132
133def _int_error(msg):
134    """Returns InternalError."""
135    return _db_error(msg, InternalError)
136
137
138def _prg_error(msg):
139    """Returns ProgrammingError."""
140    return _db_error(msg, ProgrammingError)
141
142
143class NotificationHandler(object):
144    """A PostgreSQL client-side asynchronous notification handler."""
145
146    def __init__(self, db, event, callback, arg_dict=None, timeout=None):
147        """Initialize the notification handler.
148
149        db       - PostgreSQL connection object.
150        event    - Event (notification channel) to LISTEN for.
151        callback - Event callback function.
152        arg_dict - A dictionary passed as the argument to the callback.
153        timeout  - Timeout in seconds; a floating point number denotes
154                   fractions of seconds. If it is absent or None, the
155                   callers will never time out.
156
157        """
158        if isinstance(db, DB):
159            db = db.db
160        self.db = db
161        self.event = event
162        self.stop_event = 'stop_%s' % event
163        self.listening = False
164        self.callback = callback
165        if arg_dict is None:
166            arg_dict = {}
167        self.arg_dict = arg_dict
168        self.timeout = timeout
169
170    def __del__(self):
171        self.close()
172
173    def close(self):
174        """Stop listening and close the connection."""
175        if self.db:
176            self.unlisten()
177            self.db.close()
178            self.db = None
179
180    def listen(self):
181        """Start listening for the event and the stop event."""
182        if not self.listening:
183            self.db.query('listen "%s"' % self.event)
184            self.db.query('listen "%s"' % self.stop_event)
185            self.listening = True
186
187    def unlisten(self):
188        """Stop listening for the event and the stop event."""
189        if self.listening:
190            self.db.query('unlisten "%s"' % self.event)
191            self.db.query('unlisten "%s"' % self.stop_event)
192            self.listening = False
193
194    def notify(self, db=None, stop=False, payload=None):
195        """Generate a notification.
196
197        Note: If the main loop is running in another thread, you must pass
198        a different database connection to avoid a collision.
199
200        The payload parameter is only supported in PostgreSQL >= 9.0.
201
202        """
203        if not db:
204            db = self.db
205        if self.listening:
206            q = 'notify "%s"' % (stop and self.stop_event or self.event)
207            if payload:
208                q += ", '%s'" % payload
209            return db.query(q)
210
211    def __call__(self, close=False):
212        """Invoke the notification handler.
213
214        The handler is a loop that actually LISTENs for two NOTIFY messages:
215
216        <event> and stop_<event>.
217
218        When either of these NOTIFY messages are received, its associated
219        'pid' and 'event' are inserted into <arg_dict>, and the callback is
220        invoked with <arg_dict>. If the NOTIFY message is stop_<event>, the
221        handler UNLISTENs both <event> and stop_<event> and exits.
222
223        Note: If you run this loop in another thread, don't use the same
224        database connection for database operations in the main thread.
225
226        """
227        self.listen()
228        _ilist = [self.db.fileno()]
229
230        while self.listening:
231            ilist, _olist, _elist = select.select(_ilist, [], [], self.timeout)
232            if ilist:
233                while self.listening:
234                    notice = self.db.getnotify()
235                    if not notice:  # no more messages
236                        break
237                    event, pid, extra = notice
238                    if event not in (self.event, self.stop_event):
239                        self.unlisten()
240                        raise _db_error(
241                            'listening for "%s" and "%s", but notified of "%s"'
242                            % (self.event, self.stop_event, event))
243                    if event == self.stop_event:
244                        self.unlisten()
245                    self.arg_dict['pid'] = pid
246                    self.arg_dict['event'] = event
247                    self.arg_dict['extra'] = extra
248                    self.callback(self.arg_dict)
249            else:   # we timed out
250                self.unlisten()
251                self.callback(None)
252
253
254def pgnotify(*args, **kw):
255    """Same as NotificationHandler, under the traditional name."""
256    warnings.warn("pgnotify is deprecated, use NotificationHandler instead.",
257        DeprecationWarning, stacklevel=2)
258    return NotificationHandler(*args, **kw)
259
260
261# The actual PostGreSQL database connection interface:
262
263class DB(object):
264    """Wrapper class for the _pg connection type."""
265
266    def __init__(self, *args, **kw):
267        """Create a new connection.
268
269        You can pass either the connection parameters or an existing
270        _pg or pgdb connection. This allows you to use the methods
271        of the classic pg interface with a DB-API 2 pgdb connection.
272
273        """
274        if not args and len(kw) == 1:
275            db = kw.get('db')
276        elif not kw and len(args) == 1:
277            db = args[0]
278        else:
279            db = None
280        if db:
281            if isinstance(db, DB):
282                db = db.db
283            else:
284                try:
285                    db = db._cnx
286                except AttributeError:
287                    pass
288        if not db or not hasattr(db, 'db') or not hasattr(db, 'query'):
289            db = connect(*args, **kw)
290            self._closeable = True
291        else:
292            self._closeable = False
293        self.db = db
294        self.dbname = db.db
295        self._regtypes = False
296        self._attnames = {}
297        self._pkeys = {}
298        self._privileges = {}
299        self._args = args, kw
300        self.debug = None  # For debugging scripts, this can be set
301            # * to a string format specification (e.g. in CGI set to "%s<BR>"),
302            # * to a file object to write debug statements or
303            # * to a callable object which takes a string argument
304            # * to any other true value to just print debug statements
305
306    def __getattr__(self, name):
307        # All undefined members are same as in underlying connection:
308        if self.db:
309            return getattr(self.db, name)
310        else:
311            raise _int_error('Connection is not valid')
312
313    # Context manager methods
314
315    def __enter__(self):
316        """Enter the runtime context. This will start a transaction."""
317        self.begin()
318        return self
319
320    def __exit__(self, et, ev, tb):
321        """Exit the runtime context. This will end the transaction."""
322        if et is None and ev is None and tb is None:
323            self.commit()
324        else:
325            self.rollback()
326
327    # Auxiliary methods
328
329    def _do_debug(self, s):
330        """Print a debug message."""
331        if self.debug:
332            if isinstance(self.debug, basestring):
333                print(self.debug % s)
334            elif isinstance(self.debug, file):
335                self.debug.write(s + '\n')
336            elif callable(self.debug):
337                self.debug(s)
338            else:
339                print(s)
340
341    def _make_bool(d):
342        """Get boolean value corresponding to d."""
343        if get_bool():
344            return bool(d)
345        return d and 't' or 'f'
346    _make_bool = staticmethod(_make_bool)
347
348    def _quote_text(self, d):
349        """Quote text value."""
350        if not isinstance(d, basestring):
351            d = str(d)
352        return "'%s'" % self.escape_string(d)
353
354    _bool_true = frozenset('t true 1 y yes on'.split())
355
356    def _quote_bool(self, d):
357        """Quote boolean value."""
358        if isinstance(d, basestring):
359            if not d:
360                return 'NULL'
361            d = d.lower() in self._bool_true
362        return d and "'t'" or "'f'"
363
364    _date_literals = frozenset('current_date current_time'
365        ' current_timestamp localtime localtimestamp'.split())
366
367    def _quote_date(self, d):
368        """Quote date value."""
369        if not d:
370            return 'NULL'
371        if isinstance(d, basestring) and d.lower() in self._date_literals:
372            return d
373        return self._quote_text(d)
374
375    def _quote_num(self, d):
376        """Quote numeric value."""
377        if not d and d != 0:
378            return 'NULL'
379        return str(d)
380
381    def _quote_money(self, d):
382        """Quote money value."""
383        if d is None or d == '':
384            return 'NULL'
385        if not isinstance(d, basestring):
386            d = str(d)
387        return d
388
389    _quote_funcs = dict(  # quote methods for each type
390        text=_quote_text, bool=_quote_bool, date=_quote_date,
391        int=_quote_num, num=_quote_num, float=_quote_num,
392        money=_quote_money)
393
394    def _quote(self, d, t):
395        """Return quotes if needed."""
396        if d is None:
397            return 'NULL'
398        try:
399            quote_func = self._quote_funcs[t]
400        except KeyError:
401            quote_func = self._quote_funcs['text']
402        return quote_func(self, d)
403
404    def _split_schema(self, cl):
405        """Return schema and name of object separately.
406
407        This auxiliary function splits off the namespace (schema)
408        belonging to the class with the name cl. If the class name
409        is not qualified, the function is able to determine the schema
410        of the class, taking into account the current search path.
411
412        """
413        s = _split_parts(cl)
414        if len(s) > 1:  # name already qualified?
415            # should be database.schema.table or schema.table
416            if len(s) > 3:
417                raise _prg_error('Too many dots in class name %s' % cl)
418            schema, cl = s[-2:]
419        else:
420            cl = s[0]
421            # determine search path
422            q = 'SELECT current_schemas(TRUE)'
423            schemas = self.db.query(q).getresult()[0][0][1:-1].split(',')
424            if schemas:  # non-empty path
425                # search schema for this object in the current search path
426                # (we could also use unnest with ordinality here to spare
427                # one query, but this is only possible since PostgreSQL 9.4)
428                q = ' UNION '.join(
429                    ["SELECT %d::integer AS n, '%s'::name AS nspname"
430                        % s for s in enumerate(schemas)])
431                q = ("SELECT nspname FROM pg_class r"
432                    " JOIN pg_namespace s ON r.relnamespace = s.oid"
433                    " JOIN (%s) AS p USING (nspname)"
434                    " WHERE r.relname = $1 ORDER BY n LIMIT 1" % q)
435                schema = self.db.query(q, (cl,)).getresult()
436                if schema:  # schema found
437                    schema = schema[0][0]
438                else:  # object not found in current search path
439                    schema = 'public'
440            else:  # empty path
441                schema = 'public'
442        return schema, cl
443
444    def _add_schema(self, cl):
445        """Ensure that the class name is prefixed with a schema name."""
446        return _join_parts(self._split_schema(cl))
447
448    # Public methods
449
450    # escape_string and escape_bytea exist as methods,
451    # so we define unescape_bytea as a method as well
452    unescape_bytea = staticmethod(unescape_bytea)
453
454    def close(self):
455        """Close the database connection."""
456        # Wraps shared library function so we can track state.
457        if self._closeable:
458            if self.db:
459                self.db.close()
460                self.db = None
461            else:
462                raise _int_error('Connection already closed')
463
464    def reset(self):
465        """Reset connection with current parameters.
466
467        All derived queries and large objects derived from this connection
468        will not be usable after this call.
469
470        """
471        if self.db:
472            self.db.reset()
473        else:
474            raise _int_error('Connection already closed')
475
476    def reopen(self):
477        """Reopen connection to the database.
478
479        Used in case we need another connection to the same database.
480        Note that we can still reopen a database that we have closed.
481
482        """
483        # There is no such shared library function.
484        if self._closeable:
485            db = connect(*self._args[0], **self._args[1])
486            if self.db:
487                self.db.close()
488            self.db = db
489
490    def begin(self, mode=None):
491        """Begin a transaction."""
492        qstr = 'BEGIN'
493        if mode:
494            qstr += ' ' + mode
495        return self.query(qstr)
496
497    start = begin
498
499    def commit(self):
500        """Commit the current transaction."""
501        return self.query('COMMIT')
502
503    end = commit
504
505    def rollback(self, name=None):
506        """Roll back the current transaction."""
507        qstr = 'ROLLBACK'
508        if name:
509            qstr += ' TO ' + name
510        return self.query(qstr)
511
512    def savepoint(self, name):
513        """Define a new savepoint within the current transaction."""
514        return self.query('SAVEPOINT ' + name)
515
516    def release(self, name):
517        """Destroy a previously defined savepoint."""
518        return self.query('RELEASE ' + name)
519
520    def query(self, qstr, *args):
521        """Executes a SQL command string.
522
523        This method simply sends a SQL query to the database. If the query is
524        an insert statement that inserted exactly one row into a table that
525        has OIDs, the return value is the OID of the newly inserted row.
526        If the query is an update or delete statement, or an insert statement
527        that did not insert exactly one row in a table with OIDs, then the
528        number of rows affected is returned as a string. If it is a statement
529        that returns rows as a result (usually a select statement, but maybe
530        also an "insert/update ... returning" statement), this method returns
531        a pgqueryobject that can be accessed via getresult() or dictresult()
532        or simply printed. Otherwise, it returns `None`.
533
534        The query can contain numbered parameters of the form $1 in place
535        of any data constant. Arguments given after the query string will
536        be substituted for the corresponding numbered parameter. Parameter
537        values can also be given as a single list or tuple argument.
538
539        Note that the query string must not be passed as a unicode value,
540        but you can pass arguments as unicode values if they can be decoded
541        using the current client encoding.
542
543        """
544        # Wraps shared library function for debugging.
545        if not self.db:
546            raise _int_error('Connection is not valid')
547        self._do_debug(qstr)
548        return self.db.query(qstr, args)
549
550    def pkey(self, cl, newpkey=None):
551        """This method gets or sets the primary key of a class.
552
553        Composite primary keys are represented as frozensets. Note that
554        this raises a KeyError if the table does not have a primary key.
555
556        If newpkey is set and is not a dictionary then set that
557        value as the primary key of the class.  If it is a dictionary
558        then replace the internal cache of primary keys with a copy of it.
559
560        """
561        # First see if the caller is supplying a dictionary
562        if isinstance(newpkey, dict):
563            # make sure that all classes have a namespace
564            self._pkeys = dict([
565                ('.' in cl and cl or 'public.' + cl, pkey)
566                for cl, pkey in newpkey.items()])
567            return self._pkeys
568
569        qcl = self._add_schema(cl)  # build fully qualified class name
570        # Check if the caller is supplying a new primary key for the class
571        if newpkey:
572            self._pkeys[qcl] = newpkey
573            return newpkey
574
575        # Get all the primary keys at once
576        if qcl not in self._pkeys:
577            # if not found, check again in case it was added after we started
578            self._pkeys = {}
579            if self.server_version >= 80200:
580                # the ANY syntax works correctly only with PostgreSQL >= 8.2
581                any_indkey = "= ANY (i.indkey)"
582            else:
583                any_indkey = "IN (%s)" % ', '.join(
584                    ['i.indkey[%d]' % i for i in range(16)])
585            q = ("SELECT s.nspname, r.relname, a.attname"
586                " FROM pg_class r"
587                " JOIN pg_namespace s ON s.oid = r.relnamespace"
588                " AND s.nspname NOT SIMILAR"
589                " TO 'pg/_%|information/_schema' ESCAPE '/'"
590                " JOIN pg_attribute a ON a.attrelid = r.oid"
591                " AND NOT a.attisdropped"
592                " JOIN pg_index i ON i.indrelid = r.oid"
593                " AND i.indisprimary AND a.attnum " + any_indkey)
594            for r in self.db.query(q).getresult():
595                cl, pkey = _join_parts(r[:2]), r[2]
596                self._pkeys.setdefault(cl, []).append(pkey)
597            # (only) for composite primary keys, the values will be frozensets
598            for cl, pkey in self._pkeys.items():
599                self._pkeys[cl] = len(pkey) > 1 and frozenset(pkey) or pkey[0]
600            self._do_debug(self._pkeys)
601
602        # will raise an exception if primary key doesn't exist
603        return self._pkeys[qcl]
604
605    def get_databases(self):
606        """Get list of databases in the system."""
607        return [s[0] for s in
608            self.db.query('SELECT datname FROM pg_database').getresult()]
609
610    def get_relations(self, kinds=None):
611        """Get list of relations in connected database of specified kinds.
612
613        If kinds is None or empty, all kinds of relations are returned.
614        Otherwise kinds can be a string or sequence of type letters
615        specifying which kind of relations you want to list.
616
617        """
618        where = kinds and " AND r.relkind IN (%s)" % ','.join(
619            ["'%s'" % k for k in kinds]) or ''
620        q = ("SELECT s.nspname, r.relname"
621            " FROM pg_class r"
622            " JOIN pg_namespace s ON s.oid = r.relnamespace"
623            " WHERE s.nspname NOT SIMILAR"
624            " TO 'pg/_%%|information/_schema' ESCAPE '/' %s"
625            " ORDER BY 1, 2") % where
626        return [_join_parts(r) for r in self.db.query(q).getresult()]
627
628    def get_tables(self):
629        """Return list of tables in connected database."""
630        return self.get_relations('r')
631
632    def get_attnames(self, cl, newattnames=None):
633        """Given the name of a table, digs out the set of attribute names.
634
635        Returns a dictionary of attribute names (the names are the keys,
636        the values are the names of the attributes' types).
637        If the optional newattnames exists, it must be a dictionary and
638        will become the new attribute names dictionary.
639
640        By default, only a limited number of simple types will be returned.
641        You can get the regular types after calling use_regtypes(True).
642
643        """
644        if isinstance(newattnames, dict):
645            self._attnames = newattnames
646            return
647        elif newattnames:
648            raise _prg_error('If supplied, newattnames must be a dictionary')
649        cl = self._split_schema(cl)  # split into schema and class
650        qcl = _join_parts(cl)  # build fully qualified name
651        # May as well cache them:
652        if qcl in self._attnames:
653            return self._attnames[qcl]
654        if qcl not in self.get_relations('rv'):
655            raise _prg_error('Class %s does not exist' % qcl)
656
657        q = ("SELECT a.attname, t.typname%s"
658            " FROM pg_class r"
659            " JOIN pg_namespace s ON r.relnamespace = s.oid"
660            " JOIN pg_attribute a ON a.attrelid = r.oid"
661            " JOIN pg_type t ON t.oid = a.atttypid"
662            " WHERE s.nspname = $1 AND r.relname = $2"
663            " AND (a.attnum > 0 OR a.attname = 'oid')"
664            " AND NOT a.attisdropped") % (
665                self._regtypes and '::regtype' or '',)
666        q = self.db.query(q, cl).getresult()
667
668        if self._regtypes:
669            t = dict(q)
670        else:
671            t = {}
672            for att, typ in q:
673                if typ.startswith('bool'):
674                    typ = 'bool'
675                elif typ.startswith('abstime'):
676                    typ = 'date'
677                elif typ.startswith('date'):
678                    typ = 'date'
679                elif typ.startswith('interval'):
680                    typ = 'date'
681                elif typ.startswith('timestamp'):
682                    typ = 'date'
683                elif typ.startswith('oid'):
684                    typ = 'int'
685                elif typ.startswith('int'):
686                    typ = 'int'
687                elif typ.startswith('float'):
688                    typ = 'float'
689                elif typ.startswith('numeric'):
690                    typ = 'num'
691                elif typ.startswith('money'):
692                    typ = 'money'
693                else:
694                    typ = 'text'
695                t[att] = typ
696
697        self._attnames[qcl] = t  # cache it
698        return self._attnames[qcl]
699
700    def use_regtypes(self, regtypes=None):
701        """Use regular type names instead of simplified type names."""
702        if regtypes is None:
703            return self._regtypes
704        else:
705            regtypes = bool(regtypes)
706            if regtypes != self._regtypes:
707                self._regtypes = regtypes
708                self._attnames.clear()
709            return regtypes
710
711    def has_table_privilege(self, cl, privilege='select'):
712        """Check whether current user has specified table privilege."""
713        qcl = self._add_schema(cl)
714        privilege = privilege.lower()
715        try:
716            return self._privileges[(qcl, privilege)]
717        except KeyError:
718            q = "SELECT has_table_privilege($1, $2)"
719            q = self.db.query(q, (qcl, privilege))
720            ret = q.getresult()[0][0] == self._make_bool(True)
721            self._privileges[(qcl, privilege)] = ret
722            return ret
723
724    def get(self, cl, arg, keyname=None):
725        """Get a row from a database table or view.
726
727        This method is the basic mechanism to get a single row.  The keyname
728        that the key specifies a unique row.  If keyname is not specified
729        then the primary key for the table is used.  If arg is a dictionary
730        then the value for the key is taken from it and it is modified to
731        include the new values, replacing existing values where necessary.
732        For a composite key, keyname can also be a sequence of key names.
733        The OID is also put into the dictionary if the table has one, but
734        in order to allow the caller to work with multiple tables, it is
735        munged as oid(schema.table).
736
737        """
738        if cl.endswith('*'):  # scan descendant tables?
739            cl = cl[:-1].rstrip()  # need parent table name
740        # build qualified class name
741        qcl = self._add_schema(cl)
742        # To allow users to work with multiple tables,
743        # we munge the name of the "oid" key
744        qoid = _oid_key(qcl)
745        if not keyname:
746            # use the primary key by default
747            try:
748                keyname = self.pkey(qcl)
749            except KeyError:
750                raise _prg_error('Class %s has no primary key' % qcl)
751        # We want the oid for later updates if that isn't the key
752        if keyname == 'oid':
753            if isinstance(arg, dict):
754                if qoid not in arg:
755                    raise _db_error('%s not in arg' % qoid)
756            else:
757                arg = {qoid: arg}
758            where = 'oid = %s' % arg[qoid]
759            attnames = '*'
760        else:
761            attnames = self.get_attnames(qcl)
762            if isinstance(keyname, basestring):
763                keyname = (keyname,)
764            if not isinstance(arg, dict):
765                if len(keyname) > 1:
766                    raise _prg_error('Composite key needs dict as arg')
767                arg = dict([(k, arg) for k in keyname])
768            where = ' AND '.join(['%s = %s'
769                % (k, self._quote(arg[k], attnames[k])) for k in keyname])
770            attnames = ', '.join(attnames)
771        q = 'SELECT %s FROM %s WHERE %s LIMIT 1' % (attnames, qcl, where)
772        self._do_debug(q)
773        res = self.db.query(q).dictresult()
774        if not res:
775            raise _db_error('No such record in %s where %s' % (qcl, where))
776        for att, value in res[0].items():
777            arg[att == 'oid' and qoid or att] = value
778        return arg
779
780    def insert(self, cl, d=None, **kw):
781        """Insert a row into a database table.
782
783        This method inserts a row into a table.  The name of the table must
784        be passed as the first parameter.  The other parameters are used for
785        providing the data of the row that shall be inserted into the table.
786        If a dictionary is supplied as the second parameter, it starts with
787        that.  Otherwise it uses a blank dictionary. Either way the dictionary
788        is updated from the keywords.
789
790        The dictionary is then, if possible, reloaded with the values actually
791        inserted in order to pick up values modified by rules, triggers, etc.
792
793        Note: The method currently doesn't support insert into views
794        although PostgreSQL does.
795
796        """
797        qcl = self._add_schema(cl)
798        qoid = _oid_key(qcl)
799        if d is None:
800            d = {}
801        d.update(kw)
802        attnames = self.get_attnames(qcl)
803        names, values = [], []
804        for n in attnames:
805            if n != 'oid' and n in d:
806                names.append('"%s"' % n)
807                values.append(self._quote(d[n], attnames[n]))
808        names, values = ', '.join(names), ', '.join(values)
809        selectable = self.has_table_privilege(qcl)
810        if selectable and self.server_version >= 80200:
811            ret = ' RETURNING %s*' % ('oid' in attnames and 'oid, ' or '')
812        else:
813            ret = ''
814        q = 'INSERT INTO %s (%s) VALUES (%s)%s' % (qcl, names, values, ret)
815        self._do_debug(q)
816        res = self.db.query(q)
817        if ret:
818            res = res.dictresult()
819            for att, value in res[0].items():
820                d[att == 'oid' and qoid or att] = value
821        elif isinstance(res, int):
822            d[qoid] = res
823            if selectable:
824                self.get(qcl, d, 'oid')
825        elif selectable:
826            if qoid in d:
827                self.get(qcl, d, 'oid')
828            else:
829                try:
830                    self.get(qcl, d)
831                except ProgrammingError:
832                    pass  # table has no primary key
833        return d
834
835    def update(self, cl, d=None, **kw):
836        """Update an existing row in a database table.
837
838        Similar to insert but updates an existing row.  The update is based
839        on the OID value as munged by get or passed as keyword, or on the
840        primary key of the table.  The dictionary is modified, if possible,
841        to reflect any changes caused by the update due to triggers, rules,
842        default values, etc.
843
844        """
845        # Update always works on the oid which get returns if available,
846        # otherwise use the primary key.  Fail if neither.
847        # Note that we only accept oid key from named args for safety
848        qcl = self._add_schema(cl)
849        qoid = _oid_key(qcl)
850        if 'oid' in kw:
851            kw[qoid] = kw['oid']
852            del kw['oid']
853        if d is None:
854            d = {}
855        d.update(kw)
856        attnames = self.get_attnames(qcl)
857        if qoid in d:
858            where = 'oid = %s' % d[qoid]
859            keyname = ()
860        else:
861            try:
862                keyname = self.pkey(qcl)
863            except KeyError:
864                raise _prg_error('Class %s has no primary key' % qcl)
865            if isinstance(keyname, basestring):
866                keyname = (keyname,)
867            try:
868                where = ' AND '.join(['%s = %s'
869                    % (k, self._quote(d[k], attnames[k])) for k in keyname])
870            except KeyError:
871                raise _prg_error('Update needs primary key or oid.')
872        values = []
873        for n in attnames:
874            if n in d and n not in keyname:
875                values.append('%s = %s' % (n, self._quote(d[n], attnames[n])))
876        if not values:
877            return d
878        values = ', '.join(values)
879        selectable = self.has_table_privilege(qcl)
880        if selectable and self.server_version >= 80200:
881            ret = ' RETURNING %s*' % ('oid' in attnames and 'oid, ' or '')
882        else:
883            ret = ''
884        q = 'UPDATE %s SET %s WHERE %s%s' % (qcl, values, where, ret)
885        self._do_debug(q)
886        res = self.db.query(q)
887        if ret:
888            res = res.dictresult()[0]
889            for att, value in res.items():
890                d[att == 'oid' and qoid or att] = value
891        else:
892            if selectable:
893                if qoid in d:
894                    self.get(qcl, d, 'oid')
895                else:
896                    self.get(qcl, d)
897        return d
898
899    def clear(self, cl, a=None):
900        """Clear all the attributes to values determined by the types.
901
902        Numeric types are set to 0, Booleans are set to false, and everything
903        else is set to the empty string.  If the array argument is present,
904        it is used as the array and any entries matching attribute names are
905        cleared with everything else left unchanged.
906
907        """
908        # At some point we will need a way to get defaults from a table.
909        qcl = self._add_schema(cl)
910        if a is None:
911            a = {}  # empty if argument is not present
912        attnames = self.get_attnames(qcl)
913        for n, t in attnames.items():
914            if n == 'oid':
915                continue
916            if t in ('int', 'integer', 'smallint', 'bigint',
917                    'float', 'real', 'double precision',
918                    'num', 'numeric', 'money'):
919                a[n] = 0
920            elif t in ('bool', 'boolean'):
921                a[n] = self._make_bool(False)
922            else:
923                a[n] = ''
924        return a
925
926    def delete(self, cl, d=None, **kw):
927        """Delete an existing row in a database table.
928
929        This method deletes the row from a table.  It deletes based on the
930        OID value as munged by get or passed as keyword, or on the primary
931        key of the table.  The return value is the number of deleted rows
932        (i.e. 0 if the row did not exist and 1 if the row was deleted).
933
934        """
935        # Like update, delete works on the oid.
936        # One day we will be testing that the record to be deleted
937        # isn't referenced somewhere (or else PostgreSQL will).
938        # Note that we only accept oid key from named args for safety
939        qcl = self._add_schema(cl)
940        qoid = _oid_key(qcl)
941        if 'oid' in kw:
942            kw[qoid] = kw['oid']
943            del kw['oid']
944        if d is None:
945            d = {}
946        d.update(kw)
947        if qoid in d:
948            where = 'oid = %s' % d[qoid]
949        else:
950            try:
951                keyname = self.pkey(qcl)
952            except KeyError:
953                raise _prg_error('Class %s has no primary key' % qcl)
954            if isinstance(keyname, basestring):
955                keyname = (keyname,)
956            attnames = self.get_attnames(qcl)
957            try:
958                where = ' AND '.join(['%s = %s'
959                    % (k, self._quote(d[k], attnames[k])) for k in keyname])
960            except KeyError:
961                raise _prg_error('Delete needs primary key or oid.')
962        q = 'DELETE FROM %s WHERE %s' % (qcl, where)
963        self._do_debug(q)
964        return int(self.db.query(q))
965
966    def notification_handler(self, event, callback, arg_dict={}, timeout=None):
967        """Get notification handler that will run the given callback."""
968        return NotificationHandler(self.db, event, callback, arg_dict, timeout)
969
970
971# if run as script, print some information
972
973if __name__ == '__main__':
974    print('PyGreSQL version' + version)
975    print('')
976    print(__doc__)
Note: See TracBrowser for help on using the repository browser.