mirror of
https://github.com/Phundrak/georm.git
synced 2026-07-28 20:09:18 +02:00
feat: add SQLite support behind a sqlite Cargo feature
Adds a SqliteDialect alongside PostgresDialect, gated by mutually exclusive postgres (default) / sqlite Cargo features, plus a feature-selected ActiveDatabase type alias used throughout the public Georm/Defaultable traits. Basic CRUD and Defaultable are fully covered by a new SQLite test suite (tests/sqlite/*) running against a real SQLite database, alongside split migrations/sqlite/*. Two real dialect differences surfaced beyond placeholder syntax: - SQLite's INTEGER columns type-infer as i64 in sqlx's compile-time query macros (unlike Postgres SERIAL -> i32), so the SQLite test models use i64 for integer PK/FK fields. - sqlx's SQLite query macros need bind arguments bound to a place rather than passed as an inline expression (fixed once, centrally, in SqlDialect::generate_relation_lookup). Composite-key entities with chrono::DateTime columns (tests/composite_key.rs) are not yet ported to SQLite: SQLite has no TIMESTAMPTZ equivalent, so sqlx infers TEXT date/time columns as String rather than DateTime<Utc> unless the query explicitly overrides the column type. That needs per-field type overrides threaded through the generated queries, left as follow-up. CI now matrixes over both backends; formatting/audit only run once since they don't vary by backend. examples/postgres/* stays out of --no-default-features builds by scoping sqlite lint/test just recipes to `-p georm` (it depends on georm's default postgres feature via Cargo feature unification, so building it under --features sqlite at the workspace level double-activates both dialects).
This commit is contained in:
@@ -2,8 +2,6 @@ name: CI
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
env:
|
||||
DATABASE_URL: postgresql://georm:georm@postgres:5432/georm
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -17,6 +15,10 @@ jobs:
|
||||
options: --security-opt seccomp=unconfined
|
||||
permissions:
|
||||
pull-requests: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
backend: [postgres, sqlite]
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
@@ -29,19 +31,32 @@ jobs:
|
||||
--health-interval 10s
|
||||
--health-timeout 10s
|
||||
--health-retries 5
|
||||
env:
|
||||
DATABASE_URL: ${{ matrix.backend == 'postgres' && 'postgresql://georm:georm@postgres:5432/georm' || 'sqlite:///tmp/georm-ci.db' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@v31
|
||||
- name: Install devenv
|
||||
run: nix profile install nixpkgs#devenv
|
||||
- name: Migrate database
|
||||
run: devenv shell just migrate
|
||||
- name: Create SQLite database file
|
||||
if: matrix.backend == 'sqlite'
|
||||
run: touch /tmp/georm-ci.db
|
||||
- name: Migrate database (postgres)
|
||||
if: matrix.backend == 'postgres'
|
||||
run: devenv shell just migrate-postgres
|
||||
- name: Migrate database (sqlite)
|
||||
if: matrix.backend == 'sqlite'
|
||||
run: devenv shell just migrate-sqlite
|
||||
# Formatting and dependency audit don't vary by backend, so only run
|
||||
# them once rather than duplicating across both matrix legs.
|
||||
- name: Formatting check
|
||||
if: matrix.backend == 'postgres'
|
||||
run: devenv shell just format-check
|
||||
- name: Lint
|
||||
run: devenv shell just lint
|
||||
- name: Audit
|
||||
if: matrix.backend == 'postgres'
|
||||
run: devenv shell just audit
|
||||
- name: Lint
|
||||
run: devenv shell just ${{ matrix.backend == 'postgres' && 'lint' || 'lint-sqlite' }}
|
||||
- name: Tests
|
||||
run: devenv shell just test
|
||||
run: devenv shell just ${{ matrix.backend == 'postgres' && 'test-postgres' || 'test-sqlite' }}
|
||||
|
||||
@@ -4,6 +4,12 @@
|
||||
/.sqls
|
||||
/examples/target
|
||||
|
||||
# Local SQLite databases used for manual testing
|
||||
*.db
|
||||
*.db-journal
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# Devenv
|
||||
.devenv*
|
||||
devenv.local.nix
|
||||
|
||||
Generated
+1
@@ -951,6 +951,7 @@ version = "0.30.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
+27
-3
@@ -18,7 +18,7 @@ categories = ["database"]
|
||||
[package]
|
||||
name = "georm"
|
||||
readme = "README.md"
|
||||
description = "Georm, a simple, opiniated SQLx ORM for PostgreSQL"
|
||||
description = "Georm, a simple, opiniated SQLx ORM for PostgreSQL and SQLite"
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
homepage.workspace = true
|
||||
@@ -26,13 +26,18 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["postgres"]
|
||||
postgres = ["georm-macros/postgres", "sqlx/postgres", "sqlx/bigdecimal"]
|
||||
sqlite = ["georm-macros/sqlite", "sqlx/sqlite"]
|
||||
|
||||
[workspace.dependencies]
|
||||
georm-macros = { version = "=0.2.1", path = "georm-macros" }
|
||||
|
||||
[workspace.dependencies.sqlx]
|
||||
version = "0.8.6"
|
||||
default-features = false
|
||||
features = ["postgres", "runtime-tokio", "macros", "migrate", "bigdecimal"]
|
||||
features = ["runtime-tokio", "macros", "migrate"]
|
||||
|
||||
[dependencies]
|
||||
sqlx = { workspace = true }
|
||||
@@ -43,9 +48,28 @@ chrono = { version = "0.4", features = ["serde"] }
|
||||
rand = "0.9"
|
||||
|
||||
[dev-dependencies.sqlx]
|
||||
# Unlike the crate's own [features] above, dev-dependencies are always built
|
||||
# for `cargo test` regardless of --no-default-features/--features passed for
|
||||
# the georm package itself. Tests bind directly to sqlx::PgPool/SqlitePool,
|
||||
# so both drivers must be enabled here unconditionally.
|
||||
version = "0.8.6"
|
||||
default-features = false
|
||||
features = ["postgres", "runtime-tokio", "macros", "migrate", "chrono"]
|
||||
features = ["postgres", "sqlite", "runtime-tokio", "macros", "migrate", "chrono", "bigdecimal"]
|
||||
|
||||
# Cargo's test auto-discovery only scans tests/*.rs (not subdirectories), so
|
||||
# the tests/sqlite/*.rs files (kept in their own directory to avoid colliding
|
||||
# with the postgres tests/models.rs module) need explicit [[test]] entries.
|
||||
[[test]]
|
||||
name = "sqlite_simple_struct"
|
||||
path = "tests/sqlite/simple_struct.rs"
|
||||
|
||||
[[test]]
|
||||
name = "sqlite_defaultable_struct"
|
||||
path = "tests/sqlite/defaultable_struct.rs"
|
||||
|
||||
# sqlite_composite_key intentionally deferred: UserRole's chrono::DateTime<Utc>
|
||||
# column needs per-field query_as! type overrides under SQLite (see the note
|
||||
# in tests/sqlite/models.rs) that don't exist yet.
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<h1 align="center">Georm</h1>
|
||||
<div align="center">
|
||||
<strong>
|
||||
A simple, type-safe SQLx ORM for PostgreSQL
|
||||
A simple, type-safe SQLx ORM for PostgreSQL and SQLite
|
||||
</strong>
|
||||
</div>
|
||||
<br/>
|
||||
@@ -606,7 +606,7 @@ Georm is designed for zero runtime overhead:
|
||||
- **Compile-time queries**: All SQL is verified at compile time
|
||||
- **No reflection**: Direct field access, no runtime introspection
|
||||
- **Minimal allocations**: Efficient use of owned vs borrowed data
|
||||
- **SQLx integration**: Leverages SQLx's optimized PostgreSQL driver
|
||||
- **SQLx integration**: Leverages SQLx's optimized PostgreSQL or SQLite driver, selected via the `postgres`/`sqlite` Cargo features
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -651,7 +651,7 @@ cargo run help # For a list of all available actions
|
||||
|
||||
### High Priority
|
||||
- **Simplified Relationship Syntax**: Remove redundant table/remote_id specifications by inferring them from target entity metadata
|
||||
- **Multi-Database Support**: MySQL and SQLite support with feature flags
|
||||
- **Multi-Database Support**: SQLite support landed behind the `sqlite` feature flag (composite keys with `chrono` columns still pending); MySQL remains unstarted
|
||||
|
||||
### Medium Priority
|
||||
- **Composite Key Relationships**: Add relationship support (one-to-one, one-to-many, many-to-many) for entities with composite primary keys
|
||||
|
||||
@@ -10,6 +10,10 @@ repository.workspace = true
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[features]
|
||||
postgres = []
|
||||
sqlite = []
|
||||
|
||||
[dependencies]
|
||||
deluxe = "0.5.0"
|
||||
proc-macro2 = "1.0.93"
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
//! `Defaultable` trait.
|
||||
|
||||
use crate::georm::ir::GeneratedType;
|
||||
use crate::georm::sql::{self, SqlDialect};
|
||||
|
||||
use super::ir::{GeormField, GeormStructAttributes};
|
||||
use quote::quote;
|
||||
@@ -92,11 +93,15 @@ fn generate_defaultable_trait_impl(
|
||||
});
|
||||
}
|
||||
|
||||
let database = sql::DIALECT.database_type();
|
||||
let index_var = syn::Ident::new("i", proc_macro2::Span::call_site());
|
||||
let placeholder_expr = sql::DIALECT.runtime_placeholder(&index_var);
|
||||
|
||||
quote! {
|
||||
impl ::georm::Defaultable<#id_type, #struct_name> for #defaultable_struct_name {
|
||||
async fn create<'e, E>(&self, mut executor: E) -> ::sqlx::Result<#struct_name>
|
||||
where
|
||||
E: ::sqlx::Executor<'e, Database = ::sqlx::Postgres>
|
||||
E: ::sqlx::Executor<'e, Database = #database>
|
||||
{
|
||||
let mut dynamic_fields = Vec::new();
|
||||
|
||||
@@ -106,7 +111,7 @@ fn generate_defaultable_trait_impl(
|
||||
all_fields.extend(dynamic_fields);
|
||||
|
||||
let placeholders: Vec<String> = (1..=all_fields.len())
|
||||
.map(|i| format!("${}", i))
|
||||
.map(|#index_var| #placeholder_expr)
|
||||
.collect();
|
||||
|
||||
let query = format!(
|
||||
|
||||
@@ -4,10 +4,22 @@ use crate::georm::ir::GeormField;
|
||||
use quote::quote;
|
||||
|
||||
mod postgres;
|
||||
pub use postgres::PostgresDialect;
|
||||
mod sqlite;
|
||||
|
||||
#[cfg(feature = "postgres")]
|
||||
pub use postgres::PostgresDialect;
|
||||
#[cfg(feature = "sqlite")]
|
||||
pub use sqlite::SqliteDialect;
|
||||
|
||||
#[cfg(feature = "postgres")]
|
||||
pub type ActiveDialect = PostgresDialect;
|
||||
#[cfg(feature = "sqlite")]
|
||||
pub type ActiveDialect = SqliteDialect;
|
||||
|
||||
#[cfg(feature = "postgres")]
|
||||
pub const DIALECT: ActiveDialect = PostgresDialect;
|
||||
#[cfg(feature = "sqlite")]
|
||||
pub const DIALECT: ActiveDialect = SqliteDialect;
|
||||
|
||||
/// How a relation-lookup query should fetch its result.
|
||||
pub enum FetchKind {
|
||||
@@ -29,6 +41,13 @@ pub trait SqlDialect {
|
||||
fn database_type(&self) -> proc_macro2::TokenStream;
|
||||
fn row_type(&self) -> proc_macro2::TokenStream;
|
||||
|
||||
/// Like [`SqlDialect::placeholder`], but for placeholder lists whose
|
||||
/// length is only known at runtime (the defaultable-struct insert, which
|
||||
/// varies its column count based on which `Option` fields are `Some`).
|
||||
/// `index_var` names the runtime `usize` loop variable holding the 1-based
|
||||
/// position of the placeholder being built.
|
||||
fn runtime_placeholder(&self, index_var: &syn::Ident) -> proc_macro2::TokenStream;
|
||||
|
||||
fn generate_from_row(
|
||||
&self,
|
||||
struct_name: &syn::Ident,
|
||||
@@ -325,7 +344,11 @@ pub trait SqlDialect {
|
||||
where
|
||||
E: ::sqlx::Executor<'e, Database = #database>
|
||||
{
|
||||
::sqlx::query_as!(#entity, #query, #arg).#fetch_method(executor).await
|
||||
// Bound to a place rather than passed inline: sqlx's SQLite
|
||||
// query macros need the bind argument to outlive the
|
||||
// temporary produced by expressions like `self.get_id()`.
|
||||
let arg = #arg;
|
||||
::sqlx::query_as!(#entity, #query, arg).#fetch_method(executor).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,4 +15,8 @@ impl SqlDialect for PostgresDialect {
|
||||
fn row_type(&self) -> proc_macro2::TokenStream {
|
||||
quote! { ::sqlx::postgres::PgRow }
|
||||
}
|
||||
|
||||
fn runtime_placeholder(&self, index_var: &syn::Ident) -> proc_macro2::TokenStream {
|
||||
quote! { format!("${}", #index_var) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
use super::SqlDialect;
|
||||
use quote::quote;
|
||||
|
||||
pub struct SqliteDialect;
|
||||
|
||||
impl SqlDialect for SqliteDialect {
|
||||
fn placeholder(&self, _index: usize) -> String {
|
||||
// SQLite accepts unnumbered `?` placeholders resolved in positional
|
||||
// (left-to-right) order, which matches the order Georm binds values in.
|
||||
"?".to_string()
|
||||
}
|
||||
|
||||
fn database_type(&self) -> proc_macro2::TokenStream {
|
||||
quote! { ::sqlx::Sqlite }
|
||||
}
|
||||
|
||||
fn row_type(&self) -> proc_macro2::TokenStream {
|
||||
quote! { ::sqlx::sqlite::SqliteRow }
|
||||
}
|
||||
|
||||
fn runtime_placeholder(&self, index_var: &syn::Ident) -> proc_macro2::TokenStream {
|
||||
quote! {
|
||||
{
|
||||
let _ = #index_var;
|
||||
"?".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,36 @@ default: lint
|
||||
clean:
|
||||
cargo clean
|
||||
|
||||
test:
|
||||
# Runs the whole workspace (examples included) against the default
|
||||
# "postgres" feature.
|
||||
test: test-postgres
|
||||
|
||||
test-postgres:
|
||||
cargo test --all-targets --all
|
||||
|
||||
# Scoped to -p georm: examples/postgres/* depends on georm's default
|
||||
# ("postgres") feature via Cargo feature unification, so it must stay out of
|
||||
# a --no-default-features build rather than be dragged into it.
|
||||
test-sqlite:
|
||||
cargo test -p georm --no-default-features --features sqlite --all-targets
|
||||
|
||||
lint:
|
||||
cargo clippy --all-targets
|
||||
|
||||
lint-sqlite:
|
||||
cargo clippy -p georm -p georm-macros --no-default-features --features sqlite --all-targets
|
||||
|
||||
audit:
|
||||
cargo deny check all
|
||||
|
||||
migrate:
|
||||
migrate: migrate-postgres
|
||||
|
||||
migrate-postgres:
|
||||
cargo sqlx migrate run
|
||||
|
||||
migrate-sqlite:
|
||||
cargo sqlx migrate run --source migrations/sqlite
|
||||
|
||||
build:
|
||||
cargo build
|
||||
|
||||
@@ -27,7 +45,7 @@ format:
|
||||
format-check:
|
||||
cargo fmt --check --all
|
||||
|
||||
check-all: format-check lint audit test
|
||||
check-all: format-check lint audit test test-sqlite
|
||||
|
||||
## Local Variables:
|
||||
## mode: makefile
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
DROP TABLE IF EXISTS reviews;
|
||||
DROP TABLE IF EXISTS book_genres;
|
||||
DROP TABLE IF EXISTS books;
|
||||
DROP TABLE IF EXISTS genres;
|
||||
DROP TABLE IF EXISTS authors;
|
||||
DROP TABLE IF EXISTS biographies;
|
||||
@@ -0,0 +1,38 @@
|
||||
CREATE TABLE biographies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
content TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE authors (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
biography_id INT,
|
||||
FOREIGN KEY (biography_id) REFERENCES biographies(id)
|
||||
);
|
||||
|
||||
CREATE TABLE books (
|
||||
ident INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title VARCHAR(100) NOT NULL,
|
||||
author_id INT NOT NULL,
|
||||
FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE reviews (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
book_id INT NOT NULL,
|
||||
review TEXT NOT NULL,
|
||||
FOREIGN KEY (book_id) REFERENCES books(ident) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE genres (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(100) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE book_genres (
|
||||
book_id INT NOT NULL,
|
||||
genre_id INT NOT NULL,
|
||||
PRIMARY KEY (book_id, genre_id),
|
||||
FOREIGN KEY (book_id) REFERENCES books(ident) ON DELETE CASCADE,
|
||||
FOREIGN KEY (genre_id) REFERENCES genres(id) ON DELETE CASCADE
|
||||
);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Add down migration script here
|
||||
DROP TABLE IF EXISTS UserRoles;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Add up migration script here
|
||||
CREATE TABLE UserRoles (
|
||||
user_id INTEGER NOT NULL,
|
||||
role_id INTEGER NOT NULL,
|
||||
assigned_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
PRIMARY KEY (user_id, role_id)
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
//! The SQL backend selected via Cargo feature flags (`postgres` or `sqlite`,
|
||||
//! mutually exclusive — see the guard in `lib.rs`).
|
||||
|
||||
#[cfg(feature = "postgres")]
|
||||
pub type ActiveDatabase = ::sqlx::Postgres;
|
||||
#[cfg(feature = "sqlite")]
|
||||
pub type ActiveDatabase = ::sqlx::Sqlite;
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
use sqlx::{Executor, Postgres};
|
||||
use crate::ActiveDatabase;
|
||||
use sqlx::Executor;
|
||||
|
||||
/// Trait for creating entities with database defaults and auto-generated values.
|
||||
///
|
||||
@@ -277,5 +278,5 @@ pub trait Defaultable<Id, Entity> {
|
||||
) -> impl std::future::Future<Output = sqlx::Result<Entity>> + Send
|
||||
where
|
||||
Self: Sized,
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
}
|
||||
|
||||
+10
-9
@@ -1,4 +1,5 @@
|
||||
use sqlx::{Executor, Postgres};
|
||||
use crate::ActiveDatabase;
|
||||
use sqlx::Executor;
|
||||
|
||||
/// Core database operations trait for Georm entities.
|
||||
///
|
||||
@@ -125,7 +126,7 @@ pub trait Georm<Id> {
|
||||
) -> impl ::std::future::Future<Output = ::sqlx::Result<Vec<Self>>> + Send
|
||||
where
|
||||
Self: Sized,
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
|
||||
/// Find a single entity by its primary key.
|
||||
///
|
||||
@@ -161,7 +162,7 @@ pub trait Georm<Id> {
|
||||
) -> impl std::future::Future<Output = sqlx::Result<Option<Self>>> + Send
|
||||
where
|
||||
Self: Sized,
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
|
||||
/// Insert this entity as a new record in the database.
|
||||
///
|
||||
@@ -201,7 +202,7 @@ pub trait Georm<Id> {
|
||||
) -> impl std::future::Future<Output = sqlx::Result<Self>> + Send
|
||||
where
|
||||
Self: Sized,
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
|
||||
/// Update an existing entity in the database.
|
||||
///
|
||||
@@ -240,7 +241,7 @@ pub trait Georm<Id> {
|
||||
) -> impl std::future::Future<Output = sqlx::Result<Self>> + Send
|
||||
where
|
||||
Self: Sized,
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
|
||||
/// Insert or update this entity using PostgreSQL's upsert functionality.
|
||||
///
|
||||
@@ -276,7 +277,7 @@ pub trait Georm<Id> {
|
||||
fn upsert<'e, E>(&self, executor: E) -> impl ::std::future::Future<Output = sqlx::Result<Self>>
|
||||
where
|
||||
Self: Sized,
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
|
||||
#[deprecated(since = "0.3.0", note = "Please use `upsert` instead")]
|
||||
fn create_or_update<'e, E>(
|
||||
@@ -285,7 +286,7 @@ pub trait Georm<Id> {
|
||||
) -> impl ::std::future::Future<Output = sqlx::Result<Self>>
|
||||
where
|
||||
Self: Sized,
|
||||
E: Executor<'e, Database = Postgres>,
|
||||
E: Executor<'e, Database = ActiveDatabase>,
|
||||
{
|
||||
self.upsert(executor)
|
||||
}
|
||||
@@ -324,7 +325,7 @@ pub trait Georm<Id> {
|
||||
executor: E,
|
||||
) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
|
||||
where
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
|
||||
/// Delete an entity by its primary key without needing an entity instance.
|
||||
///
|
||||
@@ -364,7 +365,7 @@ pub trait Georm<Id> {
|
||||
id: &Id,
|
||||
) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
|
||||
where
|
||||
E: Executor<'e, Database = Postgres>;
|
||||
E: Executor<'e, Database = ActiveDatabase>;
|
||||
|
||||
/// Get the primary key of this entity.
|
||||
///
|
||||
|
||||
+21
-4
@@ -1,6 +1,7 @@
|
||||
//! # Georm
|
||||
//!
|
||||
//! A simple, type-safe PostgreSQL ORM built on SQLx with zero runtime overhead.
|
||||
//! A simple, type-safe ORM for PostgreSQL and SQLite built on SQLx with zero
|
||||
//! runtime overhead.
|
||||
//!
|
||||
//! ## Quick Start
|
||||
//!
|
||||
@@ -618,8 +619,16 @@
|
||||
//!
|
||||
//! ### Database Support
|
||||
//!
|
||||
//! Georm is currently limited to PostgreSQL. Other databases may be supported in
|
||||
//! the future, such as SQLite or MySQL, but that is not the case yet.
|
||||
//! Georm supports PostgreSQL and SQLite, selected via the mutually exclusive
|
||||
//! `postgres` (default) and `sqlite` Cargo features. Basic CRUD (`find_all`,
|
||||
//! `find`, `create`, `update`, `upsert`, `delete`) and `Defaultable` are
|
||||
//! supported on both backends; relationship queries (`one_to_one`,
|
||||
//! `one_to_many`, `many_to_many`, field-level `relation`) are implemented for
|
||||
//! both dialects at the SQL-generation level, but composite-key entities with
|
||||
//! `chrono::DateTime` columns are not yet covered by the SQLite test suite
|
||||
//! (SQLite's compile-time query macros need explicit column type overrides
|
||||
//! for non-primitive types, which is follow-up work). `sqlx::types::BigDecimal`
|
||||
//! fields require the `postgres` feature — SQLite has no equivalent type.
|
||||
//!
|
||||
//! ### Identifiers
|
||||
//!
|
||||
@@ -635,7 +644,8 @@
|
||||
//! - **No advanced queries**: No complex WHERE clauses or joins beyond relationships
|
||||
//! - **No eager loading**: Each relationship call is a separate database query
|
||||
//! - **No field-based queries**: No `find_by_{field_name}` methods generated automatically
|
||||
//! - **PostgreSQL only**: No support for other database systems
|
||||
//! - **SQLite + `chrono`**: composite-key entities with `chrono::DateTime` columns aren't yet
|
||||
//! covered under the `sqlite` feature (see "Database Support" above)
|
||||
//!
|
||||
//! ## Generated Code
|
||||
//!
|
||||
@@ -646,8 +656,15 @@
|
||||
//! - Relationship methods for accessing related entities
|
||||
//! - All CRUD operations with proper PostgreSQL optimizations
|
||||
|
||||
#[cfg(all(feature = "postgres", feature = "sqlite"))]
|
||||
compile_error!("georm: \"postgres\" and \"sqlite\" are mutually exclusive; enable only one");
|
||||
#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
|
||||
compile_error!("georm: enable exactly one of \"postgres\" or \"sqlite\"");
|
||||
|
||||
pub use georm_macros::Georm;
|
||||
|
||||
mod database;
|
||||
pub use database::ActiveDatabase;
|
||||
mod georm;
|
||||
pub use georm::Georm;
|
||||
mod defaultable;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::Georm;
|
||||
|
||||
mod models;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::Georm;
|
||||
|
||||
// Test struct with defaultable fields using existing table structure
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::{Defaultable, Georm};
|
||||
use sqlx::types::BigDecimal;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::Georm;
|
||||
|
||||
mod models;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::Georm;
|
||||
use sqlx::{Postgres, types::BigDecimal};
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::Georm;
|
||||
|
||||
mod models;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::Georm;
|
||||
|
||||
mod models;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg(feature = "postgres")]
|
||||
|
||||
use georm::Georm;
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
#![cfg(feature = "sqlite")]
|
||||
|
||||
use georm::Georm;
|
||||
|
||||
// Test struct with defaultable fields using existing table structure
|
||||
#[derive(Georm, Debug)]
|
||||
#[georm(table = "authors")]
|
||||
struct TestAuthor {
|
||||
#[georm(id, defaultable)]
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub biography_id: Option<i64>, // Don't mark Option fields as defaultable
|
||||
}
|
||||
|
||||
// Test struct with only ID defaultable
|
||||
#[derive(Georm)]
|
||||
#[georm(table = "authors")]
|
||||
struct MinimalDefaultable {
|
||||
#[georm(id, defaultable)]
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub biography_id: Option<i64>,
|
||||
}
|
||||
|
||||
// Test struct with multiple defaultable fields
|
||||
#[derive(Georm)]
|
||||
#[georm(table = "authors")]
|
||||
struct MultiDefaultable {
|
||||
#[georm(id, defaultable)]
|
||||
pub id: i64,
|
||||
#[georm(defaultable)]
|
||||
pub name: String,
|
||||
pub biography_id: Option<i64>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaultable_struct_should_exist() {
|
||||
let _author_default = TestAuthorDefault {
|
||||
id: Some(1),
|
||||
name: "Test Author".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_defaultable_struct_should_exist() {
|
||||
let _minimal_default = MinimalDefaultableDefault {
|
||||
id: None,
|
||||
name: "testuser".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaultable_fields_can_be_none() {
|
||||
let _author_default = TestAuthorDefault {
|
||||
id: None,
|
||||
name: "Test Author".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_visibility_is_preserved() {
|
||||
let _author_default = TestAuthorDefault {
|
||||
id: Some(1),
|
||||
name: "Test".to_string(),
|
||||
biography_id: Some(1),
|
||||
};
|
||||
}
|
||||
|
||||
mod defaultable_tests {
|
||||
use super::*;
|
||||
use georm::Defaultable;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_create_entity_from_defaultable_with_id(pool: SqlitePool) {
|
||||
let author_default = TestAuthorDefault {
|
||||
id: Some(999),
|
||||
name: "John Doe".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let created_author = author_default.create(&pool).await.unwrap();
|
||||
|
||||
assert_eq!(created_author.id, 999);
|
||||
assert_eq!(created_author.name, "John Doe");
|
||||
assert_eq!(created_author.biography_id, None);
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_create_entity_from_defaultable_without_id(pool: SqlitePool) {
|
||||
let author_default = TestAuthorDefault {
|
||||
id: None,
|
||||
name: "Jane Smith".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let created_author = author_default.create(&pool).await.unwrap();
|
||||
|
||||
assert!(created_author.id > 0);
|
||||
assert_eq!(created_author.name, "Jane Smith");
|
||||
assert_eq!(created_author.biography_id, None);
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_create_entity_from_minimal_defaultable(pool: SqlitePool) {
|
||||
let minimal_default = MinimalDefaultableDefault {
|
||||
id: None,
|
||||
name: "Alice Wonder".to_string(),
|
||||
biography_id: Some(1),
|
||||
};
|
||||
|
||||
let created_author = minimal_default.create(&pool).await.unwrap();
|
||||
|
||||
assert!(created_author.id > 0);
|
||||
assert_eq!(created_author.name, "Alice Wonder");
|
||||
assert_eq!(created_author.biography_id, Some(1));
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_create_multiple_entities_from_defaultable(pool: SqlitePool) {
|
||||
let author1_default = TestAuthorDefault {
|
||||
id: None,
|
||||
name: "Author One".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let author2_default = TestAuthorDefault {
|
||||
id: None,
|
||||
name: "Author Two".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let created_author1 = author1_default.create(&pool).await.unwrap();
|
||||
let created_author2 = author2_default.create(&pool).await.unwrap();
|
||||
|
||||
assert!(created_author1.id > 0);
|
||||
assert!(created_author2.id > 0);
|
||||
assert_ne!(created_author1.id, created_author2.id);
|
||||
|
||||
assert_eq!(created_author1.name, "Author One");
|
||||
assert_eq!(created_author2.name, "Author Two");
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_multiple_defaultable_fields_mixed(pool: SqlitePool) {
|
||||
let multi_default = MultiDefaultableDefault {
|
||||
id: None,
|
||||
name: Some("Explicit Name".to_string()),
|
||||
biography_id: Some(1),
|
||||
};
|
||||
|
||||
let created = multi_default.create(&pool).await.unwrap();
|
||||
|
||||
assert!(created.id > 0);
|
||||
assert_eq!(created.name, "Explicit Name");
|
||||
assert_eq!(created.biography_id, Some(1));
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_multiple_defaultable_fields_all_explicit(pool: SqlitePool) {
|
||||
let multi_default = MultiDefaultableDefault {
|
||||
id: Some(888),
|
||||
name: Some("All Explicit".to_string()),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let created = multi_default.create(&pool).await.unwrap();
|
||||
|
||||
assert_eq!(created.id, 888);
|
||||
assert_eq!(created.name, "All Explicit");
|
||||
assert_eq!(created.biography_id, None);
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_error_duplicate_id(pool: SqlitePool) {
|
||||
let author1 = TestAuthorDefault {
|
||||
id: Some(777),
|
||||
name: "First Author".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let author2 = TestAuthorDefault {
|
||||
id: Some(777),
|
||||
name: "Second Author".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let _created1 = author1.create(&pool).await.unwrap();
|
||||
|
||||
let result2 = author2.create(&pool).await;
|
||||
assert!(result2.is_err());
|
||||
}
|
||||
|
||||
mod sql_validation_tests {
|
||||
use super::*;
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_sql_generation_no_defaultable_fields(pool: SqlitePool) {
|
||||
let author_default = TestAuthorDefault {
|
||||
id: Some(100),
|
||||
name: "Test Name".to_string(),
|
||||
biography_id: Some(1),
|
||||
};
|
||||
|
||||
let created = author_default.create(&pool).await.unwrap();
|
||||
|
||||
assert_eq!(created.id, 100);
|
||||
assert_eq!(created.name, "Test Name");
|
||||
assert_eq!(created.biography_id, Some(1));
|
||||
|
||||
let found: TestAuthor = sqlx::query_as!(
|
||||
TestAuthor,
|
||||
"SELECT id, name, biography_id FROM authors WHERE id = ?",
|
||||
100
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(found.id, 100);
|
||||
assert_eq!(found.name, "Test Name");
|
||||
assert_eq!(found.biography_id, Some(1));
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_sql_generation_with_defaultable_none(pool: SqlitePool) {
|
||||
let author_default = TestAuthorDefault {
|
||||
id: None,
|
||||
name: "Auto ID Test".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let created = author_default.create(&pool).await.unwrap();
|
||||
|
||||
assert!(created.id > 0);
|
||||
assert_eq!(created.name, "Auto ID Test");
|
||||
assert_eq!(created.biography_id, None);
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_placeholder_ordering_consistency(pool: SqlitePool) {
|
||||
let record2 = MultiDefaultableDefault {
|
||||
id: Some(201),
|
||||
name: Some("Full Record".to_string()),
|
||||
biography_id: Some(1),
|
||||
};
|
||||
|
||||
let record3 = MultiDefaultableDefault {
|
||||
id: None,
|
||||
name: Some("Mixed Record".to_string()),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let created2 = record2.create(&pool).await.unwrap();
|
||||
assert_eq!(created2.id, 201);
|
||||
assert_eq!(created2.name, "Full Record");
|
||||
assert_eq!(created2.biography_id, Some(1));
|
||||
|
||||
let created3 = record3.create(&pool).await.unwrap();
|
||||
assert!(created3.id > 0);
|
||||
assert_eq!(created3.name, "Mixed Record");
|
||||
assert_eq!(created3.biography_id, None);
|
||||
}
|
||||
|
||||
#[sqlx::test(
|
||||
migrations = "./migrations/sqlite",
|
||||
fixtures(path = "fixtures", scripts("simple_struct"))
|
||||
)]
|
||||
async fn test_returning_clause_functionality(pool: SqlitePool) {
|
||||
let author_default = TestAuthorDefault {
|
||||
id: None,
|
||||
name: "Return Test".to_string(),
|
||||
biography_id: None,
|
||||
};
|
||||
|
||||
let created = author_default.create(&pool).await.unwrap();
|
||||
|
||||
assert!(created.id > 0);
|
||||
assert_eq!(created.name, "Return Test");
|
||||
assert_eq!(created.biography_id, None);
|
||||
|
||||
let verified: TestAuthor = sqlx::query_as!(
|
||||
TestAuthor,
|
||||
"SELECT id, name, biography_id FROM authors WHERE id = ?",
|
||||
created.id
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(verified.id, created.id);
|
||||
assert_eq!(verified.name, created.name);
|
||||
assert_eq!(verified.biography_id, created.biography_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
INSERT INTO biographies (content)
|
||||
VALUES ('Some text'),
|
||||
('Some other text'),
|
||||
('Biography for no one');
|
||||
|
||||
INSERT INTO authors (name, biography_id)
|
||||
VALUES ('J.R.R. Tolkien', 2),
|
||||
('George Orwell', NULL),
|
||||
('Jack London', 1);
|
||||
@@ -0,0 +1,46 @@
|
||||
#![cfg(feature = "sqlite")]
|
||||
|
||||
use georm::Georm;
|
||||
|
||||
#[derive(Debug, Georm, PartialEq, Eq, Default)]
|
||||
#[georm(
|
||||
table = "biographies",
|
||||
one_to_one = [{
|
||||
name = "author", remote_id = "biography_id", table = "authors", entity = Author
|
||||
}]
|
||||
)]
|
||||
pub struct Biography {
|
||||
#[georm(id)]
|
||||
pub id: i64,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Georm, PartialEq, Eq, Default)]
|
||||
#[georm(table = "authors")]
|
||||
pub struct Author {
|
||||
#[georm(id)]
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
#[georm(relation = {entity = Biography, table = "biographies", name = "biography", nullable = true})]
|
||||
pub biography_id: Option<i64>,
|
||||
}
|
||||
|
||||
impl PartialOrd for Author {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.id.cmp(&other.id))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Author {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.id.cmp(&other.id)
|
||||
}
|
||||
}
|
||||
|
||||
// UserRole (composite key, chrono::DateTime<Utc> column) is deliberately not
|
||||
// ported here yet: SQLite's compile-time query macros infer TEXT columns as
|
||||
// `String`, not `chrono::DateTime<Utc>` — unlike Postgres's TIMESTAMPTZ, which
|
||||
// maps directly. Fixing this needs per-column `query_as!` type overrides
|
||||
// (`"assigned_at as \"assigned_at: DateTime<Utc>\""`) threaded through the
|
||||
// dialect's generated queries, which is follow-up work, not part of this
|
||||
// first SQLite slice. See tests/sqlite/composite_key.rs (not yet added).
|
||||
@@ -0,0 +1,159 @@
|
||||
#![cfg(feature = "sqlite")]
|
||||
|
||||
use georm::Georm;
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
use models::Author;
|
||||
mod models;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite", fixtures("simple_struct"))]
|
||||
async fn find_all_query_works(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let result = Author::find_all(&pool).await?;
|
||||
assert_eq!(3, result.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite")]
|
||||
async fn find_all_returns_empty_vec_on_empty_table(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let result = Author::find_all(&pool).await?;
|
||||
assert_eq!(0, result.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite", fixtures("simple_struct"))]
|
||||
async fn find_query_works(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let id = 1;
|
||||
let res = Author::find(&pool, &id).await?;
|
||||
assert!(res.is_some());
|
||||
let res = res.unwrap();
|
||||
assert_eq!(String::from("J.R.R. Tolkien"), res.name);
|
||||
assert_eq!(1, res.id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite")]
|
||||
async fn find_returns_none_if_not_found(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let res = Author::find(&pool, &420).await?;
|
||||
assert!(res.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite")]
|
||||
async fn create_works(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let author = Author {
|
||||
id: 1,
|
||||
name: "J.R.R. Tolkien".into(),
|
||||
..Default::default()
|
||||
};
|
||||
author.create(&pool).await?;
|
||||
let all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(1, all_authors.len());
|
||||
assert_eq!(vec![author], all_authors);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite", fixtures("simple_struct"))]
|
||||
async fn create_fails_if_already_exists(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let author = Author {
|
||||
id: 2,
|
||||
name: "Miura Kentaro".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = author.create(&pool).await;
|
||||
assert!(result.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite", fixtures("simple_struct"))]
|
||||
async fn update_works(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let expected_initial = Author {
|
||||
name: "J.R.R. Tolkien".into(),
|
||||
id: 1,
|
||||
biography_id: Some(2),
|
||||
};
|
||||
let expected_final = Author {
|
||||
name: "Jolkien Rolkien Rolkien Tolkien".into(),
|
||||
id: 1,
|
||||
biography_id: Some(2),
|
||||
};
|
||||
let tolkien = Author::find(&pool, &1).await?;
|
||||
assert!(tolkien.is_some());
|
||||
let mut tolkien = tolkien.unwrap();
|
||||
assert_eq!(expected_initial, tolkien);
|
||||
tolkien.name = expected_final.name.clone();
|
||||
let updated = tolkien.update(&pool).await?;
|
||||
assert_eq!(expected_final, updated);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite")]
|
||||
async fn update_fails_if_not_already_exists(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let author = Author {
|
||||
id: 2,
|
||||
name: "Miura Kentaro".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = author.update(&pool).await;
|
||||
assert!(result.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite")]
|
||||
async fn should_create_if_does_not_exist(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(0, all_authors.len());
|
||||
let author = Author {
|
||||
id: 4,
|
||||
name: "Miura Kentaro".into(),
|
||||
..Default::default()
|
||||
};
|
||||
author.upsert(&pool).await?;
|
||||
let all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(1, all_authors.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite", fixtures("simple_struct"))]
|
||||
async fn should_update_if_exist(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(3, all_authors.len());
|
||||
let author = Author {
|
||||
id: 2,
|
||||
name: "Miura Kentaro".into(),
|
||||
..Default::default()
|
||||
};
|
||||
author.upsert(&pool).await?;
|
||||
let mut all_authors = Author::find_all(&pool).await?;
|
||||
all_authors.sort();
|
||||
assert_eq!(3, all_authors.len());
|
||||
assert_eq!(author, all_authors[1]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite", fixtures("simple_struct"))]
|
||||
async fn delete_by_id_should_delete_only_one_entry(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let id = 2;
|
||||
let all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(3, all_authors.len());
|
||||
assert!(all_authors.iter().any(|author| author.get_id() == id));
|
||||
let result = Author::delete_by_id(&pool, &id).await?;
|
||||
assert_eq!(1, result);
|
||||
let all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(2, all_authors.len());
|
||||
assert!(all_authors.iter().all(|author| author.get_id() != id));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations/sqlite", fixtures("simple_struct"))]
|
||||
async fn delete_should_delete_current_entity_from_db(pool: sqlx::SqlitePool) -> sqlx::Result<()> {
|
||||
let mut all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(3, all_authors.len());
|
||||
all_authors.shuffle(&mut rand::rng());
|
||||
let author = all_authors.first().unwrap();
|
||||
let result = author.delete(&pool).await?;
|
||||
assert_eq!(1, result);
|
||||
let all_authors = Author::find_all(&pool).await?;
|
||||
assert_eq!(2, all_authors.len());
|
||||
assert!(all_authors.iter().all(|a| a.get_id() != author.get_id()));
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user