Sqlalchemy database error

This section lists descriptions and background for common error messages and warnings raised or emitted by SQLAlchemy.

This section lists descriptions and background for common error messages
and warnings raised or emitted by SQLAlchemy.

SQLAlchemy normally raises errors within the context of a SQLAlchemy-specific
exception class. For details on these classes, see
Core Exceptions and ORM Exceptions.

SQLAlchemy errors can roughly be separated into two categories, the
programming-time error and the runtime error. Programming-time
errors are raised as a result of functions or methods being called with
incorrect arguments, or from other configuration-oriented methods such as
mapper configurations that can’t be resolved. The programming-time error is
typically immediate and deterministic. The runtime error on the other hand
represents a failure that occurs as a program runs in response to some
condition that occurs arbitrarily, such as database connections being
exhausted or some data-related issue occurring. Runtime errors are more
likely to be seen in the logs of a running application as the program
encounters these states in response to load and data being encountered.

Since runtime errors are not as easy to reproduce and often occur in response
to some arbitrary condition as the program runs, they are more difficult to
debug and also affect programs that have already been put into production.

Within this section, the goal is to try to provide background on some of the
most common runtime errors as well as programming time errors.

Connections and Transactions¶

QueuePool limit of size <x> overflow <y> reached, connection timed out, timeout <z>¶

This is possibly the most common runtime error experienced, as it directly
involves the work load of the application surpassing a configured limit, one
which typically applies to nearly all SQLAlchemy applications.

The following points summarize what this error means, beginning with the
most fundamental points that most SQLAlchemy users should already be
familiar with.

  • The SQLAlchemy Engine object uses a pool of connections by default — What
    this means is that when one makes use of a SQL database connection resource
    of an Engine object, and then releases that resource,
    the database connection itself remains connected to the database and
    is returned to an internal queue where it can be used again. Even though
    the code may appear to be ending its conversation with the database, in many
    cases the application will still maintain a fixed number of database connections
    that persist until the application ends or the pool is explicitly disposed.

  • Because of the pool, when an application makes use of a SQL database
    connection, most typically from either making use of Engine.connect()
    or when making queries using an ORM Session, this activity
    does not necessarily establish a new connection to the database at the
    moment the connection object is acquired; it instead consults the
    connection pool for a connection, which will often retrieve an existing
    connection from the pool to be re-used. If no connections are available,
    the pool will create a new database connection, but only if the
    pool has not surpassed a configured capacity.

  • The default pool used in most cases is called QueuePool. When
    you ask this pool to give you a connection and none are available, it
    will create a new connection if the total number of connections in play
    are less than a configured value
    . This value is equal to the
    pool size plus the max overflow. That means if you have configured
    your engine as:

    engine = create_engine("mysql://u:p@host/db", pool_size=10, max_overflow=20)

    The above Engine will allow at most 30 connections to be in
    play at any time, not including connections that were detached from the
    engine or invalidated. If a request for a new connection arrives and
    30 connections are already in use by other parts of the application,
    the connection pool will block for a fixed period of time,
    before timing out and raising this error message.

    In order to allow for a higher number of connections be in use at once,
    the pool can be adjusted using the
    create_engine.pool_size and create_engine.max_overflow
    parameters as passed to the create_engine() function. The timeout
    to wait for a connection to be available is configured using the
    create_engine.pool_timeout parameter.

  • The pool can be configured to have unlimited overflow by setting
    create_engine.max_overflow to the value “-1”. With this setting,
    the pool will still maintain a fixed pool of connections, however it will
    never block upon a new connection being requested; it will instead unconditionally
    make a new connection if none are available.

    However, when running in this way, if the application has an issue where it
    is using up all available connectivity resources, it will eventually hit the
    configured limit of available connections on the database itself, which will
    again return an error. More seriously, when the application exhausts the
    database of connections, it usually will have caused a great
    amount of resources to be used up before failing, and can also interfere
    with other applications and database status mechanisms that rely upon being
    able to connect to the database.

    Given the above, the connection pool can be looked at as a safety valve
    for connection use
    , providing a critical layer of protection against
    a rogue application causing the entire database to become unavailable
    to all other applications. When receiving this error message, it is vastly
    preferable to repair the issue using up too many connections and/or
    configure the limits appropriately, rather than allowing for unlimited
    overflow which does not actually solve the underlying issue.

What causes an application to use up all the connections that it has available?

  • The application is fielding too many concurrent requests to do work based
    on the configured value for the pool
    — This is the most straightforward
    cause. If you have
    an application that runs in a thread pool that allows for 30 concurrent
    threads, with one connection in use per thread, if your pool is not configured
    to allow at least 30 connections checked out at once, you will get this
    error once your application receives enough concurrent requests. Solution
    is to raise the limits on the pool or lower the number of concurrent threads.

  • The application is not returning connections to the pool — This is the
    next most common reason, which is that the application is making use of the
    connection pool, but the program is failing to release these
    connections and is instead leaving them open. The connection pool as well
    as the ORM Session do have logic such that when the session and/or
    connection object is garbage collected, it results in the underlying
    connection resources being released, however this behavior cannot be relied
    upon to release resources in a timely manner.

    A common reason this can occur is that the application uses ORM sessions and
    does not call Session.close() upon them one the work involving that
    session is complete. Solution is to make sure ORM sessions if using the ORM,
    or engine-bound Connection objects if using Core, are explicitly
    closed at the end of the work being done, either via the appropriate
    .close() method, or by using one of the available context managers (e.g.
    “with:” statement) to properly release the resource.

  • The application is attempting to run long-running transactions — A
    database transaction is a very expensive resource, and should never be
    left idle waiting for some event to occur
    . If an application is waiting
    for a user to push a button, or a result to come off of a long running job
    queue, or is holding a persistent connection open to a browser, don’t
    keep a database transaction open for the whole time
    . As the application
    needs to work with the database and interact with an event, open a short-lived
    transaction at that point and then close it.

  • The application is deadlocking — Also a common cause of this error and
    more difficult to grasp, if an application is not able to complete its use
    of a connection either due to an application-side or database-side deadlock,
    the application can use up all the available connections which then leads to
    additional requests receiving this error. Reasons for deadlocks include:

    • Using an implicit async system such as gevent or eventlet without
      properly monkeypatching all socket libraries and drivers, or which
      has bugs in not fully covering for all monkeypatched driver methods,
      or less commonly when the async system is being used against CPU-bound
      workloads and greenlets making use of database resources are simply waiting
      too long to attend to them. Neither implicit nor explicit async
      programming frameworks are typically
      necessary or appropriate for the vast majority of relational database
      operations; if an application must use an async system for some area
      of functionality, it’s best that database-oriented business methods
      run within traditional threads that pass messages to the async part
      of the application.

    • A database side deadlock, e.g. rows are mutually deadlocked

    • Threading errors, such as mutexes in a mutual deadlock, or calling
      upon an already locked mutex in the same thread

Keep in mind an alternative to using pooling is to turn off pooling entirely.
See the section Switching Pool Implementations for background on this. However, note
that when this error message is occurring, it is always due to a bigger
problem in the application itself; the pool just helps to reveal the problem
sooner.

Can’t reconnect until invalid transaction is rolled back¶

This error condition refers to the case where a Connection was
invalidated, either due to a database disconnect detection or due to an
explicit call to Connection.invalidate(), but there is still a
transaction present that was initiated by the Connection.begin()
method. When a connection is invalidated, any Transaction
that was in progress is now in an invalid state, and must be explicitly rolled
back in order to remove it from the Connection.

DBAPI Errors¶

The Python database API, or DBAPI, is a specification for database drivers
which can be located at Pep-249.
This API specifies a set of exception classes that accommodate the full range
of failure modes of the database.

SQLAlchemy does not generate these exceptions directly. Instead, they are
intercepted from the database driver and wrapped by the SQLAlchemy-provided
exception DBAPIError, however the messaging within the exception is
generated by the driver, not SQLAlchemy.

InterfaceError¶

Exception raised for errors that are related to the database interface rather
than the database itself.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

The InterfaceError is sometimes raised by drivers in the context
of the database connection being dropped, or not being able to connect
to the database. For tips on how to deal with this, see the section
Dealing with Disconnects.

DatabaseError¶

Exception raised for errors that are related to the database itself, and not
the interface or data being passed.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

DataError¶

Exception raised for errors that are due to problems with the processed data
like division by zero, numeric value out of range, etc.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

OperationalError¶

Exception raised for errors that are related to the database’s operation and
not necessarily under the control of the programmer, e.g. an unexpected
disconnect occurs, the data source name is not found, a transaction could not
be processed, a memory allocation error occurred during processing, etc.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

The OperationalError is the most common (but not the only) error class used
by drivers in the context of the database connection being dropped, or not
being able to connect to the database. For tips on how to deal with this, see
the section Dealing with Disconnects.

IntegrityError¶

Exception raised when the relational integrity of the database is affected,
e.g. a foreign key check fails.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

InternalError¶

Exception raised when the database encounters an internal error, e.g. the
cursor is not valid anymore, the transaction is out of sync, etc.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

The InternalError is sometimes raised by drivers in the context
of the database connection being dropped, or not being able to connect
to the database. For tips on how to deal with this, see the section
Dealing with Disconnects.

ProgrammingError¶

Exception raised for programming errors, e.g. table not found or already
exists, syntax error in the SQL statement, wrong number of parameters
specified, etc.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

The ProgrammingError is sometimes raised by drivers in the context
of the database connection being dropped, or not being able to connect
to the database. For tips on how to deal with this, see the section
Dealing with Disconnects.

NotSupportedError¶

Exception raised in case a method or database API was used which is not
supported by the database, e.g. requesting a .rollback() on a connection that
does not support transaction or has transactions turned off.

This error is a DBAPI Error and originates from
the database driver (DBAPI), not SQLAlchemy itself.

SQL Expression Language¶

Object will not produce a cache key, Performance Implications¶

SQLAlchemy as of version 1.4 includes a
SQL compilation caching facility which will allow
Core and ORM SQL constructs to cache their stringified form, along with other
structural information used to fetch results from the statement, allowing the
relatively expensive string compilation process to be skipped when another
structurally equivalent construct is next used. This system
relies upon functionality that is implemented for all SQL constructs, including
objects such as Column,
select(), and TypeEngine objects, to produce a
cache key which fully represents their state to the degree that it affects
the SQL compilation process.

If the warnings in question refer to widely used objects such as
Column objects, and are shown to be affecting the majority of
SQL constructs being emitted (using the estimation techniques described at
Estimating Cache Performance Using Logging) such that caching is generally not enabled for an
application, this will negatively impact performance and can in some cases
effectively produce a performance degradation compared to prior SQLAlchemy
versions. The FAQ at Why is my application slow after upgrading to 1.4 and/or 2.x? covers this in additional detail.

Caching disables itself if there’s any doubt¶

Caching relies on being able to generate a cache key that accurately represents
the complete structure of a statement in a consistent fashion. If a particular
SQL construct (or type) does not have the appropriate directives in place which
allow it to generate a proper cache key, then caching cannot be safely enabled:

  • The cache key must represent the complete structure: If the usage of two
    separate instances of that construct may result in different SQL being
    rendered, caching the SQL against the first instance of the element using a
    cache key that does not capture the distinct differences between the first and
    second elements will result in incorrect SQL being cached and rendered for the
    second instance.

  • The cache key must be consistent: If a construct represents state that
    changes every time, such as a literal value, producing unique SQL for every
    instance of it, this construct is also not safe to cache, as repeated use of
    the construct will quickly fill up the statement cache with unique SQL strings
    that will likely not be used again, defeating the purpose of the cache.

For the above two reasons, SQLAlchemy’s caching system is extremely
conservative
about deciding to cache the SQL corresponding to an object.

Assertion attributes for caching¶

The warning is emitted based on the criteria below. For further detail on
each, see the section Why is my application slow after upgrading to 1.4 and/or 2.x?.

  • The Dialect itself (i.e. the module that is specified by the
    first part of the URL we pass to create_engine(), like
    postgresql+psycopg2://), must indicate it has been reviewed and tested
    to support caching correctly, which is indicated by the
    Dialect.supports_statement_cache attribute being set to True.
    When using third party dialects, consult with the maintainers of the dialect
    so that they may follow the steps to ensure caching may be enabled in their dialect and publish a new release.

  • Third party or user defined types that inherit from either
    TypeDecorator or UserDefinedType must include the
    ExternalType.cache_ok attribute in their definition, including for
    all derived subclasses, following the guidelines described in the docstring
    for ExternalType.cache_ok. As before, if these datatypes are
    imported from third party libraries, consult with the maintainers of that
    library so that they may provide the necessary changes to their library and
    publish a new release.

  • Third party or user defined SQL constructs that subclass from classes such
    as ClauseElement, Column, Insert
    etc, including simple subclasses as well as those which are designed to
    work with the Custom SQL Constructs and Compilation Extension, should normally
    include the HasCacheKey.inherit_cache attribute set to True
    or False based on the design of the construct, following the guidelines
    described at Enabling Caching Support for Custom Constructs.

Compiler StrSQLCompiler can’t render element of type <element type>¶

This error usually occurs when attempting to stringify a SQL expression
construct that includes elements which are not part of the default compilation;
in this case, the error will be against the StrSQLCompiler class.
In less common cases, it can also occur when the wrong kind of SQL expression
is used with a particular type of database backend; in those cases, other
kinds of SQL compiler classes will be named, such as SQLCompiler or
sqlalchemy.dialects.postgresql.PGCompiler. The guidance below is
more specific to the “stringification” use case but describes the general
background as well.

Normally, a Core SQL construct or ORM Query object can be stringified
directly, such as when we use print():

>>> from sqlalchemy import column
>>> print(column("x") == 5)
x = :x_1

When the above SQL expression is stringified, the StrSQLCompiler
compiler class is used, which is a special statement compiler that is invoked
when a construct is stringified without any dialect-specific information.

However, there are many constructs that are specific to some particular kind
of database dialect, for which the StrSQLCompiler doesn’t know how
to turn into a string, such as the PostgreSQL
“insert on conflict” construct:

>>> from sqlalchemy.dialects.postgresql import insert
>>> from sqlalchemy import table, column
>>> my_table = table("my_table", column("x"), column("y"))
>>> insert_stmt = insert(my_table).values(x="foo")
>>> insert_stmt = insert_stmt.on_conflict_do_nothing(index_elements=["y"])
>>> print(insert_stmt)
Traceback (most recent call last):

...

sqlalchemy.exc.UnsupportedCompilationError:
Compiler <sqlalchemy.sql.compiler.StrSQLCompiler object at 0x7f04fc17e320>
can't render element of type
<class 'sqlalchemy.dialects.postgresql.dml.OnConflictDoNothing'>

In order to stringify constructs that are specific to particular backend,
the ClauseElement.compile() method must be used, passing either an
Engine or a Dialect object which will invoke the correct
compiler. Below we use a PostgreSQL dialect:

>>> from sqlalchemy.dialects import postgresql
>>> print(insert_stmt.compile(dialect=postgresql.dialect()))
INSERT INTO my_table (x) VALUES (%(x)s) ON CONFLICT (y) DO NOTHING

For an ORM Query object, the statement can be accessed using the
Query.statement accessor:

statement = query.statement
print(statement.compile(dialect=postgresql.dialect()))

See the FAQ link below for additional detail on direct stringification /
compilation of SQL elements.

TypeError: <operator> not supported between instances of ‘ColumnProperty’ and <something>¶

This often occurs when attempting to use a column_property() or
deferred() object in the context of a SQL expression, usually within
declarative such as:

class Bar(Base):
    __tablename__ = "bar"

    id = Column(Integer, primary_key=True)
    cprop = deferred(Column(Integer))

    __table_args__ = (CheckConstraint(cprop > 5),)

Above, the cprop attribute is used inline before it has been mapped,
however this cprop attribute is not a Column,
it’s a ColumnProperty, which is an interim object and therefore
does not have the full functionality of either the Column object
or the InstrumentedAttribute object that will be mapped onto the
Bar class once the declarative process is complete.

While the ColumnProperty does have a __clause_element__() method,
which allows it to work in some column-oriented contexts, it can’t work in an
open-ended comparison context as illustrated above, since it has no Python
__eq__() method that would allow it to interpret the comparison to the
number “5” as a SQL expression and not a regular Python comparison.

The solution is to access the Column directly using the
ColumnProperty.expression attribute:

class Bar(Base):
    __tablename__ = "bar"

    id = Column(Integer, primary_key=True)
    cprop = deferred(Column(Integer))

    __table_args__ = (CheckConstraint(cprop.expression > 5),)

A value is required for bind parameter <x> (in parameter group <y>)¶

This error occurs when a statement makes use of bindparam() either
implicitly or explicitly and does not provide a value when the statement
is executed:

stmt = select(table.c.column).where(table.c.id == bindparam("my_param"))

result = conn.execute(stmt)

Above, no value has been provided for the parameter “my_param”. The correct
approach is to provide a value:

result = conn.execute(stmt, my_param=12)

When the message takes the form “a value is required for bind parameter <x>
in parameter group <y>”, the message is referring to the “executemany” style
of execution. In this case, the statement is typically an INSERT, UPDATE,
or DELETE and a list of parameters is being passed. In this format, the
statement may be generated dynamically to include parameter positions for
every parameter given in the argument list, where it will use the
first set of parameters to determine what these should be.

For example, the statement below is calculated based on the first parameter
set to require the parameters, “a”, “b”, and “c” — these names determine
the final string format of the statement which will be used for each
set of parameters in the list. As the second entry does not contain “b”,
this error is generated:

m = MetaData()
t = Table(
    't', m,
    Column('a', Integer),
    Column('b', Integer),
    Column('c', Integer)
)

e.execute(
    t.insert(), [
        {"a": 1, "b": 2, "c": 3},
        {"a": 2, "c": 4},
        {"a": 3, "b": 4, "c": 5},
    ]
)

sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError)
A value is required for bind parameter 'b', in parameter group 1
[SQL: u'INSERT INTO t (a, b, c) VALUES (?, ?, ?)']
[parameters: [{'a': 1, 'c': 3, 'b': 2}, {'a': 2, 'c': 4}, {'a': 3, 'c': 5, 'b': 4}]]

Since “b” is required, pass it as None so that the INSERT may proceed:

e.execute(
    t.insert(),
    [
        {"a": 1, "b": 2, "c": 3},
        {"a": 2, "b": None, "c": 4},
        {"a": 3, "b": 4, "c": 5},
    ],
)

Expected FROM clause, got Select. To create a FROM clause, use the .subquery() method¶

This refers to a change made as of SQLAlchemy 1.4 where a SELECT statement as generated
by a function such as select(), but also including things like unions and textual
SELECT expressions are no longer considered to be FromClause objects and
can’t be placed directly in the FROM clause of another SELECT statement without them
being wrapped in a Subquery first. This is a major conceptual change in the
Core and the full rationale is discussed at A SELECT statement is no longer implicitly considered to be a FROM clause.

Given an example as:

m = MetaData()
t = Table("t", m, Column("a", Integer), Column("b", Integer), Column("c", Integer))
stmt = select(t)

Above, stmt represents a SELECT statement. The error is produced when we want
to use stmt directly as a FROM clause in another SELECT, such as if we
attempted to select from it:

new_stmt_1 = select(stmt)

Or if we wanted to use it in a FROM clause such as in a JOIN:

new_stmt_2 = select(some_table).select_from(some_table.join(stmt))

In previous versions of SQLAlchemy, using a SELECT inside of another SELECT
would produce a parenthesized, unnamed subquery. In most cases, this form of
SQL is not very useful as databases like MySQL and PostgreSQL require that
subqueries in FROM clauses have named aliases, which means using the
SelectBase.alias() method or as of 1.4 using the
SelectBase.subquery() method to produce this. On other databases, it
is still much clearer for the subquery to have a name to resolve any ambiguity
on future references to column names inside the subquery.

Beyond the above practical reasons, there are a lot of other SQLAlchemy-oriented
reasons the change is being made. The correct form of the above two statements
therefore requires that SelectBase.subquery() is used:

subq = stmt.subquery()

new_stmt_1 = select(subq)

new_stmt_2 = select(some_table).select_from(some_table.join(subq))

An alias is being generated automatically for raw clauseelement¶

New in version 1.4.26.

This deprecation warning refers to a very old and likely not well known pattern
that applies to the legacy Query.join() method as well as the
2.0 style Select.join() method, where a join can be stated
in terms of a relationship() but the target is the
Table or other Core selectable to which the class is mapped,
rather than an ORM entity such as a mapped class or aliased()
construct:

