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:
Claude
2026-07-21 19:06:35 +00:00
parent 0d43a3fe13
commit 4c314c2f0b
31 changed files with 802 additions and 35 deletions
+329
View File
@@ -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);
}
}
}
+9
View File
@@ -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);
+46
View File
@@ -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).
+159
View File
@@ -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(())
}