Skip to main content

antfly_embedded/
sql.rs

1// Copyright 2026 Antfly, Inc.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! SQLSTATE-preserving SQL, session, and pull-cursor operations.
17use crate::ffi::{borrow_slice, check, take_buffer};
18use crate::{Database, Error};
19use antfly_embedded_sys as sys;
20use std::fmt;
21
22#[derive(Debug, Clone)]
23pub struct SqlError {
24    pub native: Error,
25    pub sqlstate: Option<String>,
26    pub message: String,
27    pub body: Vec<u8>,
28}
29impl fmt::Display for SqlError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        if let Some(code) = &self.sqlstate {
32            write!(f, "{code}: {}", self.message)
33        } else {
34            f.write_str(&self.message)
35        }
36    }
37}
38impl SqlError {
39    fn with_request(self, request: &[u8]) -> Self {
40        let statement = serde_json::from_slice::<serde_json::Value>(request)
41            .ok()
42            .and_then(|value| value["statement"].as_str().map(str::to_owned));
43        match statement {
44            Some(statement) => self.with_statement(&statement),
45            None => self,
46        }
47    }
48
49    /// Attach bounded SQL text, never parameter values, while preserving SQLSTATE.
50    pub(crate) fn with_statement(mut self, statement: &str) -> Self {
51        const LIMIT: usize = 512;
52        let mut end = statement.len().min(LIMIT);
53        while !statement.is_char_boundary(end) {
54            end -= 1;
55        }
56        let excerpt = format!(
57            "{}{}",
58            &statement[..end],
59            if end < statement.len() { "…" } else { "" }
60        );
61        self.message.push_str(&format!(" [statement: {excerpt}]"));
62        if let Ok(mut body) = serde_json::from_slice::<serde_json::Value>(&self.body) {
63            if let Some(error) = body
64                .get_mut("error")
65                .and_then(serde_json::Value::as_object_mut)
66            {
67                error.insert("statement".into(), excerpt.into());
68                self.body = serde_json::to_vec(&body).expect("SQL diagnostic JSON");
69            }
70        }
71        self
72    }
73}
74impl SqlError {
75    /// The outcome receipt of an autocommit write that ended with
76    /// `OutcomeUnknown`, when the database issued one; resolve it with
77    /// `Database::outcome_receipt_status`.
78    pub fn outcome_receipt(&self) -> Option<&str> {
79        self.native.outcome_receipt()
80    }
81}
82impl std::error::Error for SqlError {}
83impl From<Error> for SqlError {
84    fn from(native: Error) -> Self {
85        let message = native.to_string();
86        Self {
87            native,
88            sqlstate: None,
89            message,
90            body: Vec::new(),
91        }
92    }
93}
94pub type Result<T> = std::result::Result<T, SqlError>;
95fn output(code: i32, native: Option<Error>, body: Vec<u8>) -> Result<Vec<u8>> {
96    if code == sys::ANTFLY_OK {
97        return Ok(body);
98    }
99    let parsed = serde_json::from_slice::<serde_json::Value>(&body).ok();
100    let diagnostic = parsed.as_ref().and_then(|v| v.get("error").cloned());
101    let mut native = native.unwrap_or_else(|| Error::from_code(code));
102    if native.outcome_receipt().is_none() {
103        let receipt = parsed
104            .as_ref()
105            .and_then(|v| v["outcome_receipt"].as_str())
106            .map(str::to_owned);
107        native = native.with_outcome_receipt(receipt);
108    }
109    let message = diagnostic
110        .as_ref()
111        .and_then(|value| value["message"].as_str())
112        .map(str::to_owned)
113        .unwrap_or_else(|| native.to_string());
114    Err(SqlError {
115        native,
116        sqlstate: diagnostic
117            .as_ref()
118            .and_then(|v| v["code"].as_str())
119            .map(str::to_owned),
120        message,
121        body,
122    })
123}
124impl Database {
125    fn sql_call(
126        &self,
127        f: impl FnOnce(*mut sys::antfly_db, *mut sys::antfly_buffer) -> i32,
128    ) -> Result<Vec<u8>> {
129        let (code, native, body) = self.with_handle(|handle| {
130            let mut out = sys::antfly_buffer::default();
131            let code = f(handle, &mut out);
132            // Read diagnostics (and any outcome receipt) before freeing the buffer.
133            let native = (code != sys::ANTFLY_OK).then(|| Error::from_native_with_receipt(code));
134            Ok((code, native, unsafe { take_buffer(out) }))
135        })?;
136        output(code, native, body)
137    }
138    pub fn sql_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
139        let request = request.as_ref();
140        self.sql_call(|h, out| unsafe { sys::antfly_db_sql_json(h, borrow_slice(request), out) })
141            .map_err(|error| error.with_request(request))
142    }
143    pub fn sql_describe_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
144        let request = request.as_ref();
145        self.sql_call(|h, out| unsafe {
146            sys::antfly_db_sql_describe_json(h, borrow_slice(request), out)
147        })
148        .map_err(|error| error.with_request(request))
149    }
150    pub fn sql_session_open(&self) -> crate::Result<u64> {
151        self.with_handle(|h| {
152            let mut id = 0;
153            check(unsafe { sys::antfly_db_sql_session_open(h, &mut id) })?;
154            Ok(id)
155        })
156    }
157    pub fn sql_session_close(&self, id: u64) -> crate::Result<()> {
158        self.with_handle(|h| check(unsafe { sys::antfly_db_sql_session_close(h, id) }))
159    }
160    pub fn sql_cursor_open_json(&self, request: impl AsRef<[u8]>) -> Result<u64> {
161        let request = request.as_ref();
162        let mut id = 0;
163        self.sql_call(|h, out| unsafe {
164            sys::antfly_db_sql_open_cursor_json(h, borrow_slice(request), &mut id, out)
165        })
166        .map_err(|error| error.with_request(request))?;
167        Ok(id)
168    }
169    pub fn sql_cursor_fetch_json(&self, id: u64, rows: u32) -> Result<Vec<u8>> {
170        self.sql_call(|h, out| unsafe { sys::antfly_db_sql_fetch_cursor_json(h, id, rows, out) })
171    }
172    pub fn sql_cursor_close(&self, id: u64) -> crate::Result<()> {
173        self.with_handle(|h| check(unsafe { sys::antfly_db_sql_close_cursor(h, id) }))
174    }
175    pub fn create_table_json(&self, name: &str, schema: impl AsRef<[u8]>) -> crate::Result<()> {
176        self.with_handle(|h| {
177            check(unsafe {
178                sys::antfly_db_create_table_json(
179                    h,
180                    borrow_slice(name.as_bytes()),
181                    borrow_slice(schema.as_ref()),
182                )
183            })
184        })
185    }
186    pub fn drop_table(&self, name: &str) -> crate::Result<()> {
187        self.with_handle(|h| {
188            check(unsafe { sys::antfly_db_drop_table(h, borrow_slice(name.as_bytes())) })
189        })
190    }
191    pub fn list_tables_json(&self) -> crate::Result<Vec<u8>> {
192        self.read_buffer(|h, out| unsafe { sys::antfly_db_list_tables_json(h, out) })
193    }
194}