Ejemplo n.º 1
0
    def _from_db(self, name, conn_or_curs):
        """Return a `CompositeCaster` instance for the type *name*.

        Raise `ProgrammingError` if the type is not found.
        """
        conn, curs = _solve_conn_curs(conn_or_curs)

        # Store the transaction status of the connection to revert it after use
        conn_status = conn.status

        # Use the correct schema
        if '.' in name:
            schema, tname = name.split('.', 1)
        else:
            tname = name
            schema = 'public'

        # column typarray not available before PG 8.3
        typarray = conn.info.server_version >= 80300 and "typarray" or "NULL"

        # get the type oid and attributes
        curs.execute(
            """\
SELECT t.oid, %s, attname, atttypid
FROM pg_type t
JOIN pg_namespace ns ON typnamespace = ns.oid
JOIN pg_attribute a ON attrelid = typrelid
WHERE typname = %%s AND nspname = %%s
    AND attnum > 0 AND NOT attisdropped
ORDER BY attnum;
""" % typarray, (tname, schema))

        recs = curs.fetchall()

        # revert the status of the connection as before the command
        if (conn_status != _ext.STATUS_IN_TRANSACTION and not conn.autocommit):
            conn.rollback()

        if not recs:
            raise psycopg2.ProgrammingError("PostgreSQL type '%s' not found" %
                                            name)

        type_oid = recs[0][0]
        array_oid = recs[0][1]
        type_attrs = [(r[2], r[3]) for r in recs]

        return self(tname,
                    type_oid,
                    type_attrs,
                    array_oid=array_oid,
                    schema=schema)
Ejemplo n.º 2
0
def get_system_role():
    """ Get the system role from the sysinv database"""

    conn = psycopg2.connect("dbname=sysinv user=postgres")
    cur = conn.cursor()
    cur.execute("select distributed_cloud_role from i_system;")
    row = cur.fetchone()
    if row is None:
        LOG.error("Failed to fetch i_system data")
        raise psycopg2.ProgrammingError("Failed to fetch i_system data")

    role = row[0]

    return role
Ejemplo n.º 3
0
 async def change(cls, sql=None, args=None):
     if sql is None:
         raise ValueError('sql执行语句为空')
     logging.info('[ %s %s ]' % (sql, args))
     # 未开启事务处理
     if cls.tran is None:
         async with cls.pool.acquire() as conn:
             async with conn.cursor() as cursor:
                 await cursor.execute(sql, args)
                 return cursor.rowcount
     else:
         if cls.cursor is None:
             raise psycopg2.ProgrammingError('数据库异常,游标为空')
         await cls.cursor.execute(sql, args)
         return cls.cursor.rowcount
Ejemplo n.º 4
0
def create(stmt):
    #create connection
    conn = psdb.connect(dbname='webshopdb', user='******', host='localhost', password='******')
    cur = conn.cursor()
    cur.execute(stmt)
    conn.commit()
    rows=cur.fetchall()    
    
    #TODO fix spaghetti that I tried to avoid by using this in the first place 
    if rows[0][0] == None:
        conn.rollback()
        raise psdb.ProgrammingError('Something went wrong')
    #TODO create and return api response codes
    conn.close()
    return rows