a1 = Address.__table__

q = (
    s.query(User)
    .join(a1, User.addresses)
    .filter(Address.email_address == "ed@foo.com")
    .all()
)

The above pattern also allows an arbitrary selectable, such as
a Core Join or Alias object,
however there is no automatic adaptation of this element, meaning the
Core element would need to be referred towards directly:

a1 = Address.__table__.alias()

q = (
    s.query(User)
    .join(a1, User.addresses)
    .filter(a1.c.email_address == "ed@foo.com")
    .all()
)

The correct way to specify a join target is always by using the mapped
class itself or an aliased object, in the latter case using the
PropComparator.of_type() modifier to set up an alias:

# normal join to relationship entity
q = s.query(User).join(User.addresses).filter(Address.email_address == "ed@foo.com")

# name Address target explicitly, not necessary but legal
q = (
    s.query(User)
    .join(Address, User.addresses)
    .filter(Address.email_address == "ed@foo.com")
)

Join to an alias:

from sqlalchemy.orm import aliased

a1 = aliased(Address)

# of_type() form; recommended
q = (
    s.query(User)
    .join(User.addresses.of_type(a1))
    .filter(a1.email_address == "ed@foo.com")
)

# target, onclause form
q = s.query(User).join(a1, User.addresses).filter(a1.email_address == "ed@foo.com")

An alias is being generated automatically due to overlapping tables¶

New in version 1.4.26.

This warning is typically generated when querying using the
Select.join() method or the legacy Query.join() method
with mappings that involve joined table inheritance. The issue is that when
joining between two joined inheritance models that share a common base table, a
proper SQL JOIN between the two entities cannot be formed without applying an
alias to one side or the other; SQLAlchemy applies an alias to the right side
of the join. For example given a joined inheritance mapping as:

class Employee(Base):
    __tablename__ = "employee"
    id = Column(Integer, primary_key=True)
    manager_id = Column(ForeignKey("manager.id"))
    name = Column(String(50))
    type = Column(String(50))

    reports_to = relationship("Manager", foreign_keys=manager_id)

    __mapper_args__ = {
        "polymorphic_identity": "employee",
        "polymorphic_on": type,
    }


class Manager(Employee):
    __tablename__ = "manager"
    id = Column(Integer, ForeignKey("employee.id"), primary_key=True)

    __mapper_args__ = {
        "polymorphic_identity": "manager",
        "inherit_condition": id == Employee.id,
    }

The above mapping includes a relationship between the Employee and
Manager classes. Since both classes make use of the “employee” database
table, from a SQL perspective this is a
self referential relationship. If we wanted to
query from both the Employee and Manager models using a join, at the
SQL level the “employee” table needs to be included twice in the query, which
means it must be aliased. When we create such a join using the SQLAlchemy
ORM, we get SQL that looks like the following:

>>> stmt = select(Employee, Manager).join(Employee.reports_to)
>>> print(stmt)

SELECT employee.id, employee.manager_id, employee.name, employee.type, manager_1.id AS id_1, employee_1.id AS id_2, employee_1.manager_id AS manager_id_1, employee_1.name AS name_1, employee_1.type AS type_1 FROM employee JOIN (employee AS employee_1 JOIN manager AS manager_1 ON manager_1.id = employee_1.id) ON manager_1.id = employee.manager_id

Above, the SQL selects FROM the employee table, representing the
Employee entity in the query. It then joins to a right-nested join of
employee AS employee_1 JOIN manager AS manager_1, where the employee
table is stated again, except as an anonymous alias employee_1. This is the
“automatic generation of an alias” that the warning message refers towards.

When SQLAlchemy loads ORM rows that each contain an Employee and a
Manager object, the ORM must adapt rows from what above is the
employee_1 and manager_1 table aliases into those of the un-aliased
Manager class. This process is internally complex and does not accommodate
for all API features, notably when trying to use eager loading features such as
contains_eager() with more deeply nested queries than are shown
here. As the pattern is unreliable for more complex scenarios and involves
implicit decisionmaking that is difficult to anticipate and follow,
the warning is emitted and this pattern may be considered a legacy feature. The
better way to write this query is to use the same patterns that apply to any
other self-referential relationship, which is to use the aliased()
construct explicitly. For joined-inheritance and other join-oriented mappings,
it is usually desirable to add the use of the aliased.flat
parameter, which will allow a JOIN of two or more tables to be aliased by
applying an alias to the individual tables within the join, rather than
embedding the join into a new subquery:

>>> from sqlalchemy.orm import aliased
>>> manager_alias = aliased(Manager, flat=True)
>>> stmt = select(Employee, manager_alias).join(Employee.reports_to.of_type(manager_alias))
>>> print(stmt)

SELECT employee.id, employee.manager_id, employee.name, employee.type, manager_1.id AS id_1, employee_1.id AS id_2, employee_1.manager_id AS manager_id_1, employee_1.name AS name_1, employee_1.type AS type_1 FROM employee JOIN (employee AS employee_1 JOIN manager AS manager_1 ON manager_1.id = employee_1.id) ON manager_1.id = employee.manager_id

If we then wanted to use contains_eager() to populate the
reports_to attribute, we refer to the alias:

>>> stmt = (
...     select(Employee)
...     .join(Employee.reports_to.of_type(manager_alias))
...     .options(contains_eager(Employee.reports_to.of_type(manager_alias)))
... )

Without using the explicit aliased() object, in some more nested
cases the contains_eager() option does not have enough context to
know where to get its data from, in the case that the ORM is “auto-aliasing”
in a very nested context. Therefore it’s best not to rely on this feature
and instead keep the SQL construction as explicit as possible.

Object Relational Mapping¶

Parent instance <x> is not bound to a Session; (lazy load/deferred load/refresh/etc.) operation cannot proceed¶

This is likely the most common error message when dealing with the ORM, and it
occurs as a result of the nature of a technique the ORM makes wide use of known
as lazy loading. Lazy loading is a common object-relational pattern
whereby an object that’s persisted by the ORM maintains a proxy to the database
itself, such that when various attributes upon the object are accessed, their
value may be retrieved from the database lazily. The advantage to this
approach is that objects can be retrieved from the database without having
to load all of their attributes or related data at once, and instead only that
data which is requested can be delivered at that time. The major disadvantage
is basically a mirror image of the advantage, which is that if lots of objects
are being loaded which are known to require a certain set of data in all cases,
it is wasteful to load that additional data piecemeal.

Another caveat of lazy loading beyond the usual efficiency concerns is that
in order for lazy loading to proceed, the object has to remain associated
with a Session
in order to be able to retrieve its state. This error message
means that an object has become de-associated with its Session and
is being asked to lazy load data from the database.

The most common reason that objects become detached from their Session
is that the session itself was closed, typically via the Session.close()
method. The objects will then live on to be accessed further, very often
within web applications where they are delivered to a server-side templating
engine and are asked for further attributes which they cannot load.

Mitigation of this error is via these techniques:

  • Try not to have detached objects; don’t close the session prematurely — Often, applications will close
    out a transaction before passing off related objects to some other system
    which then fails due to this error. Sometimes the transaction doesn’t need
    to be closed so soon; an example is the web application closes out
    the transaction before the view is rendered. This is often done in the name
    of “correctness”, but may be seen as a mis-application of “encapsulation”,
    as this term refers to code organization, not actual actions. The template that
    uses an ORM object is making use of the proxy pattern
    which keeps database logic encapsulated from the caller. If the
    Session can be held open until the lifespan of the objects are done,
    this is the best approach.

  • Otherwise, load everything that’s needed up front — It is very often impossible to
    keep the transaction open, especially in more complex applications that need
    to pass objects off to other systems that can’t run in the same context
    even though they’re in the same process. In this case, the application
    should prepare to deal with detached objects,
    and should try to make appropriate use of eager loading to ensure
    that objects have what they need up front.

  • And importantly, set expire_on_commit to False — When using detached objects, the
    most common reason objects need to re-load data is because they were expired
    from the last call to Session.commit(). This expiration should
    not be used when dealing with detached objects; so the
    Session.expire_on_commit parameter be set to False.
    By preventing the objects from becoming expired outside of the transaction,
    the data which was loaded will remain present and will not incur additional
    lazy loads when that data is accessed.

    Note also that Session.rollback() method unconditionally expires
    all contents in the Session and should also be avoided in
    non-error scenarios.

This Session’s transaction has been rolled back due to a previous exception during flush¶

The flush process of the Session, described at
Flushing, will roll back the database transaction if an error is
encountered, in order to maintain internal consistency. However, once this
occurs, the session’s transaction is now “inactive” and must be explicitly
rolled back by the calling application, in the same way that it would otherwise
need to be explicitly committed if a failure had not occurred.

This is a common error when using the ORM and typically applies to an
application that doesn’t yet have correct “framing” around its
Session operations. Further detail is described in the FAQ at
“This Session’s transaction has been rolled back due to a previous exception during flush.” (or similar).

For relationship <relationship>, delete-orphan cascade is normally configured only on the “one” side of a one-to-many relationship, and not on the “many” side of a many-to-one or many-to-many relationship.¶

This error arises when the “delete-orphan” cascade
is set on a many-to-one or many-to-many relationship, such as:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)

    bs = relationship("B", back_populates="a")


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    # this will emit the error message when the mapper
    # configuration step occurs
    a = relationship("A", back_populates="bs", cascade="all, delete-orphan")


configure_mappers()

Above, the “delete-orphan” setting on B.a indicates the intent that
when every B object that refers to a particular A is deleted, that the
A should then be deleted as well. That is, it expresses that the “orphan”
which is being deleted would be an A object, and it becomes an “orphan”
when every B that refers to it is deleted.

The “delete-orphan” cascade model does not support this functionality. The
“orphan” consideration is only made in terms of the deletion of a single object
which would then refer to zero or more objects that are now “orphaned” by
this single deletion, which would result in those objects being deleted as
well. In other words, it is designed only to track the creation of “orphans”
based on the removal of one and only one “parent” object per orphan, which is
the natural case in a one-to-many relationship where a deletion of the
object on the “one” side results in the subsequent deletion of the related
items on the “many” side.

The above mapping in support of this functionality would instead place the
cascade setting on the one-to-many side, which looks like:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)

    bs = relationship("B", back_populates="a", cascade="all, delete-orphan")


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    a = relationship("A", back_populates="bs")

Where the intent is expressed that when an A is deleted, all of the
B objects to which it refers are also deleted.

The error message then goes on to suggest the usage of the
relationship.single_parent flag. This flag may be used
to enforce that a relationship which is capable of having many objects
refer to a particular object will in fact have only one object referring
to it at a time. It is used for legacy or other less ideal
database schemas where the foreign key relationships suggest a “many”
collection, however in practice only one object would actually refer
to a given target object at at time. This uncommon scenario
can be demonstrated in terms of the above example as follows:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)

    bs = relationship("B", back_populates="a")


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    a = relationship(
        "A",
        back_populates="bs",
        single_parent=True,
        cascade="all, delete-orphan",
    )

The above configuration will then install a validator which will enforce
that only one B may be associated with an A at at time, within
the scope of the B.a relationship:

>>> b1 = B()
>>> b2 = B()
>>> a1 = A()
>>> b1.a = a1
>>> b2.a = a1
sqlalchemy.exc.InvalidRequestError: Instance <A at 0x7eff44359350> is
already associated with an instance of <class '__main__.B'> via its
B.a attribute, and is only allowed a single parent.

Note that this validator is of limited scope and will not prevent multiple
“parents” from being created via the other direction. For example, it will
not detect the same setting in terms of A.bs:

>>> a1.bs = [b1, b2]
>>> session.add_all([a1, b1, b2])
>>> session.commit()

INSERT INTO a DEFAULT VALUES () INSERT INTO b (a_id) VALUES (?) (1,) INSERT INTO b (a_id) VALUES (?) (1,)

However, things will not go as expected later on, as the “delete-orphan” cascade
will continue to work in terms of a single lead object, meaning if we
delete either of the B objects, the A is deleted. The other B stays
around, where the ORM will usually be smart enough to set the foreign key attribute
to NULL, but this is usually not what’s desired:

>>> session.delete(b1)
>>> session.commit()

UPDATE b SET a_id=? WHERE b.id = ? (None, 2) DELETE FROM b WHERE b.id = ? (1,) DELETE FROM a WHERE a.id = ? (1,) COMMIT

For all the above examples, similar logic applies to the calculus of a
many-to-many relationship; if a many-to-many relationship sets single_parent=True
on one side, that side can use the “delete-orphan” cascade, however this is
very unlikely to be what someone actually wants as the point of a many-to-many
relationship is so that there can be many objects referring to an object
in either direction.

Overall, “delete-orphan” cascade is usually applied
on the “one” side of a one-to-many relationship so that it deletes objects
in the “many” side, and not the other way around.

Changed in version 1.3.18: The text of the “delete-orphan” error message
when used on a many-to-one or many-to-many relationship has been updated
to be more descriptive.

Instance <instance> is already associated with an instance of <instance> via its <attribute> attribute, and is only allowed a single parent.¶

This error is emitted when the relationship.single_parent flag
is used, and more than one object is assigned as the “parent” of an object at
once.

Given the following mapping:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    a = relationship(
        "A",
        single_parent=True,
        cascade="all, delete-orphan",
    )

The intent indicates that no more than a single B object may refer
to a particular A object at once:

>>> b1 = B()
>>> b2 = B()
>>> a1 = A()
>>> b1.a = a1
>>> b2.a = a1
sqlalchemy.exc.InvalidRequestError: Instance <A at 0x7eff44359350> is
already associated with an instance of <class '__main__.B'> via its
B.a attribute, and is only allowed a single parent.

When this error occurs unexpectedly, it is usually because the
relationship.single_parent flag was applied in response
to the error message described at For relationship <relationship>, delete-orphan cascade is normally configured only on the “one” side of a one-to-many relationship, and not on the “many” side of a many-to-one or many-to-many relationship., and the issue is in
fact a misunderstanding of the “delete-orphan” cascade setting. See that
message for details.

relationship X will copy column Q to column P, which conflicts with relationship(s): ‘Y’¶

This warning refers to the case when two or more relationships will write data
to the same columns on flush, but the ORM does not have any means of
coordinating these relationships together. Depending on specifics, the solution
may be that two relationships need to be referred towards one another using
relationship.back_populates, or that one or more of the
relationships should be configured with relationship.viewonly
to prevent conflicting writes, or sometimes that the configuration is fully
intentional and should configure relationship.overlaps to
silence each warning.

For the typical example that’s missing
relationship.back_populates, given the following mapping:

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    children = relationship("Child")


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey("parent.id"))
    parent = relationship("Parent")

The above mapping will generate warnings:

SAWarning: relationship 'Child.parent' will copy column parent.id to column child.parent_id,
which conflicts with relationship(s): 'Parent.children' (copies parent.id to child.parent_id).

The relationships Child.parent and Parent.children appear to be in conflict.
The solution is to apply relationship.back_populates:

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    children = relationship("Child", back_populates="parent")


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey("parent.id"))
    parent = relationship("Parent", back_populates="children")

For more customized relationships where an “overlap” situation may be
intentional and cannot be resolved, the relationship.overlaps
parameter may specify the names of relationships for which the warning should
not take effect. This typically occurs for two or more relationships to the
same underlying table that include custom
relationship.primaryjoin conditions that limit the related
items in each case:

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    c1 = relationship(
        "Child",
        primaryjoin="and_(Parent.id == Child.parent_id, Child.flag == 0)",
        backref="parent",
        overlaps="c2, parent",
    )
    c2 = relationship(
        "Child",
        primaryjoin="and_(Parent.id == Child.parent_id, Child.flag == 1)",
        overlaps="c1, parent",
    )


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey("parent.id"))

    flag = Column(Integer)

Above, the ORM will know that the overlap between Parent.c1,
Parent.c2 and Child.parent is intentional.

Object cannot be converted to ‘persistent’ state, as this identity map is no longer valid.¶

New in version 1.4.26.

This message was added to accommodate for the case where a
Result object that would yield ORM objects is iterated after
the originating Session has been closed, or otherwise had its
Session.expunge_all() method called. When a Session
expunges all objects at once, the internal identity map used by that
Session is replaced with a new one, and the original one
discarded. An unconsumed and unbuffered Result object will
internally maintain a reference to that now-discarded identity map. Therefore,
when the Result is consumed, the objects that would be yielded
cannot be associated with that Session. This arrangement is by
design as it is generally not recommended to iterate an unbuffered
Result object outside of the transactional context in which it
was created:

# context manager creates new Session
with Session(engine) as session_obj:
    result = sess.execute(select(User).where(User.id == 7))

# context manager is closed, so session_obj above is closed, identity
# map is replaced

# iterating the result object can't associate the object with the
# Session, raises this error.
user = result.first()

The above situation typically will not occur when using the asyncio
ORM extension, as when AsyncSession returns a sync-style
Result, the results have been pre-buffered when the statement
was executed. This is to allow secondary eager loaders to invoke without needing
an additional await call.

To pre-buffer results in the above situation using the regular
Session in the same way that the asyncio extension does it,
the prebuffer_rows execution option may be used as follows:

# context manager creates new Session
with Session(engine) as session_obj:

    # result internally pre-fetches all objects
    result = sess.execute(
        select(User).where(User.id == 7), execution_options={"prebuffer_rows": True}
    )

# context manager is closed, so session_obj above is closed, identity
# map is replaced

# pre-buffered objects are returned
user = result.first()

# however they are detached from the session, which has been closed
assert inspect(user).detached
assert inspect(user).session is None

Above, the selected ORM objects are fully generated within the session_obj
block, associated with session_obj and buffered within the
Result object for iteration. Outside the block,
session_obj is closed and expunges these ORM objects. Iterating the
Result object will yield those ORM objects, however as their
originating Session has expunged them, they will be delivered in
the detached state.

Note

The above reference to a “pre-buffered” vs. “un-buffered”
Result object refers to the process by which the ORM
converts incoming raw database rows from the DBAPI into ORM
objects. It does not imply whether or not the underyling cursor
object itself, which represents pending results from the DBAPI, is itself
buffered or unbuffered, as this is essentially a lower layer of buffering.
For background on buffering of the cursor results itself, see the
section Using Server Side Cursors (a.k.a. stream results).

AsyncIO Exceptions¶

AwaitRequired¶

The SQLAlchemy async mode requires an async driver to be used to connect to the db.
This error is usually raised when trying to use the async version of SQLAlchemy
with a non compatible DBAPI.

MissingGreenlet¶

A call to the async DBAPI was initiated outside the greenlet spawn
context usually setup by the SQLAlchemy AsyncIO proxy classes. Usually this
error happens when an IO was attempted in an unexpected place, without using
the provided async api. When using the ORM this may be due to a lazy loading
attempt, which is unsupported when using SQLAlchemy with AsyncIO dialects.

No Inspection Available¶

Using the inspect() function directly on an
AsyncConnection or AsyncEngine object is
not currently supported, as there is not yet an awaitable form of the
Inspector object available. Instead, the object
is used by acquiring it using the
inspect() function in such a way that it refers to the underlying
AsyncConnection.sync_connection attribute of the
AsyncConnection object; the Inspector is
then used in a “synchronous” calling style by using the
AsyncConnection.run_sync() method along with a custom function
that performs the desired operations:

async def async_main():
    async with engine.connect() as conn:
        tables = await conn.run_sync(
            lambda sync_conn: inspect(sync_conn).get_table_names()
        )

Core Exception Classes¶

See Core Exceptions for Core exception classes.

ORM Exception Classes¶

See ORM Exceptions for ORM exception classes.

Legacy Exceptions¶

Exceptions in this section are not generated by current SQLAlchemy
versions, however are provided here to suit exception message hyperlinks.

The <some function> in SQLAlchemy 2.0 will no longer <something>¶

SQLAlchemy 2.0 represents a major shift for a wide variety of key
SQLAlchemy usage patterns in both the Core and ORM components. The goal
of the 2.0 release is to make a slight readjustment in some of the most
fundamental assumptions of SQLAlchemy since its early beginnings, and
to deliver a newly streamlined usage model that is hoped to be significantly
more minimalist and consistent between the Core and ORM components, as well as
more capable.

