Skip to main content

mixtape_tools/sqlite/transaction/
commit.rs

1//! Commit transaction tool
2
3use crate::prelude::*;
4use crate::sqlite::manager::with_connection;
5
6/// Input for committing a transaction
7#[derive(Debug, Deserialize, JsonSchema)]
8pub struct CommitTransactionInput {
9    /// Database file path. If not specified, uses the default database.
10    #[serde(default)]
11    pub db_path: Option<String>,
12}
13
14/// Tool for committing a database transaction
15///
16/// Commits all changes made during the current transaction.
17/// The transaction must have been started with begin_transaction.
18pub struct CommitTransactionTool;
19
20impl Tool for CommitTransactionTool {
21    type Input = CommitTransactionInput;
22
23    fn name(&self) -> &str {
24        "sqlite_commit_transaction"
25    }
26
27    fn description(&self) -> &str {
28        "Commit the current transaction, making all changes permanent."
29    }
30
31    async fn execute(&self, input: Self::Input) -> Result<ToolResult, ToolError> {
32        with_connection(input.db_path, |conn| {
33            conn.execute("COMMIT", [])?;
34            Ok(())
35        })
36        .await?;
37
38        let response = serde_json::json!({
39            "status": "success",
40            "message": "Transaction committed successfully"
41        });
42        Ok(ToolResult::Json(response))
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    use crate::sqlite::test_utils::TestDatabase;
50    use crate::sqlite::transaction::BeginTransactionTool;
51
52    #[tokio::test]
53    async fn test_commit_transaction() {
54        let db = TestDatabase::with_schema("CREATE TABLE test (id INTEGER);").await;
55
56        // Begin transaction
57        let begin_tool = BeginTransactionTool;
58        let begin_input = crate::sqlite::transaction::begin::BeginTransactionInput {
59            db_path: Some(db.key()),
60            transaction_type: crate::sqlite::transaction::begin::TransactionType::Deferred,
61        };
62        begin_tool.execute(begin_input).await.unwrap();
63
64        // Insert data
65        db.execute("INSERT INTO test VALUES (1)");
66
67        // Commit
68        let tool = CommitTransactionTool;
69        let input = CommitTransactionInput {
70            db_path: Some(db.key()),
71        };
72
73        let result = tool.execute(input).await;
74        assert!(result.is_ok());
75
76        // Verify data persisted
77        assert_eq!(db.count("test"), 1);
78    }
79
80    #[test]
81    fn test_tool_metadata() {
82        let tool = CommitTransactionTool;
83        assert_eq!(tool.name(), "sqlite_commit_transaction");
84        assert!(!tool.description().is_empty());
85    }
86}