Ejemplo n.º 5
0
def test_create_slot(slot):

    with patch.object(psycopg2.ProgrammingError,
                      'pgcode',
                      new_callable=PropertyMock,
                      return_value=psycopg2.errorcodes.DUPLICATE_OBJECT):
        pe = psycopg2.ProgrammingError()

        slot._repl_cursor.create_replication_slot = Mock(side_effect=pe)
        slot.create_slot()
        slot._repl_cursor.create_replication_slot.assert_called_with(
            'pg2kinesis',
            slot_type=psycopg2.extras.REPLICATION_LOGICAL,
            output_plugin=u'test_decoding')
    with patch.object(psycopg2.ProgrammingError,
                      'pgcode',
                      new_callable=PropertyMock,
                      return_value=-1):
        pe = psycopg2.ProgrammingError()
        slot._repl_cursor.create_replication_slot = Mock(side_effect=pe)

        with pytest.raises(psycopg2.ProgrammingError) as e_info:
            slot.create_slot()
            slot._repl_cursor.create_replication_slot.assert_called_with(
                'pg2kinesis',
                slot_type=psycopg2.extras.REPLICATION_LOGICAL,
                output_plugin=u'test_decoding')
        assert e_info.value.pgcode == -1

        slot._repl_cursor.create_replication_slot = Mock(side_effect=Exception)
    with pytest.raises(Exception):
        slot.create_slot()
        slot._repl_cursor.create_replication_slot.assert_called_with(
            'pg2kinesis',
            slot_type=psycopg2.extras.REPLICATION_LOGICAL,
            output_plugin=u'test_decoding')
Ejemplo n.º 6
0
 def execute(self, sql, *params):
     if sql.startswith('blabla'):
         raise psycopg2.ProgrammingError()
     elif sql == 'CHECKPOINT' or sql.startswith(
             'SELECT pg_catalog.pg_create_'):
         raise psycopg2.OperationalError()
     elif sql.startswith('RetryFailedError'):
         raise RetryFailedError('retry')
     elif sql.startswith('SELECT slot_name'):
         self.results = [('blabla', 'physical'), ('foobar', 'physical'),
                         ('ls', 'logical', 'a', 'b')]
     elif sql.startswith('SELECT CASE WHEN pg_catalog.pg_is_in_recovery()'):
         self.results = [(1, 2, 1, 1, None, None)]
     elif sql.startswith('SELECT pg_catalog.pg_is_in_recovery()'):
         self.results = [(False, 2)]
     elif sql.startswith('SELECT pg_catalog.to_char'):
         replication_info = '[{"application_name":"walreceiver","client_addr":"1.2.3.4",' +\
                            '"state":"streaming","sync_state":"async","sync_priority":0}]'
         self.results = [('', 0, '', '', '', '', False, replication_info)]
     elif sql.startswith('SELECT name, setting'):
         self.results = [
             ('wal_segment_size', '2048', '8kB', 'integer', 'internal'),
             ('wal_block_size', '8192', None, 'integer', 'internal'),
             ('shared_buffers', '16384', '8kB', 'integer', 'postmaster'),
             ('wal_buffers', '-1', '8kB', 'integer', 'postmaster'),
             ('search_path', 'public', None, 'string', 'user'),
             ('port', '5433', None, 'integer', 'postmaster'),
             ('listen_addresses', '*', None, 'string', 'postmaster'),
             ('autovacuum', 'on', None, 'bool', 'sighup'),
             ('unix_socket_directories', '/tmp', None, 'string',
              'postmaster')
         ]
     elif sql.startswith('IDENTIFY_SYSTEM'):
         self.results = [('1', 3, '0/402EEC0', '')]
     elif sql.startswith('SELECT isdir, modification'):
         self.results = [(False, datetime.datetime.now())]
     elif sql.startswith('SELECT pg_catalog.pg_read_file'):
         self.results = [('1\t0/40159C0\tno recovery target specified\n\n'
                          '2\t1/40159C0\tno recovery target specified\n', )]
     elif sql.startswith('TIMELINE_HISTORY '):
         self.results = [('',
                          b'x\t0/40159C0\tno recovery target specified\n\n'
                          b'1\t0/40159C0\tno recovery target specified\n\n'
                          b'2\t0/402DD98\tno recovery target specified\n\n'
                          b'3\t0/403DD98\tno recovery target specified\n')]
     else:
         self.results = [(None, None, None, None, None, None, None, None,
                          None, None)]
