|
|
@@ -7,7 +7,7 @@ use kuatia_types::*;
|
|
|
use sqlx::{Any, Pool, Row};
|
|
|
|
|
|
async fn new_pool() -> Pool<Any> {
|
|
|
- sqlx::any::install_default_drivers();
|
|
|
+ kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
|
|
|
sqlx::any::AnyPoolOptions::new()
|
|
|
.max_connections(1)
|
|
|
.connect("sqlite::memory:")
|
|
|
@@ -23,9 +23,12 @@ async fn new_store() -> SqlStore {
|
|
|
|
|
|
kuatia_storage::store_tests!(new_store);
|
|
|
|
|
|
-/// The point of the schema: no column holds opaque binary. A content-addressed
|
|
|
-/// id is stored as lower-case hex text, and a structured payload as readable
|
|
|
-/// JSON text, so a row can be audited in a plain SQL client.
|
|
|
+/// The point of the schema: no identifier or payload column holds opaque
|
|
|
+/// binary. A content-addressed id is stored as lower-case hex text, and a
|
|
|
+/// structured payload as readable JSON text, so a row can be audited in a plain
|
|
|
+/// SQL client. Amounts are the one exception, stored natively so the database
|
|
|
+/// can sum and order them (ADR-0024); `kuatia_i128_to_text` is how a client that
|
|
|
+/// registered the money functions reads one back.
|
|
|
#[tokio::test]
|
|
|
async fn columns_store_hex_ids_and_json_text() {
|
|
|
let pool = new_pool().await;
|
|
|
@@ -71,6 +74,15 @@ async fn columns_store_hex_ids_and_json_text() {
|
|
|
serde_json::from_str::<serde_json::Value>(&metadata).is_ok(),
|
|
|
"metadata should be JSON text, got: {metadata}"
|
|
|
);
|
|
|
+
|
|
|
+ // The amount is a 16-byte blob, and still legible through the helper.
|
|
|
+ let row =
|
|
|
+ sqlx::query("SELECT typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings")
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ assert_eq!(row.try_get::<String, _>("t").unwrap(), "blob");
|
|
|
+ assert_eq!(row.try_get::<String, _>("v").unwrap(), "100");
|
|
|
}
|
|
|
|
|
|
/// The 002 migration adds the subaccount column and a subaccount account/posting
|
|
|
@@ -241,6 +253,7 @@ async fn migration_004_backfills_index_tables() {
|
|
|
"008_live_postings",
|
|
|
"009_saga_kind",
|
|
|
"010_drop_sagas",
|
|
|
+ "011_native_amounts",
|
|
|
] {
|
|
|
sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
|
|
|
.bind(m)
|
|
|
@@ -317,8 +330,8 @@ async fn migration_005_backfills_account_head() {
|
|
|
}
|
|
|
|
|
|
// Record every migration except 005 as applied so migrate() runs only 005.
|
|
|
- // 008 is pinned as applied so it does not run against a DB whose 004 index
|
|
|
- // tables were never created.
|
|
|
+ // 008 and 011 are pinned as applied so they do not run against a DB whose
|
|
|
+ // 004 index tables were never created.
|
|
|
sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
|
|
|
.execute(&pool)
|
|
|
.await
|
|
|
@@ -333,6 +346,7 @@ async fn migration_005_backfills_account_head() {
|
|
|
"008_live_postings",
|
|
|
"009_saga_kind",
|
|
|
"010_drop_sagas",
|
|
|
+ "011_native_amounts",
|
|
|
] {
|
|
|
sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
|
|
|
.bind(m)
|
|
|
@@ -405,6 +419,7 @@ async fn migration_008_merges_live_postings() {
|
|
|
"007_balance_projection",
|
|
|
"009_saga_kind",
|
|
|
"010_drop_sagas",
|
|
|
+ "011_native_amounts",
|
|
|
] {
|
|
|
sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
|
|
|
.bind(m)
|
|
|
@@ -454,7 +469,7 @@ async fn migration_008_merges_live_postings() {
|
|
|
/// migrate() is idempotent: running it repeatedly on the same DB is a no-op.
|
|
|
#[tokio::test]
|
|
|
async fn migrate_is_idempotent() {
|
|
|
- sqlx::any::install_default_drivers();
|
|
|
+ kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
|
|
|
let pool = sqlx::any::AnyPoolOptions::new()
|
|
|
.max_connections(1)
|
|
|
.connect("sqlite::memory:")
|
|
|
@@ -519,3 +534,261 @@ async fn id_batch_primitives_chunk_large_batches() {
|
|
|
let after = store.get_posting_states(&ids).await.unwrap();
|
|
|
assert!(after.iter().all(|s| *s == PostingState::Spent));
|
|
|
}
|
|
|
+
|
|
|
+fn encoded(value: i128) -> Vec<u8> {
|
|
|
+ encode_storage_i128(value).to_vec()
|
|
|
+}
|
|
|
+
|
|
|
+fn decoded(bytes: &[u8]) -> i128 {
|
|
|
+ let bytes: [u8; 16] = bytes.try_into().expect("a 16-byte amount");
|
|
|
+ decode_storage_i128(&bytes)
|
|
|
+}
|
|
|
+
|
|
|
+/// The money scalars round-trip the full i128 range, which is what the 011
|
|
|
+/// migration relies on to convert the old text columns.
|
|
|
+#[tokio::test]
|
|
|
+async fn money_scalars_round_trip() {
|
|
|
+ let pool = new_pool().await;
|
|
|
+ for v in [
|
|
|
+ "0",
|
|
|
+ "1",
|
|
|
+ "-1",
|
|
|
+ "170141183460469231731687303715884105727",
|
|
|
+ "-170141183460469231731687303715884105728",
|
|
|
+ ] {
|
|
|
+ let row = sqlx::query("SELECT kuatia_i128_to_text(kuatia_i128_from_text($1)) AS t")
|
|
|
+ .bind(v)
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ assert_eq!(row.try_get::<String, _>("t").unwrap(), v);
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// The aggregate folds mixed signs exactly, and an empty group sums to zero
|
|
|
+/// rather than to SQL NULL, so a caller can decode the result unconditionally.
|
|
|
+#[tokio::test]
|
|
|
+async fn i128_sum_folds_and_handles_empty_group() {
|
|
|
+ let pool = new_pool().await;
|
|
|
+ sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ let values: Vec<i128> = vec![5, -3, 1_000_000_000_000_000_000_000, -7];
|
|
|
+ for v in &values {
|
|
|
+ sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
|
|
|
+ .bind(encoded(*v))
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ }
|
|
|
+
|
|
|
+ let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts")
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ assert_eq!(
|
|
|
+ decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()),
|
|
|
+ values.iter().sum::<i128>()
|
|
|
+ );
|
|
|
+
|
|
|
+ let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts WHERE 1 = 0")
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 0);
|
|
|
+}
|
|
|
+
|
|
|
+/// The aggregate raises rather than wrapping. This is the property that makes
|
|
|
+/// summing in SQL as safe as `Cent::checked_sum`.
|
|
|
+#[tokio::test]
|
|
|
+async fn i128_sum_overflows_loudly() {
|
|
|
+ let pool = new_pool().await;
|
|
|
+ sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ for _ in 0..2 {
|
|
|
+ sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
|
|
|
+ .bind(encoded(i128::MAX))
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ }
|
|
|
+ let err = match sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts")
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ {
|
|
|
+ Ok(_) => panic!("summing past i128::MAX should fail"),
|
|
|
+ Err(e) => e.to_string(),
|
|
|
+ };
|
|
|
+ assert!(err.contains("i128"), "{err}");
|
|
|
+}
|
|
|
+
|
|
|
+/// A value that is not a 16-byte amount fails the statement instead of being
|
|
|
+/// skipped, so a corrupt row can never silently change a balance.
|
|
|
+#[tokio::test]
|
|
|
+async fn i128_sum_rejects_non_amount() {
|
|
|
+ let pool = new_pool().await;
|
|
|
+ let err = match sqlx::query("SELECT kuatia_i128_sum(x) AS s FROM (SELECT 'abc' AS x)")
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ {
|
|
|
+ Ok(_) => panic!("a text argument should fail"),
|
|
|
+ Err(e) => e.to_string(),
|
|
|
+ };
|
|
|
+ assert!(err.contains("16-byte"), "{err}");
|
|
|
+}
|
|
|
+
|
|
|
+/// The storage encoding is order-preserving, so SQLite's byte-wise BLOB
|
|
|
+/// comparison orders amounts numerically. This is what the text columns could
|
|
|
+/// not do (ADR-0011) and the reason the encoding flips the sign bit.
|
|
|
+#[tokio::test]
|
|
|
+async fn blob_order_matches_numeric_order() {
|
|
|
+ let pool = new_pool().await;
|
|
|
+ sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ for v in [7i128, -9, 0, i128::MAX, i128::MIN, -1, 1] {
|
|
|
+ sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
|
|
|
+ .bind(encoded(v))
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ }
|
|
|
+ let ordered: Vec<i128> =
|
|
|
+ sqlx::query("SELECT kuatia_i128_to_text(v) AS t FROM amounts ORDER BY v")
|
|
|
+ .fetch_all(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap()
|
|
|
+ .iter()
|
|
|
+ .map(|r| r.try_get::<String, _>("t").unwrap().parse().unwrap())
|
|
|
+ .collect();
|
|
|
+ let mut expected = ordered.clone();
|
|
|
+ expected.sort();
|
|
|
+ assert_eq!(ordered, expected);
|
|
|
+ assert_eq!(ordered.first(), Some(&i128::MIN));
|
|
|
+ assert_eq!(ordered.last(), Some(&i128::MAX));
|
|
|
+}
|
|
|
+
|
|
|
+/// Amounts are stored at full i128 width, so a value past the i64 backing
|
|
|
+/// round-trips through the store under the `i128` feature.
|
|
|
+#[cfg(feature = "i128")]
|
|
|
+#[tokio::test]
|
|
|
+async fn value_beyond_i64_round_trips() {
|
|
|
+ use std::str::FromStr;
|
|
|
+
|
|
|
+ let store = new_store().await;
|
|
|
+ let value = Cent::from_str("170141183460469231731687303715884105727").unwrap();
|
|
|
+ let posting = Posting::new(
|
|
|
+ PostingId {
|
|
|
+ transfer: EnvelopeId([0x5c; 32]),
|
|
|
+ index: 0,
|
|
|
+ },
|
|
|
+ AccountId::new(1),
|
|
|
+ AssetId::new(1),
|
|
|
+ value,
|
|
|
+ );
|
|
|
+ store
|
|
|
+ .insert_postings(std::slice::from_ref(&posting))
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+
|
|
|
+ let got = store.get_postings(&[posting.id]).await.unwrap();
|
|
|
+ assert_eq!(got[0].value, value);
|
|
|
+ assert_eq!(
|
|
|
+ store
|
|
|
+ .live_balance(&AccountId::new(1), &AssetId::new(1))
|
|
|
+ .await
|
|
|
+ .unwrap(),
|
|
|
+ value
|
|
|
+ );
|
|
|
+}
|
|
|
+
|
|
|
+/// The 011 migration rewrites the existing text amounts into the native blob
|
|
|
+/// encoding, keeping their values (including negatives) and the rest of the row.
|
|
|
+#[tokio::test]
|
|
|
+async fn migration_011_converts_text_amounts() {
|
|
|
+ let pool = new_pool().await;
|
|
|
+
|
|
|
+ // Post-010 shape: money columns are still TEXT.
|
|
|
+ for ddl in [
|
|
|
+ "CREATE TABLE postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (transfer_id, idx))",
|
|
|
+ "CREATE TABLE live_postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value TEXT NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))",
|
|
|
+ "CREATE TABLE balance_projection (id BIGINT NOT NULL, account BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, balance TEXT NOT NULL, watermark BIGINT NOT NULL, PRIMARY KEY (id))",
|
|
|
+ "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
|
|
|
+ "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
|
|
|
+ "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, '100', 77)",
|
|
|
+ "INSERT INTO balance_projection (id, account, subaccount, asset, balance, watermark) VALUES (1, 1, 0, 1, '-150', 5)",
|
|
|
+ ] {
|
|
|
+ sqlx::query(ddl).execute(&pool).await.unwrap();
|
|
|
+ }
|
|
|
+
|
|
|
+ // Record every migration except 011 as applied so migrate() runs only 011.
|
|
|
+ sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ for m in [
|
|
|
+ "001_init",
|
|
|
+ "002_subaccounts",
|
|
|
+ "003_drop_user_data",
|
|
|
+ "004_index_tables",
|
|
|
+ "005_account_head",
|
|
|
+ "006_drop_policy",
|
|
|
+ "007_balance_projection",
|
|
|
+ "008_live_postings",
|
|
|
+ "009_saga_kind",
|
|
|
+ "010_drop_sagas",
|
|
|
+ ] {
|
|
|
+ sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
|
|
|
+ .bind(m)
|
|
|
+ .execute(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ }
|
|
|
+
|
|
|
+ let store = SqlStore::new(pool.clone());
|
|
|
+ store.migrate().await.unwrap();
|
|
|
+
|
|
|
+ let rows = sqlx::query(
|
|
|
+ "SELECT transfer_id, typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings ORDER BY transfer_id",
|
|
|
+ )
|
|
|
+ .fetch_all(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ let got: Vec<(String, String, String)> = rows
|
|
|
+ .iter()
|
|
|
+ .map(|r| {
|
|
|
+ (
|
|
|
+ r.try_get("transfer_id").unwrap(),
|
|
|
+ r.try_get("t").unwrap(),
|
|
|
+ r.try_get("v").unwrap(),
|
|
|
+ )
|
|
|
+ })
|
|
|
+ .collect();
|
|
|
+ assert_eq!(
|
|
|
+ got,
|
|
|
+ vec![
|
|
|
+ ("aa".to_string(), "blob".to_string(), "100".to_string()),
|
|
|
+ ("bb".to_string(), "blob".to_string(), "-250".to_string()),
|
|
|
+ ]
|
|
|
+ );
|
|
|
+
|
|
|
+ // The rest of the row survives, and the summing path reads the new column.
|
|
|
+ let row = sqlx::query("SELECT reservation, kuatia_i128_sum(value) AS s FROM live_postings")
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ assert_eq!(row.try_get::<i64, _>("reservation").unwrap(), 77);
|
|
|
+ assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 100);
|
|
|
+
|
|
|
+ let row =
|
|
|
+ sqlx::query("SELECT kuatia_i128_to_text(balance) AS b, watermark FROM balance_projection")
|
|
|
+ .fetch_one(&pool)
|
|
|
+ .await
|
|
|
+ .unwrap();
|
|
|
+ assert_eq!(row.try_get::<String, _>("b").unwrap(), "-150");
|
|
|
+ assert_eq!(row.try_get::<i64, _>("watermark").unwrap(), 5);
|
|
|
+}
|