Introduced at Migrating to SQLAlchemy 2.0, the SQLAlchemy 2.0 project includes
a comprehensive future compatibility system that’s integrated into the
1.4 series of SQLAlchemy, such that applications will have a clear,
unambiguous, and incremental upgrade path in order to migrate applications to
being fully 2.0 compatible. The RemovedIn20Warning deprecation
warning is at the base of this system to provide guidance on what behaviors in
an existing codebase will need to be modified. An overview of how to enable
this warning is at SQLAlchemy 2.0 Deprecations Mode.

Object is being merged into a Session along the backref cascade¶

This message refers to the “backref cascade” behavior of SQLAlchemy,
removed in version 2.0. This refers to the action of
an object being added into a Session as a result of another
object that’s already present in that session being associated with it.
As this behavior has been shown to be more confusing than helpful,
the relationship.cascade_backrefs and
backref.cascade_backrefs parameters were added, which can
be set to False to disable it, and in SQLAlchemy 2.0 the “cascade backrefs”
behavior has been removed entirely.

For older SQLAlchemy versions, to set
relationship.cascade_backrefs to False on a backref that
is currently configured using the relationship.backref string
parameter, the backref must be declared using the backref() function
first so that the backref.cascade_backrefs parameter may be
passed.

Alternatively, the entire “cascade backrefs” behavior can be turned off
across the board by using the Session in “future” mode,
by passing True for the Session.future parameter.

select() construct created in “legacy” mode; keyword arguments, etc.¶

The select() construct has been updated as of SQLAlchemy
1.4 to support the newer calling style that is standard in
SQLAlchemy 2.0. For backwards compatibility within
the 1.4 series, the construct accepts arguments in both the “legacy” style as well
as the “new” style.

The “new” style features that column and table expressions are passed
positionally to the select() construct only; any other
modifiers to the object must be passed using subsequent method chaining:

# this is the way to do it going forward
stmt = select(table1.c.myid).where(table1.c.myid == table2.c.otherid)

For comparison, a select() in legacy forms of SQLAlchemy,
before methods like Select.where() were even added, would like:

# this is how it was documented in original SQLAlchemy versions
# many years ago
stmt = select([table1.c.myid], whereclause=table1.c.myid == table2.c.otherid)

Or even that the “whereclause” would be passed positionally:

# this is also how it was documented in original SQLAlchemy versions
# many years ago
stmt = select([table1.c.myid], table1.c.myid == table2.c.otherid)

For some years now, the additional “whereclause” and other arguments that are
accepted have been removed from most narrative documentation, leading to a
calling style that is most familiar as the list of column arguments passed
as a list, but no further arguments:

# this is how it's been documented since around version 1.0 or so
stmt = select([table1.c.myid]).where(table1.c.myid == table2.c.otherid)

The document at select() no longer accepts varied constructor arguments, columns are passed positionally describes this change in terms
of 2.0 Migration.

A bind was located via legacy bound metadata, but since future=True is set on this Session, this bind is ignored.¶

The concept of “bound metadata” is present up until SQLAlchemy 1.4; as
of SQLAlchemy 2.0 it’s been removed.

This error refers to the MetaData.bind parameter on the
MetaData object that in turn allows objects like the ORM
Session to associate a particular mapped class with an
Engine. In SQLAlchemy 2.0, the Session must be
linked to each Engine directly. That is, instead of instantiating
the Session or sessionmaker without any arguments,
and associating the Engine with the
MetaData:

engine = create_engine("sqlite://")
Session = sessionmaker()
metadata_obj = MetaData(bind=engine)
Base = declarative_base(metadata=metadata_obj)

class MyClass(Base):
    # ...


session = Session()
session.add(MyClass())
session.commit()

The Engine must instead be associated directly with the
sessionmaker or Session. The
MetaData object should no longer be associated with any
engine:

engine = create_engine("sqlite://")
Session = sessionmaker(engine)
Base = declarative_base()

class MyClass(Base):
    # ...


session = Session()
session.add(MyClass())
session.commit()

In SQLAlchemy 1.4, this 2.0 style behavior is enabled when the
Session.future flag is set on sessionmaker
or Session.

This Compiled object is not bound to any Engine or Connection¶

This error refers to the concept of “bound metadata”, which is a legacy
SQLAlchemy pattern present only in 1.x versions. The issue occurs when one invokes
the Executable.execute() method directly off of a Core expression object
that is not associated with any Engine:

metadata_obj = MetaData()
table = Table("t", metadata_obj, Column("q", Integer))

stmt = select(table)
result = stmt.execute()  # <--- raises

What the logic is expecting is that the MetaData object has
been bound to a Engine:

engine = create_engine("mysql+pymysql://user:pass@host/db")
metadata_obj = MetaData(bind=engine)

Where above, any statement that derives from a Table which
in turn derives from that MetaData will implicitly make use of
the given Engine in order to invoke the statement.

Note that the concept of bound metadata is not present in SQLAlchemy 2.0.
The correct way to invoke statements is via
the Connection.execute() method of a Connection:

with engine.connect() as conn:
    result = conn.execute(stmt)

When using the ORM, a similar facility is available via the Session:

result = session.execute(stmt)

This connection is on an inactive transaction. Please rollback() fully before proceeding¶

This error condition was added to SQLAlchemy as of version 1.4, and does not
apply to SQLAlchemy 2.0. The error
refers to the state where a Connection is placed into a
transaction using a method like Connection.begin(), and then a
further “marker” transaction is created within that scope; the “marker”
transaction is then rolled back using Transaction.rollback() or closed
using Transaction.close(), however the outer transaction is still
present in an “inactive” state and must be rolled back.

The pattern looks like:

engine = create_engine(...)

connection = engine.connect()
transaction1 = connection.begin()

# this is a "sub" or "marker" transaction, a logical nesting
# structure based on "real" transaction transaction1
transaction2 = connection.begin()
transaction2.rollback()

# transaction1 is still present and needs explicit rollback,
# so this will raise
connection.execute(text("select 1"))

Above, transaction2 is a “marker” transaction, which indicates a logical
nesting of transactions within an outer one; while the inner transaction
can roll back the whole transaction via its rollback() method, its commit()
method has no effect except to close the scope of the “marker” transaction
itself. The call to transaction2.rollback() has the effect of
deactivating transaction1 which means it is essentially rolled back
at the database level, however is still present in order to accommodate
a consistent nesting pattern of transactions.

The correct resolution is to ensure the outer transaction is also
rolled back:

This pattern is not commonly used in Core. Within the ORM, a similar issue can
occur which is the product of the ORM’s “logical” transaction structure; this
is described in the FAQ entry at “This Session’s transaction has been rolled back due to a previous exception during flush.” (or similar).

The “subtransaction” pattern is removed in SQLAlchemy 2.0 so that this
particular programming pattern is no longer be available, preventing
this error message.

Сообщения об ошибках¶

В этом разделе приведены описания и справочная информация для распространенных сообщений об ошибках и предупреждений, выдаваемых или выдаваемых SQLAlchemy.

SQLAlchemy обычно выдает ошибки в контексте специфического для SQLAlchemy класса исключений. Подробнее об этих классах смотрите Основные исключения и Исключения ORM.

Ошибки SQLAlchemy можно условно разделить на две категории: ошибки времени программирования и ошибки времени выполнения. Ошибки времени программирования возникают в результате вызова функций или методов с неправильными аргументами, или в результате других методов, ориентированных на конфигурацию, таких как конфигурации маппера, которые не могут быть разрешены. Ошибка времени программирования обычно является немедленной и детерминированной. С другой стороны, ошибка времени выполнения представляет собой сбой, возникающий в процессе выполнения программы в ответ на некоторое условие, которое возникает произвольно, например, исчерпание соединений с базой данных или возникновение какой-либо проблемы, связанной с данными. Ошибки времени выполнения чаще всего можно увидеть в журналах работающего приложения, поскольку программа сталкивается с этими состояниями в ответ на нагрузку и встречающиеся данные.

Поскольку ошибки времени выполнения не так легко воспроизвести, и они часто возникают в ответ на какие-то произвольные условия в процессе работы программы, их сложнее отлаживать, и они также влияют на программы, которые уже запущены в производство.

В этом разделе мы попытаемся рассказать о некоторых наиболее распространенных ошибках времени выполнения, а также об ошибках времени программирования.

Связи и транзакции¶

Ограничение QueuePool размером <x> переполнение <y> достигнуто, соединение прервано, таймаут <z>¶

Это, возможно, самая распространенная ошибка времени выполнения, поскольку она напрямую связана с превышением рабочей нагрузки приложения над настроенным пределом, который обычно применяется почти ко всем приложениям SQLAlchemy.

Ниже кратко описано, что означает эта ошибка, начиная с самых основных моментов, с которыми большинство пользователей SQLAlchemy уже должны быть знакомы.

  • ** Объект SQLAlchemy Engine по умолчанию использует пул соединений** — Это означает, что при использовании ресурса соединения с базой данных SQL объекта Engine, а затем releases этого ресурса, само соединение с базой данных остается подключенным к базе данных и возвращается во внутреннюю очередь, где оно может быть использовано снова. Хотя может показаться, что код завершает общение с базой данных, во многих случаях приложение будет поддерживать фиксированное количество соединений с базой данных, которые сохраняются до завершения работы приложения или явного удаления пула.

  • Благодаря пулу, когда приложение использует соединение с базой данных SQL, чаще всего либо с помощью Engine.connect(), либо при выполнении запросов с помощью ORM Session, это действие не обязательно устанавливает новое соединение с базой данных в момент получения объекта соединения; вместо этого оно обращается к пулу соединений для поиска соединения, который часто извлекает существующее соединение из пула для повторного использования. Если доступных соединений нет, пул создаст новое соединение с базой данных, но только если пул не превысил заданную емкость.

  • Пул по умолчанию, используемый в большинстве случаев, называется QueuePool. Когда вы просите этот пул предоставить вам соединение, а ни одно из них не доступно, он создаст новое соединение если общее количество соединений в игре меньше настроенного значения. Это значение равно размеру пула плюс максимальное переполнение. Это означает, что если вы настроили свой движок как:

    engine = create_engine("mysql://u:p@host/db", pool_size=10, max_overflow=20)

    Приведенное выше Engine позволит не более 30 соединений быть в игре в любое время, не включая соединения, которые были отсоединены от движка или аннулированы. Если поступит запрос на новое соединение, а 30 соединений уже используются другими частями приложения, пул соединений будет блокироваться на определенный период времени, после чего произойдет тайминг и появится сообщение об ошибке.

    Чтобы обеспечить одновременное использование большего числа соединений, пул можно настроить с помощью параметров create_engine.pool_size и create_engine.max_overflow, передаваемых в функцию create_engine(). Тайм-аут для ожидания доступного соединения настраивается с помощью параметра create_engine.pool_timeout.

  • Пул может быть настроен на неограниченное переполнение, если установить create_engine.max_overflow на значение «-1». При такой настройке пул будет поддерживать фиксированный пул соединений, однако он никогда не будет блокироваться при запросе нового соединения; вместо этого он будет безоговорочно создавать новое соединение, если ни одно из них не доступно.

    Однако при таком способе работы, если у приложения возникнет проблема, когда оно использует все доступные ресурсы подключения, оно в конечном итоге достигнет настроенного предела доступных подключений в самой базе данных, что снова приведет к ошибке. Более серьезно, когда приложение исчерпывает базу данных подключений, оно обычно расходует большое количество ресурсов до отказа, а также может нарушить работу других приложений и механизмов состояния базы данных, которые полагаются на возможность подключения к базе данных.

    Учитывая вышесказанное, пул соединений можно рассматривать как предохранительный клапан для использования соединений, обеспечивающий критический уровень защиты от неавторизованного приложения, из-за которого вся база данных становится недоступной для всех остальных приложений. При получении этого сообщения об ошибке гораздо предпочтительнее устранить проблему, использующую слишком много соединений, и/или настроить ограничения соответствующим образом, а не допускать неограниченного переполнения, которое на самом деле не решает основную проблему.

Что заставляет приложение использовать все доступные ему соединения?

  • Приложение получает слишком много одновременных запросов для выполнения работы, основанной на настроенном значении для пула — Это самая простая причина. Если у вас есть приложение, которое работает в пуле потоков, допускающем 30 одновременных потоков, с одним используемым соединением на поток, если ваш пул не настроен на одновременную проверку не менее 30 соединений, вы получите эту ошибку, когда ваше приложение получит достаточное количество одновременных запросов. Решением является повышение лимитов на пул или снижение количества одновременных потоков.

  • Приложение не возвращает соединения в пул — Это следующая наиболее распространенная причина, которая заключается в том, что приложение использует пул соединений, но программа не может release эти соединения и вместо этого оставляет их открытыми. Пул соединений, а также ORM Session имеют логику, согласно которой, когда сессия и/или объект соединения собираются в мусор, это приводит к освобождению ресурсов базового соединения, однако на это поведение нельзя полагаться в плане своевременного освобождения ресурсов.

    Чаще всего это происходит потому, что приложение использует ORM-сессии и не обращается к ним Session.close() после завершения работы с сессией. Решение состоит в том, чтобы убедиться, что сессии ORM, если используется ORM, или связанные с движком объекты Connection, если используется Core, явно закрыты по окончании выполняемой работы, либо с помощью соответствующего метода .close(), либо с помощью одного из доступных менеджеров контекста (например, оператора «with:»), чтобы правильно освободить ресурс.

  • Приложение пытается выполнить длительные транзакции — Транзакция базы данных — это очень дорогой ресурс, и ее никогда не следует оставлять без дела в ожидании какого-либо события. Если приложение ждет, пока пользователь нажмет на кнопку, или результат выйдет из давно запущенной очереди заданий, или держит открытым постоянное соединение с браузером, не держите транзакцию базы данных открытой все это время. Когда приложению необходимо работать с базой данных и взаимодействовать с событием, откройте в этот момент короткоживущую транзакцию, а затем закройте ее.

  • Приложение находится в тупике — Также распространенная причина этой ошибки и более сложная для понимания, если приложение не может завершить использование соединения либо из-за тупика со стороны приложения, либо со стороны базы данных, приложение может использовать все доступные соединения, что приводит к тому, что дополнительные запросы получают эту ошибку. Причины возникновения тупиковых ситуаций включают:

    • Использование неявной системы async, такой как gevent или eventlet, без надлежащего monkeypatching всех библиотек сокетов и драйверов, или в которой есть ошибки, не полностью покрывающие все monkeypatched методы драйверов, или, реже, когда система async используется против нагрузок на CPU, и greenlet, использующие ресурсы базы данных, просто ждут слишком долго, чтобы их обслужить. Ни неявные, ни явные рамки программирования async обычно не нужны и не подходят для подавляющего большинства операций с реляционными базами данных; если приложение должно использовать систему async для некоторой области функциональности, лучше всего, чтобы бизнес-методы, ориентированные на базу данных, выполнялись в традиционных потоках, которые передают сообщения в асинхронную часть приложения.

    • Тупик на стороне базы данных, например, строки взаимно заблокированы

    • Ошибки потоков, например, мьютексы во взаимном тупике или обращение к уже заблокированному мьютексу в том же потоке

Помните, что альтернативой использованию пулинга является полное отключение пулинга. См. раздел Реализации коммутационных пулов для получения информации об этом. Однако обратите внимание, что когда возникает это сообщение об ошибке, это всегда связано с более серьезной проблемой в самом приложении; пул просто помогает быстрее выявить проблему.

Невозможно восстановить соединение, пока не будет откачена недействительная транзакция¶

Это состояние ошибки относится к случаю, когда соединение Connection было аннулировано либо из-за обнаружения разъединения базы данных, либо из-за явного вызова Connection.invalidate(), но все еще присутствует транзакция, инициированная методом Connection.begin(). Когда соединение аннулируется, любая транзакция Transaction, которая находилась в процессе выполнения, теперь находится в недействительном состоянии и должна быть явно откатана, чтобы удалить ее из Connection.

Ошибки DBAPI¶

API базы данных Python, или DBAPI, — это спецификация драйверов баз данных, которую можно найти по адресу Pep-249. Этот API определяет набор классов исключений, которые учитывают весь спектр режимов отказа базы данных.

SQLAlchemy не генерирует эти исключения напрямую. Вместо этого они перехватываются драйвером базы данных и оборачиваются в исключение DBAPIError, предоставляемое SQLAlchemy, однако сообщения в исключении генерируются драйвером, а не SQLAlchemy.

InterfaceError¶

Исключение, возникающее при ошибках, связанных с интерфейсом базы данных, а не с самой базой данных.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

InterfaceError иногда поднимается драйверами в контексте разрыва соединения с базой данных или невозможности подключения к базе данных. Советы о том, как с этим справиться, см. в разделе Работа с разъединениями.

DatabaseError¶

Исключение, возникающее при ошибках, связанных с самой базой данных, а не с интерфейсом или передаваемыми данными.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

DataError¶

Исключение, возникающее при ошибках, связанных с проблемами в обрабатываемых данных, таких как деление на ноль, выход числового значения за пределы диапазона и т.д.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

OperationalError¶

Исключение, возникающее при ошибках, которые связаны с работой базы данных и не обязательно находятся под контролем программиста, например, происходит неожиданное отключение, имя источника данных не найдено, транзакция не может быть обработана, во время обработки произошла ошибка выделения памяти и т.д.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

OperationalError — это наиболее распространенный (но не единственный) класс ошибок, используемый драйверами в контексте разрыва соединения с базой данных или невозможности подключения к базе данных. Советы о том, как с этим справиться, см. в разделе Работа с разъединениями.

IntegrityError¶

Исключение, возникающее при нарушении реляционной целостности базы данных, например, при неудачной проверке внешнего ключа.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

InternalError¶

Исключение, возникающее, когда база данных сталкивается с внутренней ошибкой, например, курсор больше не действителен, транзакция рассинхронизирована и т.д.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

InternalError иногда поднимается драйверами в контексте разрыва соединения с базой данных или невозможности подключения к базе данных. Советы о том, как с этим справиться, см. в разделе Работа с разъединениями.

ProgrammingError¶

Исключение, возникающее при ошибках программирования, например, таблица не найдена или уже существует, синтаксическая ошибка в SQL-запросе, неверно указано количество параметров и т.д.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

ProgrammingError иногда поднимается драйверами в контексте разрыва соединения с базой данных или невозможности подключения к базе данных. Советы о том, как с этим справиться, см. в разделе Работа с разъединениями.

NotSupportedError¶

Исключение, возникающее в случае использования метода или API базы данных, который не поддерживается базой данных, например, запрос .rollback() на соединении, которое не поддерживает транзакцию или транзакции отключены.

Эта ошибка имеет вид DBAPI Error и исходит от драйвера базы данных (DBAPI), а не от самой SQLAlchemy.

Язык выражений SQL¶

Объект не будет создавать ключ кэша, Последствия для производительности¶

SQLAlchemy начиная с версии 1.4 включает SQL compilation caching facility, который позволяет конструкциям Core и ORM SQL кэшировать их строковую форму вместе с другой структурной информацией, используемой для получения результатов из оператора, что позволяет пропустить относительно дорогостоящий процесс компиляции строки при следующем использовании структурно эквивалентной конструкции. Эта система полагается на функциональность, реализованную для всех конструкций SQL, включая такие объекты, как Column, select() и TypeEngine, чтобы создать ключ кэша, который полностью представляет их состояние в той степени, в которой оно влияет на процесс компиляции SQL.

Если предупреждения относятся к широко используемым объектам, таким как объекты Column, и показано, что они влияют на большинство используемых конструкций SQL (с использованием методов оценки, описанных в Оценка производительности кэша с помощью протоколирования) так, что кэширование обычно не включено для приложения, это негативно скажется на производительности и в некоторых случаях может привести к ухудшению производительности по сравнению с предыдущими версиями SQLAlchemy. Подробнее об этом говорится в FAQ по адресу Почему мое приложение работает медленно после обновления до 1.4 и/или 2.x?.

Кэширование отключается, если есть сомнения.¶

Кэширование основывается на возможности генерировать ключ кэша, который точно представляет полную структуру оператора в последовательном виде. Если конкретная конструкция (или тип) SQL не имеет соответствующих директив, которые позволяют ей генерировать правильный ключ кэша, то кэширование не может быть безопасно включено:

  • Ключ кэша должен представлять полную структуру: Если использование двух отдельных экземпляров этой конструкции может привести к различному отображению SQL, кэширование SQL для первого экземпляра элемента с использованием ключа кэша, который не отражает различий между первым и вторым элементами, приведет к тому, что для второго экземпляра будет кэширован и отображен некорректный SQL.

  • Ключ кэша должен быть последовательным: Если конструкция представляет состояние, которое изменяется каждый раз, например, литеральное значение, создавая уникальный SQL для каждого экземпляра, эту конструкцию также небезопасно кэшировать, поскольку повторное использование конструкции быстро заполнит кэш утверждений уникальными строками SQL, которые, скорее всего, не будут использоваться снова, что сводит на нет цель кэша.

