当前位置: 首页>>代码示例>>Python>>正文


Python psycopg2.ProgrammingError方法代码示例

本文整理汇总了Python中psycopg2.ProgrammingError方法的典型用法代码示例。如果您正苦于以下问题:Python psycopg2.ProgrammingError方法的具体用法?Python psycopg2.ProgrammingError怎么用?Python psycopg2.ProgrammingError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在psycopg2的用法示例。


在下文中一共展示了psycopg2.ProgrammingError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: register_json_typecasters

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def register_json_typecasters(conn, loads_fn):
    """Set the function for converting JSON data for a connection.

    Use the supplied function to decode JSON data returned from the database
    via the given connection. The function should accept a single argument of
    the data as a string encoded in the database's character encoding.
    psycopg2's default handler for JSON data is json.loads.
    http://initd.org/psycopg/docs/extras.html#json-adaptation

    This function attempts to register the typecaster for both JSON and JSONB
    types.

    Returns a set that is a subset of {'json', 'jsonb'} indicating which types
    (if any) were successfully registered.
    """
    available = set()

    for name in ["json", "jsonb"]:
        try:
            psycopg2.extras.register_json(conn, loads=loads_fn, name=name)
            available.add(name)
        except psycopg2.ProgrammingError:
            pass

    return available 
开发者ID:dbcli,项目名称:pgcli,代码行数:27,代码来源:pgexecute.py

示例2: view_definition

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def view_definition(self, spec):
        """Returns the SQL defining views described by `spec`"""

        template = "CREATE OR REPLACE {6} VIEW {0}.{1} AS \n{3}"
        # 2: relkind, v or m (materialized)
        # 4: reloptions, null
        # 5: checkoption: local or cascaded
        with self.conn.cursor() as cur:
            sql = self.view_definition_query
            _logger.debug("View Definition Query. sql: %r\nspec: %r", sql, spec)
            try:
                cur.execute(sql, (spec,))
            except psycopg2.ProgrammingError:
                raise RuntimeError("View {} does not exist.".format(spec))
            result = cur.fetchone()
            view_type = "MATERIALIZED" if result[2] == "m" else ""
            return template.format(*result + (view_type,)) 
开发者ID:dbcli,项目名称:pgcli,代码行数:19,代码来源:pgexecute.py

示例3: pg_connection

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def pg_connection(self):
        """
        Return a connection to the db.
        """
        dbname = self.server_opts['db_name']
        user = self.server_opts['db_user']
        host = self.server_opts['db_host']
        password = self.server_opts['db_password']
        message = ''
        try:
            pg_conn = connect("dbname='%s' user='%s' host='%s' password='%s'"\
                % (dbname, user, host, password))
        except OperationalError:
            return None, 'Error : Server cannot connect to database'
        try:
            pg_conn.cursor().execute("""SELECT * FROM USERS""")
        except ProgrammingError:
            return None, 'Error : Server cannot connect to table in database'
        return pg_conn, message 
开发者ID:nbeguier,项目名称:cassh,代码行数:21,代码来源:tools.py

示例4: register_hstore_handler

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def register_hstore_handler(connection, **kwargs):
    if connection.vendor != 'postgresql':
        return

    try:
        if six.PY2:
            register_hstore(connection.connection, globally=True, unicode=True)
        else:
            register_hstore(connection.connection, globally=True)
    except ProgrammingError:
        # Hstore is not available on the database.
        #
        # If someone tries to create an hstore field it will error there.
        # This is necessary as someone may be using PSQL without extensions
        # installed but be using other features of contrib.postgres.
        #
        # This is also needed in order to create the connection in order to
        # install the hstore extension.
        pass 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:signals.py

示例5: test_delete_slot

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def test_delete_slot(slot):
    with patch.object(psycopg2.ProgrammingError, 'pgcode',
                      new_callable=PropertyMock,
                      return_value=psycopg2.errorcodes.UNDEFINED_OBJECT):
        pe = psycopg2.ProgrammingError()
        slot._repl_cursor.drop_replication_slot = Mock(side_effect=pe)
        slot.delete_slot()
    slot._repl_cursor.drop_replication_slot.assert_called_with('pg2kinesis')

    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.delete_slot()
            slot._repl_cursor.drop_replication_slot.assert_called_with('pg2kinesis')

            assert e_info.value.pgcode == -1

    slot._repl_cursor.create_replication_slot = Mock(side_effect=Exception)
    with pytest.raises(Exception):
        slot.delete_slot()
        slot._repl_cursor.drop_replication_slot.assert_called_with('pg2kinesis') 
