跳到主要内容
版本:2.0.x

列类型

类型映射

列类型将根据以下映射自动派生。

SQL Server (MSSQL) 后端

MSSQL 的类型映射可在此处找到。

Rust 基本数据类型的映射:

Rust typeDatabase Type
(ColumnType)
SQLite
datatype
MySQL
datatype
PostgreSQL
datatype
StringCharcharcharchar
StringStringvarcharvarcharvarchar
i8TinyIntegertinyinttinyintchar
u8TinyUnsignedtinyinttinyint unsignedN/A
i16SmallIntegersmallintsmallintsmallint
u16SmallUnsignedsmallintsmallint unsignedN/A
i32Integerintegerintinteger
u32Unsignedintegerint unsignedN/A
i64BigIntegerintegerbigintbigint
u64BigUnsignedintegerbigint unsignedN/A
f32Floatfloatfloatreal
f64Doubledoubledoubledouble precision
boolBooleanbooleanboolbool
Vec<u8>Binaryblobblobbytea

Rust 非基本数据类型的映射。你可以查看 entity/prelude.rs 了解所有重新导出的类型。

Rust typeDatabase Type
(ColumnType)
SQLite
datatype
MySQL
datatype
PostgreSQL
datatype
Date: chrono::NaiveDate
TimeDate: time::Date
Datedate_textdatedate
Time: chrono::NaiveTime
TimeTime: time::Time
Timetime_texttimetime
DateTime: chrono::NaiveDateTime
TimeDateTime: time::PrimitiveDateTime
DateTimedatetime_textdatetimetimestamp
DateTimeLocal: chrono::DateTime<Local>
DateTimeUtc: chrono::DateTime<Utc>
Timestamptimestamp_texttimestampN/A
DateTimeWithTimeZone: chrono::DateTime<FixedOffset>
TimeDateTimeWithTimeZone: time::OffsetDateTime
TimestampWithTimeZonetimestamp_with_timezone_texttimestamptimestamp with time zone
Uuid: uuid::Uuid, uuid::fmt::Braced, uuid::fmt::Hyphenated, uuid::fmt::Simple, uuid::fmt::UrnUuiduuid_textbinary(16)uuid
Json: serde_json::ValueJsonjson_textjsonjson
Decimal: rust_decimal::DecimalDecimalrealdecimaldecimal
PgVector: pgvector::VectorVectorN/AN/Avector
IpNetwork: ipnetwork::IpNetworkInetN/AN/Ainet

你可以使用 column_type 属性覆盖 Rust 类型与 ColumnType 之间的默认映射。

#[sea_orm(column_type = "Text")]
pub name: String
#[sea_orm(column_type = "Decimal(Some((16, 4)))")]
pub price: Decimal,

JSON 列

如果你需要将 JSON 字段反序列化为结构体,需要为其派生 FromJsonQueryResult

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "json_struct")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
// JSON column as `serde_json::Value`
pub json: Json,
// JSON column as custom struct
pub json_value: KeyValue,
// nullable JSON column as custom struct, backed by jsonb (Postgres only)
#[sea_orm(column_type = "JsonBinary")]
pub json_value_opt: Option<KeyValue>,
// JSON column storing a vector of objects
pub json_value_vec: Vec<KeyValue>,
}

// The custom struct must derive `FromJsonQueryResult`, `Serialize` and `Deserialize`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct KeyValue {
pub id: i32,
pub name: String,
pub price: f32,
pub notes: Option<String>,
}

如果你想要一种跨数据库实现数组列的方式,可以使用封装类型包装它。

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "json_string_vec")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
// nullable JSON column storing a vector of string
pub str_vec: Option<StringVec>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct StringVec(pub Vec<String>);

更多细节和示例请参阅下一章。

Postgres 数组

数组数据类型是 Postgres 专有功能。你可以定义 SeaORM 已支持的原始类型的向量。

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "collection")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub integers: Vec<i32>,
pub integers_opt: Option<Vec<i32>>,
pub floats: Vec<f32>,
pub doubles: Vec<f64>,
pub strings: Vec<String>,
}

Postgres Vector

1.1.6 起,添加了 PgVector 支持。需要 postgres-vector feature 标志。

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "image_model")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: i32,
pub embedding: PgVector,
}

完整示例请参阅 embedding_tests

IpNetwork (Postgres)

1.1.8 起,添加了 IpNetwork 支持。需要 with-ipnetwork feature 标志。

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "host_network")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub ipaddress: IpNetwork,
#[sea_orm(column_type = "Cidr")]
pub network: IpNetwork,
}

Unix 时间戳

2.0.0 起,添加了多个新的封装类型,用于将 chrono / time 的 datetime 映射为 BigInteger。这些值在发送到数据库之前会转换为 i64

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "access_log")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub ts: ChronoUnixTimestamp,
pub ms: ChronoUnixTimestampMillis,
pub ts: TimeUnixTimestamp,
pub ms: TimeUnixTimestampMillis,
}