mixtape_tools/sqlite/query/
schema.rs1use crate::prelude::*;
4use crate::sqlite::error::SqliteToolError;
5use crate::sqlite::manager::with_connection;
6use crate::sqlite::types::json_to_sql;
7
8#[derive(Debug, Deserialize, JsonSchema)]
10pub struct SchemaQueryInput {
11 pub query: String,
13
14 #[serde(default)]
16 pub params: Vec<serde_json::Value>,
17
18 #[serde(default)]
20 pub db_path: Option<String>,
21}
22
23pub struct SchemaQueryTool;
28
29impl SchemaQueryTool {
30 fn is_schema_query(sql: &str) -> bool {
32 let normalized = sql.trim().to_uppercase();
33 let ddl_prefixes = ["CREATE", "ALTER", "DROP"];
34 ddl_prefixes
35 .iter()
36 .any(|prefix| normalized.starts_with(prefix))
37 }
38}
39
40impl Tool for SchemaQueryTool {
41 type Input = SchemaQueryInput;
42
43 fn name(&self) -> &str {
44 "sqlite_schema_query"
45 }
46
47 fn description(&self) -> &str {
48 "Execute a DDL (Data Definition Language) SQL query (CREATE, ALTER, DROP). Use for schema modifications."
49 }
50
51 async fn execute(&self, input: Self::Input) -> Result<ToolResult, ToolError> {
52 if !Self::is_schema_query(&input.query) {
54 return Err(SqliteToolError::InvalidQuery(
55 "Only CREATE, ALTER, and DROP queries are allowed. Use sqlite_write_query for INSERT/UPDATE/DELETE.".to_string()
56 ).into());
57 }
58
59 let query = input.query.clone();
60 let params = input.params;
61
62 with_connection(input.db_path, move |conn| {
63 let params_ref: Vec<Box<dyn rusqlite::ToSql>> =
65 params.iter().map(|v| json_to_sql(v)).collect();
66
67 let params_slice: Vec<&dyn rusqlite::ToSql> =
68 params_ref.iter().map(|b| b.as_ref()).collect();
69
70 conn.execute(&query, params_slice.as_slice())?;
71
72 Ok(())
73 })
74 .await?;
75
76 let response = serde_json::json!({
77 "status": "success",
78 "message": "Schema query executed successfully"
79 });
80 Ok(ToolResult::Json(response))
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use crate::sqlite::test_utils::TestDatabase;
88
89 #[tokio::test]
90 async fn test_schema_query_create() {
91 let db = TestDatabase::new().await;
92
93 let tool = SchemaQueryTool;
94 let input = SchemaQueryInput {
95 query: "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)".to_string(),
96 params: vec![],
97 db_path: Some(db.key()),
98 };
99
100 let result = tool.execute(input).await.unwrap();
101 let json = crate::sqlite::test_utils::unwrap_json(result);
102 assert_eq!(
103 json,
104 serde_json::json!({
105 "status": "success",
106 "message": "Schema query executed successfully"
107 })
108 );
109
110 let rows =
112 db.query("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='users'");
113 assert_eq!(rows[0][0], 1);
114 }
115
116 #[tokio::test]
117 async fn test_schema_query_alter() {
118 let db = TestDatabase::with_schema("CREATE TABLE users (id INTEGER);").await;
119
120 let tool = SchemaQueryTool;
121 let input = SchemaQueryInput {
122 query: "ALTER TABLE users ADD COLUMN name TEXT".to_string(),
123 params: vec![],
124 db_path: Some(db.key()),
125 };
126
127 let result = tool.execute(input).await;
128 assert!(result.is_ok());
129 }
130
131 #[tokio::test]
132 async fn test_reject_select() {
133 let db = TestDatabase::new().await;
134
135 let tool = SchemaQueryTool;
136 let input = SchemaQueryInput {
137 query: "SELECT * FROM users".to_string(),
138 params: vec![],
139 db_path: Some(db.key()),
140 };
141
142 let result = tool.execute(input).await;
143 assert!(result.is_err());
144 }
145
146 #[test]
147 fn test_is_schema_query() {
148 assert!(SchemaQueryTool::is_schema_query(
149 "CREATE TABLE users (id INT)"
150 ));
151 assert!(SchemaQueryTool::is_schema_query(
152 "ALTER TABLE users ADD COLUMN name TEXT"
153 ));
154 assert!(SchemaQueryTool::is_schema_query("DROP TABLE users"));
155 assert!(SchemaQueryTool::is_schema_query(
156 "CREATE INDEX idx ON users(id)"
157 ));
158
159 assert!(!SchemaQueryTool::is_schema_query("SELECT * FROM users"));
160 assert!(!SchemaQueryTool::is_schema_query(
161 "INSERT INTO users VALUES (1)"
162 ));
163 assert!(!SchemaQueryTool::is_schema_query(
164 "UPDATE users SET name = 'x'"
165 ));
166 }
167
168 #[test]
169 fn test_tool_metadata() {
170 let tool = SchemaQueryTool;
171 assert_eq!(tool.name(), "sqlite_schema_query");
172 assert!(!tool.description().is_empty());
173 }
174}