Skip to main content

Crate che_orm

Crate che_orm 

Source
Expand description

che-orm — экспериментальная типизированная ORM для Rust.

Backend выбирается feature sqlite или postgres: Database предоставляет async pool и high-level CRUD/query facade, а Model derive генерирует metadata, row decoding и insert values. SQL можно также использовать отдельно через SqlCompiler.

Основной рабочий сценарий для backend sqlite. create_table подходит для тестов и локальных экспериментов; для постоянной схемы используйте миграции.

use che_orm::{Database, Model};

#[derive(Debug, Model)]
#[orm(table = "users")]
struct User {
    #[orm(primary_key)]
    id: i64,
    name: String,
}

let database = Database::connect_in_memory().await?;
database.create_table::<User>().await?;
let user = database
    .create::<User>()
    .set(User::NAME, "Alice")
    .execute()
    .await?;
let loaded = database.get::<User>(user.id).await?;
assert_eq!(loaded.unwrap().name, "Alice");

Fixed string choices use DbEnum. It owns the JSON and database value, so a variant has one canonical representation everywhere:

use che_orm::DbEnum;
#[derive(Debug, Clone, Copy, DbEnum)]
enum TaskStatus {
    Draft,
    #[db_enum(rename = "in_progress")]
    InProgress,
}

assert_eq!(TaskStatus::InProgress.as_str(), "in_progress");
assert_eq!(
    che_orm::serde_json::to_string(&TaskStatus::InProgress).unwrap(),
    "\"in_progress\"",
);

Do not derive serde::Serialize or serde::Deserialize for a DbEnum; the derive generates both implementations.

Re-exports§

pub use rusqlite;
pub use serde;
pub use serde_json;
pub use time;
pub use migration::*;

Modules§

migration

Structs§

AppRegistry
Registry that combines schemas from multiple application modules.
Assignment
BelongsTo
A typed forward foreign-key relation from one model to another.
BoundQuery
A query bound to the database that created it.
ColumnRef
ColumnSchema
Metadata for one table column.
CompiledQuery
SQL text and ordered bound parameters.
CompiledSchema
Table DDL plus separately executable indexes.
CreateBuilder
CreateTableAst
AST node for a CREATE TABLE statement.
CreateTableQuery
Builder for a model’s CREATE TABLE statement.
Database
Async database using the backend selected by the crate feature.
DatabaseQuery
DeleteAst
DeleteQuery
ExecuteResult
ForeignKey
Foreign key metadata attached to a column.
HasMany
A typed reverse foreign-key relation from one model to many related models.
ImageField
A relative storage key for an image. The bytes live in a media backend, not in the database; che-rest manages uploads and URLs.
InsertAst
InsertQuery
InsertValue
JoinAst
JoinedField
JsonField
JSON stored as SQL TEXT and serialized as a JSON value, never as an escaped string.
Loaded
LoadedMany
LoadedOne
ModelField
A typed reference to one model column.
ModelWriteResult
MultiPrefetchRelatedQuery
MultiSelectRelatedQuery
NestedPrefetchPlan
NestedPrefetchQuery
OptionalRfc3339Timestamp
Serializes an optional timestamp in RFC 3339 when it has a value.
OrderBy
PostgresDialect
PrefetchRelatedQuery
Rfc3339Timestamp
Serializes a timestamp in the RFC 3339 format used by JSON API clients.
Row
An owned row with the same decoding interface for either backend.
SchemaSet
A collection of model schemas exported as one SQL schema.
SelectAst
SelectQuery
SelectRelatedQuery
SerializerField
SqlCompiler
SqliteDialect
SyncField
Stable protocol name mapped to a model-controlled SQL column.
SyncRegistration
Runtime-independent registration consumed by che-sync.
TableRef
TableSchema
Complete model table metadata used for DDL generation.
Transaction
ORM operations pinned to one transaction connection on either backend.
TransactionCreateBuilder
TransactionQuery
TransactionUpdateBuilder
UpdateAst
UpdateBuilder
UpdateQuery
Uuid
A Universally Unique Identifier (UUID).
ValidationErrors
WithMany
WithOne
WithOptionalOne

Enums§

ColumnType
SQL column types supported by the schema compiler.
CompareOp
ConstraintKind
DatabaseValue
Values bound to SQL placeholders.
DecodeError
Expr
Boolean and comparison expression tree used by query builders.
IsolationLevel
JoinType
ModelRole
Role of a synchronized model in a particular database.
OrderDirection
OrmError
PatchField
A JSON patch value. Missing means that the property was not sent; Value(None) represents an explicit JSON null.
QueryAst
QueryBuildError
Errors detected while finalizing a query builder.
SchemaError
Errors found in model-generated schema metadata.
ValidatedWrite
WriteMode

Traits§

AppConfig
Application-level model registration, similar to a Django app config.
ColumnTypeOf
Maps a Rust field type to a SQL column type.
DbEnum
A string-backed enum that can be stored in a database column.
ForeignKeyValue
Extracts the owner key from a required or nullable foreign-key field.
FromDatabaseValue
Converts a materialized database value into a model field.
Model
Trait implemented by #[derive(Model)] for ORM models.
ModelRuntime
Transactional extension point for registered model writes. Implementations use raw transaction methods internally to avoid recursively capturing writes.
ModelSerializer
Converts a materialized ORM model into an API representation.
ModelWriteSerializer
PrefetchRelation
PrimaryKey
Supported model keys, including their automatic INSERT value.
QueryValue
RelationSource
Identifies the actual foreign-key column behind a serializer relation.
SqlDialect
SyncModel
Shared model definition. Its client/server role belongs to registration.

Functions§

deserialize_optional_rfc3339
Deserializes an optional RFC 3339 timestamp sent by JSON API clients.
deserialize_patch_optional_rfc3339
Deserializes an optional RFC 3339 timestamp while preserving patch-field presence.
deserialize_patch_rfc3339
Deserializes an RFC 3339 timestamp while preserving patch-field presence.
deserialize_rfc3339
Deserializes an RFC 3339 timestamp sent by JSON API clients.
sync_migration_operations
Infrastructure tables shared by all registrations of a database role.
sync_migration_operations_for_role
Explicit role variant, also useful for an empty legacy registry.

Type Aliases§

Compiler
CurrentDialect
TransactionFuture

Derive Macros§

DbEnum
Model
ModelSerializer