Ejemplo n.º 7
0
    def _from_db(self, name, conn_or_curs):
        """Return a `CompositeCaster` instance for the type *name*.

        Raise `ProgrammingError` if the type is not found.
        """
        if hasattr(conn_or_curs, 'execute'):
            conn = conn_or_curs.connection
            curs = conn_or_curs
        else:
            conn = conn_or_curs
            curs = conn_or_curs.cursor()

        # Store the transaction status of the connection to revert it after use
        conn_status = conn.status

        # Use the correct schema
        if '.' in name:
            schema, tname = name.split('.', 1)
        else:
            tname = name
            schema = 'public'

        # get the type oid and attributes
        curs.execute(
            """\
SELECT t.oid, attname, atttypid
FROM pg_type t
JOIN pg_namespace ns ON typnamespace = ns.oid
JOIN pg_attribute a ON attrelid = typrelid
WHERE typname = %s and nspname = %s
ORDER BY attnum;
""", (tname, schema))

        recs = curs.fetchall()

        # revert the status of the connection as before the command
        if (conn_status != _ext.STATUS_IN_TRANSACTION
                and conn.isolation_level != _ext.ISOLATION_LEVEL_AUTOCOMMIT):
            conn.rollback()

        if not recs:
            raise psycopg2.ProgrammingError("PostgreSQL type '%s' not found" %
                                            name)

        type_oid = recs[0][0]
        type_attrs = [(r[1], r[2]) for r in recs]

        return CompositeCaster(tname, type_oid, type_attrs)
def get_request_tokens_datetime(chat_id):
    """
    Get request tokens datetime by chat id.
    """
    connection = connection_to_db()
    cursor = connection.cursor()

    cursor.execute(
        "SELECT token_request_datetime FROM remme_tokens_recodring WHERE chat_id={};"
        .format(chat_id))

    try:
        return cursor.fetchone()[0]
    except TypeError:
        raise psycopg2.ProgrammingError(
            'Fetching went wrong! No database record found.')
Ejemplo n.º 9
0
def check_extension(conn, extension: str) -> bool:
    """Check to see if an extension is installed."""

    query = 'SELECT installed_version FROM pg_available_extensions WHERE name=%s;'

    with conn.cursor() as cursor:
        cursor.execute(query, (extension, ))
        result = cursor.fetchone()

    if result is None:
        raise psycopg2.ProgrammingError(
            'Extension is not available for installation.', extension)
    else:
        extension_version = result[0]

        return bool(extension_version)
Ejemplo n.º 10
0
def register_hstore(conn_or_curs,
                    globally=False,
                    _unicode=False,
                    oid=None,
                    array_oid=None):
    from psycopg2.extras import HstoreAdapter
    from psycopg2 import extensions as _ext
    import psycopg2
    import sys
    import re as regex
    from .fields import HStoreDict

    def cast(s, cur, _bsdec=regex.compile(r"\\(.)")):
        if sys.version_info[0] < 3 and _unicode:
            result = HstoreAdapter.parse_unicode(s, cur)
        else:
            result = HstoreAdapter.parse(s, cur, _bsdec)
        return HStoreDict(result)

    if oid is None:
        oid = HstoreAdapter.get_oids(conn_or_curs)
        if oid is None or not oid[0]:
            raise psycopg2.ProgrammingError(
                "hstore type not found in the database. "
                "please install it from your 'contrib/hstore.sql' file")
        else:
            array_oid = oid[1]
            oid = oid[0]

    if isinstance(oid, int):
        oid = (oid, )

    if array_oid is not None:
        if isinstance(array_oid, int):
            array_oid = (array_oid, )
        else:
            array_oid = tuple([x for x in array_oid if x])

    HSTORE = _ext.new_type(oid, str("HSTORE"), cast)
    _ext.register_type(HSTORE, not globally and conn_or_curs or None)
    _ext.register_adapter(dict, HstoreAdapter)

    if array_oid:
        HSTOREARRAY = _ext.new_array_type(array_oid, str("HSTOREARRAY"),
                                          HSTORE)
        _ext.register_type(HSTOREARRAY, not globally and conn_or_curs or None)
