use super::ddl::SqliteEntity;
use crate::version::{ORIGIN_UUID, SQLITE_SNAPSHOT_VERSION};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SQLiteSnapshot {
pub version: String,
pub dialect: String,
pub id: String,
pub prev_ids: Vec<String>,
pub ddl: Vec<SqliteEntity>,
#[serde(default)]
pub renames: Vec<String>,
}
impl Default for SQLiteSnapshot {
fn default() -> Self {
Self::new()
}
}
impl SQLiteSnapshot {
pub fn new() -> Self {
Self {
version: SQLITE_SNAPSHOT_VERSION.to_string(),
dialect: "sqlite".to_string(),
id: uuid::Uuid::new_v4().to_string(),
prev_ids: vec![ORIGIN_UUID.to_string()],
ddl: Vec::new(),
renames: Vec::new(),
}
}
pub fn with_prev_ids(prev_ids: Vec<String>) -> Self {
let mut snapshot = Self::new();
snapshot.prev_ids = prev_ids;
snapshot
}
pub fn add_entity(&mut self, entity: SqliteEntity) {
self.ddl.push(entity);
}
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
pub fn load(path: &std::path::Path) -> std::io::Result<Self> {
let contents = std::fs::read_to_string(path)?;
serde_json::from_str(&contents)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
pub fn save(&self, path: &std::path::Path) -> std::io::Result<()> {
let json = serde_json::to_string_pretty(self)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, json)
}
pub fn is_empty(&self) -> bool {
self.ddl.is_empty()
}
}
use super::ddl::{Table, View};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct Meta {
#[serde(default)]
pub tables: HashMap<String, String>,
#[serde(default)]
pub columns: HashMap<String, String>,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct Internal {
#[serde(default)]
pub indexes: HashMap<String, IndexInternal>,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct IndexInternal {
#[serde(default)]
pub columns: HashMap<String, ColumnInternal>,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct ColumnInternal {
#[serde(skip_serializing_if = "Option::is_none")]
pub is_expression: Option<bool>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SQLiteSnapshotV6 {
pub version: String,
pub dialect: String,
pub id: String,
pub prev_id: String,
pub tables: HashMap<String, Table>,
#[serde(default)]
pub views: HashMap<String, View>,
#[serde(default)]
pub enums: HashMap<String, ()>,
#[serde(rename = "_meta")]
pub meta: Meta,
#[serde(skip_serializing_if = "Option::is_none")]
pub internal: Option<Internal>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sqlite::ddl::{Column, Table};
#[test]
fn test_new_snapshot() {
let snapshot = SQLiteSnapshot::new();
assert_eq!(snapshot.version, "7");
assert_eq!(snapshot.dialect, "sqlite");
assert_eq!(snapshot.prev_ids[0], crate::ORIGIN_UUID);
assert!(snapshot.ddl.is_empty());
}
#[test]
fn test_add_entity() {
let mut snapshot = SQLiteSnapshot::new();
let table = Table::new("users");
snapshot.add_entity(SqliteEntity::Table(table));
let id_col = Column::new("users", "id", "integer")
.not_null()
.autoincrement();
let name_col = Column::new("users", "name", "text").not_null();
snapshot.add_entity(SqliteEntity::Column(id_col));
snapshot.add_entity(SqliteEntity::Column(name_col));
assert_eq!(snapshot.ddl.len(), 3);
}
#[test]
fn test_snapshot_serialization() {
let mut snapshot = SQLiteSnapshot::new();
let table = Table::new("users");
snapshot.add_entity(SqliteEntity::Table(table));
let col = Column::new("users", "id", "integer").not_null();
snapshot.add_entity(SqliteEntity::Column(col));
let json = snapshot.to_json().unwrap();
assert!(json.contains("\"version\": \"7\""));
assert!(json.contains("\"dialect\": \"sqlite\""));
assert!(json.contains("\"entityType\": \"tables\""));
assert!(json.contains("\"entityType\": \"columns\""));
let parsed = SQLiteSnapshot::from_json(&json).unwrap();
assert_eq!(parsed.version, snapshot.version);
assert_eq!(parsed.ddl.len(), 2);
}
#[test]
fn test_column_json_format_matches_drizzle_kit() {
let col = Column::new("users", "id", "integer")
.not_null()
.autoincrement();
let json = serde_json::to_string_pretty(&col).unwrap();
assert!(
json.contains("\"autoincrement\""),
"Expected 'autoincrement' field, got: {}",
json
);
assert!(
json.contains("\"notNull\""),
"Expected 'notNull' field, got: {}",
json
);
assert!(
json.contains("\"type\""),
"Expected 'type' field, got: {}",
json
);
assert!(
json.contains("\"table\""),
"Expected 'table' field, got: {}",
json
);
assert!(
json.contains("\"name\""),
"Expected 'name' field, got: {}",
json
);
assert!(
!json.contains("\"sql_type\""),
"Should not contain 'sql_type'"
);
assert!(
!json.contains("\"not_null\""),
"Should not contain 'not_null'"
);
}
}