По двум вышеуказанным причинам система кэширования SQLAlchemy очень консервативна при принятии решения о кэшировании SQL, соответствующего объекту.

Атрибуты утверждения для кэширования¶

Предупреждение выдается на основании приведенных ниже критериев. Подробнее о каждом из них см. в разделе Почему мое приложение работает медленно после обновления до 1.4 и/или 2.x?.

  • Сам Dialect (т.е. модуль, указанный первой частью URL, который мы передаем в create_engine(), например postgresql+psycopg2://), должен указывать на то, что он был рассмотрен и протестирован для корректной поддержки кэширования, на что указывает атрибут Dialect.supports_statement_cache, установленный в True. При использовании диалектов сторонних разработчиков, проконсультируйтесь с сопровождающими диалекта, чтобы они могли следить за steps to ensure caching may be enabled в своем диалекте и опубликовать новый выпуск.

  • Сторонние или определенные пользователем типы, которые наследуются от TypeDecorator или UserDefinedType, должны включать атрибут ExternalType.cache_ok в свое определение, в том числе для всех производных подклассов, следуя рекомендациям, описанным в docstring для ExternalType.cache_ok. Как и раньше, если эти типы данных импортируются из библиотек сторонних производителей, проконсультируйтесь с сопровождающими этой библиотеки, чтобы они могли внести необходимые изменения в свою библиотеку и опубликовать новый выпуск.

  • Сторонние или определенные пользователем конструкции SQL, которые являются подклассами таких классов, как ClauseElement, Column, Insert и т.д., включая простые подклассы, а также те, которые предназначены для работы с Пользовательские SQL-конструкции и расширение компиляции, обычно должны включать атрибут HasCacheKey.inherit_cache, установленный в True или False в зависимости от дизайна конструкции, следуя рекомендациям, описанным в compilerext_caching.

Компилятор StrSQLCompiler не может вывести элемент типа <тип элемента>¶

Эта ошибка обычно возникает при попытке структурировать конструкцию SQL-выражения, которая включает элементы, не являющиеся частью компиляции по умолчанию; в этом случае ошибка будет относиться к классу StrSQLCompiler. В менее распространенных случаях она также может возникнуть, когда неправильный тип SQL-выражения используется с определенным типом бэкенда базы данных; в этих случаях будут названы другие типы классов компилятора SQL, такие как SQLCompiler или sqlalchemy.dialects.postgresql.PGCompiler. Приведенное ниже руководство в большей степени относится к случаю использования «стрингизации», но описывает и общие предпосылки.

Обычно конструкцию Core SQL или объект ORM Query можно строчить напрямую, например, когда мы используем print():

>>> from sqlalchemy import column
>>> print(column("x") == 5)
x = :x_1

Когда приведенное выше выражение SQL строится, используется класс компилятора StrSQLCompiler, который представляет собой специальный компилятор операторов, вызываемый, когда конструкция строится без какой-либо информации, специфичной для диалекта.

Однако существует множество конструкций, специфичных для определенного диалекта базы данных, для которых StrSQLCompiler не знает, как превратить в строку, например, конструкция PostgreSQL «insert on conflict»:

>>> from sqlalchemy.dialects.postgresql import insert
>>> from sqlalchemy import table, column
>>> my_table = table("my_table", column("x"), column("y"))
>>> insert_stmt = insert(my_table).values(x="foo")
>>> insert_stmt = insert_stmt.on_conflict_do_nothing(index_elements=["y"])
>>> print(insert_stmt)
Traceback (most recent call last):

...

sqlalchemy.exc.UnsupportedCompilationError:
Compiler <sqlalchemy.sql.compiler.StrSQLCompiler object at 0x7f04fc17e320>
can't render element of type
<class 'sqlalchemy.dialects.postgresql.dml.OnConflictDoNothing'>

Чтобы строчить конструкции, характерные для конкретного бэкенда, необходимо использовать метод ClauseElement.compile(), передавая либо Engine, либо Dialect объект, который вызовет нужный компилятор. Ниже мы используем диалект PostgreSQL:

>>> from sqlalchemy.dialects import postgresql
>>> print(insert_stmt.compile(dialect=postgresql.dialect()))
INSERT INTO my_table (x) VALUES (%(x)s) ON CONFLICT (y) DO NOTHING

Для объекта ORM Query к утверждению можно получить доступ, используя аксессор Query.statement:

statement = query.statement
print(statement.compile(dialect=postgresql.dialect()))

Дополнительную информацию о прямой структуризации / компиляции элементов SQL см. по ссылке FAQ ниже.

TypeError: <оператор> не поддерживается между экземплярами „ColumnProperty“ и <что-то>¶

Это часто происходит при попытке использовать объект column_property() или deferred() в контексте выражения SQL, обычно в декларативных выражениях типа:

class Bar(Base):
    __tablename__ = "bar"

    id = Column(Integer, primary_key=True)
    cprop = deferred(Column(Integer))

    __table_args__ = (CheckConstraint(cprop > 5),)

Выше, атрибут cprop используется в строке до того, как он был отображен, однако этот атрибут cprop не является Column, это ColumnProperty, который является промежуточным объектом и поэтому не имеет полной функциональности ни объекта Column, ни объекта InstrumentedAttribute, которые будут отображены на класс Bar после завершения декларативного процесса.

Хотя у ColumnProperty есть метод __clause_element__(), что позволяет ему работать в некоторых контекстах, ориентированных на столбцы, он не может работать в контексте открытого сравнения, как показано выше, поскольку у него нет метода Python __eq__(), который позволил бы ему интерпретировать сравнение с числом «5» как выражение SQL, а не как обычное сравнение Python.

Решением является прямой доступ к Column с помощью атрибута ColumnProperty.expression:

class Bar(Base):
    __tablename__ = "bar"

    id = Column(Integer, primary_key=True)
    cprop = deferred(Column(Integer))

    __table_args__ = (CheckConstraint(cprop.expression > 5),)

Требуется значение для параметра привязки <x> (в группе параметров <y>)¶

Эта ошибка возникает, когда оператор использует bindparam() либо неявно, либо явно и не предоставляет значения при выполнении оператора:

stmt = select(table.c.column).where(table.c.id == bindparam("my_param"))

result = conn.execute(stmt)

Выше не было указано значение для параметра «my_param». Правильным подходом является предоставление значения:

result = conn.execute(stmt, my_param=12)

Если сообщение имеет вид «требуется значение для параметра привязки <x> в группе параметров <y>», это сообщение относится к стилю выполнения «executemany». В этом случае оператор обычно представляет собой INSERT, UPDATE или DELETE и передается список параметров. В этом формате оператор может генерироваться динамически, чтобы включить позиции параметров для каждого параметра, указанного в списке аргументов, где он будет использовать первый набор параметров, чтобы определить, какими они должны быть.

Например, приведенный ниже оператор рассчитывается на основе первого набора параметров, чтобы потребовать параметры, «a», «b» и «c» — эти имена определяют окончательный строковый формат оператора, который будет использоваться для каждого набора параметров в списке. Поскольку вторая запись не содержит «b», генерируется такая ошибка:

m = MetaData()
t = Table(
    't', m,
    Column('a', Integer),
    Column('b', Integer),
    Column('c', Integer)
)

e.execute(
    t.insert(), [
        {"a": 1, "b": 2, "c": 3},
        {"a": 2, "c": 4},
        {"a": 3, "b": 4, "c": 5},
    ]
)

sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError)
A value is required for bind parameter 'b', in parameter group 1
[SQL: u'INSERT INTO t (a, b, c) VALUES (?, ?, ?)']
[parameters: [{'a': 1, 'c': 3, 'b': 2}, {'a': 2, 'c': 4}, {'a': 3, 'c': 5, 'b': 4}]]

Поскольку требуется «b», передайте его как None, чтобы INSERT можно было продолжить:

e.execute(
    t.insert(),
    [
        {"a": 1, "b": 2, "c": 3},
        {"a": 2, "b": None, "c": 4},
        {"a": 3, "b": 4, "c": 5},
    ],
)

Ожидался пункт FROM, а получился Select. Чтобы создать предложение FROM, используйте метод .subquery()¶

Это относится к изменению, внесенному в SQLAlchemy 1.4, когда оператор SELECT, сгенерированный такой функцией, как select(), но также включающий такие вещи, как союзы и текстовые выражения SELECT, больше не считается объектом FromClause и не может быть помещен непосредственно в предложение FROM другого оператора SELECT без предварительного обертывания в Subquery. Это серьезное концептуальное изменение в Core, и полное обоснование обсуждается в A SELECT statement is no longer implicitly considered to be a FROM clause.

Приведем пример:

m = MetaData()
t = Table("t", m, Column("a", Integer), Column("b", Integer), Column("c", Integer))
stmt = select(t)

Выше stmt представляет собой оператор SELECT. Ошибка возникает, когда мы хотим использовать stmt непосредственно как предложение FROM в другом SELECT, например, если мы попытаемся выбрать из него:

new_stmt_1 = select(stmt)

Или если бы мы хотели использовать его в предложении FROM, например, в JOIN:

new_stmt_2 = select(some_table).select_from(some_table.join(stmt))

В предыдущих версиях SQLAlchemy при использовании SELECT внутри другого SELECT получался безымянный подзапрос, заключенный в круглые скобки. В большинстве случаев такая форма SQL не очень полезна, поскольку такие базы данных, как MySQL и PostgreSQL, требуют, чтобы подзапросы в предложениях FROM имели именованные псевдонимы, что означает использование метода SelectBase.alias() или, начиная с версии 1.4, метода SelectBase.subquery(). В других базах данных подзапрос должен иметь имя, чтобы устранить любую двусмысленность в будущих ссылках на имена столбцов внутри подзапроса.

Помимо вышеуказанных практических причин, существует множество других, ориентированных на SQLAlchemy, причин, по которым вносится это изменение. Поэтому правильная форма двух вышеприведенных утверждений требует использования SelectBase.subquery():

subq = stmt.subquery()

new_stmt_1 = select(subq)

new_stmt_2 = select(some_table).select_from(some_table.join(subq))

Для элемента raw clauseelement автоматически создается псевдоним¶

Добавлено в версии 1.4.26.

Это предупреждение об устаревании относится к очень старому и, вероятно, не очень известному шаблону, который применяется к унаследованному методу Query.join(), а также к методу 2.0 style Select.join(), где соединение может быть указано в терминах relationship(), но целью является Table или другой Core selectable, к которому сопоставлен класс, а не ORM-сущность, такая как сопоставленный класс или aliased() конструкция:

a1 = Address.__table__

q = (
    s.query(User)
    .join(a1, User.addresses)
    .filter(Address.email_address == "ed@foo.com")
    .all()
)

Приведенный выше шаблон также позволяет произвольно выбирать, например, объект Core Join или Alias, однако автоматическая адаптация этого элемента не предусмотрена, поэтому на элемент Core нужно будет ссылаться напрямую:

a1 = Address.__table__.alias()

q = (
    s.query(User)
    .join(a1, User.addresses)
    .filter(a1.c.email_address == "ed@foo.com")
    .all()
)

Правильным способом указания цели присоединения всегда является использование самого сопоставленного класса или объекта aliased, в последнем случае используется модификатор PropComparator.of_type() для установки псевдонима:

# normal join to relationship entity
q = s.query(User).join(User.addresses).filter(Address.email_address == "ed@foo.com")

# name Address target explicitly, not necessary but legal
q = (
    s.query(User)
    .join(Address, User.addresses)
    .filter(Address.email_address == "ed@foo.com")
)

Присоединитесь к псевдониму:

from sqlalchemy.orm import aliased

a1 = aliased(Address)

# of_type() form; recommended
q = (
    s.query(User)
    .join(User.addresses.of_type(a1))
    .filter(a1.email_address == "ed@foo.com")
)

# target, onclause form
q = s.query(User).join(a1, User.addresses).filter(a1.email_address == "ed@foo.com")

Псевдоним создается автоматически из-за перекрытия таблиц¶

Добавлено в версии 1.4.26.

Это предупреждение обычно выдается при запросе с использованием метода Select.join() или унаследованного метода Query.join() с отображениями, включающими объединенное наследование таблиц. Проблема заключается в том, что при соединении двух моделей наследования, имеющих общую базовую таблицу, правильное SQL JOIN между двумя сущностями не может быть сформировано без применения псевдонима к одной или другой стороне; SQLAlchemy применяет псевдоним к правой стороне соединения. Например, объединенное отображение наследования выглядит так:

class Employee(Base):
    __tablename__ = "employee"
    id = Column(Integer, primary_key=True)
    manager_id = Column(ForeignKey("manager.id"))
    name = Column(String(50))
    type = Column(String(50))

    reports_to = relationship("Manager", foreign_keys=manager_id)

    __mapper_args__ = {
        "polymorphic_identity": "employee",
        "polymorphic_on": type,
    }


class Manager(Employee):
    __tablename__ = "manager"
    id = Column(Integer, ForeignKey("employee.id"), primary_key=True)

    __mapper_args__ = {
        "polymorphic_identity": "manager",
        "inherit_condition": id == Employee.id,
    }

Приведенное выше отображение включает отношения между классами Employee и Manager. Поскольку оба класса используют таблицу базы данных «employee», с точки зрения SQL это self referential relationship. Если бы мы хотели сделать запрос из обеих моделей Employee и Manager с помощью объединения, на уровне SQL таблица «employee» должна быть включена в запрос дважды, что означает, что она должна быть алиасирована. Когда мы создаем такое соединение с помощью SQLAlchemy ORM, мы получаем SQL, который выглядит следующим образом:

>>> stmt = select(Employee, Manager).join(Employee.reports_to)
>>> print(stmt)

SELECT employee.id, employee.manager_id, employee.name, employee.type, manager_1.id AS id_1, employee_1.id AS id_2, employee_1.manager_id AS manager_id_1, employee_1.name AS name_1, employee_1.type AS type_1 FROM employee JOIN (employee AS employee_1 JOIN manager AS manager_1 ON manager_1.id = employee_1.id) ON manager_1.id = employee.manager_id

Выше, SQL выбирает FROM таблицу employee, представляющую сущность Employee в запросе. Затем он присоединяется к право-вложенному соединению employee AS employee_1 JOIN manager AS manager_1, где снова указывается таблица employee, только в качестве анонимного псевдонима employee_1. Это и есть «автоматическое создание псевдонима», на которое ссылается предупреждающее сообщение.

Когда SQLAlchemy загружает строки ORM, каждая из которых содержит объект Employee и Manager, ORM должен адаптировать строки из того, что выше является псевдонимами таблиц employee_1 и manager_1 в строки класса Manager без псевдонимов. Этот процесс внутренне сложен и не учитывает все возможности API, особенно при попытке использовать функции нетерпеливой загрузки, такие как contains_eager(), с более глубоко вложенными запросами, чем показано здесь. Поскольку этот шаблон ненадежен для более сложных сценариев и включает неявное принятие решений, которые трудно предугадать и выполнить, выдается предупреждение, и этот шаблон можно считать устаревшей функцией. Лучший способ написать этот запрос — использовать те же шаблоны, которые применяются к любым другим самореферентным отношениям, то есть явно использовать конструкцию aliased(). Для объединенного наследования и других сопоставлений, ориентированных на объединение, обычно желательно добавить использование параметра aliased.flat, который позволит объединить две или более таблиц путем применения псевдонима к отдельным таблицам внутри объединения, а не встраивать объединение в новый подзапрос:

>>> from sqlalchemy.orm import aliased
>>> manager_alias = aliased(Manager, flat=True)
>>> stmt = select(Employee, manager_alias).join(Employee.reports_to.of_type(manager_alias))
>>> print(stmt)

SELECT employee.id, employee.manager_id, employee.name, employee.type, manager_1.id AS id_1, employee_1.id AS id_2, employee_1.manager_id AS manager_id_1, employee_1.name AS name_1, employee_1.type AS type_1 FROM employee JOIN (employee AS employee_1 JOIN manager AS manager_1 ON manager_1.id = employee_1.id) ON manager_1.id = employee.manager_id

Если мы захотим использовать contains_eager() для заполнения атрибута reports_to, мы обратимся к псевдониму:

>>> stmt = (
...     select(Employee)
...     .join(Employee.reports_to.of_type(manager_alias))
...     .options(contains_eager(Employee.reports_to.of_type(manager_alias)))
... )

Без использования явного объекта aliased() в некоторых более вложенных случаях опция contains_eager() не имеет достаточного контекста, чтобы знать, откуда брать свои данные, в случае, если ORM осуществляет «автоалиасинг» в очень вложенном контексте. Поэтому лучше не полагаться на эту возможность и вместо этого сделать конструкцию SQL как можно более явной.

Объектно-реляционное отображение¶

Родительский экземпляр <x> не привязан к сессии; (ленивая загрузка/отложенная загрузка/обновление/и т.д.) операция не может быть выполнена¶

Это, вероятно, самое распространенное сообщение об ошибке при работе с ORM, и возникает оно в результате природы техники, широко используемой ORM, известной как lazy loading. Ленивая загрузка — это распространенный объектно-реляционный паттерн, при котором объект, сохраняемый ORM, поддерживает прокси к базе данных, так что при обращении к различным атрибутам объекта их значения могут быть получены из базы данных лениво. Преимуществом такого подхода является то, что объекты могут быть извлечены из базы данных без необходимости загрузки всех их атрибутов или связанных с ними данных сразу, а вместо этого только те данные, которые запрашиваются, могут быть доставлены в это время. Основной недостаток, по сути, является зеркальным отражением преимущества: если загружается множество объектов, для которых, как известно, во всех случаях требуется определенный набор данных, то загружать эти дополнительные данные по частям будет расточительно.

Еще одним недостатком ленивой загрузки, помимо обычных проблем эффективности, является то, что для продолжения ленивой загрузки объект должен оставаться связанным с сессией, чтобы можно было получить его состояние. Это сообщение об ошибке означает, что объект отсоединился от своего Session и его просят лениво загрузить данные из базы данных.

Наиболее распространенной причиной того, что объекты отделяются от своих Session, является закрытие сессии, обычно с помощью метода Session.close(). В дальнейшем к объектам будет осуществляться дальнейший доступ, очень часто в веб-приложениях, где они передаются серверному шаблонизатору и запрашиваются дополнительные атрибуты, которые он не может загрузить.

Устранение этой ошибки осуществляется с помощью следующих приемов:

  • Постарайтесь не иметь отсоединенных объектов; не закрывайте сессию преждевременно — Часто приложения закрывают транзакцию перед передачей связанных с ней объектов другой системе, которая затем выходит из строя из-за этой ошибки. Иногда транзакцию не нужно закрывать так скоро; пример — веб-приложение закрывает транзакцию до того, как представление будет отображено. Это часто делается во имя «корректности», но может рассматриваться как неправильное применение «инкапсуляции», поскольку этот термин относится к организации кода, а не к фактическим действиям. Шаблон, использующий объект ORM, использует proxy pattern, который сохраняет логику базы данных инкапсулированной от вызывающей стороны. Если Session можно держать открытым до тех пор, пока не закончится жизнь объектов, это лучший подход.

  • В противном случае загружайте все необходимое заранее — Очень часто невозможно держать транзакцию открытой, особенно в более сложных приложениях, которым необходимо передавать объекты другим системам, которые не могут работать в том же контексте, даже если они находятся в том же процессе. В этом случае приложение должно подготовиться к работе с объектами detached и попытаться использовать eager loading для обеспечения того, чтобы объекты имели все необходимое заранее.

  • А главное, установите expire_on_commit в False — При использовании отсоединенных объектов наиболее частой причиной того, что объекты нуждаются в повторной загрузке данных, является истечение срока их действия после последнего вызова Session.commit(). Это истечение не должно использоваться при работе с отсоединенными объектами; поэтому параметр Session.expire_on_commit должен быть установлен в False. Предотвращая истечение срока действия объектов вне транзакции, данные, которые были загружены, останутся в наличии и не будут подвергаться дополнительной ленивой загрузке при обращении к этим данным.

    Обратите также внимание, что метод Session.rollback() безоговорочно уничтожает все содержимое в Session и его также следует избегать в сценариях, не связанных с ошибками.

