Skip to main content

adk_memory/
sqlite.rs

1//! SQLite-backed memory service.
2//!
3//! Provides [`SqliteMemoryService`], a [`MemoryService`] implementation
4//! that stores memory entries in SQLite with keyword-based full-text search via FTS5.
5//!
6//! This is a lightweight alternative to `PostgresMemoryService`
7//! for single-node deployments that don't need vector similarity search.
8//!
9//! # Example
10//!
11//! ```rust,ignore
12//! use adk_memory::SqliteMemoryService;
13//!
14//! let service = SqliteMemoryService::new("sqlite:memory.db").await?;
15//! service.migrate().await?;
16//! ```
17
18use crate::service::*;
19use adk_core::Result;
20use async_trait::async_trait;
21use chrono::Utc;
22use serde::Deserialize;
23use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
24use sqlx::{Row, SqlitePool};
25use std::path::Path;
26use std::str::FromStr;
27use std::time::Duration;
28use tracing::instrument;
29
30/// The session id entries added without a session are stored under.
31const DIRECT_SESSION: &str = "__direct__";
32
33/// Private struct for deserializing JSON memory entries during import.
34#[derive(Deserialize)]
35struct JsonMemoryEntry {
36    content: serde_json::Value,
37    author: String,
38    #[serde(default)]
39    timestamp: Option<chrono::DateTime<Utc>>,
40    #[serde(default)]
41    app_name: Option<String>,
42    #[serde(default)]
43    user_id: Option<String>,
44}
45
46/// Extract searchable text from a JSON content value.
47///
48/// - If the value is a string, returns it directly.
49/// - If the value is an object with a `parts` array, extracts `text` fields from each part.
50/// - Otherwise, returns the JSON serialized form as a fallback.
51fn extract_content_text(value: &serde_json::Value) -> String {
52    match value {
53        serde_json::Value::String(s) => s.clone(),
54        serde_json::Value::Object(obj) => {
55            if let Some(serde_json::Value::Array(parts)) = obj.get("parts") {
56                parts
57                    .iter()
58                    .filter_map(|part| part.get("text").and_then(|t| t.as_str()).map(String::from))
59                    .collect::<Vec<_>>()
60                    .join(" ")
61            } else {
62                value.to_string()
63            }
64        }
65        _ => value.to_string(),
66    }
67}
68
69/// Converts free text into an FTS5 query matching entries that contain every word.
70///
71/// Each whitespace-separated token becomes a quoted phrase, so FTS5 syntax
72/// characters (`"`, `'`, `*`, `^`, `:`, `?`, parentheses) are matched as text
73/// instead of parsed, and the bare operators `AND`, `OR`, `NOT` and `NEAR` are
74/// dropped. Tokens without a letter or digit produce no FTS5 term and are
75/// skipped. As with `plainto_tsquery` in the Postgres backend, the remaining
76/// terms are ANDed. Returns `None` when nothing searchable remains.
77fn fts5_match_query(query: &str) -> Option<String> {
78    let terms: Vec<String> = query
79        .split_whitespace()
80        .filter(|token| !matches!(*token, "AND" | "OR" | "NOT" | "NEAR"))
81        .filter(|token| token.chars().any(char::is_alphanumeric))
82        .map(|token| format!("\"{}\"", token.replace('"', "\"\"")))
83        .collect();
84    (!terms.is_empty()).then(|| terms.join(" "))
85}
86
87/// Opens a pool on the SQLite database at `database_url` with `pool` as its settings,
88/// creating the file if missing.
89///
90/// An in-memory database lasts only while a connection to it is open, so its pool keeps one
91/// connection and never closes it for idling or age; a file-backed pool keeps `pool` as given.
92pub(crate) async fn connect(database_url: &str, pool: SqlitePoolOptions) -> Result<SqlitePool> {
93    let options = SqliteConnectOptions::from_str(database_url)
94        .map_err(|e| adk_core::AdkError::memory(format!("invalid sqlite url: {e}")))?
95        .create_if_missing(true);
96    // Read as `SqliteConnectOptions` reads it: `:memory:` as the database, or `mode=memory`.
97    let path = database_url.trim_start_matches("sqlite://").trim_start_matches("sqlite:");
98    let (database, params) = path.split_once('?').unwrap_or((path, ""));
99    let in_memory = database == ":memory:" || params.split('&').any(|param| param == "mode=memory");
100    let pool = if in_memory {
101        pool.max_connections(1).idle_timeout(None).max_lifetime(None)
102    } else {
103        pool
104    };
105    pool.connect_with(options)
106        .await
107        .map_err(|e| adk_core::AdkError::memory(format!("sqlite connection failed: {e}")))
108}
109
110/// SQLite-backed memory service with FTS5 full-text search.
111///
112/// Stores memory entries in a SQLite database with an FTS5 virtual table
113/// for efficient keyword search. No embedding provider is needed.
114///
115/// Search and query-based deletion treat the query as plain text: an entry
116/// matches when it contains every word of the query, and FTS5 operators in the
117/// query are matched literally rather than interpreted.
118///
119/// # Example
120///
121/// ```rust,ignore
122/// use adk_memory::SqliteMemoryService;
123///
124/// let service = SqliteMemoryService::new("sqlite:memory.db").await?;
125/// service.migrate().await?;
126/// ```
127pub struct SqliteMemoryService {
128    pool: SqlitePool,
129    default_ttl: Option<Duration>,
130}
131
132impl SqliteMemoryService {
133    /// Connect to SQLite for memory storage.
134    ///
135    /// Accepts any SQLite connection string (e.g. `sqlite:memory.db`,
136    /// `sqlite::memory:` for in-memory). File-based databases are
137    /// created automatically if they don't exist.
138    ///
139    /// An in-memory database lasts only while a connection to it is open, so its pool keeps
140    /// one connection and never closes it for idling or age.
141    pub async fn new(database_url: &str) -> Result<Self> {
142        Ok(Self::from_pool(connect(database_url, SqlitePoolOptions::new()).await?))
143    }
144
145    /// Create a memory service from an existing connection pool.
146    pub fn from_pool(pool: SqlitePool) -> Self {
147        Self { pool, default_ttl: None }
148    }
149
150    /// Expires each entry written without an expiry `ttl` after it is written.
151    ///
152    /// # Example
153    ///
154    /// ```rust,ignore
155    /// use adk_memory::SqliteMemoryService;
156    /// use std::time::Duration;
157    ///
158    /// let service = SqliteMemoryService::new("sqlite:memory.db")
159    ///     .await?
160    ///     .with_default_ttl(Duration::from_secs(30 * 24 * 3600));
161    /// ```
162    pub fn with_default_ttl(mut self, ttl: Duration) -> Self {
163        self.default_ttl = Some(ttl);
164        self
165    }
166
167    /// Inserts `entries` in one transaction, each stamped with its id and expiry.
168    async fn insert(
169        &self,
170        app_name: &str,
171        user_id: &str,
172        session_id: &str,
173        project_id: Option<&str>,
174        entries: Vec<MemoryEntry>,
175    ) -> Result<()> {
176        let now = Utc::now();
177        let mut tx = self
178            .pool
179            .begin()
180            .await
181            .map_err(|e| adk_core::AdkError::memory(format!("insert failed: {e}")))?;
182        for entry in entries {
183            let entry = crate::expiry::stamp(entry, self.default_ttl, now);
184            let content_json = serde_json::to_string(&entry.content)
185                .map_err(|e| adk_core::AdkError::memory(format!("serialization failed: {e}")))?;
186            sqlx::query(
187                "INSERT INTO memory_entries \
188                 (app_name, user_id, session_id, content, content_text, author, timestamp, \
189                  project_id, memory_id, expires_at) \
190                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
191            )
192            .bind(app_name)
193            .bind(user_id)
194            .bind(session_id)
195            .bind(&content_json)
196            .bind(crate::text::extract_text(&entry.content))
197            .bind(&entry.author)
198            .bind(entry.timestamp.to_rfc3339())
199            .bind(project_id)
200            .bind(&entry.id)
201            .bind(entry.expires_at.map(|at| at.timestamp_millis()))
202            .execute(&mut *tx)
203            .await
204            .map_err(|e| adk_core::AdkError::memory(format!("insert failed: {e}")))?;
205        }
206        tx.commit().await.map_err(|e| adk_core::AdkError::memory(format!("insert failed: {e}")))
207    }
208
209    /// The registry table used to track applied migration versions.
210    const REGISTRY_TABLE: &'static str = "_adk_memory_migrations";
211
212    /// Compiled-in migration steps for the SQLite memory backend.
213    ///
214    /// Each entry is `(version, description, sql)`. Version 1 is the baseline
215    /// that creates the initial schema matching the original `CREATE TABLE IF
216    /// NOT EXISTS` / FTS5 / trigger statements.
217    const SQLITE_MEMORY_MIGRATIONS: &'static [(i64, &'static str, &'static str)] = &[
218        (
219            1,
220            "create memory_entries table, FTS5 virtual table, and sync triggers",
221            "\
222CREATE TABLE IF NOT EXISTS memory_entries (\
223    id INTEGER PRIMARY KEY AUTOINCREMENT, \
224    app_name TEXT NOT NULL, \
225    user_id TEXT NOT NULL, \
226    session_id TEXT NOT NULL, \
227    content TEXT NOT NULL, \
228    content_text TEXT NOT NULL, \
229    author TEXT NOT NULL, \
230    timestamp TEXT NOT NULL\
231);\
232CREATE INDEX IF NOT EXISTS idx_memory_app_user \
233    ON memory_entries(app_name, user_id);\
234CREATE VIRTUAL TABLE IF NOT EXISTS memory_entries_fts \
235    USING fts5(content_text, content='memory_entries', content_rowid='id');\
236CREATE TRIGGER IF NOT EXISTS memory_entries_ai AFTER INSERT ON memory_entries BEGIN \
237    INSERT INTO memory_entries_fts(rowid, content_text) VALUES (new.id, new.content_text); \
238END;\
239CREATE TRIGGER IF NOT EXISTS memory_entries_ad AFTER DELETE ON memory_entries BEGIN \
240    INSERT INTO memory_entries_fts(memory_entries_fts, rowid, content_text) VALUES('delete', old.id, old.content_text); \
241END;",
242        ),
243        (
244            2,
245            "add project_id column and index",
246            "\
247ALTER TABLE memory_entries ADD COLUMN project_id TEXT;\
248CREATE INDEX IF NOT EXISTS idx_memory_project_id ON memory_entries(project_id);",
249        ),
250        (
251            3,
252            "add memory_id and expires_at columns",
253            "\
254ALTER TABLE memory_entries ADD COLUMN memory_id TEXT;\
255ALTER TABLE memory_entries ADD COLUMN expires_at INTEGER;\
256UPDATE memory_entries SET memory_id = lower(hex(randomblob(16))) WHERE memory_id IS NULL;\
257CREATE INDEX IF NOT EXISTS idx_memory_memory_id ON memory_entries(app_name, user_id, memory_id);\
258CREATE INDEX IF NOT EXISTS idx_memory_expires_at ON memory_entries(expires_at);",
259        ),
260    ];
261
262    /// Create the `memory_entries` table and FTS5 virtual table.
263    ///
264    /// Uses the versioned migration runner to apply schema changes
265    /// incrementally. Safe to call multiple times — already-applied
266    /// steps are skipped.
267    pub async fn migrate(&self) -> Result<()> {
268        let pool = self.pool.clone();
269        crate::migration::sqlite_runner::run_sql_migrations(
270            &pool,
271            Self::REGISTRY_TABLE,
272            Self::SQLITE_MEMORY_MIGRATIONS,
273            || async {
274                let row = sqlx::query(
275                    "SELECT COUNT(*) AS cnt FROM sqlite_master \
276                     WHERE type='table' AND name='memory_entries'",
277                )
278                .fetch_one(&pool)
279                .await
280                .map_err(|e| {
281                    adk_core::AdkError::memory(format!("baseline detection failed: {e}"))
282                })?;
283                let count: i64 = row.try_get("cnt").unwrap_or(0);
284                Ok(count > 0)
285            },
286        )
287        .await
288    }
289
290    /// Returns the highest applied migration version, or 0 if no registry
291    /// exists or the registry is empty.
292    ///
293    /// # Errors
294    ///
295    /// Returns an error when the registry cannot be read for any reason other
296    /// than the table being absent, such as a lost connection or a missing
297    /// privilege.
298    pub async fn schema_version(&self) -> Result<i64> {
299        crate::migration::sqlite_runner::sql_schema_version(&self.pool, Self::REGISTRY_TABLE).await
300    }
301
302    /// Import memory entries from a JSON file into the database.
303    ///
304    /// The file must contain a JSON array of objects, each with at least
305    /// `content` (any JSON value) and `author` (string) fields. Optional
306    /// fields: `timestamp`, `app_name`, `user_id`.
307    ///
308    /// Imported entries are appended — existing data is never modified.
309    /// Returns the count of successfully imported entries.
310    ///
311    /// # Errors
312    ///
313    /// Returns a descriptive error if the file does not exist or contains
314    /// invalid JSON.
315    pub async fn import_json(&self, path: impl AsRef<Path>) -> Result<u64> {
316        let pool = self.pool.clone();
317        let path = path.as_ref();
318
319        let file_content = std::fs::read_to_string(path).map_err(|e| {
320            adk_core::AdkError::memory(format!("file not found: {}", path.display())).with_source(e)
321        })?;
322
323        let entries: Vec<JsonMemoryEntry> = serde_json::from_str(&file_content)
324            .map_err(|e| adk_core::AdkError::memory(format!("JSON parse error: {e}")))?;
325
326        let mut count: u64 = 0;
327        for entry in &entries {
328            let content_json = serde_json::to_string(&entry.content)
329                .map_err(|e| adk_core::AdkError::memory(format!("serialization failed: {e}")))?;
330
331            let content_text = extract_content_text(&entry.content);
332
333            let timestamp_str = entry.timestamp.unwrap_or_else(Utc::now).to_rfc3339();
334
335            let app_name = entry.app_name.as_deref().unwrap_or("__import__");
336
337            let user_id = entry.user_id.as_deref().unwrap_or("__import__");
338
339            let expires_at = self
340                .default_ttl
341                .map(|ttl| crate::expiry::expiry_after(Utc::now(), ttl).timestamp_millis());
342            sqlx::query(
343                "INSERT INTO memory_entries \
344                 (app_name, user_id, session_id, content, content_text, author, timestamp, \
345                  project_id, memory_id, expires_at) \
346                 VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)",
347            )
348            .bind(app_name)
349            .bind(user_id)
350            .bind("__import__")
351            .bind(&content_json)
352            .bind(&content_text)
353            .bind(&entry.author)
354            .bind(&timestamp_str)
355            .bind(crate::expiry::new_memory_id())
356            .bind(expires_at)
357            .execute(&pool)
358            .await
359            .map_err(|e| adk_core::AdkError::memory(format!("insert failed: {e}")))?;
360
361            count += 1;
362        }
363
364        Ok(count)
365    }
366}
367
368#[async_trait]
369impl MemoryService for SqliteMemoryService {
370    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, entry_count = entries.len()))]
371    async fn add_session(
372        &self,
373        app_name: &str,
374        user_id: &str,
375        session_id: &str,
376        entries: Vec<MemoryEntry>,
377    ) -> Result<()> {
378        self.insert(app_name, user_id, session_id, None, entries).await
379    }
380
381    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
382    async fn search(&self, req: SearchRequest) -> Result<SearchResponse> {
383        let pool = self.pool.clone();
384        let limit = req.limit.unwrap_or(10) as i64;
385        let Some(match_query) = fts5_match_query(&req.query) else {
386            return Ok(SearchResponse { memories: Vec::new() });
387        };
388
389        // Mirrors `expiry::is_expired`: an entry is live while `expires_at > now`.
390        let now = Utc::now().timestamp_millis();
391        let rows = if let Some(ref project_id) = req.project_id {
392            sqlx::query(
393                r#"
394                SELECT m.memory_id, m.content, m.author, m.timestamp, m.expires_at, f.rank
395                FROM memory_entries_fts f
396                JOIN memory_entries m ON m.id = f.rowid
397                WHERE memory_entries_fts MATCH ?
398                  AND m.app_name = ? AND m.user_id = ?
399                  AND (m.project_id IS NULL OR m.project_id = ?)
400                  AND (m.expires_at IS NULL OR m.expires_at > ?)
401                ORDER BY f.rank
402                LIMIT ?
403                "#,
404            )
405            .bind(&match_query)
406            .bind(&req.app_name)
407            .bind(&req.user_id)
408            .bind(project_id)
409            .bind(now)
410            .bind(limit)
411            .fetch_all(&pool)
412            .await
413            .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?
414        } else {
415            sqlx::query(
416                r#"
417                SELECT m.memory_id, m.content, m.author, m.timestamp, m.expires_at, f.rank
418                FROM memory_entries_fts f
419                JOIN memory_entries m ON m.id = f.rowid
420                WHERE memory_entries_fts MATCH ?
421                  AND m.app_name = ? AND m.user_id = ?
422                  AND m.project_id IS NULL
423                  AND (m.expires_at IS NULL OR m.expires_at > ?)
424                ORDER BY f.rank
425                LIMIT ?
426                "#,
427            )
428            .bind(&match_query)
429            .bind(&req.app_name)
430            .bind(&req.user_id)
431            .bind(now)
432            .bind(limit)
433            .fetch_all(&pool)
434            .await
435            .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?
436        };
437
438        let memories = rows
439            .iter()
440            .map(|row| {
441                let content_str: String = row.get("content");
442                let content: adk_core::Content =
443                    serde_json::from_str(&content_str).unwrap_or_else(|_| adk_core::Content {
444                        role: "user".to_string(),
445                        parts: vec![],
446                    });
447                let author: String = row.get("author");
448                let timestamp_str: String = row.get("timestamp");
449                let timestamp = chrono::DateTime::parse_from_rfc3339(&timestamp_str)
450                    .map(|dt| dt.with_timezone(&chrono::Utc))
451                    .unwrap_or_default();
452                MemoryEntry {
453                    id: row.get("memory_id"),
454                    content,
455                    author,
456                    timestamp,
457                    expires_at: row
458                        .get::<Option<i64>, _>("expires_at")
459                        .and_then(chrono::DateTime::from_timestamp_millis),
460                }
461            })
462            .collect();
463
464        Ok(SearchResponse { memories })
465    }
466
467    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
468    async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<()> {
469        let pool = self.pool.clone();
470        sqlx::query("DELETE FROM memory_entries WHERE app_name = ? AND user_id = ?")
471            .bind(app_name)
472            .bind(user_id)
473            .execute(&pool)
474            .await
475            .map_err(|e| adk_core::AdkError::memory(format!("delete_user failed: {e}")))?;
476        Ok(())
477    }
478
479    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
480    async fn export_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserMemory>> {
481        let rows = sqlx::query(
482            "SELECT session_id, project_id, memory_id, content, author, timestamp, expires_at \
483             FROM memory_entries WHERE app_name = ? AND user_id = ? ORDER BY timestamp, id",
484        )
485        .bind(app_name)
486        .bind(user_id)
487        .fetch_all(&self.pool)
488        .await
489        .map_err(|e| adk_core::AdkError::memory(format!("export_user failed: {e}")))?;
490        rows.iter()
491            .map(|row| {
492                let content: String = row.get("content");
493                let timestamp: String = row.get("timestamp");
494                let session_id: String = row.get("session_id");
495                Ok(UserMemory {
496                    entry: MemoryEntry {
497                        id: row.get("memory_id"),
498                        expires_at: row
499                            .get::<Option<i64>, _>("expires_at")
500                            .and_then(chrono::DateTime::from_timestamp_millis),
501                        content: serde_json::from_str(&content).map_err(|e| {
502                            adk_core::AdkError::memory(format!("stored content is corrupt: {e}"))
503                        })?,
504                        author: row.get("author"),
505                        timestamp: chrono::DateTime::parse_from_rfc3339(&timestamp)
506                            .map(|dt| dt.with_timezone(&chrono::Utc))
507                            .map_err(|e| {
508                                adk_core::AdkError::memory(format!(
509                                    "stored timestamp is corrupt: {e}"
510                                ))
511                            })?,
512                    },
513                    session_id: (session_id != DIRECT_SESSION).then_some(session_id),
514                    project_id: row.get("project_id"),
515                })
516            })
517            .collect()
518    }
519
520    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id))]
521    async fn delete_session(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
522        let pool = self.pool.clone();
523        sqlx::query(
524            "DELETE FROM memory_entries WHERE app_name = ? AND user_id = ? AND session_id = ?",
525        )
526        .bind(app_name)
527        .bind(user_id)
528        .bind(session_id)
529        .execute(&pool)
530        .await
531        .map_err(|e| adk_core::AdkError::memory(format!("delete_session failed: {e}")))?;
532        Ok(())
533    }
534
535    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
536    async fn add_entry(&self, app_name: &str, user_id: &str, entry: MemoryEntry) -> Result<()> {
537        self.insert(app_name, user_id, DIRECT_SESSION, None, vec![entry]).await
538    }
539
540    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
541    async fn delete_entries(&self, app_name: &str, user_id: &str, query: &str) -> Result<u64> {
542        let pool = self.pool.clone();
543        let Some(match_query) = fts5_match_query(query) else {
544            return Ok(0);
545        };
546        let result = sqlx::query(
547            "DELETE FROM memory_entries WHERE id IN (\
548                SELECT m.id FROM memory_entries_fts f \
549                JOIN memory_entries m ON m.id = f.rowid \
550                WHERE memory_entries_fts MATCH ? \
551                AND m.app_name = ? AND m.user_id = ? \
552                AND m.project_id IS NULL\
553            )",
554        )
555        .bind(&match_query)
556        .bind(app_name)
557        .bind(user_id)
558        .execute(&pool)
559        .await
560        .map_err(|e| adk_core::AdkError::memory(format!("delete failed: {e}")))?;
561
562        Ok(result.rows_affected())
563    }
564
565    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
566    async fn delete_memory(&self, app_name: &str, user_id: &str, memory_id: &str) -> Result<u64> {
567        let result = sqlx::query(
568            "DELETE FROM memory_entries WHERE app_name = ? AND user_id = ? AND memory_id = ?",
569        )
570        .bind(app_name)
571        .bind(user_id)
572        .bind(memory_id)
573        .execute(&self.pool)
574        .await
575        .map_err(|e| adk_core::AdkError::memory(format!("delete_memory failed: {e}")))?;
576        Ok(result.rows_affected())
577    }
578
579    #[instrument(skip_all)]
580    async fn purge_expired(&self) -> Result<u64> {
581        let result = sqlx::query("DELETE FROM memory_entries WHERE expires_at <= ?")
582            .bind(Utc::now().timestamp_millis())
583            .execute(&self.pool)
584            .await
585            .map_err(|e| adk_core::AdkError::memory(format!("purge_expired failed: {e}")))?;
586        Ok(result.rows_affected())
587    }
588
589    #[instrument(skip_all)]
590    async fn health_check(&self) -> Result<()> {
591        let pool = self.pool.clone();
592        sqlx::query("SELECT 1")
593            .execute(&pool)
594            .await
595            .map_err(|e| adk_core::AdkError::memory(format!("health check failed: {e}")))?;
596        Ok(())
597    }
598
599    fn supports_project_scoping(&self) -> bool {
600        true
601    }
602
603    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, project_id = %project_id, entry_count = entries.len()))]
604    async fn add_session_to_project(
605        &self,
606        app_name: &str,
607        user_id: &str,
608        session_id: &str,
609        project_id: &str,
610        entries: Vec<MemoryEntry>,
611    ) -> Result<()> {
612        validate_project_id(project_id)?;
613        self.insert(app_name, user_id, session_id, Some(project_id), entries).await
614    }
615
616    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
617    async fn add_entry_to_project(
618        &self,
619        app_name: &str,
620        user_id: &str,
621        project_id: &str,
622        entry: MemoryEntry,
623    ) -> Result<()> {
624        validate_project_id(project_id)?;
625        self.insert(app_name, user_id, DIRECT_SESSION, Some(project_id), vec![entry]).await
626    }
627
628    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
629    async fn delete_entries_in_project(
630        &self,
631        app_name: &str,
632        user_id: &str,
633        project_id: &str,
634        query: &str,
635    ) -> Result<u64> {
636        let pool = self.pool.clone();
637        let Some(match_query) = fts5_match_query(query) else {
638            return Ok(0);
639        };
640        let result = sqlx::query(
641            "DELETE FROM memory_entries WHERE id IN (\
642                SELECT m.id FROM memory_entries_fts f \
643                JOIN memory_entries m ON m.id = f.rowid \
644                WHERE memory_entries_fts MATCH ? \
645                AND m.app_name = ? AND m.user_id = ? \
646                AND m.project_id = ?\
647            )",
648        )
649        .bind(&match_query)
650        .bind(app_name)
651        .bind(user_id)
652        .bind(project_id)
653        .execute(&pool)
654        .await
655        .map_err(|e| adk_core::AdkError::memory(format!("delete failed: {e}")))?;
656
657        Ok(result.rows_affected())
658    }
659
660    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
661    async fn delete_project(&self, app_name: &str, user_id: &str, project_id: &str) -> Result<u64> {
662        let pool = self.pool.clone();
663        let result = sqlx::query(
664            "DELETE FROM memory_entries WHERE app_name = ? AND user_id = ? AND project_id = ?",
665        )
666        .bind(app_name)
667        .bind(user_id)
668        .bind(project_id)
669        .execute(&pool)
670        .await
671        .map_err(|e| adk_core::AdkError::memory(format!("delete_project failed: {e}")))?;
672
673        Ok(result.rows_affected())
674    }
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680    use adk_core::Content;
681
682    const APP: &str = "app";
683    const USER: &str = "user";
684
685    async fn service_with(texts: &[&str]) -> SqliteMemoryService {
686        // One connection: every connection to `sqlite::memory:` is its own database.
687        let pool = SqlitePoolOptions::new()
688            .max_connections(1)
689            .connect("sqlite::memory:")
690            .await
691            .expect("open in-memory sqlite");
692        let service = SqliteMemoryService::from_pool(pool);
693        service.migrate().await.expect("migrate");
694        let entries = texts
695            .iter()
696            .map(|text| MemoryEntry::new(Content::new("user").with_text(*text), "user"))
697            .collect();
698        service.add_session(APP, USER, "s1", entries).await.expect("add_session");
699        service
700    }
701
702    async fn search_texts(service: &SqliteMemoryService, query: &str) -> Vec<String> {
703        let response = service
704            .search(SearchRequest {
705                query: query.to_string(),
706                user_id: USER.to_string(),
707                app_name: APP.to_string(),
708                limit: None,
709                min_score: None,
710                project_id: None,
711            })
712            .await
713            .unwrap_or_else(|e| panic!("search for {query:?} failed: {e}"));
714        let mut texts: Vec<String> =
715            response.memories.iter().map(|m| crate::text::extract_text(&m.content)).collect();
716        texts.sort();
717        texts
718    }
719
720    #[test]
721    fn test_fts5_match_query_quotes_terms_and_drops_operators() {
722        assert_eq!(
723            [
724                fts5_match_query("what's my name?"),
725                fts5_match_query("rust AND programming OR NOT NEAR"),
726                fts5_match_query(r#"say "hi"#),
727                fts5_match_query("rust* ^start col:value (x)"),
728                fts5_match_query("编程"),
729            ],
730            [
731                Some(r#""what's" "my" "name?""#.to_string()),
732                Some(r#""rust" "programming""#.to_string()),
733                Some(r#""say" """hi""#.to_string()),
734                Some(r#""rust*" "^start" "col:value" "(x)""#.to_string()),
735                Some(r#""编程""#.to_string()),
736            ]
737        );
738    }
739
740    #[test]
741    fn test_fts5_match_query_without_searchable_terms() {
742        for query in ["", "   ", "?", "*", "AND", "OR NOT", "\"", "🦀 !"] {
743            assert_eq!(fts5_match_query(query), None, "{query:?}");
744        }
745    }
746
747    #[tokio::test]
748    async fn test_search_accepts_ordinary_text() {
749        let service = service_with(&[
750            "what's my name? It is Alice",
751            "Alice's favourite colour is blue",
752            "rust programming is fun",
753            "I like python",
754            "我喜欢 编程",
755        ])
756        .await;
757
758        assert_eq!(
759            search_texts(&service, "what's my name?").await,
760            ["what's my name? It is Alice"]
761        );
762        assert_eq!(
763            search_texts(&service, "Alice's colour?").await,
764            ["Alice's favourite colour is blue"]
765        );
766        assert_eq!(
767            search_texts(&service, "rust AND programming").await,
768            ["rust programming is fun"]
769        );
770        assert_eq!(search_texts(&service, "rust*").await, ["rust programming is fun"]);
771        assert_eq!(search_texts(&service, "编程").await, ["我喜欢 编程"]);
772        assert_eq!(search_texts(&service, "编程?").await, ["我喜欢 编程"]);
773    }
774
775    #[tokio::test]
776    async fn test_search_with_fts5_syntax_does_not_error() {
777        let service = service_with(&["rust programming is fun"]).await;
778
779        for query in [
780            "*",
781            "?",
782            "AND",
783            "OR",
784            "NOT rust",
785            "rust OR python",
786            "\"unbalanced",
787            "NEAR(rust fun)",
788            "content_text:rust",
789            "(rust",
790            "-rust +fun",
791            "^rust",
792        ] {
793            // Each query must parse; the result set itself is query-specific.
794            search_texts(&service, query).await;
795        }
796        assert_eq!(search_texts(&service, "*").await, Vec::<String>::new());
797        assert_eq!(search_texts(&service, "NOT rust").await, ["rust programming is fun"]);
798    }
799
800    #[tokio::test]
801    async fn test_delete_entries_accepts_ordinary_text() {
802        let service = service_with(&["what's my name? It is Alice", "unrelated"]).await;
803
804        assert_eq!(service.delete_entries(APP, USER, "what's my name?").await.unwrap(), 1);
805        assert_eq!(service.delete_entries(APP, USER, "*").await.unwrap(), 0);
806        assert_eq!(search_texts(&service, "unrelated").await, ["unrelated"]);
807    }
808
809    #[tokio::test]
810    async fn test_delete_entries_in_project_accepts_ordinary_text() {
811        let service = service_with(&[]).await;
812        let entry = MemoryEntry::new(
813            Content::new("user").with_text("what's the project's deadline?"),
814            "user",
815        );
816        service.add_entry_to_project(APP, USER, "proj", entry).await.unwrap();
817
818        let deleted =
819            service.delete_entries_in_project(APP, USER, "proj", "project's deadline?").await;
820        assert_eq!(deleted.unwrap(), 1);
821    }
822
823    #[tokio::test]
824    async fn an_in_memory_service_keeps_its_entries_past_the_pool_idle_timeout() {
825        let reaping = SqlitePoolOptions::new().idle_timeout(Duration::from_millis(50));
826        let service =
827            SqliteMemoryService::from_pool(connect("sqlite::memory:", reaping).await.unwrap());
828        service.migrate().await.unwrap();
829        let entry =
830            MemoryEntry::new(Content::new("user").with_text("Prefers the night shift"), "user");
831        service.add_session(APP, USER, "s1", vec![entry]).await.unwrap();
832        // Long enough for the pool's reaper to find the connection idle past the timeout.
833        tokio::time::sleep(Duration::from_millis(500)).await;
834        assert_eq!(search_texts(&service, "night shift").await, ["Prefers the night shift"]);
835    }
836
837    #[tokio::test]
838    async fn only_an_in_memory_service_changes_the_pool_settings() {
839        let settings = |options: &SqlitePoolOptions| {
840            (options.get_max_connections(), options.get_idle_timeout(), options.get_max_lifetime())
841        };
842        let path =
843            std::env::temp_dir().join(format!("adk-memory-pool-{}.db", uuid::Uuid::new_v4()));
844        let on_disk =
845            SqliteMemoryService::new(&format!("sqlite://{}", path.display())).await.unwrap();
846        assert_eq!(settings(on_disk.pool.options()), settings(&SqlitePoolOptions::new()));
847        on_disk.pool.close().await;
848        let _ = std::fs::remove_file(&path);
849
850        let named = format!("sqlite:memory-{}?mode=memory", uuid::Uuid::new_v4());
851        for url in ["sqlite::memory:", named.as_str()] {
852            let in_memory = SqliteMemoryService::new(url).await.unwrap();
853            assert_eq!(settings(in_memory.pool.options()), (1, None, None), "{url}");
854        }
855    }
856}