pub trait ToSql<A, DB: Backend>: Debug {
    fn to_sql<W: Write>(&self, out: &mut Output<'_, W, DB>) -> Result;
}
Expand description

Serializes a single value to be sent to the database.

The output is sent as a bind parameter, and the data must be written in the expected format for the given backend.

When possible, implementations of this trait should prefer using an existing implementation, rather than writing to out directly. (For example, if you are implementing this for an enum, which is represented as an integer in the database, you should use i32::to_sql(x, out) instead of writing to out yourself.

Any types which implement this trait should also #[derive(AsExpression)].

Backend specific details

  • For PostgreSQL, the bytes will be sent using the binary protocol, not text.
  • For SQLite, all implementations should be written in terms of an existing ToSql implementation.
  • For MySQL, the expected bytes will depend on the return value of type_metadata for the given SQL type. See MysqlType for details.
  • For third party backends, consult that backend’s documentation.

Examples

Most implementations of this trait will be defined in terms of an existing implementation.

#[repr(i32)]
#[derive(Debug, Clone, Copy)]
pub enum MyEnum {
    A = 1,
    B = 2,
}

impl<DB> ToSql<Integer, DB> for MyEnum
where
    DB: Backend,
    i32: ToSql<Integer, DB>,
{
    fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
        (*self as i32).to_sql(out)
    }
}

Required methods

See the trait documentation.

Implementations on Foreign Types

Implementors