Connecting to a database
p3orm currently allows you to connect to a single database within a process. You can fetch the Postgres driver with
p3orm.core and the SQLite driver with
_type: Specifies the type of the column, will be used to convert between Python and Postgres. This also generates the type annotation for an instance of your model. For a list of supported types, see the asyncpg docs.
name: Specifies the name of the column. This (currently) has to match the name of the field on the class as well.
pk: Specifies whether this is the primary key. This is used for the
autogen: Specifies whether Postgres will automatically generate/update the value of this field, e.g.
SERIALfor ids or
p3orm.table.Table provides the following convenience methods for executing queries with basic criteria.
Table.fetch_onewill raise a
NoResultsReturnedif exactly one result isn't returned.
Table.fetch_firstwill return the first result from a query or
Table.fetch_allwill return a list of results (or an empty list) of a query.
Table.insert_onewill insert exactly one model.
Table.insert_manywill insert multiple models with a performant bulk insert query.
Table.update_onewill accept a single model and update it based on its primary key.
Table.delete_wherewill delete and return all rows that match a criterion.
All of the above methods use parameterized queries under the hood to protect against SQL injections.
Note that we didn't specify the
created_at fields. Those are autogenerated by Postgres, so we let the database do the work. We also didn't explicitly specify whether the fields are nullable or not. Again, we offload all validation to the database as the source of truth, and only specify the
Optional type for local type checking and intellisense. It is best practice to discard locally created models after they've been inserted and replace them with the returned set as they will contain all the database-generated and validated field values.
It is best practice to discard the local model after an update and replace it with the updated result as it will contain any database-updated fields.
Table.delete_wherealways returns a list of the deleted records.