-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(ext/node): implement node:sqlite
#27308
Merged
Merged
Changes from 25 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
0ab878c
init
littledivy 87de655
lets see
littledivy 72c96bf
more
littledivy 87574d2
changes
littledivy 3279935
in the mirrorrrr tsh tshh
littledivy bf6825e
bench
littledivy 509bd95
:sparkles:
littledivy 11c4d61
docs
littledivy 57c29c3
use git
littledivy 95763d3
Merge branch 'main' into sqlite_node_cppgc
littledivy 0087380
setReadBigints
littledivy 9e7306a
core
littledivy 9e37da4
lint ks
littledivy d104b0b
copyright header
littledivy a9f85a7
aarch64 ptr type
littledivy e21982d
perf
littledivy 574892a
update test
littledivy f0409a6
lint
littledivy 636a6c3
deno_core 0.326.0
littledivy a43ea7a
update comments
littledivy 0c0a3e6
add tests
littledivy 58f348b
Merge branch 'main' into sqlite_node_cppgc
littledivy 83c6bfd
Merge branch 'main' of github.com:denoland/deno into sqlite_node_cppgc
littledivy f9654b3
huh
littledivy 8b030f3
Merge branch 'main' of github.com:denoland/deno into sqlite_node_cppgc
littledivy fa2a41e
Merge branch 'main' into sqlite_node_cppgc
littledivy da2bf5f
merge
littledivy 23a657d
x
littledivy f3ad511
x
littledivy bac9d03
copyright
littledivy 006e364
Merge branch 'main' into sqlite_node_cppgc
littledivy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
// deno-lint-ignore-file no-console | ||
|
||
import { DatabaseSync } from "node:sqlite"; | ||
import fs from "node:fs"; | ||
|
||
function bench(name, fun, count = 10000) { | ||
const start = Date.now(); | ||
for (let i = 0; i < count; i++) fun(); | ||
const elapsed = Date.now() - start; | ||
const rate = Math.floor(count / (elapsed / 1000)); | ||
console.log(` ${name}: time ${elapsed} ms rate ${rate}`); | ||
} | ||
|
||
for (const name of [":memory:", "test.db"]) { | ||
console.log(`Benchmarking ${name}`); | ||
try { | ||
fs.unlinkSync(name); | ||
} catch { | ||
// Ignore | ||
} | ||
|
||
const db = new DatabaseSync(name); | ||
db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)"); | ||
|
||
bench("prepare", () => db.prepare("SELECT * FROM test")); | ||
bench("exec", () => db.exec("INSERT INTO test (name) VALUES ('foo')")); | ||
|
||
const stmt = db.prepare("SELECT * FROM test"); | ||
bench("get", () => stmt.get()); | ||
|
||
const stmt2 = db.prepare("SELECT * FROM test WHERE id = ?"); | ||
bench("get (integer bind)", () => stmt2.get(1)); | ||
|
||
bench("all", () => stmt.all(), 1000); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
|
||
use std::cell::Cell; | ||
use std::cell::RefCell; | ||
use std::rc::Rc; | ||
|
||
use deno_core::op2; | ||
use deno_core::GarbageCollected; | ||
use serde::Deserialize; | ||
|
||
use super::SqliteError; | ||
use super::StatementSync; | ||
|
||
#[derive(Deserialize)] | ||
#[serde(rename_all = "camelCase")] | ||
struct DatabaseSyncOptions { | ||
#[serde(default = "true_fn")] | ||
open: bool, | ||
#[serde(default = "true_fn")] | ||
enable_foreign_key_constraints: bool, | ||
} | ||
|
||
fn true_fn() -> bool { | ||
true | ||
} | ||
|
||
impl Default for DatabaseSyncOptions { | ||
fn default() -> Self { | ||
DatabaseSyncOptions { | ||
open: true, | ||
enable_foreign_key_constraints: true, | ||
} | ||
} | ||
} | ||
|
||
pub struct DatabaseSync { | ||
conn: Rc<RefCell<Option<rusqlite::Connection>>>, | ||
options: DatabaseSyncOptions, | ||
location: String, | ||
} | ||
|
||
impl GarbageCollected for DatabaseSync {} | ||
|
||
// Represents a single connection to a SQLite database. | ||
#[op2] | ||
impl DatabaseSync { | ||
// Constructs a new `DatabaseSync` instance. | ||
// | ||
// A SQLite database can be stored in a file or in memory. To | ||
// use a file-backed database, the `location` should be a path. | ||
// To use an in-memory database, the `location` should be special | ||
// name ":memory:". | ||
#[constructor] | ||
#[cppgc] | ||
fn new( | ||
#[string] location: String, | ||
#[serde] options: Option<DatabaseSyncOptions>, | ||
bartlomieju marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) -> Result<DatabaseSync, SqliteError> { | ||
let options = options.unwrap_or_default(); | ||
|
||
let db = if options.open { | ||
let db = rusqlite::Connection::open(&location)?; | ||
if options.enable_foreign_key_constraints { | ||
db.execute("PRAGMA foreign_keys = ON", [])?; | ||
} | ||
Some(db) | ||
} else { | ||
None | ||
}; | ||
|
||
Ok(DatabaseSync { | ||
conn: Rc::new(RefCell::new(db)), | ||
location, | ||
options, | ||
}) | ||
} | ||
|
||
// Opens the database specified by `location` of this instance. | ||
// | ||
// This method should only be used when the database is not opened | ||
// via the constructor. An exception is thrown if the database is | ||
// already opened. | ||
#[fast] | ||
fn open(&self) -> Result<(), SqliteError> { | ||
if self.conn.borrow().is_some() { | ||
return Err(SqliteError::AlreadyOpen); | ||
} | ||
|
||
let db = rusqlite::Connection::open(&self.location)?; | ||
if self.options.enable_foreign_key_constraints { | ||
db.execute("PRAGMA foreign_keys = ON", [])?; | ||
} | ||
|
||
*self.conn.borrow_mut() = Some(db); | ||
|
||
Ok(()) | ||
} | ||
|
||
// Closes the database connection. An exception is thrown if the | ||
// database is not open. | ||
#[fast] | ||
fn close(&self) -> Result<(), SqliteError> { | ||
if self.conn.borrow().is_none() { | ||
return Err(SqliteError::AlreadyClosed); | ||
} | ||
|
||
*self.conn.borrow_mut() = None; | ||
Ok(()) | ||
} | ||
|
||
// This method allows one or more SQL statements to be executed | ||
// without returning any results. | ||
// | ||
// This method is a wrapper around sqlite3_exec(). | ||
#[fast] | ||
fn exec(&self, #[string] sql: &str) -> Result<(), SqliteError> { | ||
let db = self.conn.borrow(); | ||
let db = db.as_ref().ok_or(SqliteError::InUse)?; | ||
|
||
let mut stmt = db.prepare_cached(sql)?; | ||
stmt.raw_execute()?; | ||
|
||
Ok(()) | ||
} | ||
|
||
// Compiles an SQL statement into a prepared statement. | ||
// | ||
// This method is a wrapper around `sqlite3_prepare_v2()`. | ||
#[cppgc] | ||
fn prepare(&self, #[string] sql: &str) -> Result<StatementSync, SqliteError> { | ||
let db = self.conn.borrow(); | ||
let db = db.as_ref().ok_or(SqliteError::InUse)?; | ||
|
||
// SAFETY: lifetime of the connection is guaranteed by reference | ||
// counting. | ||
let raw_handle = unsafe { db.handle() }; | ||
|
||
let mut raw_stmt = std::ptr::null_mut(); | ||
|
||
// SAFETY: `sql` points to a valid memory location and its length | ||
// is correct. | ||
let r = unsafe { | ||
libsqlite3_sys::sqlite3_prepare_v2( | ||
raw_handle, | ||
sql.as_ptr() as *const _, | ||
sql.len() as i32, | ||
&mut raw_stmt, | ||
std::ptr::null_mut(), | ||
) | ||
}; | ||
|
||
if r != libsqlite3_sys::SQLITE_OK { | ||
return Err(SqliteError::PrepareFailed); | ||
} | ||
|
||
Ok(StatementSync { | ||
inner: raw_stmt, | ||
db: self.conn.clone(), | ||
use_big_ints: Cell::new(false), | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. | ||
|
||
mod database; | ||
mod statement; | ||
|
||
pub use database::DatabaseSync; | ||
pub use statement::StatementSync; | ||
|
||
#[derive(Debug, thiserror::Error)] | ||
pub enum SqliteError { | ||
#[error(transparent)] | ||
SqliteError(#[from] rusqlite::Error), | ||
#[error("Database is already in use")] | ||
InUse, | ||
#[error("Failed to step statement")] | ||
FailedStep, | ||
#[error("Failed to bind parameter. {0}")] | ||
FailedBind(&'static str), | ||
#[error("Unknown column type")] | ||
UnknownColumnType, | ||
#[error("Failed to get SQL")] | ||
GetSqlFailed, | ||
#[error("Database is already closed")] | ||
AlreadyClosed, | ||
#[error("Database is already open")] | ||
AlreadyOpen, | ||
#[error("Failed to prepare statement")] | ||
PrepareFailed, | ||
#[error("Invalid constructor")] | ||
InvalidConstructor, | ||
#[error(transparent)] | ||
Other(deno_core::error::AnyError), | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unrelated to this PR, but... we should have a
deno.json
file incli/bench
to run various benchmarks. I never remember how to run them and it feels like half of them are already code-rotted.