row.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. //! Shared row mappers and codecs: how the store turns domain values into the
  2. //! columns it stores, and rows back into domain types.
  3. //!
  4. //! Identifier and payload columns are text, so a row stays legible in any SQL
  5. //! client: content-addressed ids as hex `TEXT`, JSON payloads as their `TEXT`
  6. //! serialization. Amounts are the exception. They are stored natively so the
  7. //! database can sum and order them (ADR-0024), which means their wire form
  8. //! depends on the backend, and every amount crosses this module through
  9. //! [`bind_money`] and [`row_to_cent`] rather than through `Display`/`FromStr`.
  10. use std::str::FromStr;
  11. use sqlx::Row;
  12. use sqlx::any::{AnyArguments, AnyRow};
  13. use sqlx::query::Query;
  14. use kuatia_storage::error::StoreError;
  15. use kuatia_types::*;
  16. use crate::dialect::Dialect;
  17. /// Bind one amount, in whichever form the backend's column takes: the decimal
  18. /// string for a PostgreSQL `NUMERIC` (the SQL must wrap the placeholder in
  19. /// [`Dialect::money_bind`]), the 16-byte order-preserving encoding for a SQLite
  20. /// `BLOB`. `.bind` is typed, so the two arms cannot be collapsed.
  21. pub(crate) fn bind_money<'q>(
  22. q: Query<'q, sqlx::Any, AnyArguments<'q>>,
  23. dialect: Dialect,
  24. value: Cent,
  25. ) -> Query<'q, sqlx::Any, AnyArguments<'q>> {
  26. match dialect {
  27. Dialect::Postgres => q.bind(value.to_string()),
  28. Dialect::Sqlite => q.bind(value.to_storage_bytes().to_vec()),
  29. }
  30. }
  31. /// Read one amount back. The column must have been selected through
  32. /// [`Dialect::money_read`] or [`Dialect::money_sum`].
  33. pub(crate) fn row_to_cent(
  34. dialect: Dialect,
  35. row: &AnyRow,
  36. column: &str,
  37. ) -> Result<Cent, StoreError> {
  38. match dialect {
  39. Dialect::Postgres => {
  40. let text: String = row
  41. .try_get(column)
  42. .map_err(|e| StoreError::Internal(e.to_string()))?;
  43. Cent::from_str(&text).map_err(|e| StoreError::Internal(e.to_string()))
  44. }
  45. Dialect::Sqlite => {
  46. let bytes: Vec<u8> = row
  47. .try_get(column)
  48. .map_err(|e| StoreError::Internal(e.to_string()))?;
  49. let bytes: [u8; 16] = bytes.as_slice().try_into().map_err(|_| {
  50. StoreError::Internal(format!(
  51. "expected a 16-byte amount in {column}, got {} bytes",
  52. bytes.len()
  53. ))
  54. })?;
  55. Cent::from_storage_bytes(&bytes).map_err(|e| StoreError::Internal(e.to_string()))
  56. }
  57. }
  58. }
  59. /// Serialize a value to a JSON string. Payload columns store JSON as `TEXT` so
  60. /// the database is directly readable for auditing; the ledger never queries into
  61. /// the JSON, so no binary or indexed representation is needed.
  62. pub(crate) fn serialize_json<T: serde::Serialize>(val: &T) -> Result<String, StoreError> {
  63. serde_json::to_string(val).map_err(|e| StoreError::Internal(format!("json serialization: {e}")))
  64. }
  65. pub(crate) fn deserialize_json<T: serde::de::DeserializeOwned>(s: &str) -> Result<T, StoreError> {
  66. serde_json::from_str(s).map_err(|e| StoreError::Internal(format!("bad json: {e}")))
  67. }
  68. /// Lower-case hex encoding. Binary identifiers (content-addressed hashes) and
  69. /// opaque saga bytes are stored as hex `TEXT` so a row is legible in any SQL
  70. /// client and matches the hex form used in logs and `Debug` output.
  71. pub(crate) fn to_hex(bytes: &[u8]) -> String {
  72. const HEX: &[u8; 16] = b"0123456789abcdef";
  73. let mut s = String::with_capacity(bytes.len() * 2);
  74. for &b in bytes {
  75. s.push(HEX[(b >> 4) as usize] as char);
  76. s.push(HEX[(b & 0x0f) as usize] as char);
  77. }
  78. s
  79. }
  80. pub(crate) fn from_hex(s: &str) -> Result<Vec<u8>, StoreError> {
  81. if s.len() % 2 != 0 {
  82. return Err(StoreError::Internal(format!("odd-length hex: {s:?}")));
  83. }
  84. (0..s.len())
  85. .step_by(2)
  86. .map(|i| {
  87. u8::from_str_radix(&s[i..i + 2], 16)
  88. .map_err(|e| StoreError::Internal(format!("bad hex: {e}")))
  89. })
  90. .collect()
  91. }
  92. pub(crate) fn envelope_id_to_hex(id: &EnvelopeId) -> String {
  93. to_hex(&id.0)
  94. }
  95. pub(crate) fn envelope_id_from_hex(s: &str) -> Result<EnvelopeId, StoreError> {
  96. let bytes = from_hex(s)?;
  97. let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
  98. StoreError::Internal(format!("expected 32-byte id, got {} bytes", bytes.len()))
  99. })?;
  100. Ok(EnvelopeId(arr))
  101. }
  102. pub(crate) fn row_to_account(row: &AnyRow) -> Result<Account, StoreError> {
  103. let id: i64 = row
  104. .try_get("id")
  105. .map_err(|e| StoreError::Internal(e.to_string()))?;
  106. let subaccount: i64 = row
  107. .try_get("subaccount")
  108. .map_err(|e| StoreError::Internal(e.to_string()))?;
  109. let version: i64 = row
  110. .try_get("version")
  111. .map_err(|e| StoreError::Internal(e.to_string()))?;
  112. let flags_bits: i32 = row
  113. .try_get("flags")
  114. .map_err(|e| StoreError::Internal(e.to_string()))?;
  115. let book: i64 = row
  116. .try_get("book")
  117. .map_err(|e| StoreError::Internal(e.to_string()))?;
  118. let metadata_json: String = row
  119. .try_get("metadata")
  120. .map_err(|e| StoreError::Internal(e.to_string()))?;
  121. Ok(Account {
  122. id: AccountId::with_sub(id, subaccount),
  123. version: version as u64,
  124. flags: AccountFlags::from_bits_truncate(flags_bits as u32),
  125. book: BookId::new(book),
  126. metadata: deserialize_json(&metadata_json)?,
  127. })
  128. }
  129. pub(crate) fn row_to_posting(dialect: Dialect, row: &AnyRow) -> Result<Posting, StoreError> {
  130. let transfer_id: String = row
  131. .try_get("transfer_id")
  132. .map_err(|e| StoreError::Internal(e.to_string()))?;
  133. let idx: i16 = row
  134. .try_get("idx")
  135. .map_err(|e| StoreError::Internal(e.to_string()))?;
  136. let owner: i64 = row
  137. .try_get("owner")
  138. .map_err(|e| StoreError::Internal(e.to_string()))?;
  139. let subaccount: i64 = row
  140. .try_get("subaccount")
  141. .map_err(|e| StoreError::Internal(e.to_string()))?;
  142. let asset: i32 = row
  143. .try_get("asset")
  144. .map_err(|e| StoreError::Internal(e.to_string()))?;
  145. let value = row_to_cent(dialect, row, "value")?;
  146. Ok(Posting {
  147. id: PostingId {
  148. transfer: envelope_id_from_hex(&transfer_id)?,
  149. index: idx as u16,
  150. },
  151. owner: AccountId::with_sub(owner, subaccount),
  152. asset: AssetId::new(asset as u32),
  153. value,
  154. })
  155. }