Транзакция этого сеанса была откатана из-за предыдущего исключения во время flush¶

Процесс flush в Session, описанный в Промывка, откатит транзакцию базы данных, если возникнет ошибка, для поддержания внутренней согласованности. Однако, как только это происходит, транзакция сессии становится «неактивной» и должна быть явно откачена вызывающим приложением, точно так же, как если бы не произошел сбой, ее нужно было бы явно зафиксировать.

Это распространенная ошибка при использовании ORM и обычно относится к приложению, которое еще не имеет правильного «обрамления» вокруг своих операций Session. Более подробная информация описана в FAQ по адресу «Транзакция этого сеанса была откатана из-за предыдущего исключения во время промывки». (или аналогично).

Для отношения <relationship> каскад delete-orphan обычно настраивается только на стороне «один» отношения один-ко-многим, но не на стороне «многие» отношения многие-к-одному или многие-ко-многим.¶

Эта ошибка возникает, когда параметр «delete-orphan» cascade установлен для отношения «многие-к-одному» или «многие-ко-многим», например:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)

    bs = relationship("B", back_populates="a")


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    # this will emit the error message when the mapper
    # configuration step occurs
    a = relationship("A", back_populates="bs", cascade="all, delete-orphan")


configure_mappers()

Выше, параметр «delete-orphan» для B.a указывает на намерение, что когда каждый объект B, ссылающийся на определенный A, удаляется, то A также должен быть удален. То есть, это выражает, что «сирота», который удаляется, будет объектом A, и он становится «сиротой», когда каждый B, который ссылается на него, удаляется.

Каскадная модель «delete-orphan» не поддерживает эту функциональность. Рассмотрение «сирот» производится только с точки зрения удаления одного объекта, который затем будет ссылаться на ноль или более объектов, которые теперь «осиротеют» в результате этого единственного удаления, что приведет к тому, что эти объекты также будут удалены. Другими словами, он предназначен только для отслеживания создания «сирот» на основе удаления одного и только одного «родительского» объекта на каждого сироту, что является естественным случаем в отношениях «один ко многим», когда удаление объекта на стороне «один» приводит к последующему удалению связанных с ним объектов на стороне «многие».

Приведенное выше отображение для поддержки этой функциональности вместо этого поместило бы параметр каскада на сторону «один-ко-многим», что выглядит следующим образом:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)

    bs = relationship("B", back_populates="a", cascade="all, delete-orphan")


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    a = relationship("A", back_populates="bs")

Если выражено намерение, что при удалении объекта A все объекты B, на которые он ссылается, также удаляются.

Далее в сообщении об ошибке предлагается использовать флаг relationship.single_parent. Этот флаг может быть использован для того, чтобы гарантировать, что отношение, которое может иметь много объектов, ссылающихся на определенный объект, на самом деле будет иметь только один объект, ссылающийся на него в одно время. Он используется для унаследованных или других менее идеальных схем баз данных, где отношения внешних ключей предполагают наличие «многих» коллекций, однако на практике только один объект будет фактически ссылаться на данный целевой объект в одно и то же время. Этот нестандартный сценарий можно продемонстрировать в терминах приведенного выше примера следующим образом:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)

    bs = relationship("B", back_populates="a")


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    a = relationship(
        "A",
        back_populates="bs",
        single_parent=True,
        cascade="all, delete-orphan",
    )

Приведенная выше конфигурация установит валидатор, который будет следить за тем, чтобы только один B мог быть связан с A одновременно в рамках отношения B.a:

>>> b1 = B()
>>> b2 = B()
>>> a1 = A()
>>> b1.a = a1
>>> b2.a = a1
sqlalchemy.exc.InvalidRequestError: Instance <A at 0x7eff44359350> is
already associated with an instance of <class '__main__.B'> via its
B.a attribute, and is only allowed a single parent.

Обратите внимание, что этот валидатор имеет ограниченную область применения и не предотвратит создание нескольких «родителей» в другом направлении. Например, он не обнаружит одинаковые установки в терминах A.bs:

>>> a1.bs = [b1, b2]
>>> session.add_all([a1, b1, b2])
>>> session.commit()

INSERT INTO a DEFAULT VALUES () INSERT INTO b (a_id) VALUES (?) (1,) INSERT INTO b (a_id) VALUES (?) (1,)

Однако в дальнейшем все пойдет не так, как ожидалось, поскольку каскад «delete-orphan» будет продолжать работать в терминах одного ведущего объекта, то есть если мы удалим любой из B объектов, то A будет удален. Другой B останется, и ORM обычно достаточно умна, чтобы установить атрибут внешнего ключа в NULL, но это обычно не то, что нужно:

>>> session.delete(b1)
>>> session.commit()

UPDATE b SET a_id=? WHERE b.id = ? (None, 2) DELETE FROM b WHERE b.id = ? (1,) DELETE FROM a WHERE a.id = ? (1,) COMMIT

Для всех вышеприведенных примеров аналогичная логика применима к вычислению отношений «многие-ко-многим»; если отношения «многие-ко-многим» устанавливают single_parent=True на одной стороне, эта сторона может использовать каскад «delete-orphan», однако это очень маловероятно, что кто-то действительно хочет этого, так как смысл отношений «многие-ко-многим» заключается в том, что может быть много объектов, ссылающихся на объект в любом направлении.

В целом, каскад «удаление-сирота» обычно применяется на «одной» стороне отношения «один-ко-многим» так, чтобы удалять объекты на «многих» сторонах, а не наоборот.

Изменено в версии 1.3.18: Текст сообщения об ошибке «delete-orphan» при использовании в отношениях «многие-к-одному» или «многие-ко-многим» был обновлен для большей наглядности.

Экземпляр <instance> уже связан с экземпляром <instance> через его атрибут <attribute>, и ему разрешено иметь только одного родителя.¶

Эта ошибка возникает, когда используется флаг relationship.single_parent, и в качестве «родителя» объекта назначается сразу несколько объектов.

Учитывая следующее отображение:

class A(Base):
    __tablename__ = "a"

    id = Column(Integer, primary_key=True)


class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(ForeignKey("a.id"))

    a = relationship(
        "A",
        single_parent=True,
        cascade="all, delete-orphan",
    )

Намерение указывает, что не более одного объекта B может одновременно ссылаться на определенный объект A:

>>> b1 = B()
>>> b2 = B()
>>> a1 = A()
>>> b1.a = a1
>>> b2.a = a1
sqlalchemy.exc.InvalidRequestError: Instance <A at 0x7eff44359350> is
already associated with an instance of <class '__main__.B'> via its
B.a attribute, and is only allowed a single parent.

Когда эта ошибка возникает неожиданно, обычно это происходит потому, что флаг relationship.single_parent был применен в ответ на сообщение об ошибке, описанное в Для отношения <relationship> каскад delete-orphan обычно настраивается только на стороне «один» отношения один-ко-многим, но не на стороне «многие» отношения многие-к-одному или многие-ко-многим., и проблема на самом деле заключается в неправильном понимании настройки каскада «delete-orphan». Подробности см. в этом сообщении.

отношение X скопирует столбец Q в столбец P, что противоречит отношению(ям): „Y“¶

Это предупреждение относится к случаю, когда два или более отношения будут записывать данные в одни и те же столбцы на флеше, но ORM не имеет никаких средств для координации этих отношений вместе. В зависимости от специфики, решение может заключаться в том, что два отношения должны быть направлены друг к другу с помощью relationship.back_populates, или что одно или несколько отношений должны быть сконфигурированы с relationship.viewonly для предотвращения конфликтующих записей, или иногда, что конфигурация полностью преднамеренна и должна быть сконфигурирована relationship.overlaps, чтобы заглушить каждое предупреждение.

Для типичного примера, в котором отсутствует relationship.back_populates, учитывая следующее отображение:

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    children = relationship("Child")


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey("parent.id"))
    parent = relationship("Parent")

Приведенное выше отображение будет генерировать предупреждения:

SAWarning: relationship 'Child.parent' will copy column parent.id to column child.parent_id,
which conflicts with relationship(s): 'Parent.children' (copies parent.id to child.parent_id).

Отношения Child.parent и Parent.children находятся в конфликте. Решением является применение relationship.back_populates:

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    children = relationship("Child", back_populates="parent")


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey("parent.id"))
    parent = relationship("Parent", back_populates="children")

Для более настраиваемых отношений, где ситуация «перекрытия» может быть преднамеренной и не может быть разрешена, параметр relationship.overlaps может указывать имена отношений, для которых предупреждение не должно действовать. Обычно это происходит для двух или более отношений к одной и той же базовой таблице, которые включают пользовательские условия relationship.primaryjoin, ограничивающие связанные элементы в каждом случае:

class Parent(Base):
    __tablename__ = "parent"
    id = Column(Integer, primary_key=True)
    c1 = relationship(
        "Child",
        primaryjoin="and_(Parent.id == Child.parent_id, Child.flag == 0)",
        backref="parent",
        overlaps="c2, parent",
    )
    c2 = relationship(
        "Child",
        primaryjoin="and_(Parent.id == Child.parent_id, Child.flag == 1)",
        overlaps="c1, parent",
    )


class Child(Base):
    __tablename__ = "child"
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey("parent.id"))

    flag = Column(Integer)

Выше, ORM будет знать, что перекрытие между Parent.c1, Parent.c2 и Child.parent является намеренным.

Объект не может быть преобразован в «постоянное» состояние, так как эта карта идентификации больше не действительна.¶

Добавлено в версии 1.4.26.

Это сообщение было добавлено, чтобы учесть случай, когда объект Result, который мог бы выдать объекты ORM, итерируется после того, как исходный Session был закрыт или иным образом был вызван его метод Session.expunge_all(). Когда Session изгоняет все объекты сразу, внутренний identity map, используемый этим Session, заменяется новым, а исходный отбрасывается. Непоглощенный и небуферизованный объект Result будет внутренне поддерживать ссылку на эту удаленную карту идентичности. Поэтому, когда Result будет потреблен, объекты, которые будут получены, не смогут быть связаны с этим Session. Такая схема предусмотрена, поскольку обычно не рекомендуется итерировать небуферизованный объект Result вне транзакционного контекста, в котором он был создан:

# context manager creates new Session
with Session(engine) as session_obj:
    result = sess.execute(select(User).where(User.id == 7))

# context manager is closed, so session_obj above is closed, identity
# map is replaced

# iterating the result object can't associate the object with the
# Session, raises this error.
user = result.first()

Приведенная выше ситуация обычно **не ** возникает при использовании расширения asyncio ORM, поскольку когда AsyncSession возвращает синхронизированный Result, результаты были предварительно забуферизированы во время выполнения оператора. Это сделано для того, чтобы вторичные нетерпеливые загрузчики могли вызываться без необходимости дополнительного вызова await.

Для предварительной буферизации результатов в описанной выше ситуации с помощью обычного Session так же, как это делает расширение asyncio, можно использовать опцию выполнения prebuffer_rows следующим образом:

# context manager creates new Session
with Session(engine) as session_obj:

    # result internally pre-fetches all objects
    result = sess.execute(
        select(User).where(User.id == 7), execution_options={"prebuffer_rows": True}
    )

# context manager is closed, so session_obj above is closed, identity
# map is replaced

# pre-buffered objects are returned
user = result.first()

# however they are detached from the session, which has been closed
assert inspect(user).detached
assert inspect(user).session is None

Выше, выбранные объекты ORM полностью генерируются внутри блока session_obj, ассоциируются с session_obj и буферизируются внутри объекта Result для итерации. За пределами блока session_obj закрывается и удаляет эти объекты ORM. Итерация объекта Result приведет к появлению этих ORM-объектов, однако, поскольку их исходный Session был исключен, они будут доставлены в состоянии detached.

Примечание

Приведенная выше ссылка на «предварительно буферизованный» и «небуферизованный» объект Result относится к процессу, посредством которого ORM преобразует входящие необработанные строки базы данных из DBAPI в объекты ORM. Это не подразумевает, является ли сам объект cursor, который представляет ожидающие результаты от DBAPI, буферизованным или небуферизованным, поскольку это, по сути, нижний уровень буферизации. О буферизации самих результатов cursor см. раздел Использование курсоров на стороне сервера (они же потоковые результаты).

Исключения AsyncIO¶

AwaitRequired¶

Асинхронный режим SQLAlchemy требует использования асинхронного драйвера для подключения к базе данных. Эта ошибка обычно возникает при попытке использовать асинхронную версию SQLAlchemy с несовместимым DBAPI.

MissingGreenlet¶

Вызов async DBAPI был инициирован вне контекста спавна гринлета, обычно устанавливаемого прокси-классами SQLAlchemy AsyncIO. Обычно эта ошибка возникает, когда ввод-вывод был предпринят в неожиданном месте, без использования предоставленного async api. При использовании ORM это может быть связано с попыткой ленивой загрузки, которая не поддерживается при использовании SQLAlchemy с диалектами AsyncIO.

Осмотр не доступен¶

Использование функции inspect() непосредственно на объекте AsyncConnection или AsyncEngine в настоящее время не поддерживается, поскольку еще не существует ожидаемой формы объекта Inspector. Вместо этого объект используется путем его получения с помощью функции inspect() таким образом, что она ссылается на базовый атрибут AsyncConnection.sync_connection объекта AsyncConnection; затем объект Inspector используется в «синхронном» стиле вызова с помощью метода AsyncConnection.run_sync() вместе с пользовательской функцией, выполняющей нужные операции:

async def async_main():
    async with engine.connect() as conn:
        tables = await conn.run_sync(
            lambda sync_conn: inspect(sync_conn).get_table_names()
        )

Основные классы исключений¶

Классы исключений Core см. в Основные исключения.

Классы исключений ORM¶

Классы исключений ORM см. в Исключения ORM.

Исключения из наследия¶

Исключения в этом разделе не генерируются текущими версиями SQLAlchemy, однако приведены здесь, чтобы соответствовать гиперссылкам на сообщения об исключениях.

Функция <somome function> в SQLAlchemy 2.0 больше не будет <something¶

SQLAlchemy 2.0 представляет собой значительные изменения для широкого спектра ключевых моделей использования SQLAlchemy в компонентах Core и ORM. Цель релиза 2.0 — внести небольшие изменения в некоторые из наиболее фундаментальных предположений SQLAlchemy с момента ее зарождения и предоставить новую оптимизированную модель использования, которая, как ожидается, будет значительно более минималистичной и последовательной между компонентами Core и ORM, а также более функциональной.

Представленный в Переход на SQLAlchemy 2.0, проект SQLAlchemy 2.0 включает в себя комплексную систему будущей совместимости, интегрированную в серию SQLAlchemy 1.4, благодаря которой приложения будут иметь четкий, однозначный и постепенный путь обновления, чтобы перевести приложения на полную совместимость с 2.0. Предупреждение об устаревании RemovedIn20Warning лежит в основе этой системы, чтобы предоставить рекомендации о том, какое поведение в существующей кодовой базе необходимо изменить. Обзор того, как включить это предупреждение, находится в SQLAlchemy 2.0 Deprecations Mode.

Объект объединяется в сессию по каскаду обратных ссылок¶

Это сообщение относится к поведению «каскада обратных ссылок» в SQLAlchemy, удаленному в версии 2.0. Это относится к действию, когда объект добавляется в Session в результате того, что другой объект, который уже присутствует в этой сессии, ассоциируется с ним. Поскольку было показано, что такое поведение больше запутывает, чем помогает, были добавлены параметры relationship.cascade_backrefs и backref.cascade_backrefs, которые можно установить в False, чтобы отключить его, а в SQLAlchemy 2.0 поведение «каскадных обратных ссылок» было полностью удалено.

Для старых версий SQLAlchemy, чтобы установить relationship.cascade_backrefs в False на обратную ссылку, которая в настоящее время настроена с помощью строкового параметра relationship.backref, обратная ссылка должна быть сначала объявлена с помощью функции backref(), чтобы можно было передать параметр backref.cascade_backrefs.

В качестве альтернативы, все поведение «каскадных обратных ссылок» можно отключить, используя Session в режиме «будущего», передавая True для параметра Session.future.

конструкция select(), созданная в «унаследованном» режиме; аргументы ключевых слов и т.д.¶

Конструкция select() была обновлена в SQLAlchemy 1.4 для поддержки нового стиля вызова, который является стандартным в SQLAlchemy 2.0. Для обратной совместимости в рамках серии 1.4 конструкция принимает аргументы как в «старом», так и в «новом» стиле.

Особенностью «нового» стиля является то, что выражения столбцов и таблиц передаются только позиционно в конструкцию select(); любые другие модификаторы объекта должны передаваться с помощью последующей цепочки методов:

# this is the way to do it going forward
stmt = select(table1.c.myid).where(table1.c.myid == table2.c.otherid)

Для сравнения, select() в устаревших формах SQLAlchemy, до того как были добавлены такие методы, как Select.where(), имел вид:

# this is how it was documented in original SQLAlchemy versions
# many years ago
stmt = select([table1.c.myid], whereclause=table1.c.myid == table2.c.otherid)

Или даже то, что «whereclause» будет передаваться позиционно:

# this is also how it was documented in original SQLAlchemy versions
# many years ago
stmt = select([table1.c.myid], table1.c.myid == table2.c.otherid)

Уже несколько лет как дополнительные «whereclause» и другие принимаемые аргументы были удалены из большинства описательной документации, что привело к стилю вызова, который наиболее знаком как список аргументов столбцов, передаваемых в виде списка, но без дополнительных аргументов:

# this is how it's been documented since around version 1.0 or so
stmt = select([table1.c.myid]).where(table1.c.myid == table2.c.otherid)

Документ по адресу select() больше не принимает разнообразные аргументы конструктора, столбцы передаются позиционно описывает это изменение в терминах 2.0 Migration.

Привязка была найдена через унаследованные метаданные привязки, но поскольку для этой сессии установлено future=True, эта привязка игнорируется.¶

Концепция «связанных метаданных» присутствует вплоть до версии SQLAlchemy 1.4; начиная с версии SQLAlchemy 2.0 она была удалена.

Эта ошибка относится к параметру MetaData.bind на объекте MetaData, который, в свою очередь, позволяет объектам типа ORM Session связывать определенный сопоставленный класс с Engine. В SQLAlchemy 2.0 Session должен быть связан с каждым Engine напрямую. То есть, вместо инстанцирования Session или sessionmaker без каких-либо аргументов и связывания Engine с MetaData:

engine = create_engine("sqlite://")
Session = sessionmaker()
metadata_obj = MetaData(bind=engine)
Base = declarative_base(metadata=metadata_obj)

class MyClass(Base):
    # ...


session = Session()
session.add(MyClass())
session.commit()

Вместо этого Engine должен быть связан непосредственно с sessionmaker или Session. Объект MetaData больше не должен быть связан ни с каким двигателем:

engine = create_engine("sqlite://")
Session = sessionmaker(engine)
Base = declarative_base()

class MyClass(Base):
    # ...


session = Session()
session.add(MyClass())
session.commit()

В SQLAlchemy 1.4 это поведение 2.0 style включено, когда флаг Session.future установлен на sessionmaker или Session.

Этот скомпилированный объект не привязан ни к одному движку или соединению¶

Эта ошибка связана с концепцией «связанных метаданных», которая является унаследованным шаблоном SQLAlchemy, присутствующим только в версиях 1.x. Проблема возникает, когда вызывается метод Executable.execute() непосредственно из объекта выражения Core, который не связан ни с каким Engine:

metadata_obj = MetaData()
table = Table("t", metadata_obj, Column("q", Integer))

stmt = select(table)
result = stmt.execute()  # <--- raises

Логика ожидает, что объект MetaData был связан с объектом Engine:

engine = create_engine("mysql+pymysql://user:pass@host/db")
metadata_obj = MetaData(bind=engine)

Там, где указано выше, любое утверждение, вытекающее из Table, которое в свою очередь вытекает из MetaData, будет неявно использовать данное Engine для вызова утверждения.

Обратите внимание, что концепция связанных метаданных отсутствует в SQLAlchemy 2.0. Правильный способ вызова утверждений — через метод Connection.execute() в Connection:

with engine.connect() as conn:
    result = conn.execute(stmt)

При использовании ORM аналогичная возможность доступна через Session:

result = session.execute(stmt)

