Skip to main content

che_orm/
lib.rs

1//! `che-orm` — экспериментальная типизированная ORM для Rust.
2//!
3//! Backend выбирается feature `sqlite` или `postgres`: [`Database`] предоставляет async
4//! pool и high-level CRUD/query facade, а [`Model`] derive генерирует metadata,
5//! row decoding и insert values. SQL можно также использовать отдельно через
6//! [`SqlCompiler`].
7//!
8//! Основной рабочий сценарий для backend `sqlite`. `create_table` подходит для
9//! тестов и локальных экспериментов; для постоянной схемы используйте миграции.
10//!
11//! ```rust
12//! use che_orm::{Database, Model};
13//!
14//! #[derive(Debug, Model)]
15//! #[orm(table = "users")]
16//! struct User {
17//!     #[orm(primary_key)]
18//!     id: i64,
19//!     name: String,
20//! }
21//!
22//! # #[cfg(feature = "sqlite")]
23//! # #[tokio::main]
24//! # async fn main() -> Result<(), che_orm::OrmError> {
25//! let database = Database::connect_in_memory().await?;
26//! database.create_table::<User>().await?;
27//! let user = database
28//!     .create::<User>()
29//!     .set(User::NAME, "Alice")
30//!     .execute()
31//!     .await?;
32//! let loaded = database.get::<User>(user.id).await?;
33//! assert_eq!(loaded.unwrap().name, "Alice");
34//! # Ok(())
35//! # }
36//! # #[cfg(not(feature = "sqlite"))]
37//! # fn main() {}
38//! ```
39//!
40//! Fixed string choices use [`DbEnum`]. It owns the JSON and database value,
41//! so a variant has one canonical representation everywhere:
42//!
43//! ```rust
44//! use che_orm::DbEnum;
45//! #[derive(Debug, Clone, Copy, DbEnum)]
46//! enum TaskStatus {
47//!     Draft,
48//!     #[db_enum(rename = "in_progress")]
49//!     InProgress,
50//! }
51//!
52//! assert_eq!(TaskStatus::InProgress.as_str(), "in_progress");
53//! assert_eq!(
54//!     che_orm::serde_json::to_string(&TaskStatus::InProgress).unwrap(),
55//!     "\"in_progress\"",
56//! );
57//! ```
58//!
59//! Do not derive `serde::Serialize` or `serde::Deserialize` for a `DbEnum`;
60//! the derive generates both implementations.
61
62#![allow(clippy::type_complexity, clippy::new_without_default)]
63
64extern crate self as che_orm;
65
66pub use che_orm_macros::{DbEnum, Model, ModelSerializer};
67
68#[cfg(feature = "sqlite")]
69pub use rusqlite;
70pub use serde;
71pub use serde_json;
72pub use time;
73#[cfg(feature = "postgres")]
74pub use tokio_postgres;
75
76#[cfg(any(feature = "sqlite", feature = "postgres"))]
77mod backend;
78mod datetime;
79mod image;
80mod json;
81pub mod migration;
82pub use json::JsonField;
83mod query;
84mod row;
85mod schema;
86mod sql;
87mod sync;
88mod types;
89
90#[cfg(any(feature = "sqlite", feature = "postgres"))]
91mod connection;
92
93#[cfg(any(feature = "sqlite", feature = "postgres"))]
94mod bound_query;
95#[cfg(any(feature = "sqlite", feature = "postgres"))]
96pub use bound_query::BoundQuery;
97
98pub use image::ImageField;
99pub use migration::*;
100pub use query::*;
101pub use row::*;
102pub use schema::*;
103pub use sql::*;
104pub use sync::*;
105pub use types::*;
106pub use uuid::Uuid;
107
108/// Serializes a timestamp in the RFC 3339 format used by JSON API clients.
109pub struct Rfc3339Timestamp<'a>(pub &'a time::OffsetDateTime);
110
111impl serde::Serialize for Rfc3339Timestamp<'_> {
112    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
113    where
114        S: serde::Serializer,
115    {
116        time::serde::rfc3339::serialize(self.0, serializer)
117    }
118}
119
120/// Serializes an optional timestamp in RFC 3339 when it has a value.
121pub struct OptionalRfc3339Timestamp<'a>(pub &'a Option<time::OffsetDateTime>);
122
123impl serde::Serialize for OptionalRfc3339Timestamp<'_> {
124    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
125    where
126        S: serde::Serializer,
127    {
128        time::serde::rfc3339::option::serialize(self.0, serializer)
129    }
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum WriteMode<Key = i64> {
134    Create,
135    Update { id: Key },
136    Patch { id: Key },
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct ValidationErrors {
141    pub detail: String,
142}
143
144impl From<serde_json::Error> for ValidationErrors {
145    fn from(error: serde_json::Error) -> Self {
146        Self {
147            detail: error.to_string(),
148        }
149    }
150}
151
152pub enum ValidatedWrite<M: Model> {
153    Create(InsertQuery<M>),
154    Update(UpdateQuery<M>),
155}
156
157impl<M: Model> ValidatedWrite<M> {
158    pub fn set<T, V>(self, field: ModelField<M, T>, value: V) -> Self
159    where
160        V: QueryValue<T>,
161    {
162        match self {
163            Self::Create(query) => Self::Create(query.set(field, value)),
164            Self::Update(query) => Self::Update(query.set(field, value)),
165        }
166    }
167}
168
169pub trait ModelWriteSerializer {
170    type Model: Model;
171
172    fn is_valid(
173        data: serde_json::Value,
174        mode: WriteMode<<Self::Model as Model>::PrimaryKey>,
175    ) -> Result<ValidatedWrite<Self::Model>, ValidationErrors>;
176}
177
178/// A JSON patch value. `Missing` means that the property was not sent;
179/// `Value(None)` represents an explicit JSON null.
180#[derive(Debug, Clone, Default, PartialEq, Eq)]
181pub enum PatchField<T> {
182    #[default]
183    Missing,
184    Value(T),
185}
186
187impl<T> PatchField<T> {
188    pub const fn is_missing(&self) -> bool {
189        matches!(self, Self::Missing)
190    }
191}
192
193impl<'de, T> serde::Deserialize<'de> for PatchField<T>
194where
195    T: serde::Deserialize<'de>,
196{
197    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
198    where
199        D: serde::Deserializer<'de>,
200    {
201        T::deserialize(deserializer).map(Self::Value)
202    }
203}
204
205/// Deserializes an RFC 3339 timestamp sent by JSON API clients.
206pub fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<time::OffsetDateTime, D::Error>
207where
208    D: serde::Deserializer<'de>,
209{
210    time::serde::rfc3339::deserialize(deserializer)
211}
212
213/// Deserializes an optional RFC 3339 timestamp sent by JSON API clients.
214pub fn deserialize_optional_rfc3339<'de, D>(
215    deserializer: D,
216) -> Result<Option<time::OffsetDateTime>, D::Error>
217where
218    D: serde::Deserializer<'de>,
219{
220    time::serde::rfc3339::option::deserialize(deserializer)
221}
222
223/// Deserializes an RFC 3339 timestamp while preserving patch-field presence.
224pub fn deserialize_patch_rfc3339<'de, D>(
225    deserializer: D,
226) -> Result<PatchField<time::OffsetDateTime>, D::Error>
227where
228    D: serde::Deserializer<'de>,
229{
230    deserialize_rfc3339(deserializer).map(PatchField::Value)
231}
232
233/// Deserializes an optional RFC 3339 timestamp while preserving patch-field presence.
234pub fn deserialize_patch_optional_rfc3339<'de, D>(
235    deserializer: D,
236) -> Result<PatchField<Option<time::OffsetDateTime>>, D::Error>
237where
238    D: serde::Deserializer<'de>,
239{
240    deserialize_optional_rfc3339(deserializer).map(PatchField::Value)
241}
242
243#[cfg(any(feature = "sqlite", feature = "postgres"))]
244pub use connection::*;
245
246#[cfg(all(feature = "postgres", feature = "sqlite"))]
247compile_error!("features `postgres` and `sqlite` are mutually exclusive");
248
249#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
250compile_error!("enable exactly one database backend: `postgres` or `sqlite`");
251
252#[cfg(test)]
253mod tests;