M12b: category contract v2 on the server (schema 2, fourteen defaults, finer import mapping)
- migrations/0002_categories_v2.sql, byte-identical to contracts/schema/migrations/0002_categories_v2.sql (SPEC §14.1.1), with an identity test; SCHEMA_VERSION = 2 (E-1 reports it, the importer's check follows). - Seed test on a fresh database (the fourteen rows of AC-7.2, server_version 11 to 14) and an upgrade test of a v1 database in use (0001 applied through the migrator, then users, a custom, a renamed and an archived default, an account, a recurring template, expenses): every earlier row unchanged, the four rows above the old sequence, foreign_key_check empty, schema_version 2, a pull from the old cursor returns exactly the four rows. - DefaultCategoryKey with the fourteen keys (wire enum and contracts/openapi.yaml); icons 33 and colours 14 (§9.7) in validation. - The two category examples M12a held back (E-26 response-default, sync/pull-page-categories-v2) and its contracts-check patch for them and the enum. - Importer: splitwise_categories.csv per the §10.8 v0.8 table (D-053), DEFAULT_KEYS of fourteen, synthetic fixtures for the finer mapping (Insurance/Försäkringar to insurance among them), a schema-1 refusal test. - Test harnesses seed users at server_version 15/16 (after the fourteen seeds); pull counts 10 -> 14. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TQd3pEP9UeN2uifbHknQ7B
This commit is contained in:
@@ -171,7 +171,7 @@ impl TestApp {
|
||||
/// Only the admin (Jacob) with one device: the household is incomplete.
|
||||
pub async fn admin_only() -> Self {
|
||||
let app = Self::empty().await;
|
||||
app.insert_user(ADMIN_ID, "admin", "Jacob", 11).await;
|
||||
app.insert_user(ADMIN_ID, "admin", "Jacob", 15).await;
|
||||
app.insert_device(
|
||||
ADMIN_DEVICE_ID,
|
||||
ADMIN_ID,
|
||||
@@ -186,7 +186,7 @@ impl TestApp {
|
||||
/// Admin Jacob and member Anna, one device each, plus a revoked old device of the admin.
|
||||
pub async fn household() -> Self {
|
||||
let app = Self::admin_only().await;
|
||||
app.insert_user(MEMBER_ID, "member", "Anna", 12).await;
|
||||
app.insert_user(MEMBER_ID, "member", "Anna", 16).await;
|
||||
app.insert_device(
|
||||
MEMBER_DEVICE_ID,
|
||||
MEMBER_ID,
|
||||
|
||||
@@ -186,7 +186,7 @@ async fn e3_invalid_request_and_validation_failed() {
|
||||
async fn e3_household_full_when_two_users_exist() {
|
||||
let app = TestApp::admin_only().await;
|
||||
let code = new_invite(&app, InviteKind::Partner, None).await;
|
||||
app.insert_user(MEMBER_ID, "member", "Anna", 12).await;
|
||||
app.insert_user(MEMBER_ID, "member", "Anna", 16).await;
|
||||
let reply = accept(&app, accept_body(&code, Some("Bertil"))).await;
|
||||
assert_error(&reply, 409, "household_full");
|
||||
}
|
||||
|
||||
@@ -19,11 +19,16 @@ async fn e7_returns_user_device_household_and_public_url() {
|
||||
.insert("x-kvitt-app-version", "41".parse().unwrap());
|
||||
let reply = app.send(request).await;
|
||||
assert_eq!(reply.status, 200);
|
||||
// `server_version` is volatile here: the example's users have 11 and 12 (schema 1, after ten seeded
|
||||
// categories); since migration 0002 seeds fourteen, the harness's users have 15 and 16 (SPEC §14.1.1).
|
||||
assert_like_example(
|
||||
&reply.json,
|
||||
"E-7-me/response.json",
|
||||
&["created_at", "updated_at", "last_seen_at"],
|
||||
&["created_at", "updated_at", "last_seen_at", "server_version"],
|
||||
);
|
||||
assert_eq!(reply.json["user"]["server_version"], 15);
|
||||
assert_eq!(reply.json["household"][0]["server_version"], 15);
|
||||
assert_eq!(reply.json["household"][1]["server_version"], 16);
|
||||
assert_eq!(reply.json["device"]["id"], ADMIN_DEVICE_ID);
|
||||
assert_eq!(reply.json["device"]["is_current"], true);
|
||||
let member = app.call(Method::GET, "/me", &member_token(), None).await;
|
||||
|
||||
@@ -1,15 +1,48 @@
|
||||
//! `0001_init.sql` is the contract schema byte for byte (SPEC §14.1), and connections carry the §8.9 pragmas.
|
||||
//! The migrations are the contract texts byte for byte (`0001_init.sql` = `server-v1.sql`, SPEC §14.1;
|
||||
//! `0002_categories_v2.sql` = `contracts/schema/migrations/0002_categories_v2.sql`, §14.1.1), connections carry the
|
||||
//! §8.9 pragmas, a fresh database holds the fourteen defaults of AC-7.2, and a v1 database in use upgrades to schema
|
||||
//! 2 without losing or changing a row.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use axum::http::{Method, StatusCode};
|
||||
use kvitt_server::db;
|
||||
use sqlx::{AssertSqlSafe, SqlitePool};
|
||||
|
||||
use crate::support::TestApp;
|
||||
use crate::support::{ADMIN_ID, MEMBER_ID, TestApp, admin_token, authed};
|
||||
|
||||
fn manifest(path: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(path)
|
||||
}
|
||||
|
||||
/// The fourteen default categories of AC-7.2 and §14.1.1: id suffix, key, icon, colour, sort order, created_at and
|
||||
/// the `server_version` on a fresh database (the ten v1 seeds 1 to 10, then migration 0002's rows 11 to 14).
|
||||
const DEFAULTS: [(&str, &str, &str, &str, i64, &str, i64); 14] = [
|
||||
("001", "groceries", "shopping_cart", "green", 10, V1_AT, 1),
|
||||
("002", "restaurants", "restaurant", "orange", 20, V1_AT, 2),
|
||||
("011", "housing", "key", "indigo", 25, V2_AT, 11),
|
||||
("003", "home", "home", "brown", 30, V1_AT, 3),
|
||||
("004", "utilities", "bolt", "yellow", 40, V1_AT, 4),
|
||||
("012", "insurance", "shield", "slate", 45, V2_AT, 12),
|
||||
("005", "transport", "directions_car", "blue", 50, V1_AT, 5),
|
||||
("006", "travel", "flight", "teal", 60, V1_AT, 6),
|
||||
("007", "entertainment", "movie", "purple", 70, V1_AT, 7),
|
||||
("008", "health", "medical_services", "red", 80, V1_AT, 8),
|
||||
("013", "children", "child_care", "lime", 85, V2_AT, 13),
|
||||
("009", "shopping", "shopping_bag", "pink", 90, V1_AT, 9),
|
||||
("014", "fees", "account_balance", "amber", 95, V2_AT, 14),
|
||||
("00a", "other", "category", "grey", 100, V1_AT, 10),
|
||||
];
|
||||
const V1_AT: &str = "2026-10-17T00:00:00.000Z";
|
||||
const V2_AT: &str = "2026-10-18T00:00:00.000Z";
|
||||
const ID_PREFIX: &str = "01920000-0000-7000-8000-000000000";
|
||||
const NEW_IDS: [&str; 4] = [
|
||||
"01920000-0000-7000-8000-000000000011",
|
||||
"01920000-0000-7000-8000-000000000012",
|
||||
"01920000-0000-7000-8000-000000000013",
|
||||
"01920000-0000-7000-8000-000000000014",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn migration_0001_is_byte_identical_to_contract_schema() {
|
||||
let migration = std::fs::read(manifest("migrations/0001_init.sql")).unwrap();
|
||||
@@ -21,13 +54,371 @@ fn migration_0001_is_byte_identical_to_contract_schema() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_embedded_migrator_holds_exactly_that_migration() {
|
||||
let contract =
|
||||
std::fs::read_to_string(manifest("../../../contracts/schema/server-v1.sql")).unwrap();
|
||||
fn migration_0002_is_byte_identical_to_contract_migration() {
|
||||
let migration = std::fs::read(manifest("migrations/0002_categories_v2.sql")).unwrap();
|
||||
let contract = std::fs::read(manifest(
|
||||
"../../../contracts/schema/migrations/0002_categories_v2.sql",
|
||||
))
|
||||
.unwrap();
|
||||
assert!(
|
||||
migration == contract,
|
||||
"migrations/0002_categories_v2.sql differs from contracts/schema/migrations/0002_categories_v2.sql"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_embedded_migrator_holds_exactly_those_migrations() {
|
||||
let v1 = std::fs::read_to_string(manifest("../../../contracts/schema/server-v1.sql")).unwrap();
|
||||
let v2 = std::fs::read_to_string(manifest(
|
||||
"../../../contracts/schema/migrations/0002_categories_v2.sql",
|
||||
))
|
||||
.unwrap();
|
||||
let migrations: Vec<_> = db::MIGRATOR.iter().collect();
|
||||
assert_eq!(migrations.len(), 1);
|
||||
assert_eq!(migrations.len(), 2);
|
||||
assert_eq!(migrations[0].version, 1);
|
||||
assert_eq!(migrations[0].sql.as_ref(), contract.as_str());
|
||||
assert_eq!(migrations[0].sql.as_ref(), v1.as_str());
|
||||
assert_eq!(migrations[1].version, 2);
|
||||
assert_eq!(migrations[1].sql.as_ref(), v2.as_str());
|
||||
// sqlx wraps each migration in one transaction unless it opts out (SPEC §14.1.1 relies on it).
|
||||
assert!(migrations.iter().all(|m| !m.no_tx));
|
||||
assert_eq!(db::SCHEMA_VERSION, 2);
|
||||
}
|
||||
|
||||
/// Every row of `table` in a stable order, each rendered with SQLite's `quote()` per column (type-exact).
|
||||
async fn dump(pool: &SqlitePool, table: &str, filter: &str) -> Vec<String> {
|
||||
let columns: Vec<String> =
|
||||
sqlx::query_scalar("SELECT name FROM pragma_table_info(?) ORDER BY cid")
|
||||
.bind(table)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!columns.is_empty(), "{table} has no columns");
|
||||
let row = columns
|
||||
.iter()
|
||||
.map(|c| format!("quote({c})"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" || '|' || ");
|
||||
let order = columns.join(", ");
|
||||
sqlx::query_scalar(AssertSqlSafe(format!(
|
||||
"SELECT {row} FROM {table} {filter} ORDER BY {order}"
|
||||
)))
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn user_tables(pool: &SqlitePool) -> Vec<String> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' \
|
||||
AND name <> '_sqlx_migrations' ORDER BY name",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn scalar_i64(pool: &SqlitePool, sql: &'static str) -> i64 {
|
||||
sqlx::query_scalar(sql).fetch_one(pool).await.unwrap()
|
||||
}
|
||||
|
||||
async fn foreign_key_violations(pool: &SqlitePool) -> usize {
|
||||
sqlx::query("PRAGMA foreign_key_check")
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.len()
|
||||
}
|
||||
|
||||
type CategoryRow = (
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
String,
|
||||
String,
|
||||
i64,
|
||||
String,
|
||||
String,
|
||||
Option<String>,
|
||||
Option<String>,
|
||||
i64,
|
||||
);
|
||||
|
||||
async fn categories(pool: &SqlitePool, filter: &str) -> Vec<CategoryRow> {
|
||||
sqlx::query_as(AssertSqlSafe(format!(
|
||||
"SELECT id, default_key, name, icon, color, sort_order, created_at, updated_at, archived_at, deleted_at, \
|
||||
server_version FROM categories {filter} ORDER BY sort_order, id"
|
||||
)))
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_fresh_database_holds_exactly_the_fourteen_defaults() {
|
||||
let app = TestApp::empty().await;
|
||||
let pool = &app.state.db;
|
||||
let rows = categories(pool, "").await;
|
||||
let expected: Vec<CategoryRow> = DEFAULTS
|
||||
.iter()
|
||||
.map(|&(suffix, key, icon, color, sort, at, version)| {
|
||||
(
|
||||
format!("{ID_PREFIX}{suffix}"),
|
||||
Some(key.to_owned()),
|
||||
None,
|
||||
icon.to_owned(),
|
||||
color.to_owned(),
|
||||
sort,
|
||||
at.to_owned(),
|
||||
at.to_owned(),
|
||||
None,
|
||||
None,
|
||||
version,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(rows, expected);
|
||||
assert_eq!(
|
||||
scalar_i64(pool, "SELECT value FROM sync_sequence WHERE id = 1").await,
|
||||
14
|
||||
);
|
||||
assert_eq!(foreign_key_violations(pool).await, 0);
|
||||
// The rebuilt table keeps the v1 constraints and accepts exactly the fourteen keys.
|
||||
let insert = |key: &'static str, version: i64| {
|
||||
sqlx::query(
|
||||
"INSERT INTO categories (id, default_key, name, icon, color, sort_order, created_at, updated_at, \
|
||||
server_version) VALUES (?, ?, NULL, 'home', 'grey', 1, ?, ?, ?)",
|
||||
)
|
||||
.bind(format!("0192f000-0000-7000-8000-{version:012}"))
|
||||
.bind(key)
|
||||
.bind(V2_AT)
|
||||
.bind(V2_AT)
|
||||
.bind(version)
|
||||
.execute(pool)
|
||||
};
|
||||
assert!(insert("pets", 100).await.is_err(), "unknown key rejected");
|
||||
assert!(
|
||||
insert("fees", 101).await.is_err(),
|
||||
"default_key stays unique"
|
||||
);
|
||||
let nameless_custom = sqlx::query(
|
||||
"INSERT INTO categories (id, default_key, name, icon, color, sort_order, created_at, updated_at, \
|
||||
server_version) VALUES ('0192f000-0000-7000-8000-000000000102', NULL, NULL, 'home', 'grey', 1, ?, ?, 102)",
|
||||
)
|
||||
.bind(V2_AT)
|
||||
.bind(V2_AT)
|
||||
.execute(pool)
|
||||
.await;
|
||||
assert!(nameless_custom.is_err(), "a custom category needs a name");
|
||||
}
|
||||
|
||||
/// A v1 database in use: the household, a custom category, a renamed and an archived default, an account, a
|
||||
/// recurring template and expenses referencing default and custom categories. Rows take versions 15 to 23 and the
|
||||
/// sequence ends at 23.
|
||||
async fn fill_v1(app: &TestApp) {
|
||||
let pool = &app.state.db;
|
||||
app.seed_household().await;
|
||||
let statements = [
|
||||
"INSERT INTO categories (id, default_key, name, icon, color, sort_order, created_at, updated_at, \
|
||||
archived_at, deleted_at, server_version) VALUES ('0192c000-0000-7000-8000-000000000001', NULL, 'Hemförsäkring', \
|
||||
'pets', 'lime', 110, '2026-10-17T09:00:00.000Z', '2026-10-17T09:00:00.000Z', NULL, NULL, 17)",
|
||||
"UPDATE categories SET name = 'Mat', updated_at = '2026-10-17T09:01:00.000Z', server_version = 18 \
|
||||
WHERE default_key = 'groceries'",
|
||||
"UPDATE categories SET archived_at = '2026-10-17T09:02:00.000Z', updated_at = '2026-10-17T09:02:00.000Z', \
|
||||
server_version = 19 WHERE default_key = 'other'",
|
||||
"INSERT INTO accounts (id, name, name_key, created_by_user_id, created_at, updated_at, server_version) \
|
||||
VALUES ('0192b000-0000-7000-8000-000000000001', 'Vardag', 'vardag', '0192a000-0000-7000-8000-000000000001', \
|
||||
'2026-10-17T09:03:00.000Z', '2026-10-17T09:03:00.000Z', 20)",
|
||||
"INSERT INTO account_default_shares (account_id, user_id, share_bp) VALUES \
|
||||
('0192b000-0000-7000-8000-000000000001', '0192a000-0000-7000-8000-000000000001', 5000), \
|
||||
('0192b000-0000-7000-8000-000000000001', '0192a000-0000-7000-8000-000000000002', 5000)",
|
||||
"INSERT INTO recurring_templates (id, account_id, category_id, amount_ore, description, notes, payer_user_id, \
|
||||
split_mode, day_of_month, start_period, end_period, paused, last_generated_period, created_by_user_id, \
|
||||
updated_by_user_id, created_at, updated_at, deleted_at, server_version) VALUES \
|
||||
('0192d000-0000-7000-8000-000000000001', '0192b000-0000-7000-8000-000000000001', \
|
||||
'01920000-0000-7000-8000-000000000003', 1250000, 'Hyra', '', '0192a000-0000-7000-8000-000000000001', \
|
||||
'default', 25, '2026-10', NULL, 0, '2026-10', '0192a000-0000-7000-8000-000000000001', \
|
||||
'0192a000-0000-7000-8000-000000000001', '2026-10-17T09:04:00.000Z', '2026-10-17T09:04:00.000Z', NULL, 21)",
|
||||
"INSERT INTO expenses (id, account_id, category_id, amount_ore, description, notes, expense_date, \
|
||||
payer_user_id, split_mode, recurring_template_id, recurring_period, import_key, created_by_user_id, \
|
||||
updated_by_user_id, updated_by_device_id, created_at, updated_at, deleted_at, server_received_at, \
|
||||
server_version) VALUES ('0192e000-0000-7000-8000-000000000001', '0192b000-0000-7000-8000-000000000001', \
|
||||
'01920000-0000-7000-8000-000000000003', 1250000, 'Hyra', '', '2026-10-25', \
|
||||
'0192a000-0000-7000-8000-000000000001', 'default', '0192d000-0000-7000-8000-000000000001', '2026-10', NULL, \
|
||||
'0192a000-0000-7000-8000-000000000001', '0192a000-0000-7000-8000-000000000001', NULL, \
|
||||
'2026-10-17T09:05:00.000Z', '2026-10-17T09:05:00.000Z', NULL, '2026-10-17T09:05:00.000Z', 22)",
|
||||
"INSERT INTO expenses (id, account_id, category_id, amount_ore, description, notes, expense_date, \
|
||||
payer_user_id, split_mode, recurring_template_id, recurring_period, import_key, created_by_user_id, \
|
||||
updated_by_user_id, updated_by_device_id, created_at, updated_at, deleted_at, server_received_at, \
|
||||
server_version) VALUES ('0192e000-0000-7000-8000-000000000002', '0192b000-0000-7000-8000-000000000001', \
|
||||
'0192c000-0000-7000-8000-000000000001', 34900, 'Försäkring', 'Kvartal', '2026-10-16', \
|
||||
'0192a000-0000-7000-8000-000000000002', 'full', NULL, NULL, NULL, \
|
||||
'0192a000-0000-7000-8000-000000000002', '0192a000-0000-7000-8000-000000000002', NULL, \
|
||||
'2026-10-17T09:06:00.000Z', '2026-10-17T09:06:00.000Z', NULL, '2026-10-17T09:06:00.000Z', 23)",
|
||||
"INSERT INTO expense_splits (expense_id, user_id, share_ore, share_bp) VALUES \
|
||||
('0192e000-0000-7000-8000-000000000001', '0192a000-0000-7000-8000-000000000001', 625000, 5000), \
|
||||
('0192e000-0000-7000-8000-000000000001', '0192a000-0000-7000-8000-000000000002', 625000, 5000), \
|
||||
('0192e000-0000-7000-8000-000000000002', '0192a000-0000-7000-8000-000000000001', 0, NULL), \
|
||||
('0192e000-0000-7000-8000-000000000002', '0192a000-0000-7000-8000-000000000002', 34900, NULL)",
|
||||
"UPDATE sync_sequence SET value = 23 WHERE id = 1",
|
||||
];
|
||||
for sql in statements {
|
||||
sqlx::query(sql)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("{e}: {sql}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_v1_database_in_use_upgrades_to_schema_2_keeping_every_row() {
|
||||
let app = TestApp::at_v1().await;
|
||||
let pool = &app.state.db;
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, String>("SELECT value FROM meta WHERE key = 'schema_version'")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
"1"
|
||||
);
|
||||
assert_eq!(
|
||||
scalar_i64(pool, "SELECT COUNT(*) FROM categories").await,
|
||||
10
|
||||
);
|
||||
fill_v1(&app).await;
|
||||
let old_sequence = scalar_i64(pool, "SELECT value FROM sync_sequence WHERE id = 1").await;
|
||||
assert_eq!(old_sequence, 23);
|
||||
let epoch: String = sqlx::query_scalar("SELECT value FROM meta WHERE key = 'sync_epoch'")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let tables = user_tables(pool).await;
|
||||
let mut before = Vec::new();
|
||||
for table in &tables {
|
||||
if table != "meta" && table != "sync_sequence" {
|
||||
before.push((table.clone(), dump(pool, table, "").await));
|
||||
}
|
||||
}
|
||||
|
||||
db::migrate(pool).await.unwrap();
|
||||
|
||||
// The connection that ran the migration had foreign keys on (SPEC §8.9), and nothing dangles afterwards.
|
||||
let mut conn = pool.acquire().await.unwrap();
|
||||
let fk: i64 = sqlx::query_scalar("PRAGMA foreign_keys")
|
||||
.fetch_one(&mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fk, 1);
|
||||
drop(conn);
|
||||
assert_eq!(foreign_key_violations(pool).await, 0);
|
||||
assert_eq!(
|
||||
user_tables(pool).await,
|
||||
tables,
|
||||
"no table added or left behind"
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, String>("SELECT value FROM meta WHERE key = 'schema_version'")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, String>("SELECT value FROM meta WHERE key = 'sync_epoch'")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
epoch
|
||||
);
|
||||
assert_eq!(
|
||||
scalar_i64(pool, "SELECT value FROM sync_sequence WHERE id = 1").await,
|
||||
old_sequence + 4
|
||||
);
|
||||
|
||||
// Every earlier row, categories included, is unchanged.
|
||||
let old_only = format!("WHERE id NOT IN ('{}')", NEW_IDS.join("', '"));
|
||||
for (table, rows) in &before {
|
||||
let filter = if table == "categories" {
|
||||
old_only.as_str()
|
||||
} else {
|
||||
""
|
||||
};
|
||||
assert_eq!(&dump(pool, table, filter).await, rows, "{table} changed");
|
||||
}
|
||||
|
||||
// The four new rows, versions after the old sequence value.
|
||||
let new_rows = categories(pool, &format!("WHERE id IN ('{}')", NEW_IDS.join("', '"))).await;
|
||||
let expected: Vec<CategoryRow> = DEFAULTS
|
||||
.iter()
|
||||
.filter(|d| d.5 == V2_AT)
|
||||
.zip(1..)
|
||||
.map(|(&(suffix, key, icon, color, sort, at, _), n)| {
|
||||
(
|
||||
format!("{ID_PREFIX}{suffix}"),
|
||||
Some(key.to_owned()),
|
||||
None,
|
||||
icon.to_owned(),
|
||||
color.to_owned(),
|
||||
sort,
|
||||
at.to_owned(),
|
||||
at.to_owned(),
|
||||
None,
|
||||
None,
|
||||
old_sequence + n,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(new_rows, expected);
|
||||
assert_eq!(
|
||||
scalar_i64(pool, "SELECT COUNT(*) FROM categories").await,
|
||||
15
|
||||
);
|
||||
|
||||
// A phone at the old cursor pulls exactly the four new categories.
|
||||
let reply = app
|
||||
.send(authed(
|
||||
Method::GET,
|
||||
&format!("/sync?since={old_sequence}"),
|
||||
&admin_token(),
|
||||
))
|
||||
.await;
|
||||
assert_eq!(reply.status, StatusCode::OK);
|
||||
let page = &reply.json;
|
||||
assert_eq!(page["since"], old_sequence);
|
||||
assert_eq!(page["next_since"], old_sequence + 4);
|
||||
assert_eq!(page["has_more"], false);
|
||||
let ids: Vec<&str> = page["categories"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| c["id"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(ids, NEW_IDS);
|
||||
for array in [
|
||||
"users",
|
||||
"accounts",
|
||||
"recurring_templates",
|
||||
"expenses",
|
||||
"settlements",
|
||||
"audit_entries",
|
||||
] {
|
||||
assert_eq!(page[array], serde_json::json!([]), "{array}");
|
||||
}
|
||||
assert_eq!(page["categories"][1]["default_key"], "insurance");
|
||||
assert_eq!(page["categories"][1]["color"], "slate");
|
||||
// The users the seeding referenced are still the household.
|
||||
let users: Vec<String> = sqlx::query_scalar("SELECT id FROM users ORDER BY id")
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(users, [ADMIN_ID, MEMBER_ID]);
|
||||
|
||||
// A second run is a no-op.
|
||||
db::migrate(pool).await.unwrap();
|
||||
assert_eq!(
|
||||
scalar_i64(pool, "SELECT COUNT(*) FROM categories").await,
|
||||
15
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -48,7 +439,7 @@ async fn migrated_database_has_schema_version_seed_rows_and_pragmas() {
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(categories, 10);
|
||||
assert_eq!(categories, 14);
|
||||
|
||||
let mut conn = pool.acquire().await.unwrap();
|
||||
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
|
||||
@@ -83,14 +474,14 @@ async fn migrating_twice_is_a_no_op() {
|
||||
async fn server_version_sequence_starts_after_the_seed_and_increments() {
|
||||
let app = TestApp::empty().await;
|
||||
let mut tx = db::begin_immediate(&app.state.db).await.unwrap();
|
||||
assert_eq!(db::next_server_version(&mut tx).await.unwrap(), 11);
|
||||
assert_eq!(db::next_server_version(&mut tx).await.unwrap(), 12);
|
||||
assert_eq!(db::next_server_version(&mut tx).await.unwrap(), 15);
|
||||
assert_eq!(db::next_server_version(&mut tx).await.unwrap(), 16);
|
||||
tx.commit().await.unwrap();
|
||||
let mut conn = app.state.db.acquire().await.unwrap();
|
||||
assert_eq!(
|
||||
db::sequence::current_server_version(&mut conn)
|
||||
.await
|
||||
.unwrap(),
|
||||
12
|
||||
16
|
||||
);
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ async fn health_reports_ok_with_versions() {
|
||||
assert_eq!(reply.status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
reply.json,
|
||||
json!({"status": "ok", "server_version": env!("CARGO_PKG_VERSION"), "schema_version": 1, "db_ok": true})
|
||||
json!({"status": "ok", "server_version": env!("CARGO_PKG_VERSION"), "schema_version": 2, "db_ok": true})
|
||||
);
|
||||
assert_eq!(
|
||||
reply.headers["x-kvitt-server-version"],
|
||||
@@ -124,7 +124,7 @@ async fn health_is_503_degraded_when_the_database_is_gone() {
|
||||
assert_eq!(reply.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(reply.json["status"], "degraded");
|
||||
assert_eq!(reply.json["db_ok"], false);
|
||||
assert_eq!(reply.json["schema_version"], 1);
|
||||
assert_eq!(reply.json["schema_version"], 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -62,13 +62,26 @@ pub struct TestApp {
|
||||
impl TestApp {
|
||||
/// A migrated, empty database (no users).
|
||||
pub async fn empty() -> Self {
|
||||
Self::migrated_to(None).await
|
||||
}
|
||||
|
||||
/// An empty database at schema version 1: only `0001_init.sql` applied, through the server's own migrator, so a
|
||||
/// later `db::migrate` upgrades it the way a deployed v1 database is upgraded.
|
||||
pub async fn at_v1() -> Self {
|
||||
Self::migrated_to(Some(1)).await
|
||||
}
|
||||
|
||||
async fn migrated_to(target: Option<i64>) -> Self {
|
||||
let dir = TempDir::new();
|
||||
let config = Config::from_lookup(|k| {
|
||||
(k == "KVITT_DATA_DIR").then(|| dir.0.to_string_lossy().into_owned())
|
||||
})
|
||||
.unwrap();
|
||||
let pool = db::connect(&config.database_path()).await.unwrap();
|
||||
db::migrate(&pool).await.unwrap();
|
||||
match target {
|
||||
Some(version) => db::MIGRATOR.run_to(version, &pool).await.unwrap(),
|
||||
None => db::migrate(&pool).await.unwrap(),
|
||||
}
|
||||
let clock = FixedClock::new(parse_ts(NOW).unwrap());
|
||||
let state = AppState::new(config, pool).with_clock(Arc::new(clock.clone()));
|
||||
Self {
|
||||
@@ -81,10 +94,17 @@ impl TestApp {
|
||||
/// Admin and member users, one device each, plus a revoked device of the member.
|
||||
pub async fn household() -> Self {
|
||||
let app = Self::empty().await;
|
||||
let pool = &app.state.db;
|
||||
app.seed_household().await;
|
||||
app
|
||||
}
|
||||
|
||||
/// Inserts the users and devices of [`TestApp::household`] (users at `server_version` 15 and 16, after the
|
||||
/// fourteen seeded categories; the sequence is not advanced).
|
||||
pub async fn seed_household(&self) {
|
||||
let pool = &self.state.db;
|
||||
for (id, role, name, version) in [
|
||||
(ADMIN_ID, "admin", "Jacob", 11),
|
||||
(MEMBER_ID, "member", "Partner", 12),
|
||||
(ADMIN_ID, "admin", "Jacob", 15),
|
||||
(MEMBER_ID, "member", "Partner", 16),
|
||||
] {
|
||||
sqlx::query(
|
||||
"INSERT INTO users (id, role, display_name, picture_version, created_at, updated_at, server_version) \
|
||||
@@ -122,7 +142,6 @@ impl TestApp {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
app
|
||||
}
|
||||
|
||||
pub async fn send(&self, request: Request<Body>) -> Reply {
|
||||
|
||||
@@ -58,6 +58,7 @@ fn check(name: &str, example: &Value) -> bool {
|
||||
"E-24-patch-category/response.json" => Category,
|
||||
"E-25-archive-category/response.json" => Category,
|
||||
"E-26-unarchive-category/response.json" => Category,
|
||||
"E-26-unarchive-category/response-default.json" => Category,
|
||||
"E-27-delete-category/response.json" => Category,
|
||||
"E-28-create-recurring-template/request.json" => CreateRecurringTemplateRequest,
|
||||
"E-28-create-recurring-template/response.json" => RecurringTemplate,
|
||||
@@ -71,6 +72,7 @@ fn check(name: &str, example: &Value) -> bool {
|
||||
"E-33-settlement-proposal/response.json" => ProposalResponse,
|
||||
"sync/pull-empty-page.json" => SyncPullResponse,
|
||||
"sync/pull-page.json" => SyncPullResponse,
|
||||
"sync/pull-page-categories-v2.json" => SyncPullResponse,
|
||||
"sync/push-request.json" => SyncPushRequest,
|
||||
"sync/push-request-delete.json" => SyncPushRequest,
|
||||
"sync/push-request-rejections.json" => SyncPushRequest,
|
||||
|
||||
@@ -89,8 +89,8 @@ async fn the_first_page_has_everything_in_version_order_with_the_epoch_and_serve
|
||||
.iter()
|
||||
.map(|a| page[*a].as_array().unwrap().len())
|
||||
.collect();
|
||||
// 2 users, 10 default categories, 2 accounts, no templates, 1 expense, 1 settlement, 2 audit entries.
|
||||
assert_eq!(counts, [2, 10, 2, 0, 1, 1, 2]);
|
||||
// 2 users, 14 default categories, 2 accounts, no templates, 1 expense, 1 settlement, 2 audit entries.
|
||||
assert_eq!(counts, [2, 14, 2, 0, 1, 1, 2]);
|
||||
for a in ARRAYS {
|
||||
let v: Vec<i64> = page[a]
|
||||
.as_array()
|
||||
@@ -141,7 +141,7 @@ async fn paging_walks_every_row_once_parents_with_children_count_as_one() {
|
||||
for _ in 0..9 {
|
||||
push_one(&app, &admin_token(), exp(expense(&new_id(), T1))).await;
|
||||
}
|
||||
// 2 users + 10 categories + 2 accounts + 9 expenses + 9 audit entries = 32 rows.
|
||||
// 2 users + 14 categories + 2 accounts + 9 expenses + 9 audit entries = 36 rows.
|
||||
let mut since = 0;
|
||||
let mut seen = Vec::new();
|
||||
let mut pages = 0;
|
||||
@@ -160,8 +160,8 @@ async fn paging_walks_every_row_once_parents_with_children_count_as_one() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(pages, 7);
|
||||
assert_eq!(seen.len(), 32);
|
||||
assert_eq!(pages, 8);
|
||||
assert_eq!(seen.len(), 36);
|
||||
let mut dedup = seen.clone();
|
||||
dedup.dedup();
|
||||
assert_eq!(dedup, seen);
|
||||
@@ -170,9 +170,9 @@ async fn paging_walks_every_row_once_parents_with_children_count_as_one() {
|
||||
assert_eq!(reply.json["next_since"], since);
|
||||
assert_eq!(reply.json["has_more"], false);
|
||||
// has_more is false when the page ends exactly on the last row.
|
||||
let reply = pull(&app, &admin_token(), 0, Some(32)).await;
|
||||
let reply = pull(&app, &admin_token(), 0, Some(36)).await;
|
||||
assert_eq!(reply.json["has_more"], false);
|
||||
let reply = pull(&app, &admin_token(), 0, Some(31)).await;
|
||||
let reply = pull(&app, &admin_token(), 0, Some(35)).await;
|
||||
assert_eq!(reply.json["has_more"], true);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user