开发者ID:surbas,项目名称:pg2kinesis,代码行数:26,代码来源:test_slot.py

示例6: test_execute_failing_postgres_based_job

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def test_execute_failing_postgres_based_job(self):
        config_manager = self._setup_config_manager(
            'crontabber.tests.test_crontabber.BrokenPostgresSampleJob|1d'
        )

        with config_manager.context() as config:
            tab = app.CronTabber(config)
            tab.run_all()
            infos = [x[0][0] for x in config.logger.info.call_args_list]
            infos = [x for x in infos if x.startswith('Ran ')]
            ok_('Ran PostgresSampleJob' not in infos)

            information = tab.job_state_database['broken-pg-job']
            ok_(information['last_error'])
            ok_(
                'ProgrammingError' in
                information['last_error']['type']
            ) 
开发者ID:mozilla,项目名称:crontabber,代码行数:20,代码来源:test_crontabber.py

示例7: test_execute_failing_postgres_transaction_managed_job

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def test_execute_failing_postgres_transaction_managed_job(self):
        config_manager = self._setup_config_manager(
            'crontabber.tests.test_crontabber.'
            'BrokenPostgresTransactionManagedSampleJob|1d'
        )

        with config_manager.context() as config:
            tab = app.CronTabber(config)
            tab.run_all()
            infos = [x[0][0] for x in config.logger.info.call_args_list]
            infos = [x for x in infos if x.startswith('Ran ')]
            ok_('Ran PostgresTransactionSampleJob' not in infos)

            information = \
                tab.job_state_database['broken-transaction-managed-pg-job']
            ok_(information['last_error'])
            ok_(
                'ProgrammingError' in
                information['last_error']['type']
            ) 
开发者ID:mozilla,项目名称:crontabber,代码行数:22,代码来源:test_crontabber.py

示例8: is_operational_exception

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def is_operational_exception(self, msg):
        """return True if a conditional exception is actually an operational
        error. Return False if it's a genuine error that should probably be
        raised and propagate up.

        Some conditional exceptions might be actually be some form of
        operational exception "labelled" wrong by the psycopg2 code error
        handler.
        """
        if msg.pgerror in ('SSL SYSCALL error: EOF detected',):
            # Ideally we'd like to check against msg.pgcode values
            # but certain odd ProgrammingError exceptions don't have
            # pgcodes so we have to rely on reading the pgerror :(
            return True

        # at the of writing, the list of exceptions is short but this would be
        # where you add more as you discover more odd cases of psycopg2

        return False

    #-------------------------------------------------------------------------- 
开发者ID:mozilla,项目名称:crontabber,代码行数:23,代码来源:connection_factory.py

示例9: _get_last_dominant_index

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def _get_last_dominant_index(self, _product, _tradingday):
        try:
            self.dominant_index_cur.execute(
                "SELECT closeprice FROM {} WHERE tradingday<'{}' "
                "ORDER BY tradingday DESC LIMIT 1".format(
                    _product, _tradingday
                )
            )
            for d in self.dominant_index_cur:
                return d[0]
        except psycopg2.ProgrammingError as e:
            logging.warning(e)
            assert e.pgcode == '42P01'
            self.dominant_index_con.rollback()
            self._create_dominant_index_table(_product)
            return None 
开发者ID:ppaanngggg,项目名称:ParadoxTrading,代码行数:18,代码来源:StoreDailyData.py

示例10: connect

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def connect(self):
        """
        Connect to the PostgreSQL server. It reuses an existing connection.
        """
        if self._check_connection():
            return self._conn

        self._conn = super(PostgreSQLConnection, self).connect()
        server_version = self._conn.server_version
        use_app_name = 'application_name' in self.conn_parameters
        if server_version >= 90000 and not use_app_name:
            try:
                cur = self._conn.cursor()
                # Do not use parameter substitution with SET
                cur.execute('SET application_name TO %s' %
                            self.application_name)
                cur.close()
            # If psycopg2 fails to set the application name,
            # raise the appropriate exception
            except psycopg2.ProgrammingError as e:
                raise PostgresAppNameError(force_str(e).strip())
        return self._conn 
开发者ID:2ndquadrant-it,项目名称:barman,代码行数:24,代码来源:postgres.py