Это соединение находится в неактивной транзакции. Пожалуйста, выполните полный откат(), прежде чем продолжить¶

Это состояние ошибки было добавлено в SQLAlchemy начиная с версии 1.4 и не относится к SQLAlchemy 2.0. Ошибка относится к состоянию, когда транзакция Connection помещается в транзакцию с помощью метода типа Connection.begin(), а затем в этой области создается еще одна «маркерная» транзакция; затем «маркерная» транзакция сворачивается с помощью Transaction.rollback() или закрывается с помощью Transaction.close(), однако внешняя транзакция все еще находится в «неактивном» состоянии и должна быть свернута.

Схема выглядит следующим образом:

engine = create_engine(...)

connection = engine.connect()
transaction1 = connection.begin()

# this is a "sub" or "marker" transaction, a logical nesting
# structure based on "real" transaction transaction1
transaction2 = connection.begin()
transaction2.rollback()

# transaction1 is still present and needs explicit rollback,
# so this will raise
connection.execute(text("select 1"))

Выше, transaction2 — это «маркерная» транзакция, которая указывает на логическую вложенность транзакций внутри внешней транзакции; в то время как внутренняя транзакция может откатить всю транзакцию через свой метод rollback(), ее метод commit() не имеет никакого эффекта, кроме закрытия области действия самой «маркерной» транзакции. Вызов transaction2.rollback() имеет эффект деактивации транзакции1, что означает ее откат на уровне базы данных, однако она все еще присутствует, чтобы обеспечить последовательную схему вложенности транзакций.

Правильным решением является обеспечение отката внешней транзакции:

Этот шаблон не часто используется в Core. В ORM может возникнуть аналогичная проблема, которая является результатом «логической» структуры транзакций ORM; она описана в FAQ по адресу «Транзакция этого сеанса была откатана из-за предыдущего исключения во время промывки». (или аналогично).

Шаблон «субтранзакция» удален в SQLAlchemy 2.0, так что этот конкретный шаблон программирования больше не будет доступен, предотвращая появление этого сообщения об ошибке.

To get type of exception, you can simply call :

Firstly, import exc from sqlalchemy

from sqlalchemy import exc

To catch types of errors:

    try:
        # any query
    except exc.SQLAlchemyError as e:
        print(type(e))

This will give you exception type:
Output:

<class 'sqlalchemy.exc.IntegrityError'>
<class 'sqlalchemy.exc.IntegrityError'>

Your example says:

status = db.query("INSERT INTO users ...")
if (!status):
    raise Error, db.error

That seems to mean that you want to raise an exception if there’s some error on the query (with raise Error, db.error). However sqlalchemy already does that for you — so

user = User('Boda Cydo')
session.add(user)
session.commit()

Is just the same. The check-and-raise part is already inside SQLAlchemy.

Here is a list of the errors sqlalchemy itself can raise, taken from help(sqlalchemy.exc) and help(sqlalchemy.orm.exc):

  • sqlalchemy.exc:
    • ArgumentError — Raised when an invalid or conflicting function argument is supplied.
      This error generally corresponds to construction time state errors.
    • CircularDependencyError — Raised by topological sorts when a circular dependency is detected
    • CompileError — Raised when an error occurs during SQL compilation
    • ConcurrentModificationError
    • DBAPIError — Raised when the execution of a database operation fails.
      If the error-raising operation occured in the execution of a SQL
      statement, that statement and its parameters will be available on
      the exception object in the statement and params attributes.
      The wrapped exception object is available in the orig attribute.
      Its type and properties are DB-API implementation specific.
    • DataError Wraps a DB-API DataError.
    • DatabaseError — Wraps a DB-API DatabaseError.
    • DisconnectionError — A disconnect is detected on a raw DB-API connection.
      be raised by a PoolListener so that the host pool forces a disconnect.
    • FlushError
    • IdentifierError — Raised when a schema name is beyond the max character limit
    • IntegrityError — Wraps a DB-API IntegrityError.
    • InterfaceError — Wraps a DB-API InterfaceError.
    • InternalError — Wraps a DB-API InternalError.
    • InvalidRequestError — SQLAlchemy was asked to do something it can’t do. This error generally corresponds to runtime state errors.
    • NoReferenceError — Raised by ForeignKey to indicate a reference cannot be resolved.
    • NoReferencedColumnError — Raised by ForeignKey when the referred Column cannot be located.
    • NoReferencedTableError — Raised by ForeignKey when the referred Table cannot be located.
    • NoSuchColumnError — A nonexistent column is requested from a RowProxy.
    • NoSuchTableError — Table does not exist or is not visible to a connection.
    • NotSupportedError — Wraps a DB-API NotSupportedError.
    • OperationalError — Wraps a DB-API OperationalError.
    • ProgrammingError — Wraps a DB-API ProgrammingError.
    • SADeprecationWarning — Issued once per usage of a deprecated API.
    • SAPendingDeprecationWarning — Issued once per usage of a deprecated API.
    • SAWarning — Issued at runtime.
    • SQLAlchemyError — Generic error class.
    • SQLError — Raised when the execution of a database operation fails.
    • TimeoutError — Raised when a connection pool times out on getting a connection.
    • UnboundExecutionError — SQL was attempted without a database connection to execute it on.
    • UnmappedColumnError
  • sqlalchemy.orm.exc:
    • ConcurrentModificationError — Rows have been modified outside of the unit of work.
    • FlushError — A invalid condition was detected during flush().
    • MultipleResultsFound — A single database result was required but more than one were found.
    • NoResultFound — A database result was required but none was found.
    • ObjectDeletedError — A refresh() operation failed to re-retrieve an object’s row.
    • UnmappedClassError — A mapping operation was requested for an unknown class.
    • UnmappedColumnError — Mapping operation was requested on an unknown column.
    • UnmappedError — TODO
    • UnmappedInstanceError — A mapping operation was requested for an unknown instance.

I tried this and it showed me the specific error message.

from sqlalchemy.exc import SQLAlchemyError

try:
# try something

except SQLAlchemyError as e:
  error = str(e.__dict__['orig'])
  return error

Hope this helps

Tags:

Python

Sqlalchemy

Related

Exceptions used with SQLAlchemy.

The base exception class is SQLAlchemyError. Exceptions which are
raised as a result of DBAPI exceptions are all subclasses of
DBAPIError.

exception sqlalchemy.exc.AmbiguousForeignKeysError

Raised when more than one foreign key matching can be located
between two selectables during a join.

exception sqlalchemy.exc.ArgumentError

Raised when an invalid or conflicting function argument is supplied.

This error generally corresponds to construction time state errors.

exception sqlalchemy.exc.CircularDependencyError(message, cycles, edges, msg=None)

Raised by topological sorts when a circular dependency is detected.

There are two scenarios where this error occurs:

  • In a Session flush operation, if two objects are mutually dependent
    on each other, they can not be inserted or deleted via INSERT or
    DELETE statements alone; an UPDATE will be needed to post-associate
    or pre-deassociate one of the foreign key constrained values.
    The post_update flag described at Rows that point to themselves / Mutually Dependent Rows can resolve
    this cycle.
  • In a MetaData.sorted_tables operation, two ForeignKey
    or ForeignKeyConstraint objects mutually refer to each
    other. Apply the use_alter=True flag to one or both,
    see Creating/Dropping Foreign Key Constraints via ALTER.
exception sqlalchemy.exc.CompileError

Raised when an error occurs during SQL compilation

exception sqlalchemy.exc.DBAPIError(statement, params, orig, connection_invalidated=False)

Raised when the execution of a database operation fails.

Wraps exceptions raised by the DB-API underlying the
database operation. Driver-specific implementations of the standard
DB-API exception types are wrapped by matching sub-types of SQLAlchemy’s
DBAPIError when possible. DB-API’s Error type maps to
DBAPIError in SQLAlchemy, otherwise the names are identical. Note
that there is no guarantee that different DB-API implementations will
raise the same exception type for any given error condition.

DBAPIError features statement
and params attributes which supply context
regarding the specifics of the statement which had an issue, for the
typical case when the error was raised within the context of
emitting a SQL statement.

The wrapped exception object is available in the
orig attribute. Its type and properties are
DB-API implementation specific.

exception sqlalchemy.exc.DataError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API DataError.

exception sqlalchemy.exc.DatabaseError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API DatabaseError.

exception sqlalchemy.exc.DisconnectionError

A disconnect is detected on a raw DB-API connection.

This error is raised and consumed internally by a connection pool. It can
be raised by the PoolEvents.checkout() event so that the host pool
forces a retry; the exception will be caught three times in a row before
the pool gives up and raises InvalidRequestError
regarding the connection attempt.

class sqlalchemy.exc.DontWrapMixin

A mixin class which, when applied to a user-defined Exception class,
will not be wrapped inside of StatementError if the error is
emitted within the process of executing a statement.

E.g.:

from sqlalchemy.exc import DontWrapMixin

class MyCustomException(Exception, DontWrapMixin):
    pass

class MySpecialType(TypeDecorator):
    impl = String

    def process_bind_param(self, value, dialect):
        if value == 'invalid':
            raise MyCustomException("invalid!")
exception sqlalchemy.exc.IdentifierError

Raised when a schema name is beyond the max character limit

exception sqlalchemy.exc.IntegrityError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API IntegrityError.

exception sqlalchemy.exc.InterfaceError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API InterfaceError.

exception sqlalchemy.exc.InternalError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API InternalError.

exception sqlalchemy.exc.InvalidRequestError

SQLAlchemy was asked to do something it can’t do.

This error generally corresponds to runtime state errors.

exception sqlalchemy.exc.NoForeignKeysError

Raised when no foreign keys can be located between two selectables
during a join.

exception sqlalchemy.exc.NoInspectionAvailable

A subject passed to sqlalchemy.inspection.inspect() produced
no context for inspection.

exception sqlalchemy.exc.NoReferenceError

Raised by ForeignKey to indicate a reference cannot be resolved.

exception sqlalchemy.exc.NoReferencedColumnError(message, tname, cname)

Raised by ForeignKey when the referred Column cannot be
located.

exception sqlalchemy.exc.NoReferencedTableError(message, tname)

Raised by ForeignKey when the referred Table cannot be
located.

exception sqlalchemy.exc.NoSuchColumnError

A nonexistent column is requested from a RowProxy.

exception sqlalchemy.exc.NoSuchModuleError

Raised when a dynamically-loaded module (usually a database dialect)
of a particular name cannot be located.

exception sqlalchemy.exc.NoSuchTableError

Table does not exist or is not visible to a connection.

exception sqlalchemy.exc.NotSupportedError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API NotSupportedError.

exception sqlalchemy.exc.OperationalError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API OperationalError.

exception sqlalchemy.exc.ProgrammingError(statement, params, orig, connection_invalidated=False)

Wraps a DB-API ProgrammingError.

exception sqlalchemy.exc.ResourceClosedError

An operation was requested from a connection, cursor, or other
object that’s in a closed state.

exception sqlalchemy.exc.SADeprecationWarning

Issued once per usage of a deprecated API.

exception sqlalchemy.exc.SAPendingDeprecationWarning

Issued once per usage of a deprecated API.

exception sqlalchemy.exc.SAWarning

Issued at runtime.

exception sqlalchemy.exc.SQLAlchemyError

Generic error class.

exception sqlalchemy.exc.StatementError(message, statement, params, orig)

An error occurred during execution of a SQL statement.

StatementError wraps the exception raised
during execution, and features statement
and params attributes which supply context regarding
the specifics of the statement which had an issue.

The wrapped exception object is available in
the orig attribute.

orig = None

The DBAPI exception object.

params = None

The parameter list being used when this exception occurred.

statement = None

The string SQL statement being invoked when this exception occurred.

exception sqlalchemy.exc.TimeoutError

Raised when a connection pool times out on getting a connection.

exception sqlalchemy.exc.UnboundExecutionError

SQL was attempted without a database connection to execute it on.

exception sqlalchemy.exc.UnsupportedCompilationError(compiler, element_type)

Raised when an operation is not supported by the given compiler.

버전 0.8.3에 추가.

Here are the examples of the python api sqlalchemy.exc.SQLAlchemyError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.


4

Example 1

  def save_import(self):
    """Commit all changes in the session and update memcache."""
    try:
      modified_objects = get_modified_objects(db.session)
      import_event = log_event(db.session, None)
      update_memcache_before_commit(
          self, modified_objects, CACHE_EXPIRY_IMPORT)
      db.session.commit()
      update_memcache_after_commit(self)
      update_index(db.session, modified_objects)
      return import_event
    except exc.SQLAlchemyError as err:
      db.session.rollback()
      logger.exception("Import failed with: %s", err.message)
      self.add_errors(errors.UNKNOWN_ERROR, line=self.offset + 2)


4

Example 2

def execute(q: QueryType) -> List[Any]:
    """Query the database and convert the objects to HA native form.

    This method also retries a few times in the case of stale connections.
    """
    import sqlalchemy.exc
    try:
        for _ in range(0, RETRIES):
            try:
                return [
                    row for row in
                    (row.to_native() for row in q)
                    if row is not None]
            except sqlalchemy.exc.SQLAlchemyError as e:
                log_error(e, retry_wait=QUERY_RETRY_WAIT, rollback=True)
    finally:
        Session.close()
    return []


3

Example 3

  def import_secondary_objects(self, slugs_dict):
    for row_converter in self.row_converters:
      row_converter.setup_secondary_objects(slugs_dict)

    if not self.converter.dry_run:
      for row_converter in self.row_converters:
        try:
          row_converter.insert_secondary_objects()
        except exc.SQLAlchemyError as err:
          db.session.rollback()
          logger.exception("Import failed with: %s", err.message)
          row_converter.add_error(errors.UNKNOWN_ERROR)
      self.save_import()


3

Example 4

    def load_raw_sql(self, directory):
        self.logger.debug('trying to load raw sql with dir %s' % directory)
        sqlfile_path = os.path.normpath(os.path.join(
            __file__,
            '..',
            'raw_sql',
            directory,
            '*.sql'
        ))
        for myfile in sorted(glob(sqlfile_path)):
            self.logger.debug('trying to load file %s' % myfile)
            raw_sql = open(myfile).read()
            try:
                self.session.execute(raw_sql)
            except exc.SQLAlchemyError, e:
                self.logger.error("Something went horribly wrong: %s" % e)
                raise
        return True


3

Example 5

@contextmanager
def _sqlalchemy_error():
    # Todo(sampath): get the log handler and log out the error
    try:
        yield
    except dbexc.SQLAlchemyError, e:
        raise e


3

Example 6

@app.route('/check_worker_status', methods=['GET'])
def check_worker_status():
    ''' Check worker status route '''
    if 'workerId' not in request.args:
        resp = {"status": "bad request"}
        return jsonify(**resp)
    else:
        worker_id = request.args['workerId']
        try:
            part = Participant.query.
                filter(Participant.workerid == worker_id).one()
            status = part.status
        except exc.SQLAlchemyError:
            status = NOT_ACCEPTED
        resp = {"status" : status}
        return jsonify(**resp)


3

Example 7

    @mock.patch.object(models.Project, 'delete',
                       side_effect=sqlalchemy.exc.SQLAlchemyError)
    def test_delete_project_entities_alchemy_error_suppress_exception_true(
            self, mock_entity_delete):
        self._init_memory_db_setup()

        secret = self._create_secret_for_project(self.project1_data)
        self.assertIsNotNone(secret)

        project1_id = self.project1_data.id
        # sqlalchemy error is suppressed here
        no_error = self.project_repo.delete_project_entities(
            project1_id, suppress_exception=True)
        self.assertIsNone(no_error)


3

Example 8

    @mock.patch.object(models.Project, 'delete',
                       side_effect=sqlalchemy.exc.SQLAlchemyError)
    def test_delete_project_entities_alchemy_error_suppress_exception_false(
            self, mock_entity_delete):
        self._init_memory_db_setup()

        secret = self._create_secret_for_project(self.project1_data)
        self.assertIsNotNone(secret)

        project1_id = self.project1_data.id
        # sqlalchemy error is not suppressed here
        self.assertRaises(exception.BarbicanException,
                          self.project_repo.delete_project_entities,
                          project1_id, suppress_exception=False)


2

Example 9

    def query(self, statement, *args, **kwargs):
        statement = self.prepare(statement, kwargs.pop('escape', False))
        try:
            return self.connection.execute(statement, *args, **kwargs)
        except exc.SQLAlchemyError as e:
            raise DBError(str(e))


0

Example 10

    def archive(self, item):
        # crawl and handle archive pages
        input_data = {
            'url': item['url'],
            'country': 'US',
            'obey_robots': True,
        }

        response_data = self.api_request('fetch', input_data)
        if response_data['response'] == 599:
            # this happens from time to time with Fetch. still got some bugs to work out!
            raise APIException('Fetchcore screwed up.')
        if response_data['response'] >= 400:
            # BuzzFeed has failed us
            raise BuzzfeedException('Received %d HTTP error from Buzzfeed.' % response_data['response'])
        
        # parse the HTML into a tree for analysis
        tree = html.fromstring(response_data['content'].encode('utf-8'))
        tree.make_links_absolute(item['url'])

        # get a list of all articles listed on the page
        articles = tree.xpath('//ul[contains(@class, "flow")]/li/a')
        articles_and_items = []

        # for each article, extract useful information, create a database item, and create a queue task
        for a in articles:
            title = a.text_content().strip()
            url = a.get('href')
            new_item = {
                'function': 'article',
                'url': str(url),
            }
            article = BuzzfeedArticle(
                crawl_index=self.crawl_index,
                posted=item['date'],
                title=title,
                url=str(url),
            )
            self.session.add(article)

            articles_and_items.append((article, new_item))

        # write the new rows to the database
        try:
            self.session.commit()
        except exc.SQLAlchemyError as e:
            self.session.rollback()
            print 'Failed to commit BuzzfeedArticles to database - %s: %s' % (e.__class__.__name__, e)
            return

        # put the new tasks on the queue (which we only want to do if the database commit went okay)
        for article,new_item in articles_and_items:
            new_item['article_id'] = article.id
            self.queue.put(new_item)


0

Example 11

    def article(self, item):
        # crawl and handle article pages
        input_data = {
            'url': item['url'],
            'country': 'US',
            'obey_robots': True,
        }

        response_data = self.api_request('fetch', input_data)
        if response_data['response'] == 599:
            # this happens from time to time with Fetch. still got some bugs to work out!
            raise APIException('Fetchcore screwed up.')
        if response_data['response'] >= 400:
            # BuzzFeed has failed us
            raise BuzzfeedException('Received %d HTTP error from Buzzfeed.' % response_data['response'])

        # parse the HTML into a tree for analysis
        tree = html.fromstring(response_data['content'].encode('utf-8'))
        tree.make_links_absolute(item['url'])

        # get a list of all attribution strings on the article page
        attribution_elements = tree.xpath('//*[contains(@class, "sub_buzz_source_via") or contains(@class, "sub_buzz_grid_source_via")]')

        # get the database row corresponding to the article we're currently crawling
        article = self.session.query(BuzzfeedArticle).filter(BuzzfeedArticle.id == item['article_id']).scalar()
        input_data = {
            'url': item['url'],
        }

        # send a social request to get sharing stats for this article
        response_data = self.api_request('social', input_data)
        article.social = response_data
        self.session.add(article)

        sources_and_links = []

        # for each attribution element, extract the source text and links
        for e in attribution_elements:
            links = e.xpath('.//a/@href')
            source_text = e.text_content().strip()
            source = BuzzfeedSource(
                crawl_index=self.crawl_index,
                text=source_text,
                article_id=item['article_id'],
            )
            self.session.add(source)
            sources_and_links.append((source, links))

        # commit the sources to the database
        try:
            self.session.commit()
        except exc.SQLAlchemyError as e:
            self.session.rollback()
            print 'Failed to commit BuzzfeedSources to database - %s: %s' % (e.__class__.__name__, e)
            return

        # for each link in each source, create a link database item
        for source,links in sources_and_links:
            for link in links:
                buzzfeed_link = BuzzfeedLink(
                    crawl_index=self.crawl_index,
                    source_id=source.id,
                    url=str(link),
                )
                self.session.add(buzzfeed_link)

        # commit the links to the database
        try:
            self.session.commit()
        except exc.SQLAlchemyError as e:
            self.session.rollback()
            print 'Failed to commit BuzzfeedLinks to database - %s: %s' % (e.__class__.__name__, e)
            return


0

Example 12

