Types of your own
A column can have a type of your application: a Rust enum for a status,
a newtype around a code, a value that the database stores in a way of its
own. This is what Django does with choices (and TextChoices), or with
a custom Field subclass.
This page builds one complete example, an order whose status is an
enum, and explains each piece.
The goal
In Django:
class Order(models.Model):
class Status(models.TextChoices):
DRAFT = "draft"
SENT = "sent"
PAID = "paid"
status = models.CharField(max_length=10, choices=Status, default=Status.DRAFT)
In rind, the column stays a character varying(10) in the database, and
the field is a Rust enum, so that the code can never hold a status that
does not exist:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_order")]
pub struct Order {
pub id: i64,
#[column(sql = "character varying(10)", default = "'draft'")]
pub status: Status,
}
}
CREATE TABLE "lab_order" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"status" character varying(10) NOT NULL DEFAULT 'draft'
);
What a type needs
A type can be a column when it has four things:
| What | Why |
|---|---|
#[column(sql = "…")] on the field | rind cannot guess the SQL type of a type it does not know |
Debug, Clone and Default | the model derives them, and a model read partially (as serializers read them) fills the columns it did not read with their default |
rind::query::ToValue | how the value is sent to the database: in an insert, an update, or a comparison in a query |
tokio_postgres::types::FromSql | how the value is read from a row |
The type
#![allow(unused)]
fn main() {
/// The state of an order: stored as a text column.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Status {
#[default]
Draft,
Sent,
Paid,
}
impl Status {
pub fn as_str(self) -> &'static str {
match self {
Status::Draft => "draft",
Status::Sent => "sent",
Status::Paid => "paid",
}
}
}
}
#[default] says which variant Default gives. It does not have to be
the column’s SQL default, but keeping them the same avoids surprises.
Writing: ToValue
#![allow(unused)]
fn main() {
/// How the status is sent to the database.
impl rind::query::ToValue for Status {
fn to_value(self) -> rind::query::Value {
rind::query::Value::Text(self.as_str().to_owned())
}
}
}
ToValue turns the value into a rind::query::Value, the type of every
query parameter. Value has a variant for each kind of value PostgreSQL
receives: Text, Int, Float, Bool, Date, Timestamp, Json,
arrays, and Binary for a type sent in PostgreSQL’s binary form.
Reading: FromSql
Reading uses the PostgreSQL driver’s trait, FromSql. rind does not
re-export the driver, so add it to the models crate:
tokio-postgres = "0.7"
#![allow(unused)]
fn main() {
/// How the status is read from a row.
impl<'a> tokio_postgres::types::FromSql<'a> for Status {
fn from_sql(
ty: &tokio_postgres::types::Type,
raw: &'a [u8],
) -> Result<Status, Box<dyn std::error::Error + Sync + Send>> {
match <&str as tokio_postgres::types::FromSql>::from_sql(ty, raw)? {
"draft" => Ok(Status::Draft),
"sent" => Ok(Status::Sent),
"paid" => Ok(Status::Paid),
other => Err(format!("not a status: {other}").into()),
}
}
fn accepts(ty: &tokio_postgres::types::Type) -> bool {
<&str as tokio_postgres::types::FromSql>::accepts(ty)
}
}
}
The function reads the column as a &str, using the driver’s own
implementation, then turns it into a Status. accepts says which SQL
types it can read: the same as a &str (text, varchar…).
A value in the table that is not a status (written by hand, by another
program) is an error when the row is read, not a silent Draft.
Using it
The column now has a path of type Path<Status>, which compares with a
Status:
#![allow(unused)]
fn main() {
/// The orders not paid yet.
pub fn unpaid() -> Query<Order> {
Query::new().filter(Order::status().ne(Status::Paid))
}
/// Marks an order as paid.
pub async fn pay(db: &Db, id: i64) -> Result<u64, rind::db::Error> {
db.execute(
&Update::<Order>::new()
.set(Order::status(), Status::Paid)
.filter(Order::id().eq(id)),
)
.await
}
}
Comparing it with a text, Order::status().eq("paid"), does not compile:
the type does its job.
An insert that does not give the status gets the column’s default, read
back as Status::Draft:
#![allow(unused)]
fn main() {
let order: Order = db.insert(&Insert::<Order>::new()).await?;
assert_eq!(order.status, Status::Draft);
}
In the API
To send the field in a serializer or read it in an
input, the type also needs serde’s Serialize and
Deserialize, and rind’s rind::api::openapi::JsonSchema (the
OpenAPI document describes every field). Without
JsonSchema, the serializer does not compile.
A simpler path, often enough, is to keep the column a String in the
model, and let the input restrict its values:
#![allow(unused)]
fn main() {
// the model
#[column(max_length = 10, default = "'draft'")]
pub status: String,
// the input
#[input(choices("draft", "sent", "paid"), default = "draft")]
pub status: Option<String>,
}
This is what the sample does for its statuses. Choose the enum when
Rust code takes decisions on the value, and the String when the value
mostly goes in and out of the API.
Other examples
The same four pieces work for any type:
- A newtype (
pub struct Siret(String)):ToValuegivesValue::Text(self.0),FromSqlreads a&strand checks it. - An
i16code (enum Level { Low = 1, High = 2 }):sql = "smallint",Value::Int(self as i64),FromSqlreads ani16. - A PostgreSQL enumerated type: rind already has one,
rind::db::types::EnumValue(Fields).
Next: Primary keys.