Skip to main content

everruns_contracts/
session_sqldb.rs

1// Session SQL Database types and trait
2//
3// Types and async trait for session-scoped SQL databases.
4// Implementations live in the session-sqldb crate.
5//
6// EVE-897: this module moved out of core with its trait. The value types are
7// the signature vocabulary of `SessionSqlDbStore`, so records and trait travel
8// together; what pinned them to the kernel was `ToolContext::sqldb_store`.
9// That field is gone — the capability now resolves the store as a typed
10// extension — so the whole family lives beside the capability that uses it.
11
12use async_trait::async_trait;
13use chrono::{DateTime, Utc};
14use serde::{Deserialize, Serialize};
15
16use crate::typed_id::SessionId;
17
18/// Metadata about a session database (no content/pages).
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct DatabaseInfo {
21    pub name: String,
22    pub size_bytes: i64,
23    pub page_count: i32,
24    pub created_at: DateTime<Utc>,
25    pub updated_at: DateTime<Utc>,
26}
27
28/// Result of a SELECT query.
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct SqlQueryResult {
31    pub columns: Vec<String>,
32    pub rows: Vec<Vec<serde_json::Value>>,
33    pub row_count: usize,
34    /// True if results were truncated due to limits
35    #[serde(skip_serializing_if = "std::ops::Not::not")]
36    pub truncated: bool,
37}
38
39/// Result of an INSERT/UPDATE/DELETE/DDL statement.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct SqlExecuteResult {
42    pub rows_affected: u64,
43}
44
45/// Schema of a table.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct TableSchema {
48    pub name: String,
49    pub columns: Vec<ColumnSchema>,
50    pub row_count: i64,
51}
52
53/// Schema of a column.
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct ColumnSchema {
56    pub name: String,
57    #[serde(rename = "type")]
58    pub column_type: String,
59    pub notnull: bool,
60    pub pk: bool,
61    pub default_value: Option<String>,
62}
63
64/// Error type for session SQL database operations.
65///
66/// Tool-visible errors (validation, not found, limits) vs internal errors
67/// are distinguished by the caller when converting to ToolExecutionResult.
68#[derive(Debug, thiserror::Error)]
69pub enum SessionSqlDbError {
70    #[error("database not found: {0}")]
71    DatabaseNotFound(String),
72
73    #[error("database already exists: {0}")]
74    DatabaseAlreadyExists(String),
75
76    #[error("invalid database name: {0}")]
77    InvalidDatabaseName(String),
78
79    #[error("database limit exceeded: {0}")]
80    LimitExceeded(String),
81
82    #[error("query error: {0}")]
83    QueryError(String),
84
85    #[error("query timeout after {0} seconds")]
86    QueryTimeout(u64),
87
88    #[error("result too large: {0}")]
89    ResultTooLarge(String),
90
91    #[error("operation blocked by authorizer: {0}")]
92    AuthorizerBlocked(String),
93
94    #[error("internal error: {0}")]
95    Internal(String),
96}
97
98impl SessionSqlDbError {
99    /// Whether this error should be shown to the LLM as a tool error (vs internal error).
100    pub fn is_tool_error(&self) -> bool {
101        matches!(
102            self,
103            Self::DatabaseNotFound(_)
104                | Self::DatabaseAlreadyExists(_)
105                | Self::InvalidDatabaseName(_)
106                | Self::LimitExceeded(_)
107                | Self::QueryError(_)
108                | Self::QueryTimeout(_)
109                | Self::ResultTooLarge(_)
110                | Self::AuthorizerBlocked(_)
111        )
112    }
113}
114
115/// Async trait for session-scoped SQL database operations.
116///
117/// Implementations:
118/// - InMemorySqlDbBackend (DEV_MODE) in session-sqldb crate
119/// - Future: PostgreSQL VFS backend
120#[async_trait]
121pub trait SessionSqlDbStore: Send + Sync {
122    /// Create a named database in the session.
123    async fn create_database(
124        &self,
125        session_id: SessionId,
126        name: &str,
127    ) -> Result<DatabaseInfo, SessionSqlDbError>;
128
129    /// List all databases for a session.
130    async fn list_databases(
131        &self,
132        session_id: SessionId,
133    ) -> Result<Vec<DatabaseInfo>, SessionSqlDbError>;
134
135    /// Get metadata for a specific database.
136    async fn get_database(
137        &self,
138        session_id: SessionId,
139        name: &str,
140    ) -> Result<Option<DatabaseInfo>, SessionSqlDbError>;
141
142    /// Delete a database and all its pages.
143    async fn delete_database(
144        &self,
145        session_id: SessionId,
146        name: &str,
147    ) -> Result<bool, SessionSqlDbError>;
148
149    /// Execute DDL/DML SQL. Auto-creates database if it doesn't exist.
150    async fn sql_execute(
151        &self,
152        session_id: SessionId,
153        db_name: &str,
154        sql: &str,
155    ) -> Result<SqlExecuteResult, SessionSqlDbError>;
156
157    /// Execute read-only SQL query. Returns columns and rows.
158    async fn sql_query(
159        &self,
160        session_id: SessionId,
161        db_name: &str,
162        sql: &str,
163    ) -> Result<SqlQueryResult, SessionSqlDbError>;
164
165    /// Get schema for all tables (or a specific table) in a database.
166    async fn sql_schema(
167        &self,
168        session_id: SessionId,
169        db_name: &str,
170        table: Option<&str>,
171    ) -> Result<Vec<TableSchema>, SessionSqlDbError>;
172}
173
174/// Type-keyed wrapper installed on the tool context by hosted presets.
175///
176/// Core carries the generic extension bag but does not name this service: the
177/// session SQL database is a hosted capability's backend, so the capability and
178/// its store contract stay together in platform (EVE-897).
179#[derive(Clone)]
180pub struct SessionSqlDbStoreExt(pub std::sync::Arc<dyn SessionSqlDbStore>);