bind/java: Rename to Turso

This commit is contained in:
Diego Reis 2025-07-03 02:25:23 -03:00
parent 3bd5d4c732
commit 4b32577f80
48 changed files with 455 additions and 409 deletions

18
Cargo.lock generated
View file

@ -1717,15 +1717,6 @@ dependencies = [
"turso_core",
]
[[package]]
name = "limbo-java"
version = "0.1.1"
dependencies = [
"jni",
"thiserror 2.0.12",
"turso_core",
]
[[package]]
name = "limbo-wasm"
version = "0.1.1"
@ -3637,6 +3628,15 @@ dependencies = [
"turso_core",
]
[[package]]
name = "turso-java"
version = "0.1.1"
dependencies = [
"jni",
"thiserror 2.0.12",
"turso_core",
]
[[package]]
name = "turso_cli"
version = "0.1.1"

View file

@ -24,6 +24,7 @@ out/
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
**/debug/**
### NetBeans ###
/nbproject/private/
@ -38,5 +39,5 @@ bin/
### Mac OS ###
.DS_Store
### limbo builds ###
### turso builds ###
libs

View file

@ -1,5 +1,5 @@
[package]
name = "limbo-java"
name = "turso-java"
version.workspace = true
authors.workspace = true
edition.workspace = true
@ -8,7 +8,7 @@ repository.workspace = true
publish = false
[lib]
name = "_limbo_java"
name = "_turso_java"
crate-type = ["cdylib"]
path = "rs_src/lib.rs"

View file

@ -16,29 +16,29 @@ macos_x86:
@echo "Building release version for macOS x86_64..."
@mkdir -p $(TEMP_DIR) $(MACOS_X86_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target x86_64-apple-darwin
@cp $(TEMP_DIR)/x86_64-apple-darwin/release/lib_limbo_java.dylib $(MACOS_X86_DIR)
@cp $(TEMP_DIR)/x86_64-apple-darwin/release/lib_turso_java.dylib $(MACOS_X86_DIR)
@rm -rf $(TEMP_DIR)
macos_arm64:
@echo "Building release version for macOS ARM64..."
@mkdir -p $(TEMP_DIR) $(MACOS_ARM64_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target aarch64-apple-darwin
@cp $(TEMP_DIR)/aarch64-apple-darwin/release/lib_limbo_java.dylib $(MACOS_ARM64_DIR)
@cp $(TEMP_DIR)/aarch64-apple-darwin/release/lib_turso_java.dylib $(MACOS_ARM64_DIR)
@rm -rf $(TEMP_DIR)
# windows generates file with name `_limbo_java.dll` unlike others, so we manually add prefix
# windows generates file with name `_turso_java.dll` unlike others, so we manually add prefix
windows:
@echo "Building release version for Windows..."
@mkdir -p $(TEMP_DIR) $(WINDOWS_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target x86_64-pc-windows-gnu
@cp $(TEMP_DIR)/x86_64-pc-windows-gnu/release/_limbo_java.dll $(WINDOWS_DIR)/lib_limbo_java.dll
@cp $(TEMP_DIR)/x86_64-pc-windows-gnu/release/_turso_java.dll $(WINDOWS_DIR)/lib_turso_java.dll
@rm -rf $(TEMP_DIR)
linux_x86:
@echo "Building release version for linux x86_64..."
@mkdir -p $(TEMP_DIR) $(LINUX_X86_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target x86_64-unknown-linux-gnu
@cp $(TEMP_DIR)/x86_64-unknown-linux-gnu/release/lib_limbo_java.d $(LINUX_X86_DIR)
@cp $(TEMP_DIR)/x86_64-unknown-linux-gnu/release/lib_turso_java.d $(LINUX_X86_DIR)
@rm -rf $(TEMP_DIR)
lint:
@ -51,7 +51,7 @@ test: lint build_test
./gradlew test
build_test:
CARGO_TARGET_DIR=src/test/resources/limbo cargo build
CARGO_TARGET_DIR=src/test/resources/turso cargo build
publish_local:
./gradlew clean publishToMavenLocal

View file

@ -1,6 +1,6 @@
# Limbo JDBC Driver
# Turso JDBC Driver
The Limbo JDBC driver is a library for accessing and creating Limbo database files using Java.
The Turso JDBC driver is a library for accessing and creating Turso database files using Java.
## Project Status
@ -16,12 +16,12 @@ maven local to use it.
### Build jar and publish to maven local
```shell
$ cd bindings/java
$ cd bindings/java
# Please select the appropriate target platform, currently supports `macos_x86`, `macos_arm64`, `windows` and `linux_x86`
$ make macos_x86
# deploy to maven local
# deploy to maven local
$ make publish_local
```
@ -29,12 +29,12 @@ Now you can use the dependency as follows:
```kotlin
dependencies {
implementation("tech.turso:limbo:0.0.1-SNAPSHOT")
implementation("tech.turso:turso:0.0.1-SNAPSHOT")
}
```
## Code style
- Favor composition over inheritance. For example, `JDBC4Connection` doesn't implement `LimboConnection`. Instead,
it includes `LimboConnection` as a field. This approach allows us to preserve the characteristics of Limbo using
`LimboConnection` easily while maintaining interoperability with the Java world using `JDBC4Connection`.
- Favor composition over inheritance. For example, `JDBC4Connection` doesn't implement `TursoConnection`. Instead,
it includes `TursoConnection` as a field. This approach allows us to preserve the characteristics of Turso using
`TursoConnection` easily while maintaining interoperability with the Java world using `JDBC4Connection`.

View file

@ -27,7 +27,7 @@ publishing {
create<MavenPublication>("mavenJava") {
from(components["java"])
groupId = "tech.turso"
artifactId = "limbo"
artifactId = "turso"
version = "0.0.1-SNAPSHOT"
}
}
@ -49,10 +49,10 @@ dependencies {
}
application {
val limboSystemLibraryPath = System.getenv("LIMBO_LIBRARY_PATH")
if (limboSystemLibraryPath != null) {
val tursoSystemLibraryPath = System.getenv("TURSO_LIBRARY_PATH")
if (tursoSystemLibraryPath != null) {
applicationDefaultJvmArgs = listOf(
"-Djava.library.path=${System.getProperty("java.library.path")}:$limboSystemLibraryPath"
"-Djava.library.path=${System.getProperty("java.library.path")}:$tursoSystemLibraryPath"
)
}
}
@ -66,7 +66,7 @@ tasks.jar {
sourceSets {
test {
resources {
file("src/main/resource/limbo-jdbc.properties")
file("src/main/resource/turso-jdbc.properties")
}
}
}
@ -76,7 +76,7 @@ tasks.test {
// In order to find rust built file under resources, we need to set it as system path
systemProperty(
"java.library.path",
"${System.getProperty("java.library.path")}:$projectDir/src/test/resources/limbo/debug"
"${System.getProperty("java.library.path")}:$projectDir/src/test/resources/turso/debug"
)
// For our fancy test logging
@ -143,6 +143,7 @@ spotless {
java {
target("**/*.java")
targetExclude(layout.buildDirectory.dir("**/*.java").get().asFile)
targetExclude("example/**/*.java")
removeUnusedImports()
googleJavaFormat("1.7") // or use eclipse().configFile("path/to/eclipse-format.xml")
}

View file

@ -11,7 +11,7 @@ repositories {
}
dependencies {
implementation("tech.turso:limbo:0.0.1-SNAPSHOT")
implementation("tech.turso:turso:0.0.1-SNAPSHOT")
testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
}

View file

