#[cfg(any(feature = "native", feature = "db"))]
pub use inner::*;
#[cfg(any(feature = "native", feature = "db"))]
mod inner {
use std::io::Write;
use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
pub const SQLITE_HEADER: &[u8] = b"SQLite format 3\0";
pub const PORTABLE_ENVELOPE: &str = "CREATE TABLE IF NOT EXISTS mcard_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); PRAGMA foreign_keys = OFF;";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PortableSqliteCard {
pub hash: String,
pub content: Vec<u8>,
pub g_time: String,
pub handle: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParsedCard {
pub hash: String,
pub content: Vec<u8>,
pub g_time: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParsedHandle {
pub handle: String,
pub current_hash: String,
pub updated_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParsedHistory {
pub handle: String,
pub previous_hash: String,
pub changed_at: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParsedMeta {
pub key: String,
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParsedPortableSqlite {
pub tables: Vec<String>,
pub cards: Vec<ParsedCard>,
pub handles: Vec<ParsedHandle>,
pub history: Vec<ParsedHistory>,
pub meta: Vec<ParsedMeta>,
}
pub fn compile_portable_sqlite(
cards: &[PortableSqliteCard],
schema_profile: Option<&str>,
exported_at: Option<&str>,
exported_by: Option<&str>,
) -> Result<Vec<u8>, String> {
let temp_file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
let temp_path = temp_file.path();
{
let conn = Connection::open(temp_path).map_err(|e| e.to_string())?;
conn.execute_batch(crate::layer0::runtime_contract::SQLITE_DDL_V3_1).map_err(|e| e.to_string())?;
conn.execute_batch(PORTABLE_ENVELOPE).map_err(|e| e.to_string())?;
let _ = conn.execute_batch(
"ALTER TABLE handle_registry ADD COLUMN hash TEXT GENERATED ALWAYS AS (current_hash) VIRTUAL;
ALTER TABLE handle_history ADD COLUMN hash TEXT GENERATED ALWAYS AS (previous_hash) VIRTUAL;
ALTER TABLE handle_history ADD COLUMN created_at TEXT GENERATED ALWAYS AS (changed_at) VIRTUAL;"
);
let profile = schema_profile.unwrap_or("portable-3.0.3");
let author = exported_by.unwrap_or("RustCLM");
let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
let ts = exported_at.unwrap_or(&now);
conn.execute(
"INSERT OR REPLACE INTO mcard_meta (key, value) VALUES (?1, ?2), (?3, ?4), (?5, ?6), (?7, ?8);",
params![
"schema_profile", profile,
"exported_at", ts,
"card_count", cards.len().to_string(),
"exported_by", author
],
).map_err(|e| e.to_string())?;
let mut insert_handle = conn.prepare(
"INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3);"
).map_err(|e| e.to_string())?;
let mut insert_history = conn.prepare(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3);"
).map_err(|e| e.to_string())?;
for card in cards {
crate::layer2::record_store::insert_record(&conn, &crate::layer0::mcard_record::MCardRecord {
hash: card.hash.clone(), content: card.content.clone(), g_time: card.g_time.clone(),
}).map_err(|e| e.to_string())?;
if let Some(ref h) = card.handle {
insert_handle.execute(params![h, card.hash, card.g_time]).map_err(|e| e.to_string())?;
insert_history.execute(params![h, card.hash, card.g_time]).map_err(|e| e.to_string())?;
}
}
}
std::fs::read(temp_path).map_err(|e| e.to_string())
}
pub fn parse_portable_sqlite(bytes: &[u8]) -> Result<ParsedPortableSqlite, String> {
if bytes.len() < 16 {
return Err("File too small to be a valid SQLite database".to_string());
}
if !bytes.starts_with(SQLITE_HEADER) {
return Err("Invalid SQLite 3 binary header (magic bytes mismatch)".to_string());
}
let mut temp_file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
temp_file.write_all(bytes).map_err(|e| e.to_string())?;
let temp_path = temp_file.path();
let conn = Connection::open(temp_path).map_err(|e| e.to_string())?;
let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table';").map_err(|e| e.to_string())?;
let table_iter = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
let mut tables = Vec::new();
for t in table_iter {
tables.push(t.map_err(|e| e.to_string())?);
}
let mut cards = Vec::new();
if tables.contains(&"card".to_string()) {
let mut s = conn.prepare("SELECT hash, content, g_time FROM card;").map_err(|e| e.to_string())?;
let rows = s.query_map([], |r| {
Ok(ParsedCard {
hash: r.get(0)?,
content: r.get_ref(1)?.as_bytes()?.to_vec(),
g_time: r.get(2)?,
})
}).map_err(|e| e.to_string())?;
for c in rows {
let card = c.map_err(|e| e.to_string())?;
crate::layer2::record_store::require_verified(&crate::layer0::mcard_record::MCardRecord {
hash: card.hash.clone(), content: card.content.clone(), g_time: card.g_time.clone(),
}).map_err(|e| e.to_string())?;
cards.push(card);
}
}
let mut handles = Vec::new();
if tables.contains(&"handle_registry".to_string()) {
let mut s = conn.prepare("SELECT handle, current_hash, updated_at FROM handle_registry;").map_err(|e| e.to_string())?;
let rows = s.query_map([], |r| {
Ok(ParsedHandle {
handle: r.get(0)?,
current_hash: r.get(1)?,
updated_at: r.get(2)?,
})
}).map_err(|e| e.to_string())?;
for h in rows {
handles.push(h.map_err(|e| e.to_string())?);
}
}
let mut history = Vec::new();
if tables.contains(&"handle_history".to_string()) {
let mut s = conn.prepare("SELECT handle, previous_hash, changed_at FROM handle_history;").map_err(|e| e.to_string())?;
let rows = s.query_map([], |r| {
Ok(ParsedHistory {
handle: r.get(0)?,
previous_hash: r.get(1)?,
changed_at: r.get(2)?,
})
}).map_err(|e| e.to_string())?;
for h in rows {
history.push(h.map_err(|e| e.to_string())?);
}
}
let mut meta = Vec::new();
if tables.contains(&"mcard_meta".to_string()) {
let mut s = conn.prepare("SELECT key, value FROM mcard_meta;").map_err(|e| e.to_string())?;
let rows = s.query_map([], |r| {
Ok(ParsedMeta {
key: r.get(0)?,
value: r.get(1)?,
})
}).map_err(|e| e.to_string())?;
for m in rows {
meta.push(m.map_err(|e| e.to_string())?);
}
}
Ok(ParsedPortableSqlite {
tables,
cards,
handles,
history,
meta,
})
}
}