def init_database(connection_url, extra_init=False):
	"""
	Create and initialize the database engine. This must be done before the
	session object can be used. This will also attempt to perform any updates to
	the database schema if the backend supports such operations.

	:param str connection_url: The url for the database connection.
	:param bool extra_init: Run optional extra dbms-specific initialization logic.
	:return: The initialized database engine.
	"""
	connection_url = normalize_connection_url(connection_url)
	connection_url = sqlalchemy.engine.url.make_url(connection_url)
	logger.info("initializing database connection with driver {0}".format(connection_url.drivername))
	if connection_url.drivername == 'sqlite':
		engine = sqlalchemy.create_engine(connection_url, connect_args={'check_same_thread': False}, poolclass=sqlalchemy.pool.StaticPool)
		sqlalchemy.event.listens_for(engine, 'begin')(lambda conn: conn.execute('BEGIN'))
	elif connection_url.drivername == 'postgresql':
		if extra_init:
			init_database_postgresql(connection_url)
		engine = sqlalchemy.create_engine(connection_url)
	else:
		raise errors.KingPhisherDatabaseError('only sqlite and postgresql database drivers are supported')

	Session.remove()
	Session.configure(bind=engine)
	inspector = sqlalchemy.inspect(engine)
	if not 'meta_data' in inspector.get_table_names():
		logger.debug('meta_data table not found, creating all new tables')
		try:
			models.Base.metadata.create_all(engine)
		except sqlalchemy.exc.SQLAlchemyError as error:
			error_lines = (line.strip() for line in error.message.split('n'))
			raise errors.KingPhisherDatabaseError('SQLAlchemyError: ' + ' '.join(error_lines).strip())

	session = Session()
	set_meta_data('database_driver', connection_url.drivername, session=session)
	schema_version = (get_meta_data('schema_version', session=session) or models.SCHEMA_VERSION)
	session.commit()
	session.close()

	logger.debug("current database schema version: {0} ({1})".format(schema_version, ('latest' if schema_version == models.SCHEMA_VERSION else 'obsolete')))
	if schema_version > models.SCHEMA_VERSION:
		raise errors.KingPhisherDatabaseError('the database schema is for a newer version, automatic downgrades are not supported')
	elif schema_version < models.SCHEMA_VERSION:
		alembic_config_file = find.find_data_file('alembic.ini')
		if not alembic_config_file:
			raise errors.KingPhisherDatabaseError('cannot find the alembic.ini configuration file')
		alembic_directory = find.find_data_directory('alembic')
		if not alembic_directory:
			raise errors.KingPhisherDatabaseError('cannot find the alembic data directory')

		config = alembic.config.Config(alembic_config_file)
		config.config_file_name = alembic_config_file
		config.set_main_option('script_location', alembic_directory)
		config.set_main_option('skip_logger_config', 'True')
		config.set_main_option('sqlalchemy.url', str(connection_url))

		logger.warning("automatically updating the database schema to version {0}".format(models.SCHEMA_VERSION))
		try:
			alembic.command.upgrade(config, 'head')
		except Exception as error:
			logger.critical("database schema upgrade failed with exception: {0}.{1} {2}".format(error.__class__.__module__, error.__class__.__name__, getattr(error, 'message', '')).rstrip(), exc_info=True)
			raise errors.KingPhisherDatabaseError('failed to upgrade to the latest database schema')
		# reset it because it may have been altered by alembic
		Session.remove()
		Session.configure(bind=engine)
		session = Session()
	set_meta_data('schema_version', models.SCHEMA_VERSION)

	logger.debug("connected to {0} database: {1}".format(connection_url.drivername, connection_url.database))
	signals.db_initialized.send(connection_url)
	return engine


0

Example 13

@rpc_views.route("/rpc/associate_payouts", methods=['POST'])
def associate_payouts():
    """ Used to update a SC Payout with a network transaction. This will
    create a new CoinTransaction object and link it to the
    transactions to signify that the transaction has been processed. """
    # basic checking of input
    try:
        assert 'coin_txid' in g.signed
        assert 'pids' in g.signed
        assert len(g.signed['coin_txid']) == 64
        assert isinstance(g.signed['pids'], list)

        for id in g.signed['pids']:
            id = int(id)
        tx_fee = Decimal(g.signed['tx_fee'])
        currency = g.signed['currency']
    except (AssertionError, KeyError, TypeError):
        current_app.logger.warn("Invalid data passed to confirm",
                                exc_info=True)
        abort(400)

    with Benchmark("Associating payout transaction ids"):

        trans = (db.session.query(Transaction)
                 .filter_by(txid=g.signed['coin_txid'], currency=currency)
                 .first())
        if not trans:
            try:
                trans = Transaction(txid=g.signed['coin_txid'],
                                    network_fee=tx_fee,
                                    currency=currency)
                db.session.add(trans)
                db.session.flush()
            except sqlalchemy.exc.SQLAlchemyError as e:
                db.session.rollback()
                current_app.logger.warn("Got an SQLalchemy error attempting to "
                                        "create a new transaction with id {}. "
                                        "nError:"
                                        .format(g.signed['coin_txid'], e))
                abort(400)

        Payout.query.filter(
            Payout.id.in_(g.signed['pids'])).update(
                {Payout.transaction_id: trans.id},
                synchronize_session=False)

        db.session.commit()

    return sign(dict(result=True))


0

Example 14

    def run(self):
        # create database structure
        logging.debug("Start create database structure...")
        try:
            db.create_all()
        except exc.SQLAlchemyError as e:
            logging.critical("MySQL database error: {0}nFAQ: {1}".format(e, 'http://cobra-docs.readthedocs.io/en/latest/FAQ/'))
            sys.exit(0)
        logging.debug("Create Structure Success.")
        # insert base data
        from app.models import CobraAuth, CobraLanguages, CobraAdminUser, CobraVuls
        # table `auth`
        logging.debug('Insert api key...')
        auth = CobraAuth('manual', common.md5('CobraAuthKey'), 1)
        db.session.add(auth)

        # table `languages`
        logging.debug('Insert language...')
        languages = {
            "php": ".php|.php3|.php4|.php5",
            "jsp": ".jsp",
            "java": ".java",
            "html": ".html|.htm|.phps|.phtml",
            "js": ".js",
            "backup": ".zip|.bak|.tar|.tar.gz|.rar",
            "xml": ".xml",
            "image": ".jpg|.png|.bmp|.gif|.ico|.cur",
            "font": ".eot|.otf|.svg|.ttf|.woff",
            "css": ".css|.less|.scss|.styl",
            "exe": ".exe",
            "shell": ".sh",
            "log": ".log",
            "text": ".txt|.text",
            "flash": ".swf",
            "yml": ".yml",
            "cert": ".p12|.crt|.key|.pfx|.csr",
            "psd": ".psd",
            "iml": ".iml",
            "spf": ".spf",
            "markdown": ".md",
            "office": ".doc|.docx|.wps|.rtf|.csv|.xls|.ppt",
            "bat": ".bat",
            "PSD": ".psd",
            "Thumb": ".db",
        }
        for language, extensions in languages.items():
            a_language = CobraLanguages(language, extensions)
            db.session.add(a_language)

        # table `user`
        logging.debug('Insert admin user...')
        username = 'admin'
        password = '[email protected]#'
        role = 1  # 1: super admin, 2: admin, 3: rules admin
        a_user = CobraAdminUser(username, password, role)
        db.session.add(a_user)

        # table `vuls`
        logging.debug('Insert vuls...')
        vuls = [
            'SQL Injection',
            'LFI/RFI',
            'Header Injection',
            'XSS',
            'CSRF',
            'Logic Bug',
            'Command Execute',
            'Code Execute',
            'Information Disclosure',
            'Data Exposure',
            'Xpath Injection',
            'LDAP Injection',
            'XML/XXE Injection',
            'Unserialize',
            'Variables Override',
            'URL Redirect',
            'Weak Function',
            'Buffer Overflow',
            'Deprecated Function',
            'Stack Trace',
            'Resource Executable',
            'SSRF',
            'Misconfiguration',
            'Components'
        ]
        for vul in vuls:
            a_vul = CobraVuls(vul, 'Vul Description', 'Vul Repair', 0)
            db.session.add(a_vul)

        # commit
        db.session.commit()
        logging.debug('All Done.')


0

Example 15

    def __init__(self, url):
        self.table = Table(self.__tablename__, MetaData(),
                           Column('name', String(64)),
                           Column('group', String(64)),
                           Column('status', String(16)),
                           Column('script', Text),
                           Column('comments', String(1024)),
                           Column('rate', Float(11)),
                           Column('burst', Float(11)),
                           Column('updatetime', Float(32)),
                           mysql_engine='InnoDB',
                           mysql_charset='utf8'
                           )

        self.url = make_url(url)
        if self.url.database:
            database = self.url.database
            self.url.database = None
            try:
                engine = create_engine(self.url, pool_recycle=3600)
                conn = engine.connect()
                conn.execute("commit")
                conn.execute("CREATE DATABASE %s" % database)
            except sqlalchemy.exc.SQLAlchemyError:
                pass
            self.url.database = database
        self.engine = create_engine(url, pool_recycle=3600)
        self.table.create(self.engine, checkfirst=True)


0

Example 16

    def __init__(self, url):
        self.table = Table('__tablename__', MetaData(),
                           Column('taskid', String(64), primary_key=True, nullable=False),
                           Column('url', String(1024)),
                           Column('result', LargeBinary),
                           Column('updatetime', Float(32)),
                           mysql_engine='InnoDB',
                           mysql_charset='utf8'
                           )

        self.url = make_url(url)
        if self.url.database:
            database = self.url.database
            self.url.database = None
            try:
                engine = create_engine(self.url, convert_unicode=True,
                                       pool_recycle=3600)
                engine.execute("CREATE DATABASE IF NOT EXISTS %s" % database)
            except sqlalchemy.exc.SQLAlchemyError:
                pass
            self.url.database = database
        self.engine = create_engine(url, convert_unicode=True,
                                    pool_recycle=3600)

        self._list_project()


0

Example 17

    def __init__(self, url):
        self.table = Table('__tablename__', MetaData(),
                           Column('taskid', String(64), primary_key=True, nullable=False),
                           Column('project', String(64)),
                           Column('url', String(1024)),
                           Column('status', Integer),
                           Column('schedule', LargeBinary),
                           Column('fetch', LargeBinary),
                           Column('process', LargeBinary),
                           Column('track', LargeBinary),
                           Column('lastcrawltime', Float(32)),
                           Column('updatetime', Float(32)),
                           mysql_engine='InnoDB',
                           mysql_charset='utf8'
                           )

        self.url = make_url(url)
        if self.url.database:
            database = self.url.database
            self.url.database = None
            try:
                engine = create_engine(self.url, pool_recycle=3600)
                conn = engine.connect()
                conn.execute("commit")
                conn.execute("CREATE DATABASE %s" % database)
            except sqlalchemy.exc.SQLAlchemyError:
                pass
            self.url.database = database
        self.engine = create_engine(url, pool_recycle=3600)

        self._list_project()


0

Example 18

    def load_database(self, force=False):
        """
        Start the database and then load all the database models of every module
        so that they can be used with SQLAlchemy.
        """
        if self.__loaded_database and not force:
            logger.debug('Trying to re-load database.')
            return
        
        logger.debug('Loading database...')
        
        try:
            cbpos.database.init()
        except ImportError as e:
            # Either the required db backend is not installed
            logger.exception("Database initialization error")
            logger.fatal("Database connection failed. It seems this database backend is not installed.")
            return False
        except exc.SQLAlchemyError as e:
            # Or there is a database error (connection, etc.)
            logger.exception("Database initialization error")
            logger.fatal("Database connection failed. Check the configuration.")
            return False
        except Exception as e:
            # Or an unexpected error
            logger.exception("Database initialization error")
            return False
        
        # Load database objects of every module
        for mod in cbpos.modules.all_loaders():
            logger.debug('Loading DB models for %s', mod.base_name)
            models = mod.load_models()
        
        self.__loaded_database = True
        return True


0

Example 19

  def import_objects(self):
    """Add all objects to the database.

    This function flushes all objects to the database and if the dry_run flag
    is not set, the session gets committed and all signals for the imported
    objects get sent.
    """
    if self.ignore:
      return

    for row_converter in self.row_converters:
      row_converter.setup_object()

    for row_converter in self.row_converters:
      self._check_object(row_converter)

    if not self.converter.dry_run:
      for row_converter in self.row_converters:
        row_converter.send_pre_commit_signals()
        try:
          row_converter.insert_object()
          db.session.flush()
        except exc.SQLAlchemyError as err:
          db.session.rollback()
          logger.exception("Import failed with: %s", err.message)
          row_converter.add_error(errors.UNKNOWN_ERROR)
      import_event = self.save_import()
      for row_converter in self.row_converters:
        row_converter.send_post_commit_signals(event=import_event)


0

Example 20

    def run(self):
        """Start processing events to save."""
        from homeassistant.components.recorder.models import Events, States
        import sqlalchemy.exc

        while True:
            try:
                self._setup_connection()
                self._setup_run()
                break
            except sqlalchemy.exc.SQLAlchemyError as e:
                log_error(e, retry_wait=CONNECT_RETRY_WAIT, rollback=False,
                          message="Error during connection setup: %s")

        if self.purge_days is not None:
            def purge_ticker(event):
                """Rerun purge every second day."""
                self._purge_old_data()
                track_point_in_utc_time(self.hass, purge_ticker,
                                        dt_util.utcnow() + timedelta(days=2))
            track_point_in_utc_time(self.hass, purge_ticker,
                                    dt_util.utcnow() + timedelta(minutes=5))

        while True:
            event = self.queue.get()

            if event is None:
                self._close_run()
                self._close_connection()
                self.queue.task_done()
                return

            if event.event_type == EVENT_TIME_CHANGED:
                self.queue.task_done()
                continue

            dbevent = Events.from_event(event)
            self._commit(dbevent)

            if event.event_type != EVENT_STATE_CHANGED:
                self.queue.task_done()
                continue

            dbstate = States.from_event(event)
            dbstate.event_id = dbevent.event_id
            self._commit(dbstate)

            self.queue.task_done()


0

Example 21

def ldap_synchronize(user, pw, session, ou_list):
    """
    Queries the ETH LDAP for all our members. Adds nonexisting ones to db.
    Updates existing ones if ldap data has changed.

    :param user: the ldap user. must be privileged to search for all ldap users
    :param pw: the password for the ldap user
    :param session: a database session
    :param ou_list: list of assigned organisational units in ldap
    """
    # Part 1: Get data from ldap
    connector = ldap.AuthenticatedLdap(user, pw)

    # Build the query
    # Member? VSETH necessary, then any of the fields
    query_string = u"(& (ou=VSETH Mitglied)(| "
    for item in ou_list:
        query_string += u"(ou=%s)" % _escape(item)  # Items contain braces
    query_string += u" ) )"

    results = connector.search(query_string, attributes=LDAP_ATTR)

    res_dict = {item['cn'][0]: item for item in results}

    res_set = set(res_dict.keys())

    # Part 2: Get data from db
    users = session.query(User).all()

    u_set = set([item.nethz for item in users])

    # Part 3: Import users not yet in database
    new = res_set.difference(u_set)  # items in results which are not in users

    failed = {
        'bad_ldap_data': [],
        'failed_import': [],
        'failed_update': []
    }

    n_new = 0
    for nethz in new:
        try:
            filtered = _filter_data(res_dict[nethz], ou_list)
            user = User(
                _author=0,
                _created=dt.utcnow(),
                _updated=dt.utcnow(),
                _etag=docuement_etag(filtered),
                email="%[email protected]" % filtered['nethz'],
                **filtered  # Rest of the daa
            )
            session.add(user)
            try:
                session.commit()
                n_new += 1
            except exc.SQLAlchemyError:
                failed['failed_import'] += user
                session.rollback()
        except KeyError:  # A key error will happen if ldap data is incomplete
            failed['bad_ldap_data'] += res_dict[nethz]

    # Part 4: Update users already in database
    old = res_set.intersection(u_set)

    user_query = session.query(User)
    n_old = 0
    for nethz in old:
        try:
            filtered = _filter_data(res_dict[nethz], ou_list)
            user = user_query.filter_by(nethz=nethz)
            userdata = user.one()

            # Is anything different?
            if _changed(userdata, filtered):
                # No downgrade of membership
                if userdata.membership is not "none":
                    filtered.pop('membership')

                user.update(filtered)
                try:
                    session.commit()
                    n_old += 1
                except exc.SQLAlchemyError:
                    failed['failed_update'] += filtered
                    session.rollback()
        except KeyError:
            failed['bad_ldap_data'] += res_dict[nethz]

    return (n_new, n_old, failed)


0

Example 22

    @log_process_begin_and_end.output_log
    def masakari(self):
        """
        RecoveryController class main processing:
        This processing checks the VM list table of DB.
        If an unprocessed VM exists, and start thread to execute the recovery
        process.
        Then, the processing starts the wsgi server and waits for the
        notification.
        """
        try:
            LOG.info("masakari START.")

            # Get a session and do not pass it to other threads
            db_engine = dbapi.get_engine(self.rc_config)
            session = dbapi.get_session(db_engine)

            self._update_old_records_notification_list(session)
            result = self._find_reprocessing_records_notification_list(session)
            preprocessing_count = len(result)

            if preprocessing_count > 0:
                for row in result:
                    if row.recover_by == 0:
                        # node recovery event
                        msg = "Run thread rc_worker.host_maintenance_mode." 
                            + " notification_id=" + row.notification_id 
                            + " notification_hostname=" 
                            + row.notification_hostname 
                            + " update_progress=False"
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            row.notification_id)
                        th = threading.Thread(
                            target=self.rc_worker.host_maintenance_mode,
                            name=thread_name,
                            args=(row.notification_id,
                                  row.notification_hostname,
                                  False,))
                        th.start()

                        # Sleep until updating nova-compute service status
                        # down.
                        dic = self.rc_config.get_value('recover_starter')
                        node_err_wait = dic.get("node_err_wait")
                        msg = ("Sleeping %s sec before starting node recovery"
                               "thread, until updateing nova-compute"
                               "service status." % (node_err_wait))
                        LOG.info(msg)
                        greenthread.sleep(int(node_err_wait))

                        # Start add_failed_host thread
                        # TODO(sampath):
                        # Avoid create thread here,
                        # insted call rc_starter.add_failed_host
                        retry_mode = True
                        msg = "Run thread rc_starter.add_failed_host." 
                            + " notification_id=" + row.notification_id 
                            + " notification_hostname=" 
                            + row.notification_hostname 
                            + " notification_cluster_port=" 
                            + row.notification_cluster_port 
                            + " retry_mode=" + str(retry_mode)
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            row.notification_id)
                        th = threading.Thread(
                            target=self.rc_starter.add_failed_host,
                            name=thread_name,
                            args=(row.notification_id,
                                  row.notification_hostname,
                                  row.notification_cluster_port,
                                  retry_mode, ))
                        th.start()

                    elif row.recover_by == 1:
                        # instance recovery event
                        # TODO(sampath):
                        # Avoid create thread here,
                        # insted call rc_starter.add_failed_instance
                        msg = "Run thread rc_starter.add_failed_instance." 
                            + " notification_id=" + row.notification_id 
                            + " notification_uuid=" 
                            + row.notification_uuid
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            row.notification_id)
                        th = threading.Thread(
                            target=self.rc_starter.add_failed_instance,
                            name=thread_name,
                            args=(row.notification_id,
                                  row.notification_uuid, ))
                        th.start()

                    else:
                        # maintenance mode event
                        msg = "Run thread rc_starter.host_maintenance_mode." 
                            + " notification_id=" + row.notification_id 
                            + " notification_hostname=" 
                            + row.notification_hostname 
                            + "update_progress=True"
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            row.notification_id)
                        th = threading.Thread(
                            target=self.rc_worker.host_maintenance_mode,
                            name=thread_name,
                            args=(row.notification_id,
                                  row.notification_hostname,
                                  True, ))
                        th.start()

            # Start handle_pending_instances thread
            # TODO(sampath):
            # Avoid create thread here,
            # insted call rc_starter.handle_pending_instances()
            msg = "Run thread rc_starter.handle_pending_instances."
            LOG.info(msg)
            thread_name = "Thread:handle_pending_instances"
            th = threading.Thread(
                target=self.rc_starter.handle_pending_instances,
                name=thread_name)
            th.start()

            # Start reciever process for notification
            conf_wsgi_dic = self.rc_config.get_value('wsgi')
            wsgi.server(
                eventlet.listen(('', int(conf_wsgi_dic['server_port']))),
                self._notification_reciever)

        except exc.SQLAlchemyError:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.critical(error_type)
            LOG.critical(error_value)
            for tb in tb_list:
                LOG.critical(tb)

            sys.exit()
        except KeyError:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.critical(error_type)
            LOG.critical(error_value)
            for tb in tb_list:
                LOG.critical(tb)

            sys.exit()
        except:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.critical(error_type)
            LOG.critical(error_value)
            for tb in tb_list:
                LOG.critical(tb)

            sys.exit()