@ -6,22 +6,33 @@ import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
Statement stmt =
conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);
stmt.execute("CREATE TABLE users (id INT PRIMARY KEY, username TEXT);");
stmt.execute("INSERT INTO users VALUES (1, 'limbo');");
stmt.execute("INSERT INTO users VALUES (2, 'turso');");
stmt.execute("INSERT INTO users VALUES (3, 'who knows');");
stmt.execute("SELECT * FROM users");
System.out.println(
"result: " + stmt.getResultSet().getInt(1) + ", " + stmt.getResultSet().getString(2));
} catch (Exception e) {
System.out.println("Error: " + e);
public static void main(String[] args) {
try (
Connection conn = DriverManager.getConnection(
"jdbc:turso:sample.db"
);
) {
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT
);
stmt.execute(
"CREATE TABLE users (id INT PRIMARY KEY, username TEXT);"
);
stmt.execute("INSERT INTO users VALUES (1, 'turso');");
stmt.execute("INSERT INTO users VALUES (2, 'turso');");
stmt.execute("INSERT INTO users VALUES (3, 'who knows');");
stmt.execute("SELECT * FROM users");
System.out.println(
"result: " +
stmt.getResultSet().getInt(1) +
", " +
stmt.getResultSet().getString(2)
);
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
}

View file

@ -2,7 +2,7 @@ use jni::errors::{Error, JniError};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum LimboError {
pub enum TursoError {
#[error("Custom error: `{0}`")]
CustomError(String),
@ -16,19 +16,19 @@ pub enum LimboError {
JNIErrors(Error),
}
impl From<turso_core::LimboError> for LimboError {
impl From<turso_core::LimboError> for TursoError {
fn from(_value: turso_core::LimboError) -> Self {
todo!()
}
}
impl From<LimboError> for JniError {
fn from(value: LimboError) -> Self {
impl From<TursoError> for JniError {
fn from(value: TursoError) -> Self {
match value {
LimboError::CustomError(_)
| LimboError::InvalidDatabasePointer
| LimboError::InvalidConnectionPointer
| LimboError::JNIErrors(_) => {
TursoError::CustomError(_)
| TursoError::InvalidDatabasePointer
| TursoError::InvalidConnectionPointer
| TursoError::JNIErrors(_) => {
eprintln!("Error occurred: {:?}", value);
JniError::Other(-1)
}
@ -36,13 +36,13 @@ impl From<LimboError> for JniError {
}
}
impl From<jni::errors::Error> for LimboError {
impl From<jni::errors::Error> for TursoError {
fn from(value: jni::errors::Error) -> Self {
LimboError::JNIErrors(value)
TursoError::JNIErrors(value)
}
}
pub type Result<T> = std::result::Result<T, LimboError>;
pub type Result<T> = std::result::Result<T, TursoError>;
pub const SQLITE_OK: i32 = 0; // Successful result
pub const SQLITE_ERROR: i32 = 1; // Generic error
@ -106,6 +106,6 @@ pub const SQLITE_BLOB: i32 = 4;
#[allow(dead_code)]
pub const SQLITE_NULL: i32 = 5;
pub const LIMBO_FAILED_TO_PARSE_BYTE_ARRAY: i32 = 1100;
pub const LIMBO_FAILED_TO_PREPARE_STATEMENT: i32 = 1200;
pub const LIMBO_ETC: i32 = 9999;
pub const TURSO_FAILED_TO_PARSE_BYTE_ARRAY: i32 = 1100;
pub const TURSO_FAILED_TO_PREPARE_STATEMENT: i32 = 1200;
pub const TURSO_ETC: i32 = 9999;

View file

@ -1,5 +1,5 @@
mod errors;
mod limbo_connection;
mod limbo_db;
mod limbo_statement;
mod turso_connection;
mod turso_db;
mod turso_statement;
mod utils;

View file

@ -1,8 +1,8 @@
use crate::errors::{
LimboError, Result, LIMBO_ETC, LIMBO_FAILED_TO_PARSE_BYTE_ARRAY,
LIMBO_FAILED_TO_PREPARE_STATEMENT,
Result, TursoError, TURSO_ETC, TURSO_FAILED_TO_PARSE_BYTE_ARRAY,
TURSO_FAILED_TO_PREPARE_STATEMENT,
};
use crate::limbo_statement::LimboStatement;
use crate::turso_statement::TursoStatement;
use crate::utils::{set_err_msg_and_throw_exception, utf8_byte_arr_to_str};
use jni::objects::{JByteArray, JObject};
use jni::sys::jlong;
@ -11,14 +11,14 @@ use std::sync::Arc;
use turso_core::Connection;
#[derive(Clone)]
pub struct LimboConnection {
pub struct TursoConnection {
pub(crate) conn: Arc<Connection>,
pub(crate) io: Arc<dyn turso_core::IO>,
}
impl LimboConnection {
impl TursoConnection {
pub fn new(conn: Arc<Connection>, io: Arc<dyn turso_core::IO>) -> Self {
LimboConnection { conn, io }
TursoConnection { conn, io }
}
#[allow(clippy::wrong_self_convention)]
@ -27,38 +27,38 @@ impl LimboConnection {
}
pub fn drop(ptr: jlong) {
let _boxed = unsafe { Box::from_raw(ptr as *mut LimboConnection) };
let _boxed = unsafe { Box::from_raw(ptr as *mut TursoConnection) };
}
}
pub fn to_limbo_connection(ptr: jlong) -> Result<&'static mut LimboConnection> {
pub fn to_turso_connection(ptr: jlong) -> Result<&'static mut TursoConnection> {
if ptr == 0 {
Err(LimboError::InvalidConnectionPointer)
Err(TursoError::InvalidConnectionPointer)
} else {
unsafe { Ok(&mut *(ptr as *mut LimboConnection)) }
unsafe { Ok(&mut *(ptr as *mut TursoConnection)) }
}
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboConnection__1close<'local>(
pub extern "system" fn Java_tech_turso_core_TursoConnection__1close<'local>(
_env: JNIEnv<'local>,
_obj: JObject<'local>,
connection_ptr: jlong,
) {
LimboConnection::drop(connection_ptr);
TursoConnection::drop(connection_ptr);
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboConnection_prepareUtf8<'local>(
pub extern "system" fn Java_tech_turso_core_TursoConnection_prepareUtf8<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
connection_ptr: jlong,
sql_bytes: JByteArray<'local>,
) -> jlong {
let connection = match to_limbo_connection(connection_ptr) {
let connection = match to_turso_connection(connection_ptr) {
Ok(conn) => conn,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return 0;
}
};
@ -69,7 +69,7 @@ pub extern "system" fn Java_tech_turso_core_LimboConnection_prepareUtf8<'local>(
set_err_msg_and_throw_exception(
&mut env,
obj,
LIMBO_FAILED_TO_PARSE_BYTE_ARRAY,
TURSO_FAILED_TO_PARSE_BYTE_ARRAY,
e.to_string(),
);
return 0;
@ -77,12 +77,12 @@ pub extern "system" fn Java_tech_turso_core_LimboConnection_prepareUtf8<'local>(
};
match connection.conn.prepare(sql) {
Ok(stmt) => LimboStatement::new(stmt, connection.clone()).to_ptr(),
Ok(stmt) => TursoStatement::new(stmt, connection.clone()).to_ptr(),
Err(e) => {
set_err_msg_and_throw_exception(
&mut env,
obj,
LIMBO_FAILED_TO_PREPARE_STATEMENT,
TURSO_FAILED_TO_PREPARE_STATEMENT,
e.to_string(),
);
0

View file

@ -1,5 +1,5 @@
use crate::errors::{LimboError, Result, LIMBO_ETC};
use crate::limbo_connection::LimboConnection;
use crate::errors::{Result, TursoError, TURSO_ETC};
use crate::turso_connection::TursoConnection;
use crate::utils::set_err_msg_and_throw_exception;
use jni::objects::{JByteArray, JObject};
use jni::sys::{jint, jlong};
@ -7,14 +7,14 @@ use jni::JNIEnv;
use std::sync::Arc;
use turso_core::Database;
struct LimboDB {
struct TursoDB {
db: Arc<Database>,
io: Arc<dyn turso_core::IO>,
}
impl LimboDB {
impl TursoDB {
pub fn new(db: Arc<Database>, io: Arc<dyn turso_core::IO>) -> Self {
LimboDB { db, io }
TursoDB { db, io }
}
#[allow(clippy::wrong_self_convention)]
@ -23,21 +23,21 @@ impl LimboDB {
}
pub fn drop(ptr: jlong) {
let _boxed = unsafe { Box::from_raw(ptr as *mut LimboDB) };
let _boxed = unsafe { Box::from_raw(ptr as *mut TursoDB) };
}
}
fn to_limbo_db(ptr: jlong) -> Result<&'static mut LimboDB> {
fn to_turso_db(ptr: jlong) -> Result<&'static mut TursoDB> {
if ptr == 0 {
Err(LimboError::InvalidDatabasePointer)
Err(TursoError::InvalidDatabasePointer)
} else {
unsafe { Ok(&mut *(ptr as *mut LimboDB)) }
unsafe { Ok(&mut *(ptr as *mut TursoDB)) }
}
}
#[no_mangle]
#[allow(clippy::arc_with_non_send_sync)]
pub extern "system" fn Java_tech_turso_core_LimboDB_openUtf8<'local>(
pub extern "system" fn Java_tech_turso_core_TursoDB_openUtf8<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
file_path_byte_arr: JByteArray<'local>,
@ -46,7 +46,7 @@ pub extern "system" fn Java_tech_turso_core_LimboDB_openUtf8<'local>(
let io = match turso_core::PlatformIO::new() {
Ok(io) => Arc::new(io),
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return -1;
}
};
@ -58,12 +58,12 @@ pub extern "system" fn Java_tech_turso_core_LimboDB_openUtf8<'local>(
Ok(bytes) => match String::from_utf8(bytes) {
Ok(s) => s,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return -1;
}
},
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return -1;
}
};
@ -71,43 +71,43 @@ pub extern "system" fn Java_tech_turso_core_LimboDB_openUtf8<'local>(
let db = match Database::open_file(io.clone(), &path, false, false) {
Ok(db) => db,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return -1;
}
};
LimboDB::new(db, io).to_ptr()
TursoDB::new(db, io).to_ptr()
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboDB_connect0<'local>(
pub extern "system" fn Java_tech_turso_core_TursoDB_connect0<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
db_pointer: jlong,
) -> jlong {
let db = match to_limbo_db(db_pointer) {
let db = match to_turso_db(db_pointer) {
Ok(db) => db,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return 0;
}
};
let conn = LimboConnection::new(db.db.connect().unwrap(), db.io.clone());
let conn = TursoConnection::new(db.db.connect().unwrap(), db.io.clone());
conn.to_ptr()
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboDB_close0<'local>(
pub extern "system" fn Java_tech_turso_core_TursoDB_close0<'local>(
_env: JNIEnv<'local>,
_obj: JObject<'local>,
db_pointer: jlong,
) {
LimboDB::drop(db_pointer);
TursoDB::drop(db_pointer);
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboDB_throwJavaException<'local>(
pub extern "system" fn Java_tech_turso_core_TursoDB_throwJavaException<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
error_code: jint,

View file

@ -1,6 +1,6 @@
use crate::errors::{LimboError, LIMBO_ETC};
use crate::errors::{Result, SQLITE_ERROR, SQLITE_OK};
use crate::limbo_connection::LimboConnection;
use crate::errors::{TursoError, TURSO_ETC};
use crate::turso_connection::TursoConnection;
use crate::utils::set_err_msg_and_throw_exception;
use jni::objects::{JByteArray, JObject, JObjectArray, JString, JValue};
use jni::sys::{jdouble, jint, jlong};
@ -16,14 +16,14 @@ pub const STEP_RESULT_ID_INTERRUPT: i32 = 40;
pub const STEP_RESULT_ID_BUSY: i32 = 50;
pub const STEP_RESULT_ID_ERROR: i32 = 60;
pub struct LimboStatement {
pub struct TursoStatement {
pub(crate) stmt: Statement,
pub(crate) connection: LimboConnection,
pub(crate) connection: TursoConnection,
}
impl LimboStatement {
pub fn new(stmt: Statement, connection: LimboConnection) -> Self {
LimboStatement { stmt, connection }
impl TursoStatement {
pub fn new(stmt: Statement, connection: TursoConnection) -> Self {
TursoStatement { stmt, connection }
}
#[allow(clippy::wrong_self_convention)]
@ -32,71 +32,71 @@ impl LimboStatement {
}
pub fn drop(ptr: jlong) {
let _boxed = unsafe { Box::from_raw(ptr as *mut LimboStatement) };
let _boxed = unsafe { Box::from_raw(ptr as *mut TursoStatement) };
}
}
pub fn to_limbo_statement(ptr: jlong) -> Result<&'static mut LimboStatement> {
pub fn to_turso_statement(ptr: jlong) -> Result<&'static mut TursoStatement> {
if ptr == 0 {
Err(LimboError::InvalidConnectionPointer)
Err(TursoError::InvalidConnectionPointer)
} else {
unsafe { Ok(&mut *(ptr as *mut LimboStatement)) }
unsafe { Ok(&mut *(ptr as *mut TursoStatement)) }
}
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_step<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_step<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
stmt_ptr: jlong,
) -> JObject<'local> {
let stmt = match to_limbo_statement(stmt_ptr) {
let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
return to_limbo_step_result(&mut env, STEP_RESULT_ID_ERROR, None);
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return to_turso_step_result(&mut env, STEP_RESULT_ID_ERROR, None);
}
};
loop {
let step_result = match stmt.stmt.step() {
Ok(result) => result,
Err(_) => return to_limbo_step_result(&mut env, STEP_RESULT_ID_ERROR, None),
Err(_) => return to_turso_step_result(&mut env, STEP_RESULT_ID_ERROR, None),
};
match step_result {
StepResult::Row => {
let row = stmt.stmt.row().unwrap();
return match row_to_obj_array(&mut env, row) {
Ok(row) => to_limbo_step_result(&mut env, STEP_RESULT_ID_ROW, Some(row)),
Ok(row) => to_turso_step_result(&mut env, STEP_RESULT_ID_ROW, Some(row)),
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
to_limbo_step_result(&mut env, STEP_RESULT_ID_ERROR, None)
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
to_turso_step_result(&mut env, STEP_RESULT_ID_ERROR, None)
}
};
}
StepResult::IO => {
if let Err(e) = stmt.connection.io.run_once() {
set_err_msg_and_throw_exception(&mut env, obj, LIMBO_ETC, e.to_string());
return to_limbo_step_result(&mut env, STEP_RESULT_ID_ERROR, None);
set_err_msg_and_throw_exception(&mut env, obj, TURSO_ETC, e.to_string());
return to_turso_step_result(&mut env, STEP_RESULT_ID_ERROR, None);
}
}
StepResult::Done => return to_limbo_step_result(&mut env, STEP_RESULT_ID_DONE, None),
StepResult::Done => return to_turso_step_result(&mut env, STEP_RESULT_ID_DONE, None),
StepResult::Interrupt => {
return to_limbo_step_result(&mut env, STEP_RESULT_ID_INTERRUPT, None)
return to_turso_step_result(&mut env, STEP_RESULT_ID_INTERRUPT, None)
}
StepResult::Busy => return to_limbo_step_result(&mut env, STEP_RESULT_ID_BUSY, None),
StepResult::Busy => return to_turso_step_result(&mut env, STEP_RESULT_ID_BUSY, None),
}
}
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement__1close<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement__1close<'local>(
_env: JNIEnv<'local>,
_obj: JObject<'local>,
stmt_ptr: jlong,
) {
LimboStatement::drop(stmt_ptr);
TursoStatement::drop(stmt_ptr);
}
fn row_to_obj_array<'local>(
@ -126,12 +126,12 @@ fn row_to_obj_array<'local>(
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_columns<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_columns<'local>(
mut env: JNIEnv<'local>,
_obj: JObject<'local>,
stmt_ptr: jlong,
) -> JObject<'local> {
let stmt = to_limbo_statement(stmt_ptr).unwrap();
let stmt = to_turso_statement(stmt_ptr).unwrap();
let num_columns = stmt.stmt.num_columns();
let obj_arr: JObjectArray = env
.new_object_array(num_columns as i32, "java/lang/String", JObject::null())
@ -148,13 +148,13 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_columns<'local>(
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_bindNull<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_bindNull<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
stmt_ptr: jlong,
position: jint,
) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) {
let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string());
@ -168,14 +168,14 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_bindNull<'local>(
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_bindLong<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_bindLong<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
stmt_ptr: jlong,
position: jint,
value: jlong,
) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) {
let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string());
@ -191,14 +191,14 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_bindLong<'local>(
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_bindDouble<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_bindDouble<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
stmt_ptr: jlong,
position: jint,
value: jdouble,
) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) {
let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string());
@ -214,14 +214,14 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_bindDouble<'local>(
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_bindText<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_bindText<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
stmt_ptr: jlong,
position: jint,
value: JString<'local>,
) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) {
let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string());
@ -242,14 +242,14 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_bindText<'local>(
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_bindBlob<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_bindBlob<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
stmt_ptr: jlong,
position: jint,
value: JByteArray<'local>,
) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) {
let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string());
@ -268,12 +268,12 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_bindBlob<'local>(
}
#[no_mangle]
pub extern "system" fn Java_tech_turso_core_LimboStatement_totalChanges<'local>(
pub extern "system" fn Java_tech_turso_core_TursoStatement_totalChanges<'local>(
mut env: JNIEnv<'local>,
obj: JObject<'local>,
stmt_ptr: jlong,
) -> jlong {
let stmt = match to_limbo_statement(stmt_ptr) {
let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt,
Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string());
@ -284,10 +284,10 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_totalChanges<'local>(
stmt.connection.conn.total_changes()
}
/// Converts an optional `JObject` into Java's `LimboStepResult`.
/// Converts an optional `JObject` into Java's `TursoStepResult`.
///
/// This function takes an optional `JObject` and converts it into a Java object
/// of type `LimboStepResult`. The conversion is done by creating a new Java object with the
/// of type `TursoStepResult`. The conversion is done by creating a new Java object with the
/// appropriate constructor arguments.
///
/// # Arguments
@ -298,9 +298,9 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_totalChanges<'local>(
///
/// # Returns
///
/// A `JObject` representing the `LimboStepResult` in Java. If the object creation fails,
/// A `JObject` representing the `TursoStepResult` in Java. If the object creation fails,
/// a null `JObject` is returned
fn to_limbo_step_result<'local>(
fn to_turso_step_result<'local>(
env: &mut JNIEnv<'local>,
id: i32,
result: Option<JObject<'local>>,
@ -309,12 +309,12 @@ fn to_limbo_step_result<'local>(
if let Some(res) = result {
ctor_args.push(JValue::Object(&res));
env.new_object(
"tech/turso/core/LimboStepResult",
"tech/turso/core/TursoStepResult",
"(I[Ljava/lang/Object;)V",
&ctor_args,
)
} else {
env.new_object("tech/turso/core/LimboStepResult", "(I)V", &ctor_args)
env.new_object("tech/turso/core/TursoStepResult", "(I)V", &ctor_args)
}
.unwrap_or_else(|_| JObject::null())
}