Ejemplo n.º 11
0
    def query(self, query_string, max_rows=None, query_data=None):
        self._register()
        self.calls = self.calls + 1

        desc = ()
        res = []
        nselects = 0

        c = self.getcursor()

        try:
            for qs in [x for x in query_string.split('\0') if x]:
                try:
                    if query_data:
                        c.execute(qs, query_data)
                    else:
                        c.execute(qs)
                except TransactionRollbackError:
                    # Ha, here we have to look like we are the ZODB raising conflict errrors, raising ZPublisher.Publish.Retry just doesn't work
                    #logging.debug("Serialization Error, retrying transaction", exc_info=True)
                    raise ConflictError(
                        "TransactionRollbackError from psycopg2")
                except psycopg2.OperationalError:
                    #logging.exception("Operational error on connection, closing it.")
                    try:
                        # Only close our connection
                        self.putconn(True)
                    except:
                        #logging.debug("Something went wrong when we tried to close the pool", exc_info=True)
                        pass
                if c.description is not None:
                    nselects += 1
                    if c.description != desc and nselects > 1:
                        raise psycopg2.ProgrammingError(
                            'multiple selects in single query not allowed')
                    if max_rows:
                        res = c.fetchmany(max_rows)
                    else:
                        res = c.fetchall()
                    desc = c.description
            self.failures = 0

        except StandardError, err:
            self._abort()
            raise err
Ejemplo n.º 12
0
    def prepare(self, stmt):
        """Prepare a query for execution.

        TODO: handle literal %s and $s in the string.
        """
        # replace the python placeholders with postgres placeholders
        parlist = []
        parmap = {}
        parord = []

        def repl(m):
            par = m.group(1)
            if par is not None:
                parlist.append(par)
                return "$%d" % len(parlist)
            else:
                par = m.group(2)
                assert par
                idx = parmap.get(par)
                if idx is None:
                    idx = parmap[par] = "$%d" % (len(parmap) + 1)
                    parord.append(par)

                return idx

        pgstmt = self._re_replargs.sub(repl, stmt)

        if parlist and parmap:
            raise psycopg2.ProgrammingError(
                "you can't mix positional and named placeholders")

        self.deallocate()
        self.execute("prepare %s as %s" % (self._prepname, pgstmt))

        if parlist:
            self._execstmt = "execute %s (%s)" % (self._prepname,
                                                  ','.join(parlist))
        elif parmap:
            self._execstmt = "execute %s (%s)" % (self._prepname,
                                                  ','.join(parord))
        else:
            self._execstmt = "execute %s" % (self._prepname)

        self._prepared = stmt
Ejemplo n.º 13
0
def get_shared_services():
    """ Get the list of shared services from the sysinv database """
    shared_services = []
    DEFAULT_SHARED_SERVICES = []

    conn = psycopg2.connect("dbname=sysinv user=postgres")
    cur = conn.cursor()
    cur.execute("select capabilities from i_system;")
    row = cur.fetchone()
    if row is None:
        LOG.error("Failed to fetch i_system data")
        raise psycopg2.ProgrammingError("Failed to fetch i_system data")
    cap_obj = json.loads(row[0])
    region_config = cap_obj.get('region_config', None)
    if region_config:
        shared_services = cap_obj.get('shared_services',
                                      DEFAULT_SHARED_SERVICES)

    return shared_services
Ejemplo n.º 14
0
def _solve_conn_curs(conn_or_curs):
    """Return the connection and a DBAPI cursor from a connection or cursor.
    """
    if conn_or_curs is None:
        raise psycopg2.ProgrammingError("no connection or cursor provided")

    if hasattr(conn_or_curs, 'execute'):
        conn = conn_or_curs.connection
        curs = conn.cursor(cursor_factory=ext.cursor)

        # Django wrapper
        mod = sys.modules.get('django.db.backends.utils')
        if mod is not None:
            if isinstance(conn_or_curs, mod.CursorWrapper):
                conn_or_curs = conn_or_curs.cursor
    else:
        conn = conn_or_curs
        curs = conn.cursor(cursor_factory=ext.cursor)
        conn_or_curs = curs.connection

    return conn, curs, conn_or_curs
Ejemplo n.º 15
0
 def execute(self, sql, *params):
     if sql.startswith('blabla'):
         raise psycopg2.ProgrammingError()
     elif sql == 'CHECKPOINT':
         raise psycopg2.OperationalError()
     elif sql.startswith('RetryFailedError'):
         raise RetryFailedError('retry')
     elif sql.startswith('SELECT slot_name'):
         self.results = [('blabla', ), ('foobar', )]
     elif sql.startswith('SELECT CASE WHEN pg_is_in_recovery()'):
         self.results = [(2, )]
     elif sql == 'SELECT pg_is_in_recovery()':
         self.results = [(False, )]
     elif sql.startswith('WITH replication_info AS ('):
         replication_info = '[{"application_name":"walreceiver","client_addr":"1.2.3.4",' +\
                            '"state":"streaming","sync_state":"async","sync_priority":0}]'
         self.results = [('', True, '', '', '', '', False, replication_info)
                         ]
     elif sql.startswith('SELECT name, setting'):
         self.results = [
             ('wal_segment_size', '2048', '8kB', 'integer', 'internal'),
             ('search_path', 'public', None, 'string', 'user'),
             ('port', '5433', None, 'integer', 'postmaster'),
             ('listen_addresses', '*', None, 'string', 'postmaster'),
             ('autovacuum', 'on', None, 'bool', 'sighup'),
             ('unix_socket_directories', '/tmp', None, 'string',
              'postmaster')
         ]
     elif sql.startswith('IDENTIFY_SYSTEM'):
         self.results = [('1', 2, '0/402EEC0', '')]
     elif sql.startswith('TIMELINE_HISTORY '):
         self.results = [
             ('', b'x\t0/40159C0\tno recovery target specified\n\n' +
              b'1\t0/40159C0\tno recovery target specified\n\n' +
              b'2\t0/402DD98\tno recovery target specified\n\n' +
              b'3\t0/403DD98\tno recovery target specified\n')
         ]
     else:
         self.results = [(None, None, None, None, None, None, None, None,
                          None, None)]
Ejemplo n.º 16
0
def register_hstore_on_connection_creation(connection, sender, *args,
                                           **kwargs):
    oid = HstoreAdapter.get_oids(connection.connection)
    if oid is None or not oid[0]:
        if connection.connection.server_version < 90000:
            raise psycopg2.ProgrammingError("Database version not supported")
        elif connection.connection.server_version < 90100:
            pg_config = subprocess.Popen(["pg_config", "--sharedir"],
                                         stdout=subprocess.PIPE)
            share_dir = pg_config.communicate()[0].strip('\r\n ')
            hstore_sql = os.path.join(share_dir, 'contrib', 'hstore.sql')
            statements = re.compile(r";[ \t]*$", re.M)
            cursor = connection.cursor()
            with open(hstore_sql, 'U') as fp:
                for statement in statements.split(fp.read().decode(
                        settings.FILE_CHARSET)):
                    statement = re.sub(ur"--.*([\n\Z]|$)", "",
                                       statement).strip()
                    if statement:
                        cursor.execute(statement + u";")
        else:
            cursor = connection.cursor()
            cursor.execute("CREATE EXTENSION hstore;")
    register_hstore(connection.connection, globally=True)
Ejemplo n.º 17
0
 async def set_session(self, *args: Any, **kwargs: Any) -> None:
     raise psycopg2.ProgrammingError(
         "set_session cannot be used in asynchronous mode")
Ejemplo n.º 18
0
class DB(TM, dbi_db.DB):

    _p_oid = _p_changed = _registered = None

    def __init__(self, dsn, tilevel, typecasts, enc='utf-8'):
        self.dsn = dsn
        self.tilevel = tilevel
        self.typecasts = typecasts
        self.encoding = enc
        self.failures = 0
        self.calls = 0
        self.make_mappings()

    def getconn(self, create=True):
        conn = pool.getconn(self.dsn)
        conn.set_isolation_level(int(self.tilevel))
        conn.set_client_encoding(self.encoding)
        for tc in self.typecasts:
            register_type(tc, conn)
        return conn

    def putconn(self, close=False):
        try:
            conn = pool.getconn(self.dsn, False)
        except AttributeError:
            pass
        pool.putconn(self.dsn, conn, close)

    def getcursor(self):
        conn = self.getconn()
        return conn.cursor()

    def _finish(self, *ignored):
        try:
            conn = self.getconn(False)
            conn.commit()
            self.putconn()
        except AttributeError:
            pass

    def _abort(self, *ignored):
        try:
            conn = self.getconn(False)
            conn.rollback()
            self.putconn()
        except AttributeError:
            pass

    def open(self):
        # this will create a new pool for our DSN if not already existing,
        # then get and immediately release a connection
        self.getconn()
        self.putconn()

    def close(self):
        # FIXME: if this connection is closed we flush all the pool associated
        # with the current DSN; does this makes sense?
        pool.flushpool(self.dsn)

    def sortKey(self):
        return 1

    def make_mappings(self):
        """Generate the mappings used later by self.convert_description()."""
        self.type_mappings = {}
        for t, s in [(INTEGER, 'i'), (LONGINTEGER, 'i'), (NUMBER, 'n'),
                     (BOOLEAN, 'n'), (ROWID, 'i'), (DATETIME, 'd'),
                     (DATE, 'd'), (TIME, 'd')]:
            for v in t.values:
                self.type_mappings[v] = (t, s)

    def convert_description(self, desc, use_psycopg_types=False):
        """Convert DBAPI-2.0 description field to Zope format."""
        items = []
        for name, typ, width, ds, p, scale, null_ok in desc:
            m = self.type_mappings.get(typ, (STRING, 's'))
            items.append({
                'name': name,
                'type': use_psycopg_types and m[0] or m[1],
                'width': width,
                'precision': p,
                'scale': scale,
                'null': null_ok,
            })
        return items

    ## tables and rows ##

    def tables(self, rdb=0, _care=('TABLE', 'VIEW')):
        self._register()
        c = self.getcursor()
        c.execute("SELECT t.tablename AS NAME, 'TABLE' AS TYPE "
                  "  FROM pg_tables t WHERE tableowner <> 'postgres' "
                  "UNION SELECT v.viewname AS NAME, 'VIEW' AS TYPE "
                  "  FROM pg_views v WHERE viewowner <> 'postgres' "
                  "UNION SELECT t.tablename AS NAME, 'SYSTEM_TABLE\' AS TYPE "
                  "  FROM pg_tables t WHERE tableowner = 'postgres' "
                  "UNION SELECT v.viewname AS NAME, 'SYSTEM_TABLE' AS TYPE "
                  "FROM pg_views v WHERE viewowner = 'postgres'")
        res = []
        for name, typ in c.fetchall():
            if typ in _care:
                res.append({'TABLE_NAME': name, 'TABLE_TYPE': typ})
        self.putconn()
        return res

    def columns(self, table_name):
        self._register()
        c = self.getcursor()
        try:
            r = c.execute('SELECT * FROM "%s" WHERE 1=0' % table_name)
        except:
            return ()
        self.putconn()
        return self.convert_description(c.description, True)

    ## query execution ##

    def query(self, query_string, max_rows=None, query_data=None):
        self._register()
        self.calls = self.calls + 1

        desc = ()
        res = []
        nselects = 0

        c = self.getcursor()

        try:
            for qs in [x for x in query_string.split('\0') if x]:
                try:
                    if query_data:
                        c.execute(qs, query_data)
                    else:
                        c.execute(qs)
                except psycopg2.OperationalError, e:
                    try:
                        self.close()
                    except:
                        pass
                    self.open()
                    try:
                        if query_data:
                            c.execute(qs, query_data)
                        else:
                            c.execute(qs)
                    except (psycopg2.ProgrammingError,
                            psycopg2.IntegrityError), e:
                        if e.args[0].find("concurrent update") > -1:
                            raise ConflictError
                        raise e
                except (psycopg2.ProgrammingError, psycopg2.IntegrityError), e:
                    if e.args[0].find("concurrent update") > -1:
                        raise ConflictError
                    raise e
                if c.description is not None:
                    nselects += 1
                    if c.description != desc and nselects > 1:
                        raise psycopg2.ProgrammingError(
                            'multiple selects in single query not allowed')
                    if max_rows:
                        res = c.fetchmany(max_rows)
                    else:
                        res = c.fetchall()
                    desc = c.description
Ejemplo n.º 19
0
def register_hstore(conn_or_curs,
                    globally=False,
                    str=False,
                    oid=None,
                    array_oid=None):
    """Register adapter and typecaster for `!dict`\-\ |hstore| conversions.

    :param conn_or_curs: a connection or cursor: the typecaster will be
        registered only on this object unless *globally* is set to `!True`
    :param globally: register the adapter globally, not only on *conn_or_curs*
    :param unicode: if `!True`, keys and values returned from the database
        will be `!unicode` instead of `!str`. The option is not available on
        Python 3
    :param oid: the OID of the |hstore| type if known. If not, it will be
        queried on *conn_or_curs*.
    :param array_oid: the OID of the |hstore| array type if known. If not, it
        will be queried on *conn_or_curs*.

    The connection or cursor passed to the function will be used to query the
    database and look for the OID of the |hstore| type (which may be different
    across databases). If querying is not desirable (e.g. with
    :ref:`asynchronous connections <async-support>`) you may specify it in the
    *oid* parameter, which can be found using a query such as :sql:`SELECT
    'hstore'::regtype::oid`. Analogously you can obtain a value for *array_oid*
    using a query such as :sql:`SELECT 'hstore[]'::regtype::oid`.

    Note that, when passing a dictionary from Python to the database, both
    strings and unicode keys and values are supported. Dictionaries returned
    from the database have keys/values according to the *unicode* parameter.

    The |hstore| contrib module must be already installed in the database
    (executing the ``hstore.sql`` script in your ``contrib`` directory).
    Raise `~psycopg2.ProgrammingError` if the type is not found.
    """
    if oid is None:
        oid = HstoreAdapter.get_oids(conn_or_curs)
        if oid is None or not oid[0]:
            raise psycopg2.ProgrammingError(
                "hstore type not found in the database. "
                "please install it from your 'contrib/hstore.sql' file")
        else:
            array_oid = oid[1]
            oid = oid[0]

    if isinstance(oid, int):
        oid = (oid, )

    if array_oid is not None:
        if isinstance(array_oid, int):
            array_oid = (array_oid, )
        else:
            array_oid = tuple([x for x in array_oid if x])

    # create and register the typecaster
    if _sys.version_info[0] < 3 and str:
        cast = HstoreAdapter.parse_unicode
    else:
        cast = HstoreAdapter.parse

    HSTORE = _ext.new_type(oid, "HSTORE", cast)
    _ext.register_type(HSTORE, not globally and conn_or_curs or None)
    _ext.register_adapter(dict, HstoreAdapter)

    if array_oid:
        HSTOREARRAY = _ext.new_array_type(array_oid, "HSTOREARRAY", HSTORE)
        _ext.register_type(HSTOREARRAY, not globally and conn_or_curs or None)
    def start_replication(self,
                          slot_name=None,
                          slot_type=None,
                          start_lsn=0,
                          timeline=0,
                          options=None,
                          decode=False,
                          status_interval=10):
        """Start replication stream."""

        command = "START_REPLICATION "

        if slot_type is None:
            slot_type = self.connection.replication_type

        if slot_type == REPLICATION_LOGICAL:
            if slot_name:
                command += "SLOT %s " % quote_ident(slot_name, self)
            else:
                raise psycopg2.ProgrammingError(
                    "slot name is required for logical replication")

            command += "LOGICAL "

        elif slot_type == REPLICATION_PHYSICAL:
            if slot_name:
                command += "SLOT %s " % quote_ident(slot_name, self)
            # don't add "PHYSICAL", before 9.4 it was just START_REPLICATION XXX/XXX

        else:
            raise psycopg2.ProgrammingError(
                "unrecognized replication type: %s" % repr(slot_type))

        if type(start_lsn) is str:
            lsn = start_lsn.split('/')
            lsn = "%X/%08X" % (int(lsn[0], 16), int(lsn[1], 16))
        else:
            lsn = "%X/%08X" % (
                (start_lsn >> 32) & 0xFFFFFFFF, start_lsn & 0xFFFFFFFF)

        command += lsn

        if timeline != 0:
            if slot_type == REPLICATION_LOGICAL:
                raise psycopg2.ProgrammingError(
                    "cannot specify timeline for logical replication")

            command += " TIMELINE %d" % timeline

        if options:
            if slot_type == REPLICATION_PHYSICAL:
                raise psycopg2.ProgrammingError(
                    "cannot specify output plugin options for physical replication"
                )

            command += " ("
            for k, v in options.items():
                if not command.endswith('('):
                    command += ", "
                command += "%s %s" % (quote_ident(k, self), _A(str(v)))
            command += ")"

        self.start_replication_expert(command,
                                      decode=decode,
                                      status_interval=status_interval)
Ejemplo n.º 21
0
 async def tpc_prepare(self) -> None:
     raise psycopg2.ProgrammingError(
         "tpc_prepare cannot be used in asynchronous mode")
Ejemplo n.º 22
0
 async def tpc_begin(self, *args: Any, **kwargs: Any) -> None:
     raise psycopg2.ProgrammingError(
         "tpc_begin cannot be used in asynchronous mode")
Ejemplo n.º 23
0
 async def rollback(self) -> None:
     raise psycopg2.ProgrammingError(
         "rollback cannot be used in asynchronous mode")
Ejemplo n.º 24
0
 async def commit(self) -> None:
     raise psycopg2.ProgrammingError(
         "commit cannot be used in asynchronous mode")
Ejemplo n.º 25
0
 async def copy_expert(self, *args: Any, **kwargs: Any) -> None:
     raise psycopg2.ProgrammingError(
         "copy_expert cannot be used in asynchronous mode")
Ejemplo n.º 26
0
 async def executemany(self, *args: Any, **kwargs: Any) -> None:
     # Not supported
     raise psycopg2.ProgrammingError(
         "executemany cannot be used in asynchronous mode")
Ejemplo n.º 27
0
 def _check_release_rollback(self) -> None:
     self._check_commit_rollback()
     if self._unique_id is None:
         raise psycopg2.ProgrammingError("You do not start savepoint")
Ejemplo n.º 28
0
 def _check_commit_rollback(self) -> None:
     if not self._is_begin:
         raise psycopg2.ProgrammingError("You are trying to commit "
                                         "the transaction does not open")
Ejemplo n.º 29
0
 async def lobject(self, *args: Any, **kwargs: Any) -> None:
     raise psycopg2.ProgrammingError(
         "lobject cannot be used in asynchronous mode")
Ejemplo n.º 30
0
 def set_session(self, *, isolation_level=None, readonly=None,
                 deferrable=None, autocommit=None):
     raise psycopg2.ProgrammingError(
         "set_session cannot be used in asynchronous mode")