0

Example 23

    @log_process_begin_and_end.output_log
    def _notification_reciever(self, env, start_response):

        try:
            len = env['CONTENT_LENGTH']
            if len > 0:
                body = env['wsgi.input'].read(len)
                json_data = json.loads(body)

                msg = "Recieved notification : " + body
                LOG.info(msg)

                ret = self._check_json_param(json_data)
                if ret == 1:
                    # Return Response
                    start_response(
                        '400 Bad Request', [('Content-Type', 'text/plain')])

                    msg = "Wsgi response: " 
                          "status=400 Bad Request, " 
                          "body=method _notification_reciever returned."
                    LOG.info(msg)

                    return ['method _notification_reciever returned.rn']

                # Insert notification into notification_list_db
                notification_list_dic = {}
                notification_list_dic = self._create_notification_list_db(
                    json_data)

                # Return Response
                start_response('200 OK', [('Content-Type', 'text/plain')])

                msg = "Wsgi response: " 
                    + "status=200 OK, " 
                    + "body=method _notification_reciever returned."
                LOG.info(msg)

                if notification_list_dic != {}:
                    # Start thread
                    if notification_list_dic.get("recover_by") == 0 and 
                       notification_list_dic.get("progress") == 0:

                        msg = "Run thread rc_worker.host_maintenance_mode." 
                            + " notification_id=" 
                            + notification_list_dic.get("notification_id") 
                            + " notification_hostname=" 
                            + notification_list_dic.get(
                                "notification_hostname") 
                            + "update_progress=False"
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            notification_list_dic.get("notification_id"))
                        th = threading.Thread(
                            target=self.rc_worker.host_maintenance_mode,
                            name=thread_name,
                            args=(notification_list_dic.get(
                                "notification_id"), notification_list_dic.get(
                                "notification_hostname"),
                                False, ))
                        th.start()

                        # Sleep until nova recognizes the node down.
                        dic = self.rc_config.get_value('recover_starter')
                        node_err_wait = dic.get("node_err_wait")
                        msg = ("Sleeping %s sec before starting recovery"
                               "thread until nova recognizes the node down..."
                               % (node_err_wait)
                               )
                        LOG.info(msg)
                        greenthread.sleep(int(node_err_wait))

                        retry_mode = False
                        msg = "Run thread rc_starter.add_failed_host." 
                            + " notification_id=" 
                            + notification_list_dic.get("notification_id") 
                            + " notification_hostname=" 
                            + notification_list_dic.get(
                                "notification_hostname") 
                            + " notification_cluster_port=" 
                            + notification_list_dic.get(
                                "notification_cluster_port") 
                            + " retry_mode=" + str(retry_mode)
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            notification_list_dic.get("notification_id"))
                        th = threading.Thread(
                            target=self.rc_starter.add_failed_host,
                            name=thread_name,
                            args=(notification_list_dic.get(
                                "notification_id"),
                                notification_list_dic.get(
                                "notification_hostname"),
                                notification_list_dic.get(
                                "notification_cluster_port"),
                                retry_mode, ))

                        th.start()
                    elif notification_list_dic.get("recover_by") == 0 and 
                            notification_list_dic.get("progress") == 3:
                        msg = "Run thread rc_worker.host_maintenance_mode." 
                            + " notification_id=" 
                            + notification_list_dic.get("notification_id") 
                            + " notification_hostname=" 
                            + notification_list_dic.get(
                                "notification_hostname") 
                            + "update_progress=False"
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            notification_list_dic.get("notification_id"))
                        th = threading.Thread(
                            target=self.rc_worker.host_maintenance_mode,
                            name=thread_name,
                            args=(notification_list_dic.get(
                                "notification_id"),
                                notification_list_dic.get(
                                "notification_hostname"),
                                False, ))
                        th.start()
                    elif notification_list_dic.get("recover_by") == 1:
                        retry_mode = False
                        msg = "Run thread rc_starter.add_failed_instance." 
                            + " notification_id=" 
                            + notification_list_dic.get("notification_id") 
                            + " notification_uuid=" 
                            + notification_list_dic.get("notification_uuid") 
                            + " retry_mode=" + str(retry_mode)
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            notification_list_dic.get("notification_id"))
                        th = threading.Thread(
                            target=self.rc_starter.add_failed_instance,
                            name=thread_name,
                            args=(
                                notification_list_dic.get("notification_id"),
                                notification_list_dic.get(
                                    "notification_uuid"), retry_mode, )
                        )
                        th.start()
                    elif notification_list_dic.get("recover_by") == 2:
                        msg = "Run thread rc_worker.host_maintenance_mode." 
                            + " notification_id=" 
                            + notification_list_dic.get("notification_id") 
                            + " notification_hostname=" 
                            + notification_list_dic.get(
                                "notification_hostname") 
                            + "update_progress=False"
                        LOG.info(msg)
                        thread_name = self.rc_util.make_thread_name(
                            NOTIFICATION_LIST,
                            notification_list_dic.get("notification_id"))
                        th = threading.Thread(
                            target=self.rc_worker.host_maintenance_mode,
                            name=thread_name,
                            args=(
                                notification_list_dic.get("notification_id"),
                                notification_list_dic.get(
                                    "notification_hostname"),
                                True, )
                        )
                        th.start()
                    else:
                        LOG.warning(
                            "Column "recover_by" 
                            on notification_list DB is invalid value.")

        except exc.SQLAlchemyError:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)
            start_response(
                '500 Internal Server Error', [('Content-Type', 'text/plain')])

            msg = "Wsgi response: " 
                  "status=500 Internal Server Error, " 
                  "body=method _notification_reciever returned."
            LOG.info(msg)

        except KeyError:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)
            start_response(
                '500 Internal Server Error', [('Content-Type', 'text/plain')])

            msg = "Wsgi response: " 
                  "status=500 Internal Server Error, " 
                  "body=method _notification_reciever returned."
            LOG.info(msg)

        except:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)
            start_response(
                '500 Internal Server Error', [('Content-Type', 'text/plain')])

            msg = "Wsgi response: " 
                  "status=500 Internal Server Error, " 
                  "body=method _notification_reciever returned."
            LOG.info(msg)

        return ['method _notification_reciever returned.rn']


0

Example 24

    @log_process_begin_and_end.output_log
    def insert_vm_list_db(self, session, notification_id,
                          notification_uuid, retry_cnt):
        """
        VM list table registration
        :param :cursor: cursor object
        :param :notification_id: Notification ID
                (used as search criteria for notification list table)
        :param :notification_uuid:VM of uuid
                (used as the registered contents of the VM list table)
        :param :retry_cnt:Retry count
                (used as the registered contents of the VM list table)
        :return :primary_id: The value of LAST_INSERT_ID
        """

        try:
            msg = "Do get_all_notification_list_by_notification_id."
            LOG.info(msg)
            res = dbapi.get_all_notification_list_by_notification_id(
                session,
                notification_id
            )
            msg = "Succeeded in get_all_notification_list_by_notification_id. " 
                + "Return_value = " + str(res)
            LOG.info(msg)
            # Todo(sampath): select first and only object from the list
            # log if many records
            notification_recover_to = res[0].recover_to
            notification_recover_by = res[0].recover_by
            msg = "Do add_vm_list."
            LOG.info(msg)
            vm_item = dbapi.add_vm_list(session,
                                        datetime.datetime.now(),
                                        "0",
                                        notification_uuid,
                                        "0",
                                        str(retry_cnt),
                                        notification_id,
                                        notification_recover_to,
                                        str(notification_recover_by)
                                        )
            msg = "Succeeded in add_vm_list. " 
                + "Return_value = " + str(vm_item)
            LOG.info(msg)

            primary_id = vm_item.id

            return primary_id

        except KeyError:

            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : KeyError in insert_vm_list_db()."
            LOG.error(msg)

            raise KeyError

        except exc.SQLAlchemyError:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : sqlalchemy error in insert_vm_list_db()."
            LOG.error(msg)

            raise exc.SQLAlchemyError

        except:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)

            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : Exception in insert_vm_list_db()."
            LOG.error(msg)

            raise


0

Example 25

    @log_process_begin_and_end.output_log
    def update_notification_list_db(self, session, key, value,
                                    notification_id):
        """
        Notification list table update
        :param :key: Update column name
        :param :value: Updated value
        :param :notification_id: Notification ID
                (updated narrowing condition of notification list table)
        """
        try:
            # Update progress with update_at and delete_at
            now = datetime.datetime.now()
            update_val = {'update_at': now}
            if key == 'progress':
                update_val['progress'] = value
                update_val['delete_at'] = now
            # Updated than progress
            else:
                if hasattr(NotificationList, key):
                    update_val[key] = value
                else:
                    raise AttributeError
            msg = "Do update_notification_list_dict."
            LOG.info(msg)
            dbapi.update_notification_list_dict(
                session, notification_id, update_val)
            msg = "Succeeded in update_notification_list_dict."
            LOG.info(msg)

        except AttributeError:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : %s is not in attribute of 
            NotificationList" % (key)
            LOG.error(msg)
            raise AttributeError

        except exc.SQLAlchemyError:

            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : SQLAlchemy.Error in 
            update_notification_list_db()."
            LOG.error(msg)

            raise exc.SQLAlchemyError

        except KeyError:

            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : KeyError in update_notification_list_db()."
            LOG.error(msg)

            raise KeyError


0

Example 26

    @log_process_begin_and_end.output_log
    def update_vm_list_db(self,  session, key, value, primary_id):
        """
        VM list table update
        :param :key: Update column name
        :param :value: Updated value
        :param :uuid: VM of uuid (updated narrowing condition of VM list table)
        """

        try:
            # Updated progress to start
            now = datetime.datetime.now()
            update_val = {}
            if key == 'progress' and value == 1:
                update_val['update_at'] = now
                update_val['progress'] = value
            # End the progress([success:2][error:3][skipped old:4])
            elif key == 'progress':
                update_val['update_at'] = now
                update_val['progress'] = value
                update_val['delete_at'] = now
            # Update than progress
            else:
                if hasattr(VmList, key):
                    update_val[key] = value
                else:
                    raise AttributeError
            msg = "Do update_vm_list_by_id_dict."
            LOG.info(msg)
            dbapi.update_vm_list_by_id_dict(session, primary_id, update_val)
            msg = "Succeeded in update_vm_list_by_id_dict."
            LOG.info(msg)

        except AttributeError:
            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : %s is not in attribute of 
            VmList" % (key)
            LOG.error(msg)
            raise AttributeError

        except exc.SQLAlchemyError:

            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : SQLAlchemy.Error in 
            update_vm_list_by_id_dict()."
            LOG.error(msg)

            raise exc.SQLAlchemyError

        except KeyError:

            error_type, error_value, traceback_ = sys.exc_info()
            tb_list = traceback.format_tb(traceback_)
            LOG.error(error_type)
            LOG.error(error_value)
            for tb in tb_list:
                LOG.error(tb)

            msg = "Exception : KeyError in update_notification_list_db()."
            LOG.error(msg)

            raise KeyError


0

Example 27

@app.route('/ad', methods=['GET'])
@app.route('/pub', methods=['GET'])
@nocache
def advertisement():
    """
    This is the url we give for the ad for our 'external question'.  The ad has
    to display two different things: This page will be called from within
    mechanical turk, with url arguments hitId, assignmentId, and workerId.
    If the worker has not yet accepted the hit:
        These arguments will have null values, we should just show an ad for
        the experiment.
    If the worker has accepted the hit:
        These arguments will have appropriate values and we should enter the
        person in the database and provide a link to the experiment popup.
    """
    user_agent_string = request.user_agent.string
    user_agent_obj = user_agents.parse(user_agent_string)
    browser_ok = True
    for rule in string.split(
            CONFIG.get('HIT Configuration', 'browser_exclude_rule'), ','):
        myrule = rule.strip()
        if myrule in ["mobile", "tablet", "touchcapable", "pc", "bot"]:
            if (myrule == "mobile" and user_agent_obj.is_mobile) or
               (myrule == "tablet" and user_agent_obj.is_tablet) or
               (myrule == "touchcapable" and user_agent_obj.is_touch_capable) or
               (myrule == "pc" and user_agent_obj.is_pc) or
               (myrule == "bot" and user_agent_obj.is_bot):
                browser_ok = False
        elif (myrule == "Safari" or myrule == "safari"):
            if "Chrome" in user_agent_string and "Safari" in user_agent_string:
                pass
            elif "Safari" in user_agent_string:
                browser_ok = False
        elif myrule in user_agent_string:
            browser_ok = False

    if not browser_ok:
        # Handler for IE users if IE is not supported.
        raise ExperimentError('browser_type_not_allowed')

    if not ('hitId' in request.args and 'assignmentId' in request.args):
        raise ExperimentError('hit_assign_worker_id_not_set_in_mturk')
    hit_id = request.args['hitId']
    assignment_id = request.args['assignmentId']
    mode = request.args['mode']
    if hit_id[:5] == "debug":
        debug_mode = True
    else:
        debug_mode = False
    already_in_db = False
    if 'workerId' in request.args:
        worker_id = request.args['workerId']
        # First check if this workerId has completed the task before (v1).
        nrecords = Participant.query.
            filter(Participant.assignmentid != assignment_id).
            filter(Participant.workerid == worker_id).
            count()

        if nrecords > 0:  # Already completed task
            already_in_db = True
    else:  # If worker has not accepted the hit
        worker_id = None
    try:
        part = Participant.query.
            filter(Participant.hitid == hit_id).
            filter(Participant.assignmentid == assignment_id).
            filter(Participant.workerid == worker_id).
            one()
        status = part.status
    except exc.SQLAlchemyError:
        status = None

    if status == STARTED and not debug_mode:
        # Once participants have finished the instructions, we do not allow
        # them to start the task again.
        raise ExperimentError('already_started_exp_mturk')
    elif status == COMPLETED:
        use_psiturk_ad_server = CONFIG.getboolean('Shell Parameters', 'use_psiturk_ad_server')
        if not use_psiturk_ad_server:
            # They've finished the experiment but haven't submitted the HIT
            # yet.. Turn asignmentId into original assignment id before sending it
            # back to AMT
            return render_template(
                'thanks-mturksubmit.html',
                using_sandbox=(mode == "sandbox"),
                hitid=hit_id,
                assignmentid=assignment_id,
                workerid=worker_id
            )
        else: 
            # Show them a thanks message and tell them to go away.
            return render_template( 'thanks.html' )
    elif already_in_db and not debug_mode:
        raise ExperimentError('already_did_exp_hit')
    elif status == ALLOCATED or not status or debug_mode:
        # Participant has not yet agreed to the consent. They might not
        # even have accepted the HIT.
        with open('templates/ad.html', 'r') as temp_file:
            ad_string = temp_file.read()
        ad_string = insert_mode(ad_string, mode)
        return render_template_string(
            ad_string,
            hitid=hit_id,
            assignmentid=assignment_id,
            workerid=worker_id
        )
    else:
        raise ExperimentError('status_incorrectly_set')


0

Example 28

@app.route('/inexp', methods=['POST'])
def enterexp():
    """
    AJAX listener that listens for a signal from the user's script when they
    leave the instructions and enter the real experiment. After the server
    receives this signal, it will no longer allow them to re-access the
    experiment applet (meaning they can't do part of the experiment and
    referesh to start over).
    """
    app.logger.info("Accessing /inexp")
    if not 'uniqueId' in request.form:
        raise ExperimentError('improper_inputs')
    unique_id = request.form['uniqueId']

    try:
        user = Participant.query.
            filter(Participant.uniqueid == unique_id).one()
        user.status = STARTED
        user.beginexp = datetime.datetime.now()
        db_session.add(user)
        db_session.commit()
        resp = {"status": "success"}
    except exc.SQLAlchemyError:
        app.logger.error("DB error: Unique user not found.")
        resp = {"status": "error, uniqueId not found"}
    return jsonify(**resp)


0

Example 29

@app.route('/sync/<uid>', methods=['GET'])
def load(uid=None):
    """
    Load experiment data, which should be a JSON object and will be stored
    after converting to string.
    """
    app.logger.info("GET /sync route with id: %s" % uid)

    try:
        user = Participant.query.
            filter(Participant.uniqueid == uid).
            one()
    except exc.SQLAlchemyError:
        app.logger.error("DB error: Unique user not found.")

    try:
        resp = json.loads(user.datastring)
    except:
        resp = {
            "condition": user.cond,
            "counterbalance": user.counterbalance,
            "assignmentId": user.assignmentid,
            "workerId": user.workerid,
            "hitId": user.hitid,
            "bonus": user.bonus
        }

    return jsonify(**resp)


0

Example 30

@app.route('/sync/<uid>', methods=['PUT'])
def update(uid=None):
    """
    Save experiment data, which should be a JSON object and will be stored
    after converting to string.
    """
    app.logger.info("PUT /sync route with id: %s" % uid)

    try:
        user = Participant.query.
            filter(Participant.uniqueid == uid).
            one()
    except exc.SQLAlchemyError:
        app.logger.error("DB error: Unique user not found.")

    if hasattr(request, 'json'):
        user.datastring = request.data.decode('utf-8').encode(
            'ascii', 'xmlcharrefreplace'
        )
        db_session.add(user)
        db_session.commit()

    try:
        data = json.loads(user.datastring)
    except:
        data = {}

    trial = data.get("currenttrial", None)
    app.logger.info("saved data for %s (current trial: %s)", uid, trial)
    resp = {"status": "user data saved"}
    return jsonify(**resp)


0

Example 31

@app.route('/quitter', methods=['POST'])
def quitter():
    """
    Mark quitter as such.
    """
    unique_id = request.form['uniqueId']
    if unique_id[:5] == "debug":
        debug_mode = True
    else:
        debug_mode = False

    if debug_mode:
        resp = {"status": "didn't mark as quitter since this is debugging"}
        return jsonify(**resp)
    else:
        try:
            unique_id = request.form['uniqueId']
            app.logger.info("Marking quitter %s" % unique_id)
            user = Participant.query.
                filter(Participant.uniqueid == unique_id).
                one()
            user.status = QUITEARLY
            db_session.add(user)
            db_session.commit()
        except exc.SQLAlchemyError:
            raise ExperimentError('tried_to_quit')
        else:
            resp = {"status": "marked as quitter"}
            return jsonify(**resp)


0

Example 32

@app.route('/worker_complete', methods=['GET'])
def worker_complete():
    ''' Complete worker. '''
    if not 'uniqueId' in request.args:
        resp = {"status": "bad request"}
        return jsonify(**resp)
    else:
        unique_id = request.args['uniqueId']
        app.logger.info("Completed experiment %s" % unique_id)
        try:
            user = Participant.query.
                filter(Participant.uniqueid == unique_id).one()
            user.status = COMPLETED
            user.endhit = datetime.datetime.now()
            db_session.add(user)
            db_session.commit()
            status = "success"
        except exc.SQLAlchemyError:
            status = "database error"
        resp = {"status" : status}
        return jsonify(**resp)


0

Example 33

@app.route('/worker_submitted', methods=['GET'])
def worker_submitted():
    ''' Submit worker '''
    if not 'uniqueId' in request.args:
        resp = {"status": "bad request"}
        return jsonify(**resp)
    else:
        unique_id = request.args['uniqueId']
        app.logger.info("Submitted experiment for %s" % unique_id)
        try:
            user = Participant.query.
                filter(Participant.uniqueid == unique_id).one()
            user.status = SUBMITTED
            db_session.add(user)
            db_session.commit()
            status = "success"
        except exc.SQLAlchemyError:
            status = "database error"
        resp = {"status" : status}
        return jsonify(**resp)

Понравилась статья? Поделить с друзьями:
  • Sql1159 initialization error with db2 net data provider reason code 10
  • Sql сервер ошибка 18456
  • Sql ошибка 924
  • Sql ошибка 8152
  • Sql ошибка 3241