View file

@ -1,4 +1,4 @@
use crate::errors::LimboError;
use crate::errors::TursoError;
use jni::objects::{JByteArray, JObject};
use jni::JNIEnv;
@ -8,9 +8,9 @@ pub(crate) fn utf8_byte_arr_to_str(
) -> crate::errors::Result<String> {
let bytes = env
.convert_byte_array(bytes)
.map_err(|_| LimboError::CustomError("Failed to retrieve bytes".to_string()))?;
.map_err(|_| TursoError::CustomError("Failed to retrieve bytes".to_string()))?;
let str = String::from_utf8(bytes).map_err(|_| {
LimboError::CustomError("Failed to convert utf8 byte array into string".to_string())
TursoError::CustomError("Failed to convert utf8 byte array into string".to_string())
})?;
Ok(str)
}
@ -18,7 +18,7 @@ pub(crate) fn utf8_byte_arr_to_str(
/// Sets the error message and throws a Java exception.
///
/// This function converts the provided error message to a byte array and calls the
/// `throwLimboException` method on the provided Java object to throw an exception.
/// `throwTursoException` method on the provided Java object to throw an exception.
///
/// # Parameters
/// - `env`: The JNI environment.
@ -41,7 +41,7 @@ pub fn set_err_msg_and_throw_exception<'local>(
.expect("Failed to convert to byte array");
match env.call_method(
obj,
"throwLimboException",
"throwTursoException",
"(I[B)V",
&[err_code.into(), (&error_message_bytes).into()],
) {

View file

@ -1 +1 @@
rootProject.name = "limbo"
rootProject.name = "turso"

View file

@ -5,15 +5,16 @@ import java.util.Locale;
import java.util.Properties;
import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboPropertiesHolder;
import tech.turso.core.TursoPropertiesHolder;
import tech.turso.jdbc4.JDBC4Connection;
import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory;
public final class JDBC implements Driver {
private static final Logger logger = LoggerFactory.getLogger(JDBC.class);
private static final String VALID_URL_PREFIX = "jdbc:sqlite:";
private static final String VALID_URL_PREFIX = "jdbc:turso:";
static {
try {
@ -33,7 +34,7 @@ public final class JDBC implements Driver {
}
private static boolean isValidURL(String url) {
return url != null && url.toLowerCase(Locale.ROOT).startsWith(VALID_URL_PREFIX);
return (url != null && url.toLowerCase(Locale.ROOT).startsWith(VALID_URL_PREFIX));
}
private static String extractAddress(String url) {
@ -53,17 +54,17 @@ public final class JDBC implements Driver {
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
return LimboConfig.getDriverPropertyInfo();
return TursoConfig.getDriverPropertyInfo();
}
@Override
public int getMajorVersion() {
return Integer.parseInt(LimboPropertiesHolder.getDriverVersion().split("\\.")[0]);
return Integer.parseInt(TursoPropertiesHolder.getDriverVersion().split("\\.")[0]);
}
@Override
public int getMinorVersion() {
return Integer.parseInt(LimboPropertiesHolder.getDriverVersion().split("\\.")[1]);
return Integer.parseInt(TursoPropertiesHolder.getDriverVersion().split("\\.")[1]);
}
@Override

View file

@ -4,11 +4,12 @@ import java.sql.DriverPropertyInfo;
import java.util.Arrays;
import java.util.Properties;
/** Limbo Configuration. */
public final class LimboConfig {
private final Properties pragma;
/** Turso Configuration. */
public final class TursoConfig {
public LimboConfig(Properties properties) {
private Properties pragma;
public TursoConfig(Properties properties) {
this.pragma = properties;
}
@ -33,6 +34,7 @@ public final class LimboConfig {
public enum Pragma {
;
private final String pragmaName;
private final String description;
private final String[] choices;

View file

@ -10,19 +10,19 @@ import javax.sql.DataSource;
import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck;
/** Provides {@link DataSource} API for configuring Limbo database connection. */
public final class LimboDataSource implements DataSource {
/** Provides {@link DataSource} API for configuring Turso database connection. */
public final class TursoDataSource implements DataSource {
private final LimboConfig limboConfig;
private final TursoConfig tursoConfig;
private final String url;
/**
* Creates a datasource based on the provided configuration.
*
* @param limboConfig The configuration for the datasource.
* @param tursoConfig The configuration for the datasource.
*/
public LimboDataSource(LimboConfig limboConfig, String url) {
this.limboConfig = limboConfig;
public TursoDataSource(TursoConfig tursoConfig, String url) {
this.tursoConfig = tursoConfig;
this.url = url;
}
@ -36,7 +36,7 @@ public final class LimboDataSource implements DataSource {
@Nullable
public Connection getConnection(@Nullable String username, @Nullable String password)
throws SQLException {
Properties properties = limboConfig.toProperties();
Properties properties = tursoConfig.toProperties();
if (username != null) properties.put("user", username);
if (password != null) properties.put("pass", password);
return JDBC.createConnection(url, properties);

View file

@ -2,8 +2,8 @@ package tech.turso;
import tech.turso.core.SqliteCode;
/** Limbo error code. Superset of SQLite3 error code. */
public enum LimboErrorCode {
/** Turso error code. Superset of SQLite3 error code. */
public enum TursoErrorCode {
SQLITE_OK(SqliteCode.SQLITE_OK, "Successful result"),
SQLITE_ERROR(SqliteCode.SQLITE_ERROR, "SQL error or missing database"),
SQLITE_INTERNAL(SqliteCode.SQLITE_INTERNAL, "An internal logic error in SQLite"),
@ -37,9 +37,9 @@ public enum LimboErrorCode {
SQLITE_NULL(SqliteCode.SQLITE_NULL, "Null type"),
UNKNOWN_ERROR(-1, "Unknown error"),
LIMBO_FAILED_TO_PARSE_BYTE_ARRAY(1100, "Failed to parse ut8 byte array"),
LIMBO_FAILED_TO_PREPARE_STATEMENT(1200, "Failed to prepare statement"),
LIMBO_ETC(9999, "Unclassified error");
TURSO_FAILED_TO_PARSE_BYTE_ARRAY(1100, "Failed to parse ut8 byte array"),
TURSO_FAILED_TO_PREPARE_STATEMENT(1200, "Failed to prepare statement"),
TURSO_ETC(9999, "Unclassified error");
public final int code;
public final String message;
@ -48,14 +48,14 @@ public enum LimboErrorCode {
* @param code Error code
* @param message Message for the error.
*/
LimboErrorCode(int code, String message) {
TursoErrorCode(int code, String message) {
this.code = code;
this.message = message;
}
public static LimboErrorCode getErrorCode(int errorCode) {
for (LimboErrorCode limboErrorCode : LimboErrorCode.values()) {
if (errorCode == limboErrorCode.code) return limboErrorCode;
public static TursoErrorCode getErrorCode(int errorCode) {
for (TursoErrorCode tursoErrorCode : TursoErrorCode.values()) {
if (errorCode == tursoErrorCode.code) return tursoErrorCode;
}
return UNKNOWN_ERROR;
@ -63,6 +63,6 @@ public enum LimboErrorCode {
@Override
public String toString() {
return "LimboErrorCode{" + "code=" + code + ", message='" + message + '\'' + '}';
return ("tursoErrorCode{" + "code=" + code + ", message='" + message + '\'' + '}');
}
}

View file

@ -6,37 +6,38 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import tech.turso.annotations.NativeInvocation;
import tech.turso.utils.LimboExceptionUtils;
import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory;
import tech.turso.utils.TursoExceptionUtils;
public final class LimboConnection {
private static final Logger logger = LoggerFactory.getLogger(LimboConnection.class);
public final class TursoConnection {
private static final Logger logger = LoggerFactory.getLogger(TursoConnection.class);
private final String url;
private final long connectionPtr;
private final LimboDB database;
private final TursoDB database;
private boolean closed;
public LimboConnection(String url, String filePath) throws SQLException {
public TursoConnection(String url, String filePath) throws SQLException {
this(url, filePath, new Properties());
}
/**
* Creates a connection to limbo database
* Creates a connection to turso database
*
* @param url e.g. "jdbc:sqlite:fileName"
* @param url e.g. "jdbc:turso:fileName"
* @param filePath path to file
*/
public LimboConnection(String url, String filePath, Properties properties) throws SQLException {
public TursoConnection(String url, String filePath, Properties properties) throws SQLException {
this.url = url;
this.database = open(url, filePath, properties);
this.connectionPtr = this.database.connect();
}
private static LimboDB open(String url, String filePath, Properties properties)
private static TursoDB open(String url, String filePath, Properties properties)
throws SQLException {
return LimboDBFactory.open(url, filePath, properties);
return TursoDBFactory.open(url, filePath, properties);
}
public void checkOpen() throws SQLException {
@ -61,7 +62,7 @@ public final class LimboConnection {
return closed;
}
public LimboDB getDatabase() {
public TursoDB getDatabase() {
return database;
}
@ -72,18 +73,18 @@ public final class LimboConnection {
* @return Pointer to statement.
* @throws SQLException if a database access error occurs.
*/
public LimboStatement prepare(String sql) throws SQLException {
public TursoStatement prepare(String sql) throws SQLException {
logger.trace("DriverManager [{}] [SQLite EXEC] {}", Thread.currentThread().getName(), sql);
byte[] sqlBytes = stringToUtf8ByteArray(sql);
if (sqlBytes == null) {
throw new SQLException("Failed to convert " + sql + " into bytes");
}
return new LimboStatement(sql, prepareUtf8(connectionPtr, sqlBytes));
return new TursoStatement(sql, prepareUtf8(connectionPtr, sqlBytes));
}
private native long prepareUtf8(long connectionPtr, byte[] sqlUtf8) throws SQLException;
// TODO: check whether this is still valid for limbo
// TODO: check whether this is still valid for turso
/**
* Checks whether the type, concurrency, and holdability settings for a {@link ResultSet} are
* supported by the SQLite interface. Supported settings are:
@ -117,8 +118,8 @@ public final class LimboConnection {
* @param errorCode Error code.
* @param errorMessageBytes Error message.
*/
@NativeInvocation(invokedFrom = "limbo_connection.rs")
private void throwLimboException(int errorCode, byte[] errorMessageBytes) throws SQLException {
LimboExceptionUtils.throwLimboException(errorCode, errorMessageBytes);
@NativeInvocation(invokedFrom = "turso_connection.rs")
private void throwTursoException(int errorCode, byte[] errorMessageBytes) throws SQLException {
TursoExceptionUtils.throwTursoException(errorCode, errorMessageBytes);
}
}

View file

@ -7,16 +7,17 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import tech.turso.LimboErrorCode;
import tech.turso.TursoErrorCode;
import tech.turso.annotations.NativeInvocation;
import tech.turso.annotations.VisibleForTesting;
import tech.turso.utils.LimboExceptionUtils;
import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory;
import tech.turso.utils.TursoExceptionUtils;
/** This class provides a thin JNI layer over the SQLite3 C API. */
public final class LimboDB implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(LimboDB.class);
public final class TursoDB implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(TursoDB.class);
// Pointer to database instance
private long dbPointer;
private boolean isOpen;
@ -39,10 +40,10 @@ public final class LimboDB implements AutoCloseable {
* extensions.
*/
enum Architecture {
MACOS_ARM64("libs/macos_arm64/lib_limbo_java.dylib", ".dylib"),
MACOS_X86("libs/macos_x86/lib_limbo_java.dylib", ".dylib"),
LINUX_X86("libs/linux_x86/lib_limbo_java.so", ".so"),
WINDOWS("libs/windows/lib_limbo_java.dll", ".dll"),
MACOS_ARM64("libs/macos_arm64/lib_turso_java.dylib", ".dylib"),
MACOS_X86("libs/macos_x86/lib_turso_java.dylib", ".dylib"),
LINUX_X86("libs/linux_x86/lib_turso_java.so", ".so"),
WINDOWS("libs/windows/lib_turso_java.dll", ".dll"),
UNSUPPORTED("", "");
private final String libPath;
@ -90,7 +91,7 @@ public final class LimboDB implements AutoCloseable {
}
/**
* This method attempts to load the native library required for Limbo operations. It first tries
* This method attempts to load the native library required for turso operations. It first tries
* to load the library from the system's library path using {@link #loadFromSystemPath()}. If that
* fails, it attempts to load the library from the JAR file using {@link #loadFromJar()}. If
* either method succeeds, the `isLoaded` flag is set to true. If both methods fail, an {@link
@ -115,14 +116,14 @@ public final class LimboDB implements AutoCloseable {
/**
* Load the native library from the system path.
*
* <p>This method attempts to load the native library named "_limbo_java" from the system's
* <p>This method attempts to load the native library named "_turso_java" from the system's
* library path. If the library is successfully loaded, the `isLoaded` flag is set to true.
*
* @return true if the library was successfully loaded, false otherwise.
*/
private static boolean loadFromSystemPath() {
try {
System.loadLibrary("_limbo_java");
System.loadLibrary("_turso_java");
return true;
} catch (Throwable t) {
logger.info("Unable to load from default path: {}", String.valueOf(t));
@ -148,7 +149,7 @@ public final class LimboDB implements AutoCloseable {
}
try {
InputStream is = LimboDB.class.getClassLoader().getResourceAsStream(arch.getLibPath());
InputStream is = TursoDB.class.getClassLoader().getResourceAsStream(arch.getLibPath());
assert is != null;
File file = convertInputStreamToFile(is, arch);
System.load(file.getPath());
@ -178,15 +179,15 @@ public final class LimboDB implements AutoCloseable {
}
/**
* @param url e.g. "jdbc:sqlite:fileName
* @param url eTurso.gTursoTurso. "jdbc:turso:fileName
* @param filePath e.g. path to file
*/
public static LimboDB create(String url, String filePath) throws SQLException {
return new LimboDB(url, filePath);
public static TursoDB create(String url, String filePath) throws SQLException {
return new TursoDB(url, filePath);
}
// TODO: receive config as argument
private LimboDB(String url, String filePath) {
private TursoDB(String url, String filePath) {
this.url = url;
this.filePath = filePath;
}
@ -208,14 +209,14 @@ public final class LimboDB implements AutoCloseable {
private void open0(String filePath, int openFlags) throws SQLException {
if (isOpen) {
throw LimboExceptionUtils.buildLimboException(
LimboErrorCode.LIMBO_ETC.code, "Already opened");
throw TursoExceptionUtils.buildTursoException(
TursoErrorCode.TURSO_ETC.code, "Already opened");
}
byte[] filePathBytes = stringToUtf8ByteArray(filePath);
if (filePathBytes == null) {
throw LimboExceptionUtils.buildLimboException(
LimboErrorCode.LIMBO_ETC.code,
throw TursoExceptionUtils.buildTursoException(
TursoErrorCode.TURSO_ETC.code,
"File path cannot be converted to byteArray. File name: " + filePath);
}
@ -250,8 +251,8 @@ public final class LimboDB implements AutoCloseable {
* @param errorCode Error code.
* @param errorMessageBytes Error message.
*/
@NativeInvocation(invokedFrom = "limbo_db.rs")
private void throwLimboException(int errorCode, byte[] errorMessageBytes) throws SQLException {
LimboExceptionUtils.throwLimboException(errorCode, errorMessageBytes);
@NativeInvocation(invokedFrom = "turso_db.rs")
private void throwTursoException(int errorCode, byte[] errorMessageBytes) throws SQLException {
TursoExceptionUtils.throwTursoException(errorCode, errorMessageBytes);
}
}

View file

@ -5,12 +5,12 @@ import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* Factory class for managing and creating instances of {@link LimboDB}. This class ensures that
* multiple instances of {@link LimboDB} with the same URL are not created.
* Factory class for managing and creating instances of {@link TursoDB}. This class ensures that
* multiple instances of {@link TursoDB} with the same URL are not created.
*/
public final class LimboDBFactory {
public final class TursoDBFactory {
private static final ConcurrentHashMap<String, LimboDB> databaseHolder =
private static final ConcurrentHashMap<String, TursoDB> databaseHolder =
new ConcurrentHashMap<>();
/**
@ -20,11 +20,11 @@ public final class LimboDBFactory {
* @param url the URL of the database
* @param filePath the path to the database file
* @param properties additional properties for the database connection
* @return an instance of {@link LimboDB}
* @return an instance of {@link tursoDB}
* @throws SQLException if there is an error opening the connection
* @throws IllegalArgumentException if the fileName is empty
*/
public static LimboDB open(String url, String filePath, Properties properties)
public static TursoDB open(String url, String filePath, Properties properties)
throws SQLException {
if (databaseHolder.containsKey(url)) {
return databaseHolder.get(url);
@ -34,10 +34,10 @@ public final class LimboDBFactory {
throw new IllegalArgumentException("filePath should not be empty");
}
final LimboDB database;
final TursoDB database;
try {
LimboDB.load();
database = LimboDB.create(url, filePath);
TursoDB.load();
database = TursoDB.create(url, filePath);
} catch (Exception e) {
throw new SQLException("Error opening connection", e);
}

View file

@ -7,21 +7,24 @@ import tech.turso.jdbc4.JDBC4DatabaseMetaData;
import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory;
public class LimboPropertiesHolder {
private static final Logger logger = LoggerFactory.getLogger(LimboPropertiesHolder.class);
public class TursoPropertiesHolder {
private static final Logger logger = LoggerFactory.getLogger(TursoPropertiesHolder.class);
private static String driverName = "";
private static String driverVersion = "";
static {
try (InputStream limboJdbcPropStream =
JDBC4DatabaseMetaData.class.getClassLoader().getResourceAsStream("limbo-jdbc.properties")) {
if (limboJdbcPropStream == null) {
throw new IOException("Cannot load limbo-jdbc.properties from jar");
try (InputStream tursoJdbcPropStream =
JDBC4DatabaseMetaData.class
.getClassLoader()
.getResourceAsStream("turso-jdbc.properties"); ) {
if (tursoJdbcPropStream == null) {
throw new IOException("Cannot load turso-jdbc.properties from jar");
}
final Properties properties = new Properties();
properties.load(limboJdbcPropStream);
properties.load(tursoJdbcPropStream);
driverName = properties.getProperty("driverName");
driverVersion = properties.getProperty("driverVersion");
} catch (IOException e) {

View file

@ -7,17 +7,17 @@ import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory;
/**
* A table of data representing limbo database result set, which is generated by executing a
* A table of data representing turso database result set, which is generated by executing a
* statement that queries the database.
*
* <p>A {@link LimboResultSet} object is automatically closed when the {@link LimboStatement} object
* <p>A {@link TursoResultSet} object is automatically closed when the {@link TursoStatement} object
* that generated it is closed or re-executed.
*/
public final class LimboResultSet {
public final class TursoResultSet {
private static final Logger log = LoggerFactory.getLogger(LimboResultSet.class);
private static final Logger log = LoggerFactory.getLogger(TursoResultSet.class);
private final LimboStatement statement;
private final TursoStatement statement;
// Name of the columns
private String[] columnNames = new String[0];
@ -31,13 +31,13 @@ public final class LimboResultSet {
private int row = 0;
private boolean pastLastRow = false;
@Nullable private LimboStepResult lastStepResult;
@Nullable private TursoStepResult lastStepResult;
public static LimboResultSet of(LimboStatement statement) {
return new LimboResultSet(statement);
public static TursoResultSet of(TursoStatement statement) {
return new TursoResultSet(statement);
}
private LimboResultSet(LimboStatement statement) {
private TursoResultSet(TursoStatement statement) {
this.open = true;
this.statement = statement;
}
@ -57,13 +57,13 @@ public final class LimboResultSet {
}
/**
* Moves the cursor forward one row from its current position. A {@link LimboResultSet} cursor is
* Moves the cursor forward one row from its current position. A {@link tursoResultSet} cursor is
* initially positioned before the first fow; the first call to the method <code>next</code> makes
* the first row the current row; the second call makes the second row the current row, and so on.
* When a call to the <code>next</code> method returns <code>false</code>, the cursor is
* positioned after the last row.
*
* <p>Note that limbo only supports <code>ResultSet.TYPE_FORWARD_ONLY</code>, which means that the
* <p>Note that turso only supports <code>ResultSet.TYPE_FORWARD_ONLY</code>, which means that the
* cursor can only move forward.
*/
public boolean next() throws SQLException {
@ -157,7 +157,7 @@ public final class LimboResultSet {
@Override
public String toString() {
return "LimboResultSet{"
return ("tursoResultSet{"
+ "statement="
+ statement
+ ", isEmptyResultSet="
@ -172,6 +172,6 @@ public final class LimboResultSet {
+ pastLastRow
+ ", lastResult="
+ lastStepResult
+ '}';
+ '}');
}
}

View file

@ -3,36 +3,37 @@ package tech.turso.core;
import java.sql.SQLException;
import tech.turso.annotations.NativeInvocation;
import tech.turso.annotations.Nullable;
import tech.turso.utils.LimboExceptionUtils;
import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory;
import tech.turso.utils.TursoExceptionUtils;
/**
* By default, only one <code>resultSet</code> object per <code>LimboStatement</code> can be open at
* By default, only one <code>resultSet</code> object per <code>TursoStatement</code> can be open at
* the same time. Therefore, if the reading of one <code>resultSet</code> object is interleaved with
* the reading of another, each must have been generated by different <code>LimboStatement</code>
* objects. All execution method in the <code>LimboStatement</code> implicitly close the current
* the reading of another, each must have been generated by different <code>TursoStatement</code>
* objects. All execution method in the <code>TursoStatement</code> implicitly close the current
* <code>resultSet</code> object of the statement if an open one exists.
*/
public final class LimboStatement {
private static final Logger log = LoggerFactory.getLogger(LimboStatement.class);
public final class TursoStatement {
private static final Logger log = LoggerFactory.getLogger(TursoStatement.class);
private final String sql;
private final long statementPointer;
private final LimboResultSet resultSet;
private final TursoResultSet resultSet;
private boolean closed;
// TODO: what if the statement we ran was DDL, update queries and etc. Should we still create a
// resultSet?
public LimboStatement(String sql, long statementPointer) {
public TursoStatement(String sql, long statementPointer) {
this.sql = sql;
this.statementPointer = statementPointer;
this.resultSet = LimboResultSet.of(this);
this.resultSet = TursoResultSet.of(this);
log.debug("Creating statement with sql: {}", this.sql);
}
public LimboResultSet getResultSet() {
public TursoResultSet getResultSet() {
return resultSet;
}
@ -46,8 +47,8 @@ public final class LimboStatement {
return resultSet.hasLastStepReturnedRow();
}
LimboStepResult step() throws SQLException {
final LimboStepResult result = step(this.statementPointer);
TursoStepResult step() throws SQLException {
final TursoStepResult result = step(this.statementPointer);
if (result == null) {
throw new SQLException("step() returned null, which is only returned when an error occurs");
}
@ -56,12 +57,12 @@ public final class LimboStatement {
}
/**
* Because Limbo supports async I/O, it is possible to return a {@link LimboStepResult} with
* {@link LimboStepResult#STEP_RESULT_ID_ROW}. However, this is handled by the native side, so you
* can expect that this method will not return a {@link LimboStepResult#STEP_RESULT_ID_ROW}.
* Because turso supports async I/O, it is possible to return a {@link TursoStepResult} with
* {@link TursoStepResult#STEP_RESULT_ID_ROW}. However, this is handled by the native side, so you
* can expect that this method will not return a {@link TursoStepResult#STEP_RESULT_ID_ROW}.
*/
@Nullable
private native LimboStepResult step(long stmtPointer) throws SQLException;
private native TursoStepResult step(long stmtPointer) throws SQLException;
/**
* Throws formatted SQLException with error code and message.
@ -69,9 +70,9 @@ public final class LimboStatement {
* @param errorCode Error code.
* @param errorMessageBytes Error message.
*/
@NativeInvocation(invokedFrom = "limbo_statement.rs")
private void throwLimboException(int errorCode, byte[] errorMessageBytes) throws SQLException {
LimboExceptionUtils.throwLimboException(errorCode, errorMessageBytes);
@NativeInvocation(invokedFrom = "turso_statement.rs")
private void throwTursoException(int errorCode, byte[] errorMessageBytes) throws SQLException {
TursoExceptionUtils.throwTursoException(errorCode, errorMessageBytes);
}
/**
@ -90,8 +91,8 @@ public final class LimboStatement {
private native void _close(long statementPointer);
/**
* Initializes the column metadata, such as the names of the columns. Since {@link LimboStatement}
* can only have a single {@link LimboResultSet}, it is appropriate to place the initialization of
* Initializes the column metadata, such as the names of the columns. Since {@link tursoStatement}
* can only have a single {@link tursoResultSet}, it is appropriate to place the initialization of
* column metadata here.
*
* @throws SQLException if a database access error occurs while retrieving column names
@ -125,7 +126,7 @@ public final class LimboStatement {
/**
* Binds an integer value to the prepared statement at the specified position. This function calls
* bindLong because Limbo treats all integers as long (as well as SQLite).
* bindLong because turso treats all integers as long (as well as SQLite).
*
* <p>According to SQLite documentation, the value is a signed integer, stored in 0, 1, 2, 3, 4,
* 6, or 8 bytes depending on the magnitude of the value.
@ -229,6 +230,7 @@ public final class LimboStatement {
}
private native long totalChanges(long statementPointer) throws SQLException;
/**
* Checks if the statement is closed.
*
@ -240,12 +242,12 @@ public final class LimboStatement {
@Override
public String toString() {
return "LimboStatement{"
return ("tursoStatement{"
+ "statementPointer="
+ statementPointer
+ ", sql='"
+ sql
+ '\''
+ '}';
+ '}');
}
}

View file

@ -4,8 +4,9 @@ import java.util.Arrays;
import tech.turso.annotations.NativeInvocation;
import tech.turso.annotations.Nullable;
/** Represents the step result of limbo's statement's step function. */
public final class LimboStepResult {
/** Represents the step result of turso's statement's step function. */
public final class TursoStepResult {
private static final int STEP_RESULT_ID_ROW = 10;
private static final int STEP_RESULT_ID_IO = 20;
private static final int STEP_RESULT_ID_DONE = 30;
@ -15,18 +16,19 @@ public final class LimboStepResult {
private static final int STEP_RESULT_ID_BUSY = 50;
private static final int STEP_RESULT_ID_ERROR = 60;
// Identifier for limbo's StepResult
// Identifier for Turso's StepResult
private final int stepResultId;
@Nullable private final Object[] result;
@NativeInvocation(invokedFrom = "limbo_statement.rs")
public LimboStepResult(int stepResultId) {
@NativeInvocation(invokedFrom = "turso_statement.rs")
public TursoStepResult(int stepResultId) {
this.stepResultId = stepResultId;
this.result = null;
}
@NativeInvocation(invokedFrom = "limbo_statement.rs")
public LimboStepResult(int stepResultId, Object[] result) {
@NativeInvocation(invokedFrom = "turso_statement.rs")
public TursoStepResult(int stepResultId, Object[] result) {
this.stepResultId = stepResultId;
this.result = result;
}
@ -41,10 +43,10 @@ public final class LimboStepResult {
public boolean isInInvalidState() {
// current implementation doesn't allow STEP_RESULT_ID_IO to be returned
return stepResultId == STEP_RESULT_ID_IO
return (stepResultId == STEP_RESULT_ID_IO
|| stepResultId == STEP_RESULT_ID_INTERRUPT
|| stepResultId == STEP_RESULT_ID_BUSY
|| stepResultId == STEP_RESULT_ID_ERROR;
|| stepResultId == STEP_RESULT_ID_ERROR);
}
@Nullable
@ -54,12 +56,12 @@ public final class LimboStepResult {
@Override
public String toString() {
return "LimboStepResult{"
return ("tursoStepResult{"
+ "stepResultName="
+ getStepResultName()
+ ", result="
+ Arrays.toString(result)
+ '}';
+ '}');
}
private String getStepResultName() {

View file

@ -1,17 +0,0 @@
package tech.turso.exceptions;
import java.sql.SQLException;
import tech.turso.LimboErrorCode;
public final class LimboException extends SQLException {
private final LimboErrorCode resultCode;
public LimboException(String message, LimboErrorCode resultCode) {
super(message, null, resultCode.code & 0xff);
this.resultCode = resultCode;
}
public LimboErrorCode getResultCode() {
return resultCode;
}
}

View file

@ -0,0 +1,18 @@
package tech.turso.exceptions;
import java.sql.SQLException;
import tech.turso.TursoErrorCode;
public final class TursoException extends SQLException {
private TursoErrorCode resultCode;
public TursoException(String message, TursoErrorCode resultCode) {
super(message, null, resultCode.code & 0xff);
this.resultCode = resultCode;
}
public TursoErrorCode getResultCode() {
return resultCode;
}
}

View file

@ -6,24 +6,24 @@ import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboConnection;
import tech.turso.core.LimboStatement;
import tech.turso.core.TursoConnection;
import tech.turso.core.TursoStatement;
public final class JDBC4Connection implements Connection {
private final LimboConnection connection;
private final TursoConnection connection;
private Map<String, Class<?>> typeMap = new HashMap<>();
public JDBC4Connection(String url, String filePath) throws SQLException {
this.connection = new LimboConnection(url, filePath);
this.connection = new TursoConnection(url, filePath);
}
public JDBC4Connection(String url, String filePath, Properties properties) throws SQLException {
this.connection = new LimboConnection(url, filePath, properties);
this.connection = new TursoConnection(url, filePath, properties);
}
public LimboStatement prepare(String sql) throws SQLException {
public TursoStatement prepare(String sql) throws SQLException {
return connection.prepare(sql);
}
@ -154,7 +154,7 @@ public final class JDBC4Connection implements Connection {
public void setHoldability(int holdability) throws SQLException {
connection.checkOpen();
if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT) {
throw new SQLException("Limbo only supports CLOSE_CURSORS_AT_COMMIT");
throw new SQLException("turso only supports CLOSE_CURSORS_AT_COMMIT");
}
}
@ -201,7 +201,7 @@ public final class JDBC4Connection implements Connection {
public CallableStatement prepareCall(
String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
throw new SQLException("Limbo does not support stored procedures");
throw new SQLException("turso does not support stored procedures");
}
@Override

View file

@ -9,7 +9,7 @@ import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboPropertiesHolder;
import tech.turso.core.TursoPropertiesHolder;
import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory;
@ -18,22 +18,37 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
private static final Logger logger = LoggerFactory.getLogger(JDBC4DatabaseMetaData.class);
private final JDBC4Connection connection;
@Nullable private PreparedStatement getTables = null;
@Nullable private PreparedStatement getTableTypes = null;
@Nullable private PreparedStatement getTypeInfo = null;
@Nullable private PreparedStatement getCatalogs = null;
@Nullable private PreparedStatement getSchemas = null;
@Nullable private PreparedStatement getUDTs = null;
@Nullable private PreparedStatement getColumnsTblName = null;
@Nullable private PreparedStatement getSuperTypes = null;
@Nullable private PreparedStatement getSuperTables = null;
@Nullable private PreparedStatement getTablePrivileges = null;
@Nullable private PreparedStatement getIndexInfo = null;
@Nullable private PreparedStatement getProcedures = null;
@Nullable private PreparedStatement getProcedureColumns = null;
@Nullable private PreparedStatement getAttributes = null;
@Nullable private PreparedStatement getBestRowIdentifier = null;
@Nullable private PreparedStatement getVersionColumns = null;
@Nullable private PreparedStatement getColumnPrivileges = null;
public JDBC4DatabaseMetaData(JDBC4Connection connection) {
@ -88,7 +103,7 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public String getDatabaseProductName() {
return "Limbo";
return "turso";
}
@Override
@ -99,12 +114,12 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public String getDriverName() {
return LimboPropertiesHolder.getDriverName();
return TursoPropertiesHolder.getDriverName();
}
@Override
public String getDriverVersion() {
return LimboPropertiesHolder.getDriverVersion();
return TursoPropertiesHolder.getDriverVersion();
}
@Override
@ -174,13 +189,13 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public String getSQLKeywords() {
// TODO: add more limbo supported keywords
return "ABORT,ACTION,AFTER,ANALYZE,ATTACH,AUTOINCREMENT,BEFORE,"
// TODO: add more turso supported keywords
return ("ABORT,ACTION,AFTER,ANALYZE,ATTACH,AUTOINCREMENT,BEFORE,"
+ "CASCADE,CONFLICT,DATABASE,DEFERRABLE,DEFERRED,DESC,DETACH,"
+ "EXCLUSIVE,EXPLAIN,FAIL,GLOB,IGNORE,INDEX,INDEXED,INITIALLY,INSTEAD,ISNULL,"
+ "KEY,LIMIT,NOTNULL,OFFSET,PLAN,PRAGMA,QUERY,"
+ "RAISE,REGEXP,REINDEX,RENAME,REPLACE,RESTRICT,"
+ "TEMP,TEMPORARY,TRANSACTION,VACUUM,VIEW,VIRTUAL";
+ "TEMP,TEMPORARY,TRANSACTION,VACUUM,VIEW,VIRTUAL");
}
@Override
@ -318,7 +333,7 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
// DECLARE CURSOR
// FETCH
// CLOSE CURSOR
// TODO: Let's return true when limbo supports them all
// TODO: Let's return true when turso supports them all
return false;
}
@ -331,7 +346,7 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
// Table expressions (SELECT column FROM (SELECT * FROM table) AS subquery)
// Data type support (includes more SQL data types like FLOAT, NUMERIC, DECIMAL)
// Basic string functions (e.g., LENGTH(), SUBSTRING(), CONCAT())
// TODO: Let's return true when limbo supports them all
// TODO: Let's return true when turso supports them all
return false;
}
@ -392,7 +407,7 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public boolean isCatalogAtStart() {
// sqlite and limbo doesn't use catalog
// sqlite and turso doesn't use catalog
return false;
}
@ -498,13 +513,13 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public boolean supportsUnion() {
// TODO: return true when limbo supports
// TODO: return true when turso supports
return false;
}
@Override
public boolean supportsUnionAll() {
// TODO: return true when limbo supports
// TODO: return true when turso supports
return false;
}
@ -635,13 +650,13 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public int getDefaultTransactionIsolation() {
// TODO: after limbo introduces Hekaton MVCC, what should we return?
// TODO: after turso introduces Hekaton MVCC, what should we return?
return Connection.TRANSACTION_SERIALIZABLE;
}
@Override
public boolean supportsTransactions() {
// TODO: limbo doesn't support transactions fully, let's return true when supported
// TODO: turso doesn't support transactions fully, let's return true when supported
return false;
}
@ -922,7 +937,7 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public boolean supportsResultSetConcurrency(int type, int concurrency) {
return type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY;
return (type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY);
}
@Override
@ -1001,13 +1016,13 @@ public final class JDBC4DatabaseMetaData implements DatabaseMetaData {
@Override
public boolean supportsSavepoints() {
// TODO: return true when limbo supports save points
// TODO: return true when turso supports save points
return false;
}
@Override
public boolean supportsNamedParameters() {
// TODO: return true when both limbo and jdbc supports named parameters
// TODO: return true when both turso and jdbc supports named parameters
return false;
}

View file

@ -23,7 +23,7 @@ import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboResultSet;
import tech.turso.core.TursoResultSet;
public final class JDBC4PreparedStatement extends JDBC4Statement implements PreparedStatement {
@ -32,7 +32,6 @@ public final class JDBC4PreparedStatement extends JDBC4Statement implements Prep
public JDBC4PreparedStatement(JDBC4Connection connection, String sql) throws SQLException {
super(connection);
this.sql = sql;
this.statement = connection.prepare(sql);
this.statement.initializeColumnMetadata();
@ -48,7 +47,7 @@ public final class JDBC4PreparedStatement extends JDBC4Statement implements Prep
@Override
public int executeUpdate() throws SQLException {
requireNonNull(this.statement);
final LimboResultSet resultSet = statement.getResultSet();
final TursoResultSet resultSet = statement.getResultSet();
resultSet.consumeAll();
// TODO: return updated count

View file

@ -24,13 +24,13 @@ import java.util.Calendar;
import java.util.Map;
import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboResultSet;
import tech.turso.core.TursoResultSet;
public final class JDBC4ResultSet implements ResultSet, ResultSetMetaData {
private final LimboResultSet resultSet;
private final TursoResultSet resultSet;
public JDBC4ResultSet(LimboResultSet resultSet) {
public JDBC4ResultSet(TursoResultSet resultSet) {
this.resultSet = resultSet;
}

View file

@ -10,15 +10,16 @@ import java.sql.Statement;
import java.util.concurrent.locks.ReentrantLock;
import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboResultSet;
import tech.turso.core.LimboStatement;
import tech.turso.core.TursoResultSet;
import tech.turso.core.TursoStatement;
public class JDBC4Statement implements Statement {
private final JDBC4Connection connection;
@Nullable protected LimboStatement statement = null;
// Because JDBC4Statement has different life cycle in compared to LimboStatement, let's use this
@Nullable protected TursoStatement statement = null;
// Because JDBC4Statement has different life cycle in compared to tursoStatement, let's use this
// field to manage JDBC4Statement lifecycle
private boolean closed;
private boolean closeOnCompletion;
@ -76,7 +77,7 @@ public class JDBC4Statement implements Statement {
execute(sql);
requireNonNull(statement, "statement should not be null after running execute method");
final LimboResultSet resultSet = statement.getResultSet();
final TursoResultSet resultSet = statement.getResultSet();
resultSet.consumeAll();
return (int) (statement.totalChanges() - previousTotalChanges);

View file

@ -3,21 +3,22 @@ package tech.turso.utils;
import static tech.turso.utils.ByteArrayUtils.utf8ByteBufferToString;
import java.sql.SQLException;
import tech.turso.LimboErrorCode;
import tech.turso.TursoErrorCode;
import tech.turso.annotations.Nullable;
import tech.turso.exceptions.LimboException;
import tech.turso.exceptions.TursoException;
public final class TursoExceptionUtils {
public final class LimboExceptionUtils {
/**
* Throws formatted SQLException with error code and message.
*
* @param errorCode Error code.
* @param errorMessageBytes Error message.
*/
public static void throwLimboException(int errorCode, byte[] errorMessageBytes)
public static void throwTursoException(int errorCode, byte[] errorMessageBytes)
throws SQLException {
String errorMessage = utf8ByteBufferToString(errorMessageBytes);
throw buildLimboException(errorCode, errorMessage);
throw buildTursoException(errorCode, errorMessage);
}
/**
@ -26,16 +27,16 @@ public final class LimboExceptionUtils {
* @param errorCode Error code.
* @param errorMessage Error message.
*/
public static LimboException buildLimboException(int errorCode, @Nullable String errorMessage)
public static TursoException buildTursoException(int errorCode, @Nullable String errorMessage)
throws SQLException {
LimboErrorCode code = LimboErrorCode.getErrorCode(errorCode);
TursoErrorCode code = TursoErrorCode.getErrorCode(errorCode);
String msg;
if (code == LimboErrorCode.UNKNOWN_ERROR) {
if (code == TursoErrorCode.UNKNOWN_ERROR) {
msg = String.format("%s:%s (%s)", code, errorCode, errorMessage);
} else {
msg = String.format("%s (%s)", code, errorMessage);
}
return new LimboException(msg, code);
return new TursoException(msg, code);
}
}

View file

@ -1,3 +1,3 @@
driverName=limbo-jdbc
driverName=turso-jdbc
# find a way to relate driverVersion with project.version defined in gradle.properties
driverVersion=0.0.1-SNAPSHOT

View file

@ -15,7 +15,7 @@ public class IntegrationTest {
@BeforeEach
void setUp() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
String url = "jdbc:turso:" + filePath;
connection = new JDBC4Connection(url, filePath, new Properties());
}

View file

@ -22,26 +22,26 @@ class JDBCTest {
@Test
void non_null_connection_is_returned_when_valid_url_is_passed() throws Exception {
String fileUrl = TestUtils.createTempFile();
JDBC4Connection connection = JDBC.createConnection("jdbc:sqlite:" + fileUrl, new Properties());
JDBC4Connection connection = JDBC.createConnection("jdbc:turso:" + fileUrl, new Properties());
assertThat(connection).isNotNull();
}
@Test
void connection_can_be_retrieved_from_DriverManager() throws SQLException {
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
try (Connection connection = DriverManager.getConnection("jdbc:turso:sample.db")) {
assertThat(connection).isNotNull();
}
}
@Test
void retrieve_version() {
assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:sqlite:").getMajorVersion());
assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:sqlite:").getMinorVersion());
assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:turso:").getMajorVersion());
assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:turso:").getMinorVersion());
}
@Test
void all_driver_property_info_should_have_a_description() throws Exception {
Driver driver = DriverManager.getDriver("jdbc:sqlite:");
Driver driver = DriverManager.getDriver("jdbc:turso:");
assertThat(driver.getPropertyInfo(null, null))
.allSatisfy((info) -> assertThat(info.description).isNotNull());
}

View file

@ -6,6 +6,6 @@ import java.nio.file.Files;
public class TestUtils {
/** Create temporary file and returns the path. */
public static String createTempFile() throws IOException {
return Files.createTempFile("limbo_test_db", null).toAbsolutePath().toString();
return Files.createTempFile("turso_test_db", null).toAbsolutePath().toString();
}
}

View file

@ -7,14 +7,14 @@ import java.util.Properties;
import org.junit.jupiter.api.Test;
import tech.turso.TestUtils;
class LimboDBFactoryTest {
class TursoDBFactoryTest {
@Test
void single_database_should_be_created_when_urls_are_same() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
LimboDB db1 = LimboDBFactory.open(url, filePath, new Properties());
LimboDB db2 = LimboDBFactory.open(url, filePath, new Properties());
String url = "jdbc:turso:" + filePath;
TursoDB db1 = TursoDBFactory.open(url, filePath, new Properties());
TursoDB db2 = TursoDBFactory.open(url, filePath, new Properties());
assertEquals(db1, db2);
}
@ -22,10 +22,10 @@ class LimboDBFactoryTest {
void multiple_databases_should_be_created_when_urls_differ() throws Exception {
String filePath1 = TestUtils.createTempFile();
String filePath2 = TestUtils.createTempFile();
String url1 = "jdbc:sqlite:" + filePath1;
String url2 = "jdbc:sqlite:" + filePath2;
LimboDB db1 = LimboDBFactory.open(url1, filePath1, new Properties());
LimboDB db2 = LimboDBFactory.open(url2, filePath2, new Properties());
String url1 = "jdbc:turso:" + filePath1;
String url2 = "jdbc:turso:" + filePath2;
TursoDB db1 = TursoDBFactory.open(url1, filePath1, new Properties());
TursoDB db2 = TursoDBFactory.open(url2, filePath2, new Properties());
assertNotEquals(db1, db2);
}
}

View file

@ -6,25 +6,25 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import java.sql.SQLException;
import org.junit.jupiter.api.Test;
import tech.turso.LimboErrorCode;
import tech.turso.TestUtils;
import tech.turso.exceptions.LimboException;
import tech.turso.TursoErrorCode;
import tech.turso.exceptions.TursoException;
public class LimboDBTest {
public class TursoDBTest {
@Test
void db_should_open_normally() throws Exception {
LimboDB.load();
TursoDB.load();
String dbPath = TestUtils.createTempFile();
LimboDB db = LimboDB.create("jdbc:sqlite" + dbPath, dbPath);
TursoDB db = TursoDB.create("jdbc:turso" + dbPath, dbPath);
db.open(0);
}
@Test
void db_should_close_normally() throws Exception {
LimboDB.load();
TursoDB.load();
String dbPath = TestUtils.createTempFile();
LimboDB db = LimboDB.create("jdbc:sqlite" + dbPath, dbPath);
TursoDB db = TursoDB.create("jdbc:turso" + dbPath, dbPath);
db.open(0);
db.close();
@ -33,9 +33,9 @@ public class LimboDBTest {
@Test
void should_throw_exception_when_opened_twice() throws Exception {
LimboDB.load();
TursoDB.load();
String dbPath = TestUtils.createTempFile();
LimboDB db = LimboDB.create("jdbc:sqlite:" + dbPath, dbPath);
TursoDB db = TursoDB.create("jdbc:turso:" + dbPath, dbPath);
db.open(0);
assertThatThrownBy(() -> db.open(0)).isInstanceOf(SQLException.class);
@ -43,17 +43,17 @@ public class LimboDBTest {
@Test
void throwJavaException_should_throw_appropriate_java_exception() throws Exception {
LimboDB.load();
TursoDB.load();
String dbPath = TestUtils.createTempFile();
LimboDB db = LimboDB.create("jdbc:sqlite:" + dbPath, dbPath);
TursoDB db = TursoDB.create("jdbc:turso:" + dbPath, dbPath);
final int limboExceptionCode = LimboErrorCode.LIMBO_ETC.code;
final int tursoExceptionCode = TursoErrorCode.TURSO_ETC.code;
try {
db.throwJavaException(limboExceptionCode);
db.throwJavaException(tursoExceptionCode);
} catch (Exception e) {
assertThat(e).isInstanceOf(LimboException.class);
LimboException limboException = (LimboException) e;
assertThat(limboException.getResultCode().code).isEqualTo(limboExceptionCode);
assertThat(e).isInstanceOf(TursoException.class);
TursoException tursoException = (TursoException) e;
assertThat(tursoException.getResultCode().code).isEqualTo(tursoExceptionCode);
}
}
}

View file

@ -12,20 +12,20 @@ import org.junit.jupiter.api.Test;
import tech.turso.TestUtils;
import tech.turso.jdbc4.JDBC4Connection;
class LimboStatementTest {
class TursoStatementTest {
private JDBC4Connection connection;
@BeforeEach
void setUp() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
String url = "jdbc:turso:" + filePath;
connection = new JDBC4Connection(url, filePath, new Properties());
}
@Test
void closing_statement_closes_related_resources() throws Exception {
LimboStatement stmt = connection.prepare("SELECT 1;");
TursoStatement stmt = connection.prepare("SELECT 1;");
stmt.execute();
stmt.close();
@ -38,9 +38,9 @@ class LimboStatementTest {
runSql("CREATE TABLE users (name TEXT, age INT, country TEXT);");
runSql("INSERT INTO users VALUES ('seonwoo', 30, 'KR');");
final LimboStatement stmt = connection.prepare("SELECT * FROM users");
final TursoStatement stmt = connection.prepare("SELECT * FROM users");
stmt.initializeColumnMetadata();
final LimboResultSet rs = stmt.getResultSet();
final TursoResultSet rs = stmt.getResultSet();
final String[] columnNames = rs.getColumnNames();
assertEquals("name", columnNames[0]);
@ -51,12 +51,12 @@ class LimboStatementTest {
@Test
void test_bindNull() throws Exception {
runSql("CREATE TABLE test (col1 TEXT);");
LimboStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
TursoStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
stmt.bindNull(1);
stmt.execute();
stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute();
assertNull(selectStmt.getResultSet().get(1));
selectStmt.close();
@ -65,12 +65,12 @@ class LimboStatementTest {
@Test
void test_bindLong() throws Exception {
runSql("CREATE TABLE test (col1 BIGINT);");
LimboStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
TursoStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
stmt.bindLong(1, 123456789L);
stmt.execute();
stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute();
assertEquals(123456789L, selectStmt.getResultSet().get(1));
selectStmt.close();
@ -79,12 +79,12 @@ class LimboStatementTest {
@Test
void test_bindDouble() throws Exception {
runSql("CREATE TABLE test (col1 DOUBLE);");
LimboStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
TursoStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
stmt.bindDouble(1, 3.14);
stmt.execute();
stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute();
assertEquals(3.14, selectStmt.getResultSet().get(1));
selectStmt.close();
@ -93,12 +93,12 @@ class LimboStatementTest {
@Test
void test_bindText() throws Exception {
runSql("CREATE TABLE test (col1 TEXT);");
LimboStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
TursoStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
stmt.bindText(1, "hello");
stmt.execute();
stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute();
assertEquals("hello", selectStmt.getResultSet().get(1));
selectStmt.close();
@ -107,20 +107,20 @@ class LimboStatementTest {
@Test
void test_bindBlob() throws Exception {
runSql("CREATE TABLE test (col1 BLOB);");
LimboStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
TursoStatement stmt = connection.prepare("INSERT INTO test (col1) VALUES (?);");
byte[] blob = {1, 2, 3, 4, 5};
stmt.bindBlob(1, blob);
stmt.execute();
stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute();
assertArrayEquals(blob, (byte[]) selectStmt.getResultSet().get(1));
selectStmt.close();
}
private void runSql(String sql) throws Exception {
LimboStatement stmt = connection.prepare(sql);
TursoStatement stmt = connection.prepare(sql);
while (stmt.execute()) {
stmt.execute();
}

View file

@ -17,7 +17,7 @@ class JDBC4ConnectionTest {
@BeforeEach
void setUp() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
String url = "jdbc:turso:" + filePath;
connection = new JDBC4Connection(url, filePath, new Properties());
}

View file

@ -22,7 +22,7 @@ class JDBC4DatabaseMetaDataTest {
@BeforeEach
void set_up() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
String url = "jdbc:turso:" + filePath;
connection = new JDBC4Connection(url, filePath, new Properties());
metaData = new JDBC4DatabaseMetaData(connection);
}

View file

@ -21,7 +21,7 @@ class JDBC4PreparedStatementTest {
@BeforeEach
void setUp() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
String url = "jdbc:turso:" + filePath;
connection = new JDBC4Connection(url, filePath, new Properties());
}

View file

@ -27,7 +27,7 @@ class JDBC4ResultSetTest {
@BeforeEach
void setUp() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
String url = "jdbc:turso:" + filePath;
final JDBC4Connection connection = new JDBC4Connection(url, filePath, new Properties());
stmt =
connection.createStatement(

View file

@ -21,7 +21,7 @@ class JDBC4StatementTest {
@BeforeEach
void setUp() throws Exception {
String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath;
String url = "jdbc:turso:" + filePath;
final JDBC4Connection connection = new JDBC4Connection(url, filePath, new Properties());
stmt =
connection.createStatement(
@ -38,20 +38,20 @@ class JDBC4StatementTest {
@Test
void execute_insert_should_return_false() throws Exception {
stmt.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT);");
assertFalse(stmt.execute("INSERT INTO users VALUES (1, 'limbo');"));
assertFalse(stmt.execute("INSERT INTO users VALUES (1, 'turso');"));
}
@Test
void execute_update_should_return_false() throws Exception {
stmt.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT);");
stmt.execute("INSERT INTO users VALUES (1, 'limbo');");
stmt.execute("INSERT INTO users VALUES (1, 'turso');");
assertFalse(stmt.execute("UPDATE users SET username = 'seonwoo' WHERE id = 1;"));
}
@Test
void execute_select_should_return_true() throws Exception {
stmt.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT);");
stmt.execute("INSERT INTO users VALUES (1, 'limbo');");
stmt.execute("INSERT INTO users VALUES (1, 'turso');");
assertTrue(stmt.execute("SELECT * FROM users;"));
}

View file

@ -0,0 +1 @@
{"rustc_fingerprint":11551670960185020797,"outputs":{"14427667104029986310":{"success":true,"status":"","code":0,"stdout":"rustc 1.83.0 (90b35a623 2024-11-26)\nbinary: rustc\ncommit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf\ncommit-date: 2024-11-26\nhost: x86_64-unknown-linux-gnu\nrelease: 1.83.0\nLLVM version: 19.1.1\n","stderr":""},"11399821309745579047":{"success":true,"status":"","code":0,"stdout":"___\nlib___.rlib\nlib___.so\nlib___.so\nlib___.a\nlib___.so\n/home/merlin/.rustup/toolchains/1.83.0-x86_64-unknown-linux-gnu\noff\npacked\nunpacked\n___\ndebug_assertions\npanic=\"unwind\"\nproc_macro\ntarget_abi=\"\"\ntarget_arch=\"x86_64\"\ntarget_endian=\"little\"\ntarget_env=\"gnu\"\ntarget_family=\"unix\"\ntarget_feature=\"fxsr\"\ntarget_feature=\"sse\"\ntarget_feature=\"sse2\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"ptr\"\ntarget_os=\"linux\"\ntarget_pointer_width=\"64\"\ntarget_vendor=\"unknown\"\nunix\n","stderr":""}},"successes":{}}

View file

@ -0,0 +1,3 @@
Signature: 8a477f597d28d172789f06886806bc55
# This file is a cache directory tag created by cargo.
# For information about cache directory tags see https://bford.info/cachedir/