
◇公式ホームページ
自分の頭を整理するために、公式ホームページのチュートリアルに日本語の解説を加えました。
翻訳はもっぱらGoogle翻訳に頼っています。
Google翻訳で訳した部分は、文の冒頭に ’G訳:’ と記載しています。
日本語として多少ぎこちない部分がありますが、私が誤訳するよりもよっぽど良いと思いますので、そのまま掲載しています。
自分用に、日本語訳をJupyter notebookへ追記したものを、ブログへ貼り付けていますので、表記が乱れている部分がありますが、ご容赦願います。
SQLAlchemyのインストール
SQLAlchemyのインストールはpipで行います。
1 |
pip install SQLAlchemy |
Version Check(バージョンの確認)
インストールされているSQLAlchemyのバージョンを確認します。
A quick check to verify that we are on at least version 1.3 of SQLAlchemy:
G訳:SQLAlchemyのバージョン1.3以上を使用していることを確認するための簡単なチェック:
1 2 |
import sqlalchemy sqlalchemy.__version__ |
Connecting(接続)
For this tutorial we will use an in-memory-only SQLite database. To connect we use create_engine():
G訳:接続このチュートリアルでは、メモリ内のみのSQLiteデータベースを使用します。 接続するには、create_engine()を使用します。
1 2 |
from sqlalchemy import create_engine engine = create_engine('sqlite:///:memory:', echo=True) |
The echo flag is a shortcut to setting up SQLAlchemy logging, which is accomplished via Python’s standard logging module. With it enabled, we’ll see all the generated SQL produced. If you are working through this tutorial and want less output generated, set it to False. This tutorial will format the SQL behind a popup window so it doesn’t get in our way; just click the “SQL” links to see what’s being generated.
G訳:エコーフラグは、SQLAlchemyロギングを設定するためのショートカットであり、Pythonの標準ロギングモジュールを介して実行されます。 有効にすると、生成されたすべてのSQLが生成されます。 このチュートリアルを実行していて、生成される出力を少なくしたい場合は、Falseに設定してください。 このチュートリアルでは、ポップアップウィンドウの背後でSQLをフォーマットして、邪魔にならないようにします。 「SQL」リンクをクリックするだけで、何が生成されているかを確認できます。
The return value of create_engine() is an instance of Engine, and it represents the core interface to the database, adapted through a dialect that handles the details of the database and DBAPI in use. In this case the SQLite dialect will interpret instructions to the Python built-in sqlite3 module.
Declare a Mapping(マッピング)
When using the ORM, the configurational process starts by describing the database tables we’ll be dealing with, and then by defining our own classes which will be mapped to those tables. In modern SQLAlchemy, these two tasks are usually performed together, using a system known as Declarative, which allows us to create classes that include directives to describe the actual database table they will be mapped to.
G訳:ORMを使用する場合、構成プロセスは、処理するデータベーステーブルを記述し、次にそれらのテーブルにマップされる独自のクラスを定義することから始まります。 最新のSQLAlchemyでは、これら2つのタスクは通常、宣言型と呼ばれるシステムを使用して一緒に実行されます。これにより、マップされる実際のデータベーステーブルを記述するディレクティブを含むクラスを作成できます。
Classes mapped using the Declarative system are defined in terms of a base class which maintains a catalog of classes and tables relative to that base – this is known as the declarative base class. Our application will usually have just one instance of this base in a commonly imported module. We create the base class using the declarative_base() function, as follows:
G訳:宣言型システムを使用してマップされたクラスは、そのベースに関連するクラスとテーブルのカタログを維持する基本クラスに関して定義されます。これは、宣言型基本クラスと呼ばれます。 私たちのアプリケーションは通常、一般的にインポートされるモジュールにこのベースのインスタンスを1つだけ持っています。 次のように、declarative_base()関数を使用して基本クラスを作成します。
1 2 3 |
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() |
Now that we have a “base”, we can define any number of mapped classes in terms of it. We will start with just a single table called users, which will store records for the end-users using our application. A new class called User will be the class to which we map this table. Within the class, we define details about the table to which we’ll be mapping, primarily the table name, and names and datatypes of columns:
G訳:「ベース」ができたので、それに関してマップされたクラスをいくつでも定義できます。 まず、usersという単一のテーブルから始めます。このテーブルには、アプリケーションを使用するエンドユーザーのレコードが格納されます。 Userという新しいクラスが、このテーブルをマップするクラスになります。 クラス内で、マッピング先のテーブルに関する詳細、主にテーブル名、列の名前とデータ型を定義します。
1 2 3 4 5 6 7 8 9 10 11 12 |
from sqlalchemy import Column, Integer, String class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) nickname = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', nickname='%s')>" % ( self.name, self.fullname, self.nickname) |
A class using Declarative at a minimum needs a tablename attribute, and at least one Column which is part of a primary key 1. SQLAlchemy never makes any assumptions by itself about the table to which a class refers, including that it has no built-in conventions for names, datatypes, or constraints. But this doesn’t mean boilerplate is required; instead, you’re encouraged to create your own automated conventions using helper functions and mixin classes, which is described in detail at Mixin and Custom Base Classes.
G訳:Declarativeを使用するクラスには、少なくともtablename属性と、主キー1の一部である少なくとも1つの列が必要です。SQLAlchemyは、クラスが参照するテーブルについて、組み込みがないことを含め、それ自体で仮定を行うことはありません。 名前、データ型、または制約の規則。 しかし、これは定型文が必要であることを意味するものではありません。 代わりに、ヘルパー関数とミックスインクラスを使用して、独自の自動化された規則を作成することをお勧めします。これについては、ミックスインクラスとカスタムベースクラスで詳しく説明されています。
When our class is constructed, Declarative replaces all the Column objects with special Python accessors known as descriptors; this is a process known as instrumentation. The “instrumented” mapped class will provide us with the means to refer to our table in a SQL context as well as to persist and load the values of columns from the database.
Outside of what the mapping process does to our class, the class remains otherwise mostly a normal Python class, to which we can define any number of ordinary attributes and methods needed by our application.
Create a Schema(スキーマを作成)
With our User class constructed via the Declarative system, we have defined information about our table, known as table metadata. The object used by SQLAlchemy to represent this information for a specific table is called the Table object, and here Declarative has made one for us. We can see this object by inspecting the table attribute:
G訳:宣言型システムを介して構築されたUserクラスを使用して、テーブルメタデータと呼ばれるテーブルに関する情報を定義しました。 SQLAlchemyが特定のテーブルのこの情報を表すために使用するオブジェクトはTableオブジェクトと呼ばれ、ここではDeclarativeが作成しました。 table属性を調べると、このオブジェクトを確認できます。
1 |
User.__table__ |
Table(‘users’, MetaData(bind=None), Column(‘id’, Integer(), table=<users>, primary_key=True, nullable=False), Column(‘name’, String(), table=<users>), Column(‘fullname’, String(), table=<users>), Column(‘nickname’, String(), table=<users>), schema=None)
When we declared our class, Declarative used a Python metaclass in order to perform additional activities once the class declaration was complete; within this phase, it then created a Table object according to our specifications, and associated it with the class by constructing a Mapper object. This object is a behind-the-scenes object we normally don’t need to deal with directly (though it can provide plenty of information about our mapping when we need it).
G訳:クラスを宣言したとき、Declarativeは、クラス宣言が完了すると追加のアクティビティを実行するためにPythonメタクラスを使用しました。 このフェーズでは、仕様に従ってTableオブジェクトを作成し、Mapperオブジェクトを作成してクラスに関連付けました。 このオブジェクトは、通常は直接処理する必要のない舞台裏のオブジェクトです(ただし、必要なときにマッピングに関する多くの情報を提供できます)。
The Table object is a member of a larger collection known as MetaData. When using Declarative, this object is available using the .metadata attribute of our declarative base class.
The MetaData is a registry which includes the ability to emit a limited set of schema generation commands to the database. As our SQLite database does not actually have a users table present, we can use MetaData to issue CREATE TABLE statements to the database for all tables that don’t yet exist. Below, we call the MetaData.create_all() method, passing in our Engine as a source of database connectivity. We will see that special commands are first emitted to check for the presence of the users table, and following that the actual CREATE TABLE statement:
1 |
Base.metadata.create_all(engine) |
2021-09-12 12:18:20,480 INFO sqlalchemy.engine.base.Engine SELECT CAST(‘test plain returns’ AS VARCHAR(60)) AS anon_1
2021-09-12 12:18:20,480 INFO sqlalchemy.engine.base.Engine ()
2021-09-12 12:18:20,481 INFO sqlalchemy.engine.base.Engine SELECT CAST(‘test unicode returns’ AS VARCHAR(60)) AS anon_1
2021-09-12 12:18:20,482 INFO sqlalchemy.engine.base.Engine ()
2021-09-12 12:18:20,483 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info(“users”)
2021-09-12 12:18:20,483 INFO sqlalchemy.engine.base.Engine ()
2021-09-12 12:18:20,484 INFO sqlalchemy.engine.base.Engine PRAGMA temp.table_info(“users”)
2021-09-12 12:18:20,485 INFO sqlalchemy.engine.base.Engine ()
2021-09-12 12:18:20,486 INFO sqlalchemy.engine.base.Engine
CREATE TABLE users (
id INTEGER NOT NULL,
name VARCHAR,
fullname VARCHAR,
nickname VARCHAR,
PRIMARY KEY (id)
)
2021-09-12 12:18:20,487 INFO sqlalchemy.engine.base.Engine ()
2021-09-12 12:18:20,488 INFO sqlalchemy.engine.base.Engine COMMIT
Minimal Table Descriptions vs. Full Descriptions
G訳:最小限のテーブルの説明と完全な説明
Users familiar with the syntax of CREATE TABLE may notice that the VARCHAR columns were generated without a length; on SQLite and PostgreSQL, this is a valid datatype, but on others, it’s not allowed. So if running this tutorial on one of those databases, and you wish to use SQLAlchemy to issue CREATE TABLE, a “length” may be provided to the String type as below:
G訳:CREATE TABLEの構文に精通しているユーザーは、VARCHAR列が長さなしで生成されたことに気付くかもしれません。 SQLiteとPostgreSQLでは、これは有効なデータ型ですが、その他の場合は許可されていません。 したがって、これらのデータベースの1つでこのチュートリアルを実行し、SQLAlchemyを使用してCREATE TABLEを発行する場合は、次のように文字列型に「長さ」を指定できます。
1 |
Column(String(50)) |
The length field on String, as well as similar precision/scale fields available on Integer, Numeric, etc. are not referenced by SQLAlchemy other than when creating tables.
G訳:文字列の長さフィールド、および整数、数値などで使用可能な同様の精度/スケールフィールドは、テーブルを作成する場合を除いて、SQLAlchemyによって参照されません。
Additionally, Firebird and Oracle require sequences to generate new primary key identifiers, and SQLAlchemy doesn’t generate or assume these without being instructed. For that, you use the Sequence construct:
G訳:さらに、FirebirdとOracleは、新しい主キー識別子を生成するためのシーケンスを必要とし、SQLAlchemyは、指示なしにこれらを生成または想定しません。 そのためには、Sequenceコンストラクトを使用します。
1 2 |
from sqlalchemy import Sequence Column(Integer, Sequence('user_id_seq'), primary_key=True) |
Column(None, Integer(), table=None, primary_key=True, nullable=False, default=Sequence(‘user_id_seq’))
A full, foolproof Table generated via our declarative mapping is therefore:
G訳:したがって、宣言型マッピングを介して生成された完全で確実なテーブルは次のとおりです。
1 2 3 4 5 6 7 8 9 10 |
class User(Base): __tablename__ = 'users' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) name = Column(String(50)) fullname = Column(String(50)) nickname = Column(String(50)) def __repr__(self): return "<User(name='%s', fullname='%s', nickname='%s')>" % ( self.name, self.fullname, self.nickname) |
We include this more verbose table definition separately to highlight the difference between a minimal construct geared primarily towards in-Python usage only, versus one that will be used to emit CREATE TABLE statements on a particular set of backends with more stringent requirements.
G訳:このより詳細なテーブル定義を個別に含めて、主にPython内での使用のみを対象とした最小限の構成と、より厳しい要件を持つ特定のバックエンドのセットでCREATETABLEステートメントを発行するために使用される構成との違いを強調します。
Create an Instance of the Mapped Class¶
G訳:マップされたクラスのインスタンスを作成する¶
With mappings complete, let’s now create and inspect a User object:
G訳:マッピングが完了したら、次にUserオブジェクトを作成して検査します。
1 |
ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname') |
1 |
ed_user.name |
‘ed’
1 |
ed_user.nickname |
‘edsnickname’
1 |
str(ed_user.id) |
‘None’
the init() method
Our User class, as defined using the Declarative system, has been provided with a constructor (e.g. init() method) which automatically accepts keyword names that match the columns we’ve mapped. We are free to define any explicit init() method we prefer on our class, which will override the default method provided by Declarative.
G訳:宣言型システムを使用して定義されたUserクラスには、マッピングした列に一致するキーワード名を自動的に受け入れるコンストラクター(init ()メソッドなど)が用意されています。 クラスで優先する明示的なinit ()メソッドを自由に定義できます。これにより、Declarativeによって提供されるデフォルトのメソッドがオーバーライドされます。
Even though we didn’t specify it in the constructor, the id attribute still produces a value of None when we access it (as opposed to Python’s usual behavior of raising AttributeError for an undefined attribute). SQLAlchemy’s instrumentation normally produces this default value for column-mapped attributes when first accessed. For those attributes where we’ve actually assigned a value, the instrumentation system is tracking those assignments for use within an eventual INSERT statement to be emitted to the database.
G訳:コンストラクターで指定しなかった場合でも、id属性にアクセスすると、値Noneが生成されます(未定義の属性に対してAttributeErrorを発生させるPythonの通常の動作とは対照的です)。 SQLAlchemyのインストルメンテーションは通常、最初にアクセスされたときに、列にマップされた属性に対してこのデフォルト値を生成します。 実際に値を割り当てた属性の場合、インストルメンテーションシステムは、データベースに発行される最終的なINSERTステートメント内で使用するためにそれらの割り当てを追跡します。
Creating a Session(セッションの作成)
We’re now ready to start talking to the database. The ORM’s “handle” to the database is the Session. When we first set up the application, at the same level as our create_engine() statement, we define a Session class which will serve as a factory for new Session objects:
G訳:これで、データベースとの通信を開始する準備が整いました。 データベースに対するORMの「ハンドル」はセッションです。 アプリケーションを最初にセットアップするとき、create_engine()ステートメントと同じレベルで、新しいSessionオブジェクトのファクトリとして機能するSessionクラスを定義します。
1 2 3 |
from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) |
In the case where your application does not yet have an Engine when you define your module-level objects, just set it up like this:
G訳:モジュールレベルのオブジェクトを定義するときにアプリケーションにまだエンジンがない場合は、次のように設定します。
1 |
#Session = sessionmaker() |
Later, when you create your engine with create_engine(), connect it to the Session using sessionmaker.configure():
G訳:後で、create_engine()を使用してエンジンを作成するときに、sessionmaker.configure()を使用してエンジンをセッションに接続します。
1 |
# Session.configure(bind=engine) # once engine is available |
This custom-made Session class will create new Session objects which are bound to our database. Other transactional characteristics may be defined when calling sessionmaker as well; these are described in a later chapter. Then, whenever you need to have a conversation with the database, you instantiate a Session:
G訳:このカスタムメイドのSessionクラスは、データベースにバインドされる新しいSessionオブジェクトを作成します。 セッションメーカーを呼び出すときに、他のトランザクション特性も定義できます。 これらについては、後の章で説明します。 次に、データベースと会話する必要があるときはいつでも、セッションをインスタンス化します。
1 |
session = Session() |
G訳:上記のセッションはSQLite対応エンジンに関連付けられていますが、まだ接続を開いていません。最初に使用されるときは、エンジンによって維持されている接続のプールから接続を取得し、すべての変更をコミットするか、セッションオブジェクトを閉じるまで、その接続を保持します。
Adding and Updating Objects(オブジェクトの追加と更新)
To persist our User object, we Session.add() it to our Session:
G訳:Userオブジェクトを永続化するには、Session.add()をSessionに追加します。
1 2 |
ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname') session.add(ed_user) |
At this point, we say that the instance is pending; no SQL has yet been issued and the object is not yet represented by a row in the database. The Session will issue the SQL to persist Ed Jones as soon as is needed, using a process known as a flush. If we query the database for Ed Jones, all pending information will first be flushed, and the query is issued immediately thereafter.
G訳:この時点で、インスタンスは保留中であると言います。 SQLはまだ発行されておらず、オブジェクトはデータベース内の行でまだ表されていません。 セッションは、フラッシュと呼ばれるプロセスを使用して、必要に応じてすぐにEdJonesを永続化するSQLを発行します。 データベースにEdJonesを照会すると、保留中のすべての情報が最初にフラッシュされ、その後すぐに照会が発行されます。
For example, below we create a new Query object which loads instances of User. We “filter by” the name attribute of ed, and indicate that we’d like only the first result in the full list of rows. A User instance is returned which is equivalent to that which we’ve added:
G訳:たとえば、以下では、Userのインスタンスをロードする新しいQueryオブジェクトを作成します。 edのname属性で「フィルタリング」し、行の完全なリストの最初の結果のみが必要であることを示します。 追加したものと同等のユーザーインスタンスが返されます。
1 2 |
our_user = session.query(User).filter_by(name='ed').first() our_user |
2021-09-12 12:18:52,414 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2021-09-12 12:18:52,416 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, nickname) VALUES (?, ?, ?) 2021-09-12 12:18:52,416 INFO sqlalchemy.engine.base.Engine (‘ed’, ‘Ed Jones’, ‘edsnickname’) 2021-09-12 12:18:52,418 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname FROM users WHERE users.name = ? LIMIT ? OFFSET ? 2021-09-12 12:18:52,418 INFO sqlalchemy.engine.base.Engine (‘ed’, 1, 0)
In fact, the Session has identified that the row returned is the same row as one already represented within its internal map of objects, so we actually got back the identical instance as that which we just added:
1 |
ed_user is our_user |
True
The ORM concept at work here is known as an identity map and ensures that all operations upon a particular row within a Session operate upon the same set of data. Once an object with a particular primary key is present in the Session, all SQL queries on that Session will always return the same Python object for that particular primary key; it also will raise an error if an attempt is made to place a second, already-persisted object with the same primary key within the session.
We can add more User objects at once using add_all():
G訳:add_all()を使用して、一度にさらにUserオブジェクトを追加できます
1 2 3 4 |
session.add_all([ User(name='wendy', fullname='Wendy Williams', nickname='windy'), User(name='mary', fullname='Mary Contrary', nickname='mary'), User(name='fred', fullname='Fred Flintstone', nickname='freddy')]) |
Also, we’ve decided Ed’s nickname isn’t that great, so lets change it:
G訳:また、エドのニックネームはそれほど素晴らしいものではないと判断したので、変更してみましょう。
1 |
ed_user.nickname = 'eddie' |
The Session is paying attention. It knows, for example, that Ed Jones has been modified:
G訳:セッションは注目を集めています。たとえば、EdJonesが変更されたことを知っています
1 |
session.dirty |
IdentitySet([<User(name=’ed’, fullname=’Ed Jones’, nickname=’eddie’)>])
and that three new User objects are pending:
G訳:そして、3つの新しいUserオブジェクトが保留中です。
1 |
session.new |
IdentitySet([<User(name=’wendy’, fullname=’Wendy Williams’, nickname=’windy’)>, <User(name=’mary’, fullname=’Mary Contrary’, nickname=’mary’)>, <User(name=’fred’, fullname=’Fred Flintstone’, nickname=’freddy’)>])
We tell the Session that we’d like to issue all remaining changes to the database and commit the transaction, which has been in progress throughout. We do this via Session.commit(). The Session emits the UPDATE statement for the nickname change on “ed”, as well as INSERT statements for the three new User objects we’ve added:
1 |
session.commit() |
2021-09-12 12:18:56,538 INFO sqlalchemy.engine.base.Engine UPDATE users SET nickname=? WHERE users.id = ? 2021-09-12 12:18:56,539 INFO sqlalchemy.engine.base.Engine (‘eddie’, 1) 2021-09-12 12:18:56,540 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, nickname) VALUES (?, ?, ?) 2021-09-12 12:18:56,541 INFO sqlalchemy.engine.base.Engine (‘wendy’, ‘Wendy Williams’, ‘windy’) 2021-09-12 12:18:56,541 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, nickname) VALUES (?, ?, ?) 2021-09-12 12:18:56,542 INFO sqlalchemy.engine.base.Engine (‘mary’, ‘Mary Contrary’, ‘mary’) 2021-09-12 12:18:56,543 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, nickname) VALUES (?, ?, ?) 2021-09-12 12:18:56,543 INFO sqlalchemy.engine.base.Engine (‘fred’, ‘Fred Flintstone’, ‘freddy’) 2021-09-12 12:18:56,544 INFO sqlalchemy.engine.base.Engine COMMIT
Session.commit() flushes the remaining changes to the database, and commits the transaction. The connection resources referenced by the session are now returned to the connection pool. Subsequent operations with this session will occur in a new transaction, which will again re-acquire connection resources when first needed.
If we look at Ed’s id attribute, which earlier was None, it now has a value:
G訳:以前はNoneであったEdのid属性を見ると、次の値になっています。
1 |
ed_user.id |
1
After the Session inserts new rows in the database, all newly generated identifiers and database-generated defaults become available on the instance, either immediately or via load-on-first-access. In this case, the entire row was re-loaded on access because a new transaction was begun after we issued Session.commit(). SQLAlchemy by default refreshes data from a previous transaction the first time it’s accessed within a new transaction, so that the most recent state is available. The level of reloading is configurable as is described in Using the Session.
Rolling Back(ロールバック)
Since the Session works within a transaction, we can roll back changes made too. Let’s make two changes that we’ll revert; ed_user’s user name gets set to Edwardo:
G訳:セッションはトランザクション内で機能するため、行った変更をロールバックすることもできます。 元に戻す2つの変更を加えましょう。 ed_userのユーザー名はEdwardoに設定されます。
1 |
ed_user.name = 'Edwardo' |
and we’ll add another erroneous user, fake_user:
G訳:そして、別の誤ったユーザーfake_userを追加します
1 2 |
fake_user = User(name='fakeuser', fullname='Invalid', nickname='12345') session.add(fake_user) |
Querying the session, we can see that they’re flushed into the current transaction:
G訳:セッションをクエリすると、現在のトランザクションにフラッシュされていることがわかります。
1 |
session.query(User).filter(User.name.in_(['Edwardo', 'fakeuser'])).all() |
2021-09-12 12:19:00,004 INFO sqlalchemy.engine.base.Engine UPDATE users SET name=? WHERE users.id = ?
2021-09-12 12:19:00,005 INFO sqlalchemy.engine.base.Engine (‘Edwardo’, 1)
2021-09-12 12:19:00,006 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, nickname) VALUES (?, ?, ?)
2021-09-12 12:19:00,006 INFO sqlalchemy.engine.base.Engine (‘fakeuser’, ‘Invalid’, ‘12345’)
2021-09-12 12:19:00,007 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name IN (?, ?)
2021-09-12 12:19:00,008 INFO sqlalchemy.engine.base.Engine (‘Edwardo’, ‘fakeuser’)
<User(name=’fakeuser’, fullname=’Invalid’, nickname=’12345′)>]
Rolling back, we can see that ed_user’s name is back to ed, and fake_user has been kicked out of the session:
G訳:ロールバックすると、ed_userの名前がedに戻り、fake_userがセッションから追い出されたことがわかります。
1 |
session.rollback() |
2021-09-12 12:19:02,873 INFO sqlalchemy.engine.base.Engine ROLLBACK
1 |
<span class="n">ed_user</span><span class="o">.</span><span class="n">name</span> |
2021-09-12 12:19:07,333 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.id = ?
2021-09-12 12:19:07,334 INFO sqlalchemy.engine.base.Engine (1,)
1 |
fake_user in session |
issuing a SELECT illustrates the changes made to the database:
G訳:SELECTを発行すると、データベースに加えられた変更がわかります。
1 |
session.query(User).filter(User.name.in_(['ed', 'fakeuser'])).all() |
2021-09-12 12:19:11,870 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name IN (?, ?)
2021-09-12 12:19:11,871 INFO sqlalchemy.engine.base.Engine (‘ed’, ‘fakeuser’)
[<User(name=’ed’, fullname=’Ed Jones’, nickname=’eddie’)>]
Querying(クエリ)
A Query object is created using the query() method on Session. This function takes a variable number of arguments, which can be any combination of classes and class-instrumented descriptors. Below, we indicate a Query which loads User instances. When evaluated in an iterative context, the list of User objects present is returned:
1 2 |
for instance in session.query(User).order_by(User.id): print(instance.name, instance.fullname) |
2021-09-12 12:19:14,450 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users ORDER BY users.id
2021-09-12 12:19:14,450 INFO sqlalchemy.engine.base.Engine ()
ed Ed Jones
wendy Wendy Williams
mary Mary Contrary
fred Fred Flintstone
The Query also accepts ORM-instrumented descriptors as arguments. Any time multiple class entities or column-based entities are expressed as arguments to the query() function, the return result is expressed as tuples:
1 2 |
for name, fullname in session.query(User.name, User.fullname): print(name, fullname) |
2021-09-12 12:19:16,939 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name, users.fullname AS users_fullname FROM users 2021-09-12 12:19:16,940 INFO sqlalchemy.engine.base.Engine () ed Ed Jones wendy Wendy Williams mary Mary Contrary fred Fred Flintstone
The tuples returned by Query are named tuples, supplied by the KeyedTuple class, and can be treated much like an ordinary Python object. The names are the same as the attribute’s name for an attribute, and the class name for a class:
G訳:Queryによって返されるタプルは、KeyedTupleクラスによって提供される名前付きタプルであり、通常のPythonオブジェクトとほとんど同じように扱うことができます。名前は、属性の属性の名前、およびクラスのクラス名と同じです。
1 2 |
for row in session.query(User, User.name).all(): print(row.User, row.name) |
2021-09-12 12:19:20,510 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
2021-09-12 12:19:20,511 INFO sqlalchemy.engine.base.Engine ()
<User(name=’ed’, fullname=’Ed Jones’, nickname=’eddie’)> ed
<User(name=’wendy’, fullname=’Wendy Williams’, nickname=’windy’)> wendy
<User(name=’mary’, fullname=’Mary Contrary’, nickname=’mary’)> mary
<User(name=’fred’, fullname=’Fred Flintstone’, nickname=’freddy’)> fred
You can control the names of individual column expressions using the ColumnElement.label() construct, which is available from any ColumnElement-derived object, as well as any class attribute which is mapped to one (such as User.name):
1 2 |
for row in session.query(User.name.label('name_label')).all(): print(row.name_label) |
2021-09-12 12:19:22,714 INFO sqlalchemy.engine.base.Engine SELECT users.name AS name_label
FROM users
2021-09-12 12:19:22,715 INFO sqlalchemy.engine.base.Engine ()
ed
wendy
mary
fred
The name given to a full entity such as User, assuming that multiple entities are present in the call to Session.query(), can be controlled using aliased() :
G訳:Session.query()の呼び出しに複数のエンティティが存在すると仮定して、Userなどの完全なエンティティに付けられた名前は、aliased()を使用して制御できます。
エイリアス:エイリアスとは、偽名、別名、通称などの意味を持つ英単語。ITの分野では、ある対象や実体を、複数の異なるシンボルや識別子で同じように参照できるする仕組みを指す。別名。
1 2 3 4 5 6 |
from sqlalchemy.orm import aliased user_alias = aliased(User, name='user_alias') for row in session.query(user_alias, user_alias.name).all(): print(row.user_alias) |
2021-09-12 12:19:27,560 INFO sqlalchemy.engine.base.Engine SELECT user_alias.id AS user_alias_id, user_alias.name AS user_alias_name, user_alias.fullname AS user_alias_fullname, user_alias.nickname AS user_alias_nickname FROM users AS user_alias 2021-09-12 12:19:27,561 INFO sqlalchemy.engine.base.Engine () <User(name=’ed’, fullname=’Ed Jones’, nickname=’eddie’)> <User(name=’wendy’, fullname=’Wendy Williams’, nickname=’windy’)> <User(name=’mary’, fullname=’Mary Contrary’, nickname=’mary’)> <User(name=’fred’, fullname=’Fred Flintstone’, nickname=’freddy’)>
Basic operations with Query include issuing LIMIT and OFFSET, most conveniently using Python array slices and typically in conjunction with ORDER BY:
G訳:クエリの基本的な操作には、LIMITとOFFSETの発行が含まれます。最も便利なのは、Python配列スライスを使用し、通常はORDERBYと組み合わせて使用することです。
1 2 |
for u in session.query(User).order_by(User.id)[1:3]: print(u) |
2021-09-12 12:19:29,809 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users ORDER BY users.id
LIMIT ? OFFSET ?
2021-09-12 12:19:29,810 INFO sqlalchemy.engine.base.Engine (2, 1)
<User(name=’wendy’, fullname=’Wendy Williams’, nickname=’windy’)>
<User(name=’mary’, fullname=’Mary Contrary’, nickname=’mary’)>
and filtering results, which is accomplished either with filter_by(), which uses keyword arguments:
G訳:結果のフィルタリング。これは、キーワード引数を使用するfilter_by()を使用して実行されます。
1 2 3 |
for name, in session.query(User.name).\ filter_by(fullname='Ed Jones'): print(name) |
2021-09-12 12:19:47,210 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name
FROM users
WHERE users.fullname = ?
2021-09-12 12:19:47,211 INFO sqlalchemy.engine.base.Engine (‘Ed Jones’,)
ed
The Query object is fully generative, meaning that most method calls return a new Query object upon which further criteria may be added. For example, to query for users named “ed” with a full name of “Ed Jones”, you can call filter() twice, which joins criteria using AND:
G訳:Queryオブジェクトは完全に生成的です。つまり、ほとんどのメソッド呼び出しは新しいQueryオブジェクトを返し、その上にさらに基準を追加できます。 たとえば、フルネームが「EdJones」の「ed」という名前のユーザーをクエリするには、filter()を2回呼び出して、ANDを使用して条件を結合します。
1 2 3 4 |
for user in session.query(User).\ filter(User.name=='ed').\ filter(User.fullname=='Ed Jones'): print(user) |
2021-09-12 12:19:50,840 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name = ? AND users.fullname = ?
2021-09-12 12:19:50,841 INFO sqlalchemy.engine.base.Engine (‘ed’, ‘Ed Jones’)
<User(name=’ed’, fullname=’Ed Jones’, nickname=’eddie’)>
Common Filter Operators(一般的なフィルタ演算子)
Here’s a rundown of some of the most common operators used in filter():
G訳:filter()で使用される最も一般的な演算子の概要を次に示します。
ColumnOperators.eq():
query.filter(User.name == ‘ed’)
ColumnOperators.ne():
query.filter(User.name != ‘ed’)
ColumnOperators.like():
query.filter(User.name.like(‘%ed%’))
◇Note(備考)
ColumnOperators.like() renders the LIKE operator, which is case insensitive on some backends, and case sensitive on others. For guaranteed case-insensitive comparisons, use ColumnOperators.ilike().
G訳:ColumnOperators.like()は、LIKE演算子をレンダリングします。これは、一部のバックエンドでは大文字と小文字を区別せず、他のバックエンドでは大文字と小文字を区別します。大文字と小文字を区別しない比較を保証するには、ColumnOperators.ilike()を使用します。
ColumnOperators.ilike() (case-insensitive LIKE):
query.filter(User.name.ilike(‘%ed%’))
◇Note(備考)
most backends don’t support ILIKE directly. For those, the ColumnOperators.ilike() operator renders an expression combining LIKE with the LOWER SQL function applied to each operand.
G訳:ほとんどのバックエンドはILIKEを直接サポートしていません。これらの場合、ColumnOperators.ilike()演算子は、LIKEと各オペランドに適用されるLOWERSQL関数を組み合わせた式をレンダリングします。
ColumnOperators.in_():
query.filter(User.name.in_([‘ed’, ‘wendy’, ‘jack’]))
’# works with query objects too: query.filter(User.name.in_( session.query(User.name).filter(User.name.like(‘%ed%’)) ))
‘# use tuple() for composite (multi-column) queries from sqlalchemy import tuple query.filter( tuple(User.name, User.nickname).\ in([(‘ed’, ‘edsnickname’), (‘wendy’, ‘windy’)]) )
ColumnOperators.notin_():
query.filter(~User.name.in_([‘ed’, ‘wendy’, ‘jack’]))
ColumnOperators.notin_():
query.filter(~User.name.in_([‘ed’, ‘wendy’, ‘jack’]))
ColumnOperators.is_():
query.filter(User.name == None)
’# alternatively, if pep8/linters are a concern
query.filter(User.name.is_(None))
ColumnOperators.isnot():
query.filter(User.name != None)
’# alternatively, if pep8/linters are a concern
query.filter(User.name.isnot(None))
AND:
‘# use and_()
from sqlalchemy import and_
query.filter(and_(User.name == ‘ed’, User.fullname == ‘Ed Jones’))
‘# or send multiple expressions to .filter()
query.filter(User.name == ‘ed’, User.fullname == ‘Ed Jones’)
‘# or chain multiple filter()/filter_by() calls
query.filter(User.name == ‘ed’).filter(User.fullname == ‘Ed Jones’)
◇Note
Make sure you use and_() and not the Python and operator!
G訳:Pythonと演算子ではなく、必ずand_()を使用してください。
OR:
from sqlalchemy import or_
query.filter(or_(User.name == ‘ed’, User.name == ‘wendy’))
◇Note
Make sure you use or_() and not the Python or operator!
G訳:ノート Pythonや演算子ではなく、必ずor_()を使用してください。
ColumnOperators.match():
query.filter(User.name.match(‘wendy’))
◇Note
ColumnOperators.match() uses a database-specific MATCH or CONTAINS function; its behavior will vary by backend and is not available on some backends such as SQLite.
G訳:ColumnOperators.match()は、データベース固有のMATCHまたはCONTAINS関数を使用します。その動作はバックエンドによって異なり、SQLiteなどの一部のバックエンドでは使用できません。
Returning Lists and Scalars(リストとスカラーを返す)
A number of methods on Query immediately issue SQL and return a value containing loaded database results. Here’s a brief tour:
G訳:クエリの多くのメソッドはすぐにSQLを発行し、ロードされたデータベースの結果を含む値を返します。簡単なツアーは次のとおりです。
Query.all()
returns a list:
リストを返します
1 2 |
query = session.query(User).filter(User.name.like('%ed')).order_by(User.id) query.all() |
2021-09-12 12:19:57,695 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name LIKE ? ORDER BY users.id
2021-09-12 12:19:57,696 INFO sqlalchemy.engine.base.Engine (‘%ed’,)
<User(name=’fred’, fullname=’Fred Flintstone’, nickname=’freddy’)>]
◇Warning
When the Query object returns lists of ORM-mapped objects such as the User object above, the entries are deduplicated based on primary key, as the results are interpreted from the SQL result set. That is, if SQL query returns a row with id=7 twice, you would only get a single User(id=7) object back in the result list. This does not apply to the case when individual columns are queried.
G訳:Queryオブジェクトが上記のUserオブジェクトなどのORMにマップされたオブジェクトのリストを返す場合、結果はSQL結果セットから解釈されるため、エントリは主キーに基づいて重複排除されます。 つまり、SQLクエリがid = 7の行を2回返す場合、結果リストには1つのUser(id = 7)オブジェクトしか返されません。 これは、個々の列が照会される場合には適用されません。
・See also
My Query does not return the same number of objects as query.count() tells me – why?
G訳:私のクエリは、query.count()が教えてくれるのと同じ数のオブジェクトを返しません-なぜですか?
Query.first()
applies a limit of one and returns the first result as a scalar:
G訳:1の制限を適用し、最初の結果をスカラーとして返します。
1 |
query.first() |
2021-09-12 12:19:58,385 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname FROM users WHERE users.name LIKE ? ORDER BY users.id LIMIT ? OFFSET ? 2021-09-12 12:19:58,385 INFO sqlalchemy.engine.base.Engine (‘%ed’, 1, 0)
<User(name=’ed’, fullname=’Ed Jones’, nickname=’eddie’)>
Query.one()
fully fetches all rows, and if not exactly one object identity or composite row is present in the result, raises an error. With multiple rows found:
G訳:すべての行を完全にフェッチし、結果にオブジェクトIDまたは複合行が1つだけ存在しない場合は、エラーが発生します。複数の行が見つかりました
user = query.one() Traceback (most recent call last): … MultipleResultsFound: Multiple rows were found for one()
With no rows found:
G訳:行が見つかりません:
user = query.filter(User.id == 99).one() Traceback (most recent call last): … NoResultFound: No row was found for one()
The Query.one() method is great for systems that expect to handle “no items found” versus “multiple items found” differently; such as a RESTful web service, which may want to raise a “404 not found” when no results are found, but raise an application error when multiple results are found.
G訳:Query.one()メソッドは、「アイテムが見つかりません」と「複数のアイテムが見つかりました」を異なる方法で処理することを期待するシステムに最適です。 結果が見つからない場合は「404notfound」を発生させたいが、複数の結果が見つかった場合はアプリケーションエラーを発生させたい場合があるRESTfulWebサービスなど。
Query.one_or_none()
Query.one_or_none() is like Query.one(), except that if no results are found, it doesn’t raise an error; it just returns None. Like Query.one(), however, it does raise an error if multiple results are found.
G訳:Query.one_or_none()はQuery.one()に似ていますが、結果が見つからない場合でもエラーが発生しない点が異なります。 Noneを返すだけです。ただし、Query.one()と同様に、複数の結果が見つかった場合はエラーが発生します。
Query.scalar()
Query.scalar() invokes the Query.one() method, and upon success returns the first column of the row:
G訳:Query.scalar()はQuery.one()メソッドを呼び出し、成功すると行の最初の列を返します。
query = session.query(User.id).filter(User.name == ‘ed’).\ … order_by(User.id) query.scalar() 1
Using Textual SQL(テキストSQLの使用)
Literal strings can be used flexibly with Query, by specifying their use with the text() construct, which is accepted by most applicable methods. For example, Query.filter() and Query.order_by():
G訳:リテラル文字列は、ほとんどの適用可能なメソッドで受け入れられるtext()構造で使用を指定することにより、Queryで柔軟に使用できます。 たとえば、Query.filter()およびQuery.order_by():
1 2 3 4 5 |
from sqlalchemy import text for user in session.query(User).\ filter(text("id<224")).\ order_by(text("id")).all(): print(user.name) |
2021-09-12 12:20:07,275 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE id<224 ORDER BY id
2021-09-12 12:20:07,276 INFO sqlalchemy.engine.base.Engine ()
ed
wendy
mary
fred
Bind parameters can be specified with string-based SQL, using a colon. To specify the values, use the Query.params() method:
G訳:バインドパラメータは、コロンを使用して文字列ベースのSQLで指定できます。値を指定するには、Query.params()メソッドを使用します。
1 2 |
session.query(User).filter(text("id<:value and name=:name")).\ params(value=224, name='fred').order_by(User.id).one() |
2021-09-12 12:20:08,360 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE id<? and name=? ORDER BY users.id
2021-09-12 12:20:08,361 INFO sqlalchemy.engine.base.Engine (224, ‘fred’)
<User(name=’fred’, fullname=’Fred Flintstone’, nickname=’freddy’)>
To use an entirely string-based statement, a text() construct representing a complete statement can be passed to Query.from_statement(). Without additional specifiers, the columns in the string SQL are matched to the model columns based on name, such as below where we use just an asterisk to represent loading all columns:
G訳:完全に文字列ベースのステートメントを使用するには、完全なステートメントを表すtext()コンストラクトをQuery.from_statement()に渡すことができます。 追加の指定子がない場合、文字列SQLの列は、名前に基づいてモデル列と照合されます。たとえば、以下のように、すべての列の読み込みを表すためにアスタリスクのみを使用します。
1 2 |
session.query(User).from_statement( text("SELECT * FROM users where name=:name")).params(name='ed').all() |
2021-09-12 12:20:09,216 INFO sqlalchemy.engine.base.Engine SELECT * FROM users where name=?
2021-09-12 12:20:09,217 INFO sqlalchemy.engine.base.Engine (‘ed’,)
Matching columns on name works for simple cases but can become unwieldy when dealing with complex statements that contain duplicate column names or when using anonymized ORM constructs that don’t easily match to specific names. Additionally, there is typing behavior present in our mapped columns that we might find necessary when handling result rows. For these cases, the text() construct allows us to link its textual SQL to Core or ORM-mapped column expressions positionally; we can achieve this by passing column expressions as positional arguments to the TextClause.columns() method:
G訳:名前の列の一致は単純な場合には機能しますが、重複する列名を含む複雑なステートメントを処理する場合や、特定の名前に簡単に一致しない匿名化されたORM構造を使用する場合は扱いにくくなる可能性があります。 さらに、マップされた列には、結果行を処理するときに必要になる可能性のある入力動作があります。 このような場合、text()構文を使用すると、テキストSQLをコアまたはORMにマップされた列式に位置的にリンクできます。 これは、列式を位置引数としてTextClause.columns()メソッドに渡すことで実現できます。
1 2 3 4 |
stmt = text("SELECT name, id, fullname, nickname " "FROM users where name=:name") stmt = stmt.columns(User.name, User.id, User.fullname, User.nickname) session.query(User).from_statement(stmt).params(name='ed').all() |
2021-09-12 12:20:10,070 INFO sqlalchemy.engine.base.Engine SELECT name, id, fullname, nickname FROM users where name=?
2021-09-12 12:20:10,071 INFO sqlalchemy.engine.base.Engine (‘ed’,)
◇New in version 1.1: The TextClause.columns() method now accepts column expressions which will be matched positionally to a plain text SQL result set, eliminating the need for column names to match or even be unique in the SQL statement.
G訳:バージョン1.1の新機能:TextClause.columns()メソッドは、プレーンテキストのSQL結果セットと位置的に一致する列式を受け入れるようになり、SQLステートメントで列名を一致または一意にする必要がなくなりました。
When selecting from a text() construct, the Query may still specify what columns and entities are to be returned; instead of query(User) we can also ask for the columns individually, as in any other case:
G訳:text()構造から選択する場合でも、クエリは返される列とエンティティを指定する場合があります。 query(User)の代わりに、他の場合と同様に、列を個別に要求することもできます。
1 2 3 4 |
stmt = text("SELECT name, id FROM users where name=:name") stmt = stmt.columns(User.name, User.id) session.query(User.id, User.name).\ from_statement(stmt).params(name='ed').all() |
2021-09-12 12:20:11,000 INFO sqlalchemy.engine.base.Engine SELECT name, id FROM users where name=? 2021-09-12 12:20:11,001 INFO sqlalchemy.engine.base.Engine (‘ed’,)
[(1, ‘ed’)]
◇See also
Using Textual SQL – The text() construct explained from the perspective of Core-only queries.
Counting(カウント)
Query includes a convenience method for counting called Query.count():
G訳:Queryには、Query.count()と呼ばれるカウント用の便利なメソッドが含まれています。
1 |
session.query(User).filter(User.name.like('%ed')).count() |
2021-09-12 12:20:11,991 INFO sqlalchemy.engine.base.Engine SELECT count(*) AS count_1 FROM (SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname FROM users WHERE users.name LIKE ?) AS anon_1 2021-09-12 12:20:11,992 INFO sqlalchemy.engine.base.Engine (‘%ed’,)
2
Counting on count()
Query.count() used to be a very complicated method when it would try to guess whether or not a subquery was needed around the existing query, and in some exotic cases it wouldn’t do the right thing. Now that it uses a simple subquery every time, it’s only two lines long and always returns the right answer. Use func.count() if a particular statement absolutely cannot tolerate the subquery being present.
G訳:Query.count()は、既存のクエリの周囲にサブクエリが必要かどうかを推測しようとするときに非常に複雑なメソッドであり、一部のエキゾチックなケースでは正しく機能しませんでした。 毎回単純なサブクエリを使用するようになったため、長さはわずか2行で、常に正しい答えを返します。 特定のステートメントがサブクエリの存在を絶対に許容できない場合は、func.count()を使用します。
The Query.count() method is used to determine how many rows the SQL statement would return. Looking at the generated SQL above, SQLAlchemy always places whatever it is we are querying into a subquery, then counts the rows from that. In some cases this can be reduced to a simpler SELECT count(*) FROM table, however modern versions of SQLAlchemy don’t try to guess when this is appropriate, as the exact SQL can be emitted using more explicit means.
G訳:Query.count()メソッドは、SQLステートメントが返す行数を決定するために使用されます。 上記で生成されたSQLを見ると、SQLAlchemyは常に、クエリを実行しているものをすべてサブクエリに配置し、そこから行をカウントします。 場合によっては、これをより単純なSELECT count(*)FROMテーブルに減らすことができますが、SQLAlchemyの最新バージョンでは、より明示的な手段を使用して正確なSQLを出力できるため、これが適切な場合を推測しようとはしません。
For situations where the “thing to be counted” needs to be indicated specifically, we can specify the “count” function directly using the expression func.count(), available from the expression.func construct. Below we use it to return the count of each distinct user name:
G訳:「カウントするもの」を具体的に指定する必要がある場合は、expression.funcコンストラクトから入手できる式func.count()を使用して、「count」関数を直接指定できます。 以下では、これを使用して、個別のユーザー名の数を返します。
1 2 3 |
from sqlalchemy import func session.query(func.count(User.name), User.name).group_by(User.name).all() |
2021-09-12 12:20:13,446 INFO sqlalchemy.engine.base.Engine SELECT count(users.name) AS count_1, users.name AS users_name
FROM users GROUP BY users.name
2021-09-12 12:20:13,446 INFO sqlalchemy.engine.base.Engine ()
[(1, ‘ed’), (1, ‘fred’), (1, ‘mary’), (1, ‘wendy’)]
To achieve our simple SELECT count(*) FROM table, we can apply it as:
G訳:単純なSELECTcount(*)FROMテーブルを実現するために、次のように適用できます。
1 |
session.query(func.count('*')).select_from(User).scalar() |
2021-09-12 12:20:14,225 INFO sqlalchemy.engine.base.Engine SELECT count(?) AS count_1
FROM users
2021-09-12 12:20:14,225 INFO sqlalchemy.engine.base.Engine (‘*’,)
The usage of Query.select_from() can be removed if we express the count in terms of the User primary key directly:
G訳:ユーザーの主キーでカウントを直接表すと、Query.select_from()の使用を削除できます。
1 |
session.query(func.count(User.id)).scalar() |
2021-09-12 12:20:14,795 INFO sqlalchemy.engine.base.Engine SELECT count(users.id) AS count_1
FROM users
2021-09-12 12:20:14,796 INFO sqlalchemy.engine.base.Engine ()
Building a Relationship(リレーションシップの構築)
Let’s consider how a second table, related to User, can be mapped and queried. Users in our system can store any number of email addresses associated with their username. This implies a basic one to many association from the users to a new table which stores email addresses, which we will call addresses. Using declarative, we define this table along with its mapped class, Address:
G訳:ユーザーに関連する2番目のテーブルをマッピングしてクエリする方法を考えてみましょう。 システムのユーザーは、ユーザー名に関連付けられた電子メールアドレスをいくつでも保存できます。 これは、ユーザーから、アドレスと呼ばれる電子メールアドレスを格納する新しいテーブルへの基本的な1対多の関連付けを意味します。 宣言型を使用して、このテーブルをそのマップされたクラスであるアドレスとともに定義します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship class Address(Base): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) email_address = Column(String, nullable=False) user_id = Column(Integer, ForeignKey('users.id')) user = relationship("User", back_populates="addresses") def __repr__(self): return "<Address(email_address='%s')>" % self.email_address User.addresses = relationship( "Address", order_by=Address.id, back_populates="user") |
The above class introduces the ForeignKey construct, which is a directive applied to Column that indicates that values in this column should be constrained to be values present in the named remote column. This is a core feature of relational databases, and is the “glue” that transforms an otherwise unconnected collection of tables to have rich overlapping relationships. The ForeignKey above expresses that values in the addresses.user_id column should be constrained to those values in the users.id column, i.e. its primary key.
G訳:上記のクラスは、この列の値が指定されたリモート列に存在する値になるように制約する必要があることを示す、Columnに適用されるディレクティブであるForeignKey構造を導入します。 これはリレーショナルデータベースのコア機能であり、他の方法では接続されていないテーブルのコレクションを変換して、豊富な重複関係を持つようにする「接着剤」です。 上記のForeignKeyは、addresses.user_id列の値を、users.id列の値、つまり主キーに制限する必要があることを示しています。
A second directive, known as relationship(), tells the ORM that the Address class itself should be linked to the User class, using the attribute Address.user. relationship() uses the foreign key relationships between the two tables to determine the nature of this linkage, determining that Address.user will be many to one. An additional relationship() directive is placed on the User mapped class under the attribute User.addresses. In both relationship() directives, the parameter relationship.back_populates is assigned to refer to the complementary attribute names; by doing so, each relationship() can make intelligent decision about the same relationship as expressed in reverse; on one side, Address.user refers to a User instance, and on the other side, User.addresses refers to a list of Address instances.
G訳:Relationship()として知られる2番目のディレクティブは、属性Address.userを使用して、Addressクラス自体をUserクラスにリンクする必要があることをORMに通知します。 Relationship()は、2つのテーブル間の外部キー関係を使用して、このリンケージの性質を判別し、Address.userが多対1になることを判別します。 追加のrelationship()ディレクティブは、属性User.addressesの下のUserマップクラスに配置されます。 両方のrelationship()ディレクティブで、パラメーターrelationship.back_populatesが割り当てられ、補完的な属性名を参照します。 そうすることで、各relationship()は、逆に表現されたものと同じ関係についてインテリジェントな決定を下すことができます。 一方では、Address.userはUserインスタンスを参照し、もう一方では、User.addressesはAddressインスタンスのリストを参照します。
◇Note
The relationship.back_populates parameter is a newer version of a very common SQLAlchemy feature called relationship.backref. The relationship.backref parameter hasn’t gone anywhere and will always remain available! The relationship.back_populates is the same thing, except a little more verbose and easier to manipulate. For an overview of the entire topic, see the section Linking Relationships with Backref.
G訳:注relationship.back_populatesパラメーターは、relationship.backrefと呼ばれる非常に一般的なSQLAlchemy機能の新しいバージョンです。 Relationship.backrefパラメータはどこにも移動しておらず、いつでも利用できます。 Relationship.back_populatesは同じものですが、もう少し冗長で操作が簡単です。 トピック全体の概要については、バックリファレンスとの関係のリンクのセクションを参照してください。
The reverse side of a many-to-one relationship is always one to many. A full catalog of available relationship() configurations is at Basic Relationship Patterns.
G訳:多対1の関係の裏側は、常に1対多です。 利用可能なrelationship()構成の完全なカタログは、Basic RelationshipPatternsにあります。
The two complementing relationships Address.user and User.addresses are referred to as a bidirectional relationship, and is a key feature of the SQLAlchemy ORM. The section Linking Relationships with Backref discusses the “backref” feature in detail.
G訳:2つの補完関係Address.userとUser.addressesは双方向関係と呼ばれ、SQLAlchemyORMの重要な機能です。 「関係とBackrefのリンク」セクションでは、「backref」機能について詳しく説明しています。
Arguments to relationship() which concern the remote class can be specified using strings, assuming the Declarative system is in use. Once all mappings are complete, these strings are evaluated as Python expressions in order to produce the actual argument, in the above case the User class. The names which are allowed during this evaluation include, among other things, the names of all classes which have been created in terms of the declared base.
G訳:リモートクラスに関係するrelationship()の引数は、宣言型システムが使用されていることを前提として、文字列を使用して指定できます。 すべてのマッピングが完了すると、これらの文字列は、実際の引数(上記の場合はUserクラス)を生成するためにPython式として評価されます。 この評価中に許可される名前には、特に、宣言されたベースに関して作成されたすべてのクラスの名前が含まれます。
See the docstring for relationship() for more detail on argument style.
G訳:引数のスタイルの詳細については、relationship()のdocstringを参照してください。
We’ll need to create the addresses table in the database, so we will issue another CREATE from our metadata, which will skip over tables which have already been created:
G訳:データベースにaddressesテーブルを作成する必要があるため、メタデータから別のCREATEを発行します。これにより、すでに作成されているテーブルがスキップされます。
1 |
Base.metadata.create_all(engine) |
2021-09-12 12:27:51,533 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info(“users”) 2021-09-12 12:27:51,533 INFO sqlalchemy.engine.base.Engine () 2021-09-12 12:27:51,534 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info(“addresses”) 2021-09-12 12:27:51,535 INFO sqlalchemy.engine.base.Engine () 2021-09-12 12:27:51,535 INFO sqlalchemy.engine.base.Engine PRAGMA temp.table_info(“addresses”) 2021-09-12 12:27:51,536 INFO sqlalchemy.engine.base.Engine () 2021-09-12 12:27:51,537 INFO sqlalchemy.engine.base.Engine CREATE TABLE addresses ( id INTEGER NOT NULL, email_address VARCHAR NOT NULL, user_id INTEGER, PRIMARY KEY (id), FOREIGN KEY(user_id) REFERENCES users (id) ) 2021-09-12 12:27:51,538 INFO sqlalchemy.engine.base.Engine () 2021-09-12 12:27:51,539 INFO sqlalchemy.engine.base.Engine COMMIT
Working with Related Objects(関連オブジェクトの操作)
Now when we create a User, a blank addresses collection will be present. Various collection types, such as sets and dictionaries, are possible here (see Customizing Collection Access for details), but by default, the collection is a Python list.
G訳:これで、ユーザーを作成すると、空白のアドレスコレクションが表示されます。ここでは、セットや辞書などのさまざまなコレクションタイプを使用できます(詳細については、コレクションアクセスのカスタマイズを参照してください)が、デフォルトでは、コレクションはPythonリストです。
1 2 |
jack = User(name='jack', fullname='Jack Bean', nickname='gjffdd') jack.addresses |
[]
We are free to add Address objects on our User object. In this case we just assign a full list directly:
G訳:UserオブジェクトにAddressオブジェクトを自由に追加できます。この場合、完全なリストを直接割り当てます。
1 2 3 |
jack.addresses = [ Address(email_address='jack@google.com'), Address(email_address='j25@yahoo.com')] |
When using a bidirectional relationship, elements added in one direction automatically become visible in the other direction. This behavior occurs based on attribute on-change events and is evaluated in Python, without using any SQL:
G訳:双方向の関係を使用する場合、一方向に追加された要素は自動的に他の方向に表示されます。 この動作は、属性の変更時イベントに基づいて発生し、SQLを使用せずにPythonで評価されます。
1 |
jack.addresses[1] |
<Address(email_address=’j25@yahoo.com’)>
1 |
jack.addresses[1].user |
<User(name=’jack’, fullname=’Jack Bean’, nickname=’gjffdd’)>
Let’s add and commit Jack Bean to the database. jack as well as the two Address members in the corresponding addresses collection are both added to the session at once, using a process known as cascading:
G訳:JackBeanをデータベースに追加してコミットしましょう。 ジャックと、対応するアドレスコレクション内の2つのアドレスメンバーの両方が、カスケードと呼ばれるプロセスを使用して、一度にセッションに追加されます。
1 2 |
session.add(jack) session.commit() |
2021-09-12 12:35:01,059 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, fullname, nickname) VALUES (?, ?, ?)
2021-09-12 12:35:01,060 INFO sqlalchemy.engine.base.Engine (‘jack’, ‘Jack Bean’, ‘gjffdd’)
2021-09-12 12:35:01,061 INFO sqlalchemy.engine.base.Engine INSERT INTO addresses (email_address, user_id) VALUES (?, ?)
2021-09-12 12:35:01,062 INFO sqlalchemy.engine.base.Engine (‘jack@google.com’, 5)
2021-09-12 12:35:01,063 INFO sqlalchemy.engine.base.Engine INSERT INTO addresses (email_address, user_id) VALUES (?, ?)
2021-09-12 12:35:01,063 INFO sqlalchemy.engine.base.Engine (‘j25@yahoo.com’, 5)
2021-09-12 12:35:01,064 INFO sqlalchemy.engine.base.Engine COMMIT
Querying for Jack, we get just Jack back. No SQL is yet issued for Jack’s addresses:
G訳:ジャックを照会すると、ジャックだけが返されます。ジャックの住所に対してSQLはまだ発行されていません。
1 2 3 |
jack = session.query(User).\ filter_by(name='jack').one() jack |
2021-09-12 12:36:54,597 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2021-09-12 12:36:54,597 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name = ?
2021-09-12 12:36:54,598 INFO sqlalchemy.engine.base.Engine (‘jack’,)
<User(name=’jack’, fullname=’Jack Bean’, nickname=’gjffdd’)>
Let’s look at the addresses collection. Watch the SQL:
G訳:アドレスコレクションを見てみましょう。 SQLを見る:
1 |
jack.addresses |
2021-09-12 12:38:13,961 INFO sqlalchemy.engine.base.Engine SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id
FROM addresses
WHERE ? = addresses.user_id ORDER BY addresses.id
2021-09-12 12:38:13,962 INFO sqlalchemy.engine.base.Engine (5,)
<Address(email_address=’j25@yahoo.com’)>]
When we accessed the addresses collection, SQL was suddenly issued. This is an example of a lazy loading relationship. The addresses collection is now loaded and behaves just like an ordinary list. We’ll cover ways to optimize the loading of this collection in a bit.
G訳:アドレスコレクションにアクセスすると、SQLが突然発行されました。 これは、遅延読み込み関係の例です。 これで、アドレスコレクションが読み込まれ、通常のリストと同じように動作します。 このコレクションの読み込みを最適化する方法については、後ほど説明します。
Querying with Joins(結合を使用したクエリ)
Now that we have two tables, we can show some more features of Query, specifically how to create queries that deal with both tables at the same time. The Wikipedia page on SQL JOIN offers a good introduction to join techniques, several of which we’ll illustrate here.
G訳:2つのテーブルができたので、クエリのいくつかの機能、特に両方のテーブルを同時に処理するクエリを作成する方法を示すことができます。 SQL JOINのWikipediaページには、結合手法の優れた紹介があります。そのいくつかをここで説明します。
To construct a simple implicit join between User and Address, we can use Query.filter() to equate their related columns together. Below we load the User and Address entities at once using this method:
G訳:UserとAddressの間に単純な暗黙の結合を構築するには、Query.filter()を使用して、関連する列を同等にします。 以下では、このメソッドを使用して、UserエンティティとAddressエンティティを一度にロードします。
1 2 3 4 5 6 |
for u, a in session.query(User, Address).\ filter(User.id==Address.user_id).\ filter(Address.email_address=='jack@google.com').\ all(): print(u) print(a) |
FROM users, addresses
WHERE users.id = addresses.user_id AND addresses.email_address = ?
2021-09-12 12:41:32,878 INFO sqlalchemy.engine.base.Engine (‘jack@google.com’,)
<User(name=’jack’, fullname=’Jack Bean’, nickname=’gjffdd’)>
<Address(email_address=’jack@google.com’)>
G訳:一方、実際のSQL JOIN構文は、Query.join()メソッドを使用して最も簡単に実現できます。
1 2 3 |
session.query(User).join(Address).\ filter(Address.email_address=='jack@google.com').\ all() |
2021-09-12 12:43:16,137 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users JOIN addresses ON users.id = addresses.user_id
WHERE addresses.email_address = ?
2021-09-12 12:43:16,138 INFO sqlalchemy.engine.base.Engine (‘jack@google.com’,)
Query.join() knows how to join between User and Address because there’s only one foreign key between them. If there were no foreign keys, or several, Query.join() works better when one of the following forms are used:
G訳:Query.join()は、ユーザーとアドレスの間に外部キーが1つしかないため、それらの間で結合する方法を知っています。 外部キーがないか、複数ある場合は、次のいずれかの形式を使用すると、Query.join()の方がうまく機能します。
query.join(Address, User.id==Address.user_id) # explicit condition
query.join(User.addresses) # specify relationship from left to right
query.join(Address, User.addresses) # same, with explicit target
As you would expect, the same idea is used for “outer” joins, using the Query.outerjoin() function:
G訳:ご想像のとおり、Query.outerjoin()関数を使用して、同じアイデアが「外部」結合に使用されます。
query.outerjoin(User.addresses) # LEFT OUTER JOIN
The reference documentation for Query.join() contains detailed information and examples of the calling styles accepted by this method; Query.join() is an important method at the center of usage for any SQL-fluent application.
G訳:Query.join()のリファレンスドキュメントには、このメソッドで受け入れられる呼び出しスタイルの詳細情報と例が含まれています。 Query.join()は、SQLに精通したアプリケーションの使用の中心となる重要なメソッドです。
What does Query select from if there’s multiple entities?
The Query.join() method will typically join from the leftmost item in the list of entities, when the ON clause is omitted, or if the ON clause is a plain SQL expression. To control the first entity in the list of JOINs, use the Query.select_from() method:
G訳:Query.join()メソッドは通常、ON句が省略されている場合、またはON句がプレーンSQL式である場合に、エンティティのリストの左端の項目から結合します。 JOINのリストの最初のエンティティを制御するには、Query.select_from()メソッドを使用します。
query = session.query(User, Address).select_from(Address).join(User)
Using Aliases(エイリアス)
When querying across multiple tables, if the same table needs to be referenced more than once, SQL typically requires that the table be aliased with another name, so that it can be distinguished against other occurrences of that table. This is supported using the aliased() construct. When joining to relationships using using aliased(), the special attribute method PropComparator.of_type() may be used to alter the target of a relationship join to refer to a given aliased() object. Below we join to the Address entity twice, to locate a user who has two distinct email addresses at the same time:
G訳:複数のテーブルにまたがってクエリを実行するときに、同じテーブルを複数回参照する必要がある場合、SQLでは通常、テーブルを別の名前でエイリアス化して、そのテーブルの他のオカレンスと区別できるようにする必要があります。 これは、aliased()構造を使用してサポートされます。 aliased()を使用して関係に結合する場合、特別な属性メソッドPropComparator.of_type()を使用して、特定のalias()オブジェクトを参照するように関係結 合のターゲットを変更できます。 以下では、Addressエンティティに2回参加して、2つの異なる電子メールアドレスを同時に持っているユーザーを見つけます。
1 2 3 4 5 6 7 8 9 10 |
from sqlalchemy.orm import aliased adalias1 = aliased(Address) adalias2 = aliased(Address) for username, email1, email2 in \ session.query(User.name, adalias1.email_address, adalias2.email_address).\ join(User.addresses.of_type(adalias1)).\ join(User.addresses.of_type(adalias2)).\ filter(adalias1.email_address=='jack@google.com').\ filter(adalias2.email_address=='j25@yahoo.com'): print(username, email1, email2) |
2021-09-12 12:51:31,746 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name, addresses_1.email_address AS addresses_1_email_address, addresses_2.email_address AS addresses_2_email_address
FROM users JOIN addresses AS addresses_1 ON users.id = addresses_1.user_id JOIN addresses AS addresses_2 ON users.id = addresses_2.user_id
WHERE addresses_1.email_address = ? AND addresses_2.email_address = ?
2021-09-12 12:51:31,746 INFO sqlalchemy.engine.base.Engine (‘jack@google.com’, ‘j25@yahoo.com’)
jack jack@google.com j25@yahoo.com
In addition to using the PropComparator.of_type() method, it is common to see the Query.join() method joining to a specific target by indicating it separately:
G訳:PropComparator.of_type()メソッドを使用することに加えて、Query.join()メソッドが特定のターゲットに個別に指定することで結合するのを見るのが一般的です。
1 2 |
# equivalent to query.join(User.addresses.of_type(adalias1)) q = query.join(adalias1, User.addresses) |
Using Subqueries(サブクエリ)
The Query is suitable for generating statements which can be used as subqueries. Suppose we wanted to load User objects along with a count of how many Address records each user has. The best way to generate SQL like this is to get the count of addresses grouped by user ids, and JOIN to the parent. In this case we use a LEFT OUTER JOIN so that we get rows back for those users who don’t have any addresses, e.g.:
G訳:クエリは、サブクエリとして使用できるステートメントの生成に適しています。 各ユーザーが持っているAddressレコードの数とともにUserオブジェクトをロードしたいとします。 このようなSQLを生成する最良の方法は、ユーザーIDでグループ化されたアドレスの数を取得し、親にJOINすることです。 この場合、LEFT OUTER JOINを使用して、アドレスを持たないユーザーの行を取得します。例:
1 2 3 4 5 |
(SELECT user_id, count(*) AS address_count FROM addresses GROUP BY user_id) AS adr_count ON users.id=adr_count.user_id |
Using the Query, we build a statement like this from the inside out. The statement accessor returns a SQL expression representing the statement generated by a particular Query – this is an instance of a select() construct, which are described in SQL Expression Language Tutorial:
G訳:クエリを使用して、このようなステートメントを裏返しに作成します。 ステートメントアクセサは、特定のクエリによって生成されたステートメントを表すSQL式を返します。これはselect()構造のインスタンスであり、SQL式言語チュートリアルで説明されています。
1 2 3 4 |
from sqlalchemy.sql import func stmt = session.query(Address.user_id, func.count('*').\ label('address_count')).\ group_by(Address.user_id).subquery() |
The func keyword generates SQL functions, and the subquery() method on Query produces a SQL expression construct representing a SELECT statement embedded within an alias (it’s actually shorthand for query.statement.alias()).
G訳:funcキーワードはSQL関数を生成し、Queryのsubquery()メソッドはエイリアス内に埋め込まれたSELECTステートメントを表すSQL式コンストラクトを生成します(実際にはquery.statement.alias()の省略形です)。
Once we have our statement, it behaves like a Table construct, such as the one we created for users at the start of this tutorial. The columns on the statement are accessible through an attribute called c:
G訳:ステートメントを取得すると、このチュートリアルの開始時にユーザー用に作成したようなTableコンストラクトのように動作します。 ステートメントの列には、cと呼ばれる属性を介してアクセスできます。
1 2 3 |
for u, count in session.query(User, stmt.c.address_count).\ outerjoin(stmt, User.id==stmt.c.user_id).order_by(User.id): print(u, count) |
2021-09-12 12:57:53,013 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname, anon_1.address_count AS anon_1_address_count
FROM users LEFT OUTER JOIN (SELECT addresses.user_id AS user_id, count(?) AS address_count
FROM addresses GROUP BY addresses.user_id) AS anon_1 ON users.id = anon_1.user_id ORDER BY users.id
2021-09-12 12:57:53,014 INFO sqlalchemy.engine.base.Engine (‘*’,)
<User(name=’ed’, fullname=’Ed Jones’, nickname=’eddie’)> None
<User(name=’wendy’, fullname=’Wendy Williams’, nickname=’windy’)> None
<User(name=’mary’, fullname=’Mary Contrary’, nickname=’mary’)> None
<User(name=’fred’, fullname=’Fred Flintstone’, nickname=’freddy’)> None
<User(name=’jack’, fullname=’Jack Bean’, nickname=’gjffdd’)> 2
Selecting Entities from Subqueries
Above, we just selected a result that included a column from a subquery. What if we wanted our subquery to map to an entity ? For this we use aliased() to associate an “alias” of a mapped class to a subquery:
G訳:上記では、サブクエリの列を含む結果を選択しました。 サブクエリをエンティティにマップする場合はどうなりますか? このために、aliased()を使用して、マップされたクラスの「エイリアス」をサブクエリに関連付けます。
1 2 3 4 5 6 7 8 |
stmt = session.query(Address).\ filter(Address.email_address != 'j25@yahoo.com').\ subquery() adalias = aliased(Address, stmt) for user, address in session.query(User, adalias).\ join(adalias, User.addresses): print(user) print(address) |
2021-09-12 12:59:41,854 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname, anon_1.id AS anon_1_id, anon_1.email_address AS anon_1_email_address, anon_1.user_id AS anon_1_user_id
FROM users JOIN (SELECT addresses.id AS id, addresses.email_address AS email_address, addresses.user_id AS user_id
FROM addresses
WHERE addresses.email_address != ?) AS anon_1 ON users.id = anon_1.user_id
2021-09-12 12:59:41,854 INFO sqlalchemy.engine.base.Engine (‘j25@yahoo.com’,)
<User(name=’jack’, fullname=’Jack Bean’, nickname=’gjffdd’)>
<Address(email_address=’jack@google.com’)>
Using EXISTS
The EXISTS keyword in SQL is a boolean operator which returns True if the given expression contains any rows. It may be used in many scenarios in place of joins, and is also useful for locating rows which do not have a corresponding row in a related table.
G訳:SQLのEXISTSキーワードは、指定された式に行が含まれている場合にTrueを返すブール演算子です。 これは、結合の代わりに多くのシナリオで使用される可能性があり、関連するテーブルに対応する行がない行を見つけるのにも役立ちます。
There is an explicit EXISTS construct, which looks like this:
次のような明示的なEXISTS構造があります。
1 2 3 4 |
from sqlalchemy.sql import exists stmt = exists().where(Address.user_id==User.id) for name, in session.query(User.name).filter(stmt): print(name) |
2021-09-12 13:18:58,595 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name
FROM users
WHERE EXISTS (SELECT *
FROM addresses
WHERE addresses.user_id = users.id)
2021-09-12 13:18:58,595 INFO sqlalchemy.engine.base.Engine ()
jack
The Query features several operators which make usage of EXISTS automatically. Above, the statement can be expressed along the User.addresses relationship using Comparator.any():
G訳:クエリは、EXISTSを自動的に使用するいくつかの演算子を備えています。上記のステートメントは、Comparator.any()を使用してUser.addresses関係に沿って表現できます。
1 2 3 |
for name, in session.query(User.name).\ filter(User.addresses.any()): print(name) |
2021-09-12 13:19:59,999 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name
FROM users
WHERE EXISTS (SELECT 1
FROM addresses
WHERE users.id = addresses.user_id)
2021-09-12 13:20:00,000 INFO sqlalchemy.engine.base.Engine ()
jack
Comparator.any() takes criterion as well, to limit the rows matched:
G訳:Comparator.any()も基準を取り、一致する行を制限します。
1 2 3 |
for name, in session.query(User.name).\ filter(User.addresses.any(Address.email_address.like('%google%'))): print(name) |
2021-09-12 13:21:13,844 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name
FROM users
WHERE EXISTS (SELECT 1
FROM addresses
WHERE users.id = addresses.user_id AND addresses.email_address LIKE ?)
2021-09-12 13:21:13,844 INFO sqlalchemy.engine.base.Engine (‘%google%’,)
jack
Comparator.has() is the same operator as Comparator.any() for many-to-one relationships (note the ~ operator here too, which means “NOT”):
G訳:Comparator.has()は、多対1の関係のComparator.any()と同じ演算子です(ここでも〜演算子に注意してください。これは「NOT」を意味します)。
1 2 |
session.query(Address).\ filter(~Address.user.has(User.name=='jack')).all() |
2021-09-12 13:22:01,259 INFO sqlalchemy.engine.base.Engine SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id
FROM addresses
WHERE NOT (EXISTS (SELECT 1
FROM users
WHERE users.id = addresses.user_id AND users.name = ?))
2021-09-12 13:22:01,260 INFO sqlalchemy.engine.base.Engine (‘jack’,)
Common Relationship Operators(一般的な関係演算子)
Here’s all the operators which build on relationships – each one is linked to its API documentation which includes full details on usage and behavior:
G訳:関係に基づいて構築されるすべての演算子は次のとおりです。各演算子は、使用法と動作の詳細を含むAPIドキュメントにリンクされています。
Comparator.eq() (many-to-one “equals” comparison):
query.filter(Address.user == someuser)
Comparator.ne() (many-to-one “not equals” comparison):
query.filter(Address.user != someuser)
IS NULL (many-to-one comparison, also uses Comparator.eq()):
query.filter(Address.user == None)
Comparator.contains() (used for one-to-many collections):
query.filter(User.addresses.contains(someaddress))
Comparator.any() (used for collections):
query.filter(User.addresses.any(Address.email_address == ‘bar’))
’# also takes keyword arguments: query.filter(User.addresses.any(email_address=’bar’))
Comparator.has() (used for scalar references):
query.filter(Address.user.has(name=’ed’))
Query.with_parent() (used for any relationship):
session.query(Address).with_parent(someuser, ‘addresses’)
Eager Loading
Recall earlier that we illustrated a lazy loading operation, when we accessed the User.addresses collection of a User and SQL was emitted. If you want to reduce the number of queries (dramatically, in many cases), we can apply an eager load to the query operation. SQLAlchemy offers three types of eager loading, two of which are automatic, and a third which involves custom criterion. All three are usually invoked via functions known as query options which give additional instructions to the Query on how we would like various attributes to be loaded, via the Query.options() method.
G訳:ユーザーのUser.addressesコレクションにアクセスし、SQLが発行されたときに、遅延読み込み操作を示したことを前に思い出してください。 クエリの数を(多くの場合、劇的に)減らしたい場合は、クエリ操作に熱心な負荷をかけることができます。 SQLAlchemyは、3種類の積極的な読み込みを提供します。そのうちの2つは自動で、3つ目はカスタム基準を含みます。 3つすべては通常、Query.options()メソッドを介して、さまざまな属性をどのようにロードするかについてクエリに追加の指示を与えるクエリオプションと呼ばれる関数を介して呼び出されます。
Selectin Load
In this case we’d like to indicate that User.addresses should load eagerly. A good choice for loading a set of objects as well as their related collections is the selectinload() option, which emits a second SELECT statement that fully loads the collections associated with the results just loaded. The name “selectin” originates from the fact that the SELECT statement uses an IN clause in order to locate related rows for multiple objects at once:
G訳:この場合、User.addressesを積極的に読み込む必要があることを示したいと思います。 オブジェクトのセットとそれに関連するコレクションをロードするための適切な選択は、selectinload()オプションです。これは、ロードされたばかりの結果に関連付けられたコレクションを完全にロードする2番目のSELECTステートメントを発行します。 「selectin」という名前は、SELECTステートメントが複数のオブジェクトの関連する行を一度に見つけるためにIN句を使用するという事実に由来しています。
1 2 3 4 5 |
from sqlalchemy.orm import selectinload jack = session.query(User).\ options(selectinload(User.addresses)).\ filter_by(name='jack').one() jack |
2021-09-12 13:28:13,771 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name = ?
2021-09-12 13:28:13,772 INFO sqlalchemy.engine.base.Engine (‘jack’,)
2021-09-12 13:28:13,774 INFO sqlalchemy.engine.base.Engine SELECT addresses.user_id AS addresses_user_id, addresses.id AS addresses_id, addresses.email_address AS addresses_email_address
FROM addresses
WHERE addresses.user_id IN (?) ORDER BY addresses.id
2021-09-12 13:28:13,774 INFO sqlalchemy.engine.base.Engine (5,)
1 |
jack.addresses |
<Address(email_address=’j25@yahoo.com’)>]
Joined Load
The other automatic eager loading function is more well known and is called joinedload(). This style of loading emits a JOIN, by default a LEFT OUTER JOIN, so that the lead object as well as the related object or collection is loaded in one step. We illustrate loading the same addresses collection in this way – note that even though the User.addresses collection on jack is actually populated right now, the query will emit the extra join regardless:
G訳:他の自動イーガーロード関数はよりよく知られており、joinedload()と呼ばれます。 このスタイルのロードでは、JOIN(デフォルトではLEFT OUTER JOIN)が発行されるため、リードオブジェクトと関連オブジェクトまたはコレクションが1つのステップでロードされます。 この方法で同じアドレスコレクションをロードする方法を説明します。ジャックのUser.addressesコレクションは現在実際に入力されていますが、クエリは次のことに関係なく追加の結合を発行することに注意してください。
1 2 3 4 5 6 |
from sqlalchemy.orm import joinedload jack = session.query(User).\ options(joinedload(User.addresses)).\ filter_by(name='jack').one() jack |
2021-09-12 13:29:52,488 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname, addresses_1.id AS addresses_1_id, addresses_1.email_address AS addresses_1_email_address, addresses_1.user_id AS addresses_1_user_id
FROM users LEFT OUTER JOIN addresses AS addresses_1 ON users.id = addresses_1.user_id
WHERE users.name = ? ORDER BY addresses_1.id
2021-09-12 13:29:52,488 INFO sqlalchemy.engine.base.Engine (‘jack’,)
1 |
jack.addresses |
[<Address(email_address=’jack@google.com’)>,
<Address(email_address=’j25@yahoo.com’)>]
Note that even though the OUTER JOIN resulted in two rows, we still only got one instance of User back. This is because Query applies a “uniquing” strategy, based on object identity, to the returned entities. This is specifically so that joined eager loading can be applied without affecting the query results.
G訳:OUTER JOINの結果が2行になったとしても、Userのインスタンスが1つしか返されなかったことに注意してください。 これは、クエリがオブジェクトIDに基づいて、返されたエンティティに「一意の」戦略を適用するためです。 これは特に、クエリ結果に影響を与えることなく、結合された積極的な読み込みを適用できるようにするためです。
While joinedload() has been around for a long time, selectinload() is a newer form of eager loading. selectinload() tends to be more appropriate for loading related collections while joinedload() tends to be better suited for many-to-one relationships, due to the fact that only one row is loaded for both the lead and the related object. Another form of loading, subqueryload(), also exists, which can be used in place of selectinload() when making use of composite primary keys on certain backends.
G訳:joinload()は長い間存在していましたが、selectinload()は新しい形式の積極的な読み込みです。 selectinload()は、関連するコレクションのロードに適している傾向がありますが、joinedload()は、リードと関連オブジェクトの両方に1つの行のみがロードされるため、多対1の関係に適している傾向があります。 別の形式のロードであるsubqueryload()も存在します。これは、特定のバックエンドで複合主キーを使用するときにselectinload()の代わりに使用できます。
Explicit Join + Eagerload
A third style of eager loading is when we are constructing a JOIN explicitly in order to locate the primary rows, and would like to additionally apply the extra table to a related object or collection on the primary object. This feature is supplied via the contains_eager() function, and is most typically useful for pre-loading the many-to-one object on a query that needs to filter on that same object. Below we illustrate loading an Address row as well as the related User object, filtering on the User named “jack” and using contains_eager() to apply the “user” columns to the Address.user attribute:
G訳:積極的な読み込みの3番目のスタイルは、プライマリ行を見つけるためにJOINを明示的に構築し、プライマリオブジェクトの関連オブジェクトまたはコレクションに追加のテーブルを追加で適用する場合です。 この機能はcontains_eager()関数を介して提供され、通常、同じオブジェクトでフィルタリングする必要があるクエリで多対1オブジェクトをプリロードする場合に役立ちます。 以下では、Address行と関連するUserオブジェクトをロードし、「jack」という名前のユーザーをフィルタリングし、contains_eager()を使用して「user」列をAddress.user属性に適用する方法を示します。
1 2 3 4 5 6 7 |
from sqlalchemy.orm import contains_eager jacks_addresses = session.query(Address).\ join(Address.user).\ filter(User.name=='jack').\ options(contains_eager(Address.user)).\ all() jacks_addresses |
2021-09-12 13:33:05,943 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname, addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id
FROM addresses JOIN users ON users.id = addresses.user_id
WHERE users.name = ?
2021-09-12 13:33:05,944 INFO sqlalchemy.engine.base.Engine (‘jack’,)
<Address(email_address=’j25@yahoo.com’)>]
1 |
jacks_addresses[0].user |
<User(name=’jack’, fullname=’Jack Bean’, nickname=’gjffdd’)>
For more information on eager loading, including how to configure various forms of loading by default, see the section Relationship Loading Techniques.
G訳:さまざまな形式の読み込みをデフォルトで構成する方法など、積極的な読み込みの詳細については、「リレーションシップ読み込みテクニック」のセクションを参照してください。
Deleting(削除)
Let’s try to delete jack and see how that goes. We’ll mark the object as deleted in the session, then we’ll issue a count query to see that no rows remain:
G訳:ジャックを削除して、どうなるか見てみましょう。セッションでオブジェクトを削除済みとしてマークしてから、カウントクエリを発行して、行が残っていないことを確認します。
1 2 |
session.delete(jack) session.query(User).filter_by(name='jack').count() |
2021-09-12 13:35:08,914 INFO sqlalchemy.engine.base.Engine UPDATE addresses SET user_id=? WHERE addresses.id = ?
2021-09-12 13:35:08,915 INFO sqlalchemy.engine.base.Engine ((None, 1), (None, 2))
2021-09-12 13:35:08,916 INFO sqlalchemy.engine.base.Engine DELETE FROM users WHERE users.id = ?
2021-09-12 13:35:08,917 INFO sqlalchemy.engine.base.Engine (5,)
2021-09-12 13:35:08,918 INFO sqlalchemy.engine.base.Engine SELECT count(*) AS count_1
FROM (SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name = ?) AS anon_1
2021-09-12 13:35:08,919 INFO sqlalchemy.engine.base.Engine (‘jack’,)
0
So far, so good. How about Jack’s Address objects ?
G訳:ここまでは順調ですね。ジャックのアドレスオブジェクトはどうですか?
1 2 3 |
session.query(Address).filter( Address.email_address.in_(['jack@google.com', 'j25@yahoo.com']) ).count() |
2021-09-12 13:36:10,149 INFO sqlalchemy.engine.base.Engine SELECT count(*) AS count_1
FROM (SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id
FROM addresses
WHERE addresses.email_address IN (?, ?)) AS anon_1
2021-09-12 13:36:10,150 INFO sqlalchemy.engine.base.Engine (‘jack@google.com’, ‘j25@yahoo.com’)
Uh oh, they’re still there ! Analyzing the flush SQL, we can see that the user_id column of each address was set to NULL, but the rows weren’t deleted. SQLAlchemy doesn’t assume that deletes cascade, you have to tell it to do so.
G訳:ええと、彼らはまだそこにいます!フラッシュSQLを分析すると、各アドレスのuser_id列がNULLに設定されているが、行は削除されていないことがわかります。 SQLAlchemyはカスケードを削除することを想定していないので、そうするように指示する必要があります。
Configuring delete/delete-orphan Cascade
We will configure cascade options on the User.addresses relationship to change the behavior. While SQLAlchemy allows you to add new attributes and relationships to mappings at any point in time, in this case the existing relationship needs to be removed, so we need to tear down the mappings completely and start again – we’ll close the Session:
G訳:User.addresses関係にカスケードオプションを構成して、動作を変更します。 SQLAlchemyを使用すると、いつでもマッピングに新しい属性と関係を追加できますが、この場合、既存の関係を削除する必要があるため、マッピングを完全に破棄してやり直す必要があります。セッションを閉じます。
1 |
session.close() |
2021-09-12 13:38:17,043 INFO sqlalchemy.engine.base.Engine ROLLBACK
and use a new declarative_base():
G訳:そして、新しいdeclarative_base()を使用します。
1 |
Base = declarative_base() |
Next we’ll declare the User class, adding in the addresses relationship including the cascade configuration (we’ll leave the constructor out too):
G訳:次に、Userクラスを宣言し、カスケード構成を含むアドレス関係を追加します(コンストラクターも省略します)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
>>> class User(Base): ... __tablename__ = 'users' ... ... id = Column(Integer, primary_key=True) ... name = Column(String) ... fullname = Column(String) ... nickname = Column(String) ... ... addresses = relationship("Address", back_populates='user', ... cascade="all, delete, delete-orphan") ... ... def __repr__(self): ... return "<User(name='%s', fullname='%s', nickname='%s')>" % ( ... self.name, self.fullname, self.nickname) |
Then we recreate Address, noting that in this case we’ve created the Address.user relationship via the User class already:
G訳:次に、Addressを再作成します。この場合、Userクラスを介してAddress.user関係をすでに作成していることに注意してください。
1 2 3 4 5 6 7 8 9 |
>>> class Address(Base): ... __tablename__ = 'addresses' ... id = Column(Integer, primary_key=True) ... email_address = Column(String, nullable=False) ... user_id = Column(Integer, ForeignKey('users.id')) ... user = relationship("User", back_populates="addresses") ... ... def __repr__(self): ... return "<Address(email_address='%s')>" % self.email_address |
Now when we load the user jack (below using Query.get(), which loads by primary key), removing an address from the corresponding addresses collection will result in that Address being deleted:
G訳:ここで、ユーザージャックをロードすると(以下では主キーでロードするQuery.get()を使用)、対応するアドレスコレクションからアドレスを削除すると、そのアドレスが削除されます。
‘# load Jack by primary key
jack = session.query(User).get(5)
‘# remove one Address (lazy load fires off)
del jack.addresses[1]
‘# only one address remains
session.query(Address).filter(
… Address.emailaddress.in([‘jack@google.com’, ‘j25@yahoo.com’])
… ).count()
1
Deleting Jack will delete both Jack and the remaining Address associated with the user:
G訳:ジャックを削除すると、ジャックとユーザーに関連付けられている残りのアドレスの両方が削除されます。
Building a Many To Many Relationship(多対多の関係を構築する)
We’re moving into the bonus round here, but lets show off a many-to-many relationship. We’ll sneak in some other features too, just to take a tour. We’ll make our application a blog application, where users can write BlogPost items, which have Keyword items associated with them.
G訳:ここではボーナスラウンドに移行しますが、多対多の関係を誇示しましょう。 ツアーに参加するために、他のいくつかの機能も紹介します。 アプリケーションをブログアプリケーションにします。このアプリケーションでは、ユーザーがキーワードアイテムが関連付けられたBlogPostアイテムを作成できます。
For a plain many-to-many, we need to create an un-mapped Table construct to serve as the association table. This looks like the following:
G訳:単純な多対多の場合、関連付けテーブルとして機能するマップされていないTable構造を作成する必要があります。これは次のようになります。
1 2 3 4 5 6 |
from sqlalchemy import Table, Text # association table post_keywords = Table('post_keywords', Base.metadata, Column('post_id', ForeignKey('posts.id'), primary_key=True), Column('keyword_id', ForeignKey('keywords.id'), primary_key=True) ) |
Above, we can see declaring a Table directly is a little different than declaring a mapped class. Table is a constructor function, so each individual Column argument is separated by a comma. The Column object is also given its name explicitly, rather than it being taken from an assigned attribute name.
G訳:上記では、テーブルを直接宣言することは、マップされたクラスを宣言することとは少し異なることがわかります。 テーブルはコンストラクター関数であるため、個々の列引数はコンマで区切られます。 Columnオブジェクトには、割り当てられた属性名から取得されるのではなく、明示的に名前が付けられます。
Next we define BlogPost and Keyword, using complementary relationship() constructs, each referring to the post_keywords table as an association table:
G訳:次に、補完的なrelationship()構造を使用して、BlogPostとKeywordを定義します。それぞれ、post_keywordsテーブルを関連付けテーブルとして参照します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
>>> class BlogPost(Base): ... __tablename__ = 'posts' ... ... id = Column(Integer, primary_key=True) ... user_id = Column(Integer, ForeignKey('users.id')) ... headline = Column(String(255), nullable=False) ... body = Column(Text) ... ... # many to many BlogPost<->Keyword ... keywords = relationship('Keyword', ... secondary=post_keywords, ... back_populates='posts') ... ... def __init__(self, headline, body, author): ... self.author = author ... self.headline = headline ... self.body = body ... ... def __repr__(self): ... return "BlogPost(%r, %r, %r)" % (self.headline, self.body, self.author) >>> class Keyword(Base): ... __tablename__ = 'keywords' ... ... id = Column(Integer, primary_key=True) ... keyword = Column(String(50), nullable=False, unique=True) ... posts = relationship('BlogPost', ... secondary=post_keywords, ... back_populates='keywords') ... ... def __init__(self, keyword): ... self.keyword = keyword |
◇Note
The above class declarations illustrate explicit init() methods. Remember, when using Declarative, it’s optional!
G訳:ノート 上記のクラス宣言は、明示的なinit ()メソッドを示しています。宣言型を使用する場合、それはオプションであることを忘れないでください!
Above, the many-to-many relationship is BlogPost.keywords. The defining feature of a many-to-many relationship is the secondary keyword argument which references a Table object representing the association table. This table only contains columns which reference the two sides of the relationship; if it has any other columns, such as its own primary key, or foreign keys to other tables, SQLAlchemy requires a different usage pattern called the “association object”, described at Association Object.
G訳:上記の多対多の関係はBlogPost.keywordsです。 多対多の関係を定義する機能は、連想テーブルを表すTableオブジェクトを参照する2番目のキーワード引数です。 このテーブルには、関係の2つの側面を参照する列のみが含まれています。 独自の主キーや他のテーブルへの外部キーなど、他の列がある場合、SQLAlchemyには、アソシエーションオブジェクトで説明されている「アソシエーションオブジェクト」と呼ばれる別の使用パターンが必要です。
We would also like our BlogPost class to have an author field. We will add this as another bidirectional relationship, except one issue we’ll have is that a single user might have lots of blog posts. When we access User.posts, we’d like to be able to filter results further so as not to load the entire collection. For this we use a setting accepted by relationship() called lazy=’dynamic’, which configures an alternate loader strategy on the attribute:
G訳:また、BlogPostクラスに作成者フィールドを持たせたいと思います。 これを別の双方向の関係として追加します。ただし、1人のユーザーが多数のブログ投稿を持っている可能性があるという問題が1つあります。 User.postsにアクセスするときに、コレクション全体が読み込まれないように、結果をさらにフィルタリングできるようにしたいと考えています。 このために、lazy = ‘dynamic’と呼ばれるrelationship()によって受け入れられる設定を使用します。これは、属性に代替ローダー戦略を構成します。
1 2 |
>>> BlogPost.author = relationship(User, back_populates="posts") >>> User.posts = relationship(BlogPost, back_populates="author", lazy="dynamic") |
新しくテーブルを作成します。
1 |
>>> Base.metadata.create_all(engine) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
2021-09-12 13:52:57,918 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info("users") 2021-09-12 13:52:57,918 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,919 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info("addresses") 2021-09-12 13:52:57,920 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,921 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info("post_keywords") 2021-09-12 13:52:57,921 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,922 INFO sqlalchemy.engine.base.Engine PRAGMA temp.table_info("post_keywords") 2021-09-12 13:52:57,923 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,923 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info("posts") 2021-09-12 13:52:57,924 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,925 INFO sqlalchemy.engine.base.Engine PRAGMA temp.table_info("posts") 2021-09-12 13:52:57,925 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,926 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info("keywords") 2021-09-12 13:52:57,926 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,927 INFO sqlalchemy.engine.base.Engine PRAGMA temp.table_info("keywords") 2021-09-12 13:52:57,928 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,929 INFO sqlalchemy.engine.base.Engine CREATE TABLE posts ( id INTEGER NOT NULL, user_id INTEGER, headline VARCHAR(255) NOT NULL, body TEXT, PRIMARY KEY (id), FOREIGN KEY(user_id) REFERENCES users (id) ) 2021-09-12 13:52:57,929 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,930 INFO sqlalchemy.engine.base.Engine COMMIT 2021-09-12 13:52:57,931 INFO sqlalchemy.engine.base.Engine CREATE TABLE keywords ( id INTEGER NOT NULL, keyword VARCHAR(50) NOT NULL, PRIMARY KEY (id), UNIQUE (keyword) ) 2021-09-12 13:52:57,931 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,932 INFO sqlalchemy.engine.base.Engine COMMIT 2021-09-12 13:52:57,933 INFO sqlalchemy.engine.base.Engine CREATE TABLE post_keywords ( post_id INTEGER NOT NULL, keyword_id INTEGER NOT NULL, PRIMARY KEY (post_id, keyword_id), FOREIGN KEY(post_id) REFERENCES posts (id), FOREIGN KEY(keyword_id) REFERENCES keywords (id) ) 2021-09-12 13:52:57,934 INFO sqlalchemy.engine.base.Engine () 2021-09-12 13:52:57,934 INFO sqlalchemy.engine.base.Engine COMMIT |
Usage is not too different from what we’ve been doing. Let’s give Wendy some blog posts:
G訳:使用法は、これまで行ってきたものとそれほど変わりません。ウェンディにいくつかのブログ投稿をしましょう:
1 2 3 4 5 |
>>> wendy = session.query(User).\ ... filter_by(name='wendy').\ ... one() >>> post = BlogPost("Wendy's Blog Post", "This is a test", wendy) >>> session.add(post) |
2021-09-12 13:53:25,843 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2021-09-12 13:53:25,844 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.nickname AS users_nickname
FROM users
WHERE users.name = ?
2021-09-12 13:53:25,845 INFO sqlalchemy.engine.base.Engine (‘wendy’,)
We’re storing keywords uniquely in the database, but we know that we don’t have any yet, so we can just create them:
G訳:キーワードをデータベースに一意に保存していますが、まだキーワードがないことがわかっているので、キーワードを作成するだけです。
1 2 |
>>> post.keywords.append(Keyword('wendy')) >>> post.keywords.append(Keyword('firstpost')) |
We can now look up all blog posts with the keyword ‘firstpost’. We’ll use the any operator to locate “blog posts where any of its keywords has the keyword string ‘firstpost’”:
G訳:これで、「firstpost」というキーワードですべてのブログ投稿を検索できます。 any演算子を使用して、「キーワードのいずれかにキーワード文字列「firstpost」が含まれるブログ投稿」を検索します。
1 2 3 |
>>> session.query(BlogPost).\ ... filter(BlogPost.keywords.any(keyword='firstpost')).\ ... all() |
2021-09-12 13:54:52,796 INFO sqlalchemy.engine.base.Engine (‘wendy’,)
2021-09-12 13:54:52,797 INFO sqlalchemy.engine.base.Engine INSERT INTO keywords (keyword) VALUES (?)
2021-09-12 13:54:52,798 INFO sqlalchemy.engine.base.Engine (‘firstpost’,)
2021-09-12 13:54:52,799 INFO sqlalchemy.engine.base.Engine INSERT INTO posts (user_id, headline, body) VALUES (?, ?, ?)
2021-09-12 13:54:52,800 INFO sqlalchemy.engine.base.Engine (2, “Wendy’s Blog Post”, ‘This is a test’)
2021-09-12 13:54:52,801 INFO sqlalchemy.engine.base.Engine INSERT INTO post_keywords (post_id, keyword_id) VALUES (?, ?)
2021-09-12 13:54:52,801 INFO sqlalchemy.engine.base.Engine ((1, 1), (1, 2))
2021-09-12 13:54:52,803 INFO sqlalchemy.engine.base.Engine SELECT posts.id AS posts_id, posts.user_id AS posts_user_id, posts.headline AS posts_headline, posts.body AS posts_body
FROM posts
WHERE EXISTS (SELECT 1
FROM post_keywords, keywords
WHERE posts.id = post_keywords.post_id AND keywords.id = post_keywords.keyword_id AND keywords.keyword = ?)
2021-09-12 13:54:52,803 INFO sqlalchemy.engine.base.Engine (‘firstpost’,)
If we want to look up posts owned by the user wendy, we can tell the query to narrow down to that User object as a parent:
G訳:ユーザーwendyが所有する投稿を検索する場合は、親としてそのUserオブジェクトに絞り込むようにクエリに指示できます。
1 2 3 4 |
>>> session.query(BlogPost).\ ... filter(BlogPost.author==wendy).\ ... filter(BlogPost.keywords.any(keyword='firstpost')).\ ... all() |
2021-09-12 13:55:33,699 INFO sqlalchemy.engine.base.Engine SELECT posts.id AS posts_id, posts.user_id AS posts_user_id, posts.headline AS posts_headline, posts.body AS posts_body
FROM posts
WHERE ? = posts.user_id AND (EXISTS (SELECT 1
FROM post_keywords, keywords
WHERE posts.id = post_keywords.post_id AND keywords.id = post_keywords.keyword_id AND keywords.keyword = ?))
2021-09-12 13:55:33,700 INFO sqlalchemy.engine.base.Engine (2, ‘firstpost’)
[BlogPost(“Wendy’s Blog Post”, ‘This is a test’, <User(name=’wendy’, fullname=’Wendy Williams’, nickname=’windy’)>)]
Or we can use Wendy’s own posts relationship, which is a “dynamic” relationship, to query straight from there:
G訳:または、「動的」な関係であるウェンディ独自の投稿関係を使用して、そこから直接クエリを実行することもできます。
1 2 3 |
>>> wendy.posts.\ ... filter(BlogPost.keywords.any(keyword='firstpost')).\ ... all() |
2021-09-12 13:56:16,314 INFO sqlalchemy.engine.base.Engine SELECT posts.id AS posts_id, posts.user_id AS posts_user_id, posts.headline AS posts_headline, posts.body AS posts_body
FROM posts
WHERE ? = posts.user_id AND (EXISTS (SELECT 1
FROM post_keywords, keywords
WHERE posts.id = post_keywords.post_id AND keywords.id = post_keywords.keyword_id AND keywords.keyword = ?))
2021-09-12 13:56:16,315 INFO sqlalchemy.engine.base.Engine (2, ‘firstpost’)
[BlogPost(“Wendy’s Blog Post”, ‘This is a test’, <User(name=’wendy’, fullname=’Wendy Williams’, nickname=’windy’)>)]
Further Reference(さらに深く学ぶために)
※このリンク先は英語のサイトです。
Query Reference: Query API
Mapper Reference: Mapper Configuration
Relationship Reference: Relationship Configuration
Session Reference: Using the Session
SQLAlchemy 1.3 Documentation
https://docs.sqlalchemy.org/en/13/orm/tutorial.html#using-textual-sql