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 image;
79mod json;
80pub mod migration;
81pub use json::JsonField;
82mod query;
83mod row;
84mod schema;
85mod sql;
86mod sync;
87mod types;
88
89#[cfg(any(feature = "sqlite", feature = "postgres"))]
90mod connection;
91
92pub use image::ImageField;
93pub use migration::*;
94pub use query::*;
95pub use row::*;
96pub use schema::*;
97pub use sql::*;
98pub use sync::*;
99pub use types::*;
100pub use uuid::Uuid;
101
102/// Serializes a timestamp in the RFC 3339 format used by JSON API clients.
103pub struct Rfc3339Timestamp<'a>(pub &'a time::OffsetDateTime);
104
105impl serde::Serialize for Rfc3339Timestamp<'_> {
106    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
107    where
108        S: serde::Serializer,
109    {
110        time::serde::rfc3339::serialize(self.0, serializer)
111    }
112}
113
114/// Serializes an optional timestamp in RFC 3339 when it has a value.
115pub struct OptionalRfc3339Timestamp<'a>(pub &'a Option<time::OffsetDateTime>);
116
117impl serde::Serialize for OptionalRfc3339Timestamp<'_> {
118    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
119    where
120        S: serde::Serializer,
121    {
122        time::serde::rfc3339::option::serialize(self.0, serializer)
123    }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum WriteMode<Key = i64> {
128    Create,
129    Update { id: Key },
130    Patch { id: Key },
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct ValidationErrors {
135    pub detail: String,
136}
137
138impl From<serde_json::Error> for ValidationErrors {
139    fn from(error: serde_json::Error) -> Self {
140        Self {
141            detail: error.to_string(),
142        }
143    }
144}
145
146pub enum ValidatedWrite<M: Model> {
147    Create(InsertQuery<M>),
148    Update(UpdateQuery<M>),
149}
150
151impl<M: Model> ValidatedWrite<M> {
152    pub fn set<T, V>(self, field: ModelField<M, T>, value: V) -> Self
153    where
154        V: QueryValue<T>,
155    {
156        match self {
157            Self::Create(query) => Self::Create(query.set(field, value)),
158            Self::Update(query) => Self::Update(query.set(field, value)),
159        }
160    }
161}
162
163pub trait ModelWriteSerializer {
164    type Model: Model;
165
166    fn is_valid(
167        data: serde_json::Value,
168        mode: WriteMode<<Self::Model as Model>::PrimaryKey>,
169    ) -> Result<ValidatedWrite<Self::Model>, ValidationErrors>;
170}
171
172/// A JSON patch value. `Missing` means that the property was not sent;
173/// `Value(None)` represents an explicit JSON null.
174#[derive(Debug, Clone, Default, PartialEq, Eq)]
175pub enum PatchField<T> {
176    #[default]
177    Missing,
178    Value(T),
179}
180
181impl<T> PatchField<T> {
182    pub const fn is_missing(&self) -> bool {
183        matches!(self, Self::Missing)
184    }
185}
186
187impl<'de, T> serde::Deserialize<'de> for PatchField<T>
188where
189    T: serde::Deserialize<'de>,
190{
191    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
192    where
193        D: serde::Deserializer<'de>,
194    {
195        T::deserialize(deserializer).map(Self::Value)
196    }
197}
198
199/// Deserializes an RFC 3339 timestamp sent by JSON API clients.
200pub fn deserialize_rfc3339<'de, D>(deserializer: D) -> Result<time::OffsetDateTime, D::Error>
201where
202    D: serde::Deserializer<'de>,
203{
204    time::serde::rfc3339::deserialize(deserializer)
205}
206
207/// Deserializes an optional RFC 3339 timestamp sent by JSON API clients.
208pub fn deserialize_optional_rfc3339<'de, D>(
209    deserializer: D,
210) -> Result<Option<time::OffsetDateTime>, D::Error>
211where
212    D: serde::Deserializer<'de>,
213{
214    time::serde::rfc3339::option::deserialize(deserializer)
215}
216
217/// Deserializes an RFC 3339 timestamp while preserving patch-field presence.
218pub fn deserialize_patch_rfc3339<'de, D>(
219    deserializer: D,
220) -> Result<PatchField<time::OffsetDateTime>, D::Error>
221where
222    D: serde::Deserializer<'de>,
223{
224    deserialize_rfc3339(deserializer).map(PatchField::Value)
225}
226
227/// Deserializes an optional RFC 3339 timestamp while preserving patch-field presence.
228pub fn deserialize_patch_optional_rfc3339<'de, D>(
229    deserializer: D,
230) -> Result<PatchField<Option<time::OffsetDateTime>>, D::Error>
231where
232    D: serde::Deserializer<'de>,
233{
234    deserialize_optional_rfc3339(deserializer).map(PatchField::Value)
235}
236
237#[cfg(any(feature = "sqlite", feature = "postgres"))]
238pub use connection::*;
239
240#[cfg(all(feature = "postgres", feature = "sqlite"))]
241compile_error!("features `postgres` and `sqlite` are mutually exclusive");
242
243#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
244compile_error!("enable exactly one database backend: `postgres` or `sqlite`");
245
246#[cfg(test)]
247mod tests;