本文整理汇总了Python中sqlalchemy.exc.ProgrammingError方法的典型用法代码示例。如果您正苦于以下问题:Python exc.ProgrammingError方法的具体用法?Python exc.ProgrammingError怎么用?Python exc.ProgrammingError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.exc
的用法示例。
在下文中一共展示了exc.ProgrammingError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _fetch_sql
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def _fetch_sql(self, path):
"""
fetch the information and pricetable from sql, not recommend to use manually,
just set the fetch label to be true when init the object
:param path: engine object from sqlalchemy
"""
try:
content = pd.read_sql("xa" + self.code, path)
pricetable = content.iloc[1:]
commentl = [float(com) for com in pricetable.comment]
self.price = pricetable[["date", "netvalue", "totvalue"]]
self.price["comment"] = commentl
self.name = json.loads(content.iloc[0].comment)["name"]
except exc.ProgrammingError as e:
# print('no saved copy of %s' % self.code)
raise e
示例2: fetch_backend
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def fetch_backend(key):
prefix = ioconf.get("prefix", "")
key = prefix + key
backend = ioconf.get("backend")
path = ioconf.get("path")
if backend == "csv":
key = key + ".csv"
try:
if backend == "csv":
df0 = pd.read_csv(os.path.join(path, key))
elif backend == "sql":
df0 = pd.read_sql(key, path)
else:
raise ValueError("no %s option for backend" % backend)
return df0
except (FileNotFoundError, exc.ProgrammingError, KeyError):
return None
示例3: remove_snapshot
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def remove_snapshot(self, snapshot):
for table in snapshot.tables:
try:
self.operations.remove_database(
table.get_table_name('master')
)
except ProgrammingError:
pass
try:
self.operations.remove_database(
table.get_table_name('slave')
)
except ProgrammingError:
pass
self.db.session.delete(table)
self.db.session.delete(snapshot)
self.db.session.commit()
示例4: restore
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def restore(self, snapshot):
for table in snapshot.tables:
click.echo("Restoring database %s" % table.table_name)
if not self.operations.database_exists(
table.get_table_name('slave')
):
click.echo(
"Database %s does not exist."
% table.get_table_name('slave')
)
sys.exit(1)
try:
self.operations.remove_database(table.table_name)
except ProgrammingError:
logger.warn('Database %s does not exist.' % table.table_name)
self.operations.rename_database(
table.get_table_name('slave'),
table.table_name
)
snapshot.worker_pid = 1
self.db.session.commit()
self.start_background_slave_copy(snapshot)
示例5: upgrade
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def upgrade():
try:
op.create_table('eventhandlercondition',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('eventhandler_id', sa.Integer(), nullable=True),
sa.Column('Key', sa.Unicode(length=255), nullable=False),
sa.Column('Value', sa.Unicode(length=2000), nullable=True),
sa.Column('comparator', sa.Unicode(length=255), nullable=True),
sa.ForeignKeyConstraint(['eventhandler_id'], ['eventhandler.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('eventhandler_id', 'Key', name='ehcix_1')
)
except (OperationalError, ProgrammingError, InternalError) as exx:
if "duplicate column name" in str(exx.orig).lower():
print("Good. Table eventhandlercondition already exists.")
else:
print("Table already exists")
print(exx)
except Exception as exx:
print("Could not add Table eventhandlercondition")
print (exx)
示例6: upgrade
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def upgrade():
try:
op.create_table('passwordreset',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('recoverycode', sa.Unicode(length=255), nullable=False),
sa.Column('username', sa.Unicode(length=64), nullable=False),
sa.Column('realm', sa.Unicode(length=64), nullable=False),
sa.Column('resolver', sa.Unicode(length=64), nullable=True),
sa.Column('email', sa.Unicode(length=255), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('expiration', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_passwordreset_realm'), 'passwordreset',
['realm'], unique=False)
op.create_index(op.f('ix_passwordreset_username'), 'passwordreset',
['username'], unique=False)
except (OperationalError, ProgrammingError, InternalError) as exx:
if "duplicate column name" in str(exx.orig).lower():
print("Good. Table passwordreset already exists.")
else:
print(exx)
except Exception as exx:
print ("Could not add table 'passwordreset'")
print (exx)
示例7: upgrade
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def upgrade():
try:
op.add_column('token', sa.Column('revoked', sa.Boolean(),
default=False))
except (OperationalError, ProgrammingError, InternalError) as exx:
if "duplicate column name" in str(exx.orig).lower():
print("Good. Column revoked already exists.")
else:
print(exx)
except Exception as exx:
print ("Could not add column 'revoked' to table 'token'")
print (exx)
try:
op.add_column('token', sa.Column('locked', sa.Boolean(),
default=False))
except (OperationalError, ProgrammingError) as exx:
if "duplicate column name" in str(exx.orig).lower():
print("Good. Column locked already exists.")
else:
print(exx)
except Exception as exx:
print ("Could not add column 'locked' to table 'token'")
print (exx)
示例8: upgrade
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def upgrade():
try:
op.create_table('radiusserver',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('identifier', sa.Unicode(length=255), nullable=False),
sa.Column('server', sa.Unicode(length=255), nullable=False),
sa.Column('port', sa.Integer(), nullable=True),
sa.Column('secret', sa.Unicode(length=255), nullable=True),
sa.Column('description', sa.Unicode(length=2000), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('identifier')
)
except (OperationalError, ProgrammingError, InternalError) as exx:
if "duplicate column name" in str(exx.orig).lower():
print("Good. Table 'radiusserver' already exists.")
else:
print(exx)
except Exception as exx:
print ("Could not add table 'radiusserver'")
print (exx)
示例9: test_errors_while_doing_db
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def test_errors_while_doing_db(clean_before_and_after):
with get_sa_session() as session:
try:
PullRequestModel.get_or_create(
pr_id="nope",
namespace="",
repo_name=False,
project_url="https://github.com/the-namespace/the-repo",
)
except ProgrammingError:
pass
assert len(session.query(PullRequestModel).all()) == 0
PullRequestModel.get_or_create(
pr_id=111,
namespace="asd",
repo_name="qwe",
project_url="https://github.com/asd/qwe",
)
assert len(session.query(PullRequestModel).all()) == 1
# return all builds in table
示例10: test_engine_execute_errors
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def test_engine_execute_errors(self):
# ensures that SQL errors are reported
with pytest.raises(ProgrammingError):
with self.connection() as conn:
conn.execute("SELECT * FROM a_wrong_table").fetchall()
spans = self.memory_exporter.get_finished_spans()
self.assertEqual(len(spans), 1)
span = spans[0]
# span fields
self.assertEqual(span.name, "{}.query".format(self.VENDOR))
self.assertEqual(span.attributes.get("service"), self.SERVICE)
self.assertEqual(
span.attributes.get(_STMT), "SELECT * FROM a_wrong_table"
)
self.assertEqual(span.attributes.get(_DB), self.SQL_DB)
self.assertIsNone(span.attributes.get(_ROWS))
self.check_meta(span)
self.assertTrue(span.end_time - span.start_time > 0)
# check the error
self.assertIs(
span.status.canonical_code,
trace.status.StatusCanonicalCode.UNKNOWN,
)
self.assertIn("a_wrong_table", span.status.description)
示例11: test_bad_sql_logged_and_raised
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def test_bad_sql_logged_and_raised(caplog):
"""SQL failures during a store should be logged, and raised."""
class BadQuery(Query):
def _make_query(self):
return "THIS IS NOT VALID SQL"
@property
def column_names(self):
return []
with pytest.raises(ProgrammingError):
fut = BadQuery().store()
exec = fut.exception()
raise exec
assert "Error executing SQL" in caplog.messages[-1]
示例12: execute
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def execute(cls, engine, query):
try:
conn = engine.connect()
conn.execute(query)
except (OperationalError, ProgrammingError, InternalError) as e:
code = e.orig.args[0]
if isinstance(e, ProgrammingError) and code == 1007:
# Query for creating database failed because it exists
raise DatabaseExists(error=e.orig.args[1], code=code)
else:
raise DatabaseError(error=e.orig.args[1], code=code)
示例13: list_records
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def list_records(self):
try:
query = self.datastore.session.query(IntegerSequencedNoIDRecord)
return list(query)
except (OperationalError, ProgrammingError) as e:
# OperationalError from sqlite, ProgrammingError from psycopg2.
self.datastore.session.rollback()
raise DatastoreTableError(e)
finally:
self.datastore.session.close()
示例14: create_record
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def create_record(self):
try:
record = IntegerSequencedNoIDRecord(
sequence_id=uuid4(), position=0, topic="topic", state=b"{}"
)
self.datastore.session.add(record)
self.datastore.session.commit()
except (OperationalError, ProgrammingError) as e:
self.datastore.session.rollback()
raise DatastoreTableError(e)
return record
示例15: run_sql
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import ProgrammingError [as 别名]
def run_sql(db, q):
q = q.strip()
if not q:
return
start = time.time()
try:
con = db.engine.connect()
trans = con.begin()
con.execute(q)
trans.commit()
except exc.ProgrammingError as e:
pass
finally:
con.close()