|
| 1 | +// Copyright 2018-2025 the Deno authors. MIT license. |
| 2 | + |
| 3 | +use std::cell::Cell; |
| 4 | +use std::cell::RefCell; |
| 5 | +use std::rc::Rc; |
| 6 | + |
| 7 | +use deno_core::anyhow; |
| 8 | +use deno_core::anyhow::anyhow; |
| 9 | +use deno_core::op2; |
| 10 | +use deno_core::GarbageCollected; |
| 11 | +use deno_core::OpState; |
| 12 | +use deno_permissions::PermissionsContainer; |
| 13 | +use serde::Deserialize; |
| 14 | + |
| 15 | +use super::StatementSync; |
| 16 | + |
| 17 | +#[derive(Deserialize)] |
| 18 | +#[serde(rename_all = "camelCase")] |
| 19 | +struct DatabaseSyncOptions { |
| 20 | + #[serde(default = "true_fn")] |
| 21 | + open: bool, |
| 22 | + #[serde(default = "true_fn")] |
| 23 | + enable_foreign_key_constraints: bool, |
| 24 | + read_only: bool, |
| 25 | +} |
| 26 | + |
| 27 | +fn true_fn() -> bool { |
| 28 | + true |
| 29 | +} |
| 30 | + |
| 31 | +impl Default for DatabaseSyncOptions { |
| 32 | + fn default() -> Self { |
| 33 | + DatabaseSyncOptions { |
| 34 | + open: true, |
| 35 | + enable_foreign_key_constraints: true, |
| 36 | + read_only: false, |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +pub struct DatabaseSync { |
| 42 | + conn: Rc<RefCell<Option<rusqlite::Connection>>>, |
| 43 | + options: DatabaseSyncOptions, |
| 44 | + location: String, |
| 45 | +} |
| 46 | + |
| 47 | +impl GarbageCollected for DatabaseSync {} |
| 48 | + |
| 49 | +fn open_db( |
| 50 | + state: &mut OpState, |
| 51 | + readonly: bool, |
| 52 | + location: &str, |
| 53 | +) -> Result<rusqlite::Connection, anyhow::Error> { |
| 54 | + if location == ":memory:" { |
| 55 | + return Ok(rusqlite::Connection::open_in_memory()?); |
| 56 | + } |
| 57 | + |
| 58 | + state |
| 59 | + .borrow::<PermissionsContainer>() |
| 60 | + .check_read_with_api_name(location, Some("node:sqlite"))?; |
| 61 | + |
| 62 | + if readonly { |
| 63 | + return Ok(rusqlite::Connection::open_with_flags( |
| 64 | + location, |
| 65 | + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY, |
| 66 | + )?); |
| 67 | + } |
| 68 | + |
| 69 | + state |
| 70 | + .borrow::<PermissionsContainer>() |
| 71 | + .check_write_with_api_name(location, Some("node:sqlite"))?; |
| 72 | + |
| 73 | + Ok(rusqlite::Connection::open(location)?) |
| 74 | +} |
| 75 | + |
| 76 | +// Represents a single connection to a SQLite database. |
| 77 | +#[op2] |
| 78 | +impl DatabaseSync { |
| 79 | + // Constructs a new `DatabaseSync` instance. |
| 80 | + // |
| 81 | + // A SQLite database can be stored in a file or in memory. To |
| 82 | + // use a file-backed database, the `location` should be a path. |
| 83 | + // To use an in-memory database, the `location` should be special |
| 84 | + // name ":memory:". |
| 85 | + #[constructor] |
| 86 | + #[cppgc] |
| 87 | + fn new( |
| 88 | + state: &mut OpState, |
| 89 | + #[string] location: String, |
| 90 | + #[serde] options: Option<DatabaseSyncOptions>, |
| 91 | + ) -> Result<DatabaseSync, anyhow::Error> { |
| 92 | + let options = options.unwrap_or_default(); |
| 93 | + |
| 94 | + let db = if options.open { |
| 95 | + let db = open_db(state, options.read_only, &location)?; |
| 96 | + |
| 97 | + if options.enable_foreign_key_constraints { |
| 98 | + db.execute("PRAGMA foreign_keys = ON", [])?; |
| 99 | + } |
| 100 | + Some(db) |
| 101 | + } else { |
| 102 | + None |
| 103 | + }; |
| 104 | + |
| 105 | + Ok(DatabaseSync { |
| 106 | + conn: Rc::new(RefCell::new(db)), |
| 107 | + location, |
| 108 | + options, |
| 109 | + }) |
| 110 | + } |
| 111 | + |
| 112 | + // Opens the database specified by `location` of this instance. |
| 113 | + // |
| 114 | + // This method should only be used when the database is not opened |
| 115 | + // via the constructor. An exception is thrown if the database is |
| 116 | + // already opened. |
| 117 | + #[fast] |
| 118 | + fn open(&self, state: &mut OpState) -> Result<(), anyhow::Error> { |
| 119 | + if self.conn.borrow().is_some() { |
| 120 | + return Err(anyhow!("Database is already open")); |
| 121 | + } |
| 122 | + |
| 123 | + let db = open_db(state, self.options.read_only, &self.location)?; |
| 124 | + if self.options.enable_foreign_key_constraints { |
| 125 | + db.execute("PRAGMA foreign_keys = ON", [])?; |
| 126 | + } |
| 127 | + |
| 128 | + *self.conn.borrow_mut() = Some(db); |
| 129 | + |
| 130 | + Ok(()) |
| 131 | + } |
| 132 | + |
| 133 | + // Closes the database connection. An exception is thrown if the |
| 134 | + // database is not open. |
| 135 | + #[fast] |
| 136 | + fn close(&self) -> Result<(), anyhow::Error> { |
| 137 | + if self.conn.borrow().is_none() { |
| 138 | + return Err(anyhow!("Database is already closed")); |
| 139 | + } |
| 140 | + |
| 141 | + *self.conn.borrow_mut() = None; |
| 142 | + Ok(()) |
| 143 | + } |
| 144 | + |
| 145 | + // This method allows one or more SQL statements to be executed |
| 146 | + // without returning any results. |
| 147 | + // |
| 148 | + // This method is a wrapper around sqlite3_exec(). |
| 149 | + #[fast] |
| 150 | + fn exec(&self, #[string] sql: &str) -> Result<(), anyhow::Error> { |
| 151 | + let db = self.conn.borrow(); |
| 152 | + let db = db.as_ref().ok_or(anyhow!("Database is already in use"))?; |
| 153 | + |
| 154 | + let mut stmt = db.prepare_cached(sql)?; |
| 155 | + stmt.raw_execute()?; |
| 156 | + |
| 157 | + Ok(()) |
| 158 | + } |
| 159 | + |
| 160 | + // Compiles an SQL statement into a prepared statement. |
| 161 | + // |
| 162 | + // This method is a wrapper around `sqlite3_prepare_v2()`. |
| 163 | + #[cppgc] |
| 164 | + fn prepare( |
| 165 | + &self, |
| 166 | + #[string] sql: &str, |
| 167 | + ) -> Result<StatementSync, anyhow::Error> { |
| 168 | + let db = self.conn.borrow(); |
| 169 | + let db = db.as_ref().ok_or(anyhow!("Database is already in use"))?; |
| 170 | + |
| 171 | + // SAFETY: lifetime of the connection is guaranteed by reference |
| 172 | + // counting. |
| 173 | + let raw_handle = unsafe { db.handle() }; |
| 174 | + |
| 175 | + let mut raw_stmt = std::ptr::null_mut(); |
| 176 | + |
| 177 | + // SAFETY: `sql` points to a valid memory location and its length |
| 178 | + // is correct. |
| 179 | + let r = unsafe { |
| 180 | + libsqlite3_sys::sqlite3_prepare_v2( |
| 181 | + raw_handle, |
| 182 | + sql.as_ptr() as *const _, |
| 183 | + sql.len() as i32, |
| 184 | + &mut raw_stmt, |
| 185 | + std::ptr::null_mut(), |
| 186 | + ) |
| 187 | + }; |
| 188 | + |
| 189 | + if r != libsqlite3_sys::SQLITE_OK { |
| 190 | + return Err(anyhow!("Failed to prepare statement")); |
| 191 | + } |
| 192 | + |
| 193 | + Ok(StatementSync { |
| 194 | + inner: raw_stmt, |
| 195 | + db: self.conn.clone(), |
| 196 | + use_big_ints: Cell::new(false), |
| 197 | + }) |
| 198 | + } |
| 199 | +} |
0 commit comments