示例11: test_server_txt_version

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def test_server_txt_version(self, conn_mock):
        """
        simple test for the server_txt_version property
        """
        # Build a server
        server = build_real_server()
        cursor_mock = conn_mock.return_value.cursor.return_value

        # Connection error
        conn_mock.side_effect = PostgresConnectionError
        assert server.postgres.server_txt_version is None

        # Communication error
        conn_mock.side_effect = None
        cursor_mock.execute.side_effect = psycopg2.ProgrammingError
        assert server.postgres.server_txt_version is None

        # Good connection
        cursor_mock.execute.side_effect = None
        cursor_mock.fetchone.return_value = (
            "PostgreSQL 9.4.5 on x86_64-apple-darwin15.0.0, compiled by "
            "Apple LLVM version 7.0.0 (clang-700.1.76), 64-bit",)

        assert server.postgres.server_txt_version == '9.4.5'
        cursor_mock.execute.assert_called_with("SELECT version()") 
开发者ID:2ndquadrant-it,项目名称:barman,代码行数:27,代码来源:test_postgres.py

示例12: __get_previously_aggregated__

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def __get_previously_aggregated__(self,workflow_id):
        """
        get the list of all previously aggregated subjects - so we when upserting new results
        we know which subjects we are updating and which we are inserting (i.e. no previously existing results)
        :param workflow_id:
        :return:
        """

        try:
            postgres_cursor = self.postgres_writeable_session.cursor()
            postgres_cursor.execute("select subject_id from aggregations where workflow_id = " + str(workflow_id))
            previously_aggregated = [i[0] for i in postgres_cursor.fetchall()]
        except psycopg2.ProgrammingError as e:
            # again, not sure why there would be an error - but in this case just to be certain
            # assume that there are no pre-existing aggregation results
            print(e)
            self.postgres_session.rollback()
            previously_aggregated = []

        return previously_aggregated 
开发者ID:zooniverse,项目名称:aggregation,代码行数:22,代码来源:aggregation_api.py

示例13: write_files

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def write_files(self, base_path, models, **kwargs):
        for model in models:
            try:
                self.cur.execute("SELECT pk FROM %s", camel_to_snake(model.name))
            except psycopg2.ProgrammingError as e:
                self._report_query_error(e)

            pks = []

            row = self.cur.fetchone()
            while row:
                pks.append(row[0])

                row = self.cur.fetchone()

            for pk in pks:
                path = os.path.join(base_path, "%s.yaml" % pk)

                if not self.override and os.path.isfile(path):
                    continue
                with open(path, "w") as f:
                    yaml.dump(self.to_dict(model, pk), f, default_flow_style=False) 
开发者ID:thanethomson,项目名称:statik,代码行数:24,代码来源:external_database.py

示例14: __cleanup_schema

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def __cleanup_schema(self):
        with psycopg2.connect(os.environ['GREASE_TEST_DSN_ORIGINAL']) as conn:
            conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
            with conn.cursor() as cursor:
                cursor.execute("""
                  SELECT  
                    pg_terminate_backend(pid) 
                    FROM pg_stat_activity 
                    WHERE datname='test_data'
                """)
                try:
                    cursor.execute("""
                        DROP DATABASE test_data;
                    """)
                except psycopg2.ProgrammingError as e:
                    print("Schema Does Not Exist: {0}".format(e.pgerror))
        os.environ['GREASE_TEST_DSN'] = os.environ['GREASE_TEST_DSN_ORIGINAL'] 
开发者ID:target,项目名称:grease,代码行数:19,代码来源:test_sql_parser.py

示例15: __init__

# 需要导入模块: import psycopg2 [as 别名]
# 或者: from psycopg2 import ProgrammingError [as 别名]
def __init__(self, tableName = None, load_database = True, *args, **kwargs):


		# Create the table twice, because horrible.
		if tableName:
			self.tableName = self.tableName+"_"+tableName
		super().__init__(*args, **kwargs)

		try:
			with self.transaction() as cur:
				cur.execute("BEGIN;")
				self.log.info("Clearing table")
				cur.execute('DELETE FROM {table};'.format(table=self.tableName))
				self.log.info("cleared")
				cur.execute("COMMIT;")

		except psycopg2.Error:
			traceback.print_exc()


		try:
			cur.execute('''CREATE        INDEX {table}_phash_bk_tree_index    ON {table} USING spgist ( phash bktree_ops );'''.format(table=self.tableName))
		except psycopg2.ProgrammingError:
			traceback.print_exc()
			print("Failed to create index?") 
开发者ID:fake-name,项目名称:IntraArchiveDeduplicator,代码行数:27,代码来源:baseDbBkTree.py


注:本文中的psycopg2.ProgrammingError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。