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", "turso_core",
] ]
[[package]]
name = "limbo-java"
version = "0.1.1"
dependencies = [
"jni",
"thiserror 2.0.12",
"turso_core",
]
[[package]] [[package]]
name = "limbo-wasm" name = "limbo-wasm"
version = "0.1.1" version = "0.1.1"
@ -3637,6 +3628,15 @@ dependencies = [
"turso_core", "turso_core",
] ]
[[package]]
name = "turso-java"
version = "0.1.1"
dependencies = [
"jni",
"thiserror 2.0.12",
"turso_core",
]
[[package]] [[package]]
name = "turso_cli" name = "turso_cli"
version = "0.1.1" version = "0.1.1"

View file

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

View file

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

View file

@ -16,29 +16,29 @@ macos_x86:
@echo "Building release version for macOS x86_64..." @echo "Building release version for macOS x86_64..."
@mkdir -p $(TEMP_DIR) $(MACOS_X86_DIR) @mkdir -p $(TEMP_DIR) $(MACOS_X86_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target x86_64-apple-darwin @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) @rm -rf $(TEMP_DIR)
macos_arm64: macos_arm64:
@echo "Building release version for macOS ARM64..." @echo "Building release version for macOS ARM64..."
@mkdir -p $(TEMP_DIR) $(MACOS_ARM64_DIR) @mkdir -p $(TEMP_DIR) $(MACOS_ARM64_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target aarch64-apple-darwin @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) @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: windows:
@echo "Building release version for Windows..." @echo "Building release version for Windows..."
@mkdir -p $(TEMP_DIR) $(WINDOWS_DIR) @mkdir -p $(TEMP_DIR) $(WINDOWS_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target x86_64-pc-windows-gnu @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) @rm -rf $(TEMP_DIR)
linux_x86: linux_x86:
@echo "Building release version for linux x86_64..." @echo "Building release version for linux x86_64..."
@mkdir -p $(TEMP_DIR) $(LINUX_X86_DIR) @mkdir -p $(TEMP_DIR) $(LINUX_X86_DIR)
@CARGO_TARGET_DIR=$(TEMP_DIR) $(CARGO_BUILD) --target x86_64-unknown-linux-gnu @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) @rm -rf $(TEMP_DIR)
lint: lint:
@ -51,7 +51,7 @@ test: lint build_test
./gradlew test ./gradlew test
build_test: build_test:
CARGO_TARGET_DIR=src/test/resources/limbo cargo build CARGO_TARGET_DIR=src/test/resources/turso cargo build
publish_local: publish_local:
./gradlew clean publishToMavenLocal ./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 ## Project Status
@ -16,12 +16,12 @@ maven local to use it.
### Build jar and publish to maven local ### Build jar and publish to maven local
```shell ```shell
$ cd bindings/java $ cd bindings/java
# Please select the appropriate target platform, currently supports `macos_x86`, `macos_arm64`, `windows` and `linux_x86` # Please select the appropriate target platform, currently supports `macos_x86`, `macos_arm64`, `windows` and `linux_x86`
$ make macos_x86 $ make macos_x86
# deploy to maven local # deploy to maven local
$ make publish_local $ make publish_local
``` ```
@ -29,12 +29,12 @@ Now you can use the dependency as follows:
```kotlin ```kotlin
dependencies { dependencies {
implementation("tech.turso:limbo:0.0.1-SNAPSHOT") implementation("tech.turso:turso:0.0.1-SNAPSHOT")
} }
``` ```
## Code style ## Code style
- Favor composition over inheritance. For example, `JDBC4Connection` doesn't implement `LimboConnection`. Instead, - Favor composition over inheritance. For example, `JDBC4Connection` doesn't implement `TursoConnection`. Instead,
it includes `LimboConnection` as a field. This approach allows us to preserve the characteristics of Limbo using it includes `TursoConnection` as a field. This approach allows us to preserve the characteristics of Turso using
`LimboConnection` easily while maintaining interoperability with the Java world using `JDBC4Connection`. `TursoConnection` easily while maintaining interoperability with the Java world using `JDBC4Connection`.

View file

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

View file

@ -11,7 +11,7 @@ repositories {
} }
dependencies { 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(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.junit.jupiter:junit-jupiter")
} }

View file

@ -6,22 +6,33 @@ import java.sql.ResultSet;
import java.sql.Statement; import java.sql.Statement;
public class Main { public class Main {
public static void main(String[] args) {
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:sample.db")) { public static void main(String[] args) {
Statement stmt = try (
conn.createStatement( Connection conn = DriverManager.getConnection(
ResultSet.TYPE_FORWARD_ONLY, "jdbc:turso:sample.db"
ResultSet.CONCUR_READ_ONLY, );
ResultSet.CLOSE_CURSORS_AT_COMMIT); ) {
stmt.execute("CREATE TABLE users (id INT PRIMARY KEY, username TEXT);"); Statement stmt = conn.createStatement(
stmt.execute("INSERT INTO users VALUES (1, 'limbo');"); ResultSet.TYPE_FORWARD_ONLY,
stmt.execute("INSERT INTO users VALUES (2, 'turso');"); ResultSet.CONCUR_READ_ONLY,
stmt.execute("INSERT INTO users VALUES (3, 'who knows');"); ResultSet.CLOSE_CURSORS_AT_COMMIT
stmt.execute("SELECT * FROM users"); );
System.out.println( stmt.execute(
"result: " + stmt.getResultSet().getInt(1) + ", " + stmt.getResultSet().getString(2)); "CREATE TABLE users (id INT PRIMARY KEY, username TEXT);"
} catch (Exception e) { );
System.out.println("Error: " + e); 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; use thiserror::Error;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum LimboError { pub enum TursoError {
#[error("Custom error: `{0}`")] #[error("Custom error: `{0}`")]
CustomError(String), CustomError(String),
@ -16,19 +16,19 @@ pub enum LimboError {
JNIErrors(Error), JNIErrors(Error),
} }
impl From<turso_core::LimboError> for LimboError { impl From<turso_core::LimboError> for TursoError {
fn from(_value: turso_core::LimboError) -> Self { fn from(_value: turso_core::LimboError) -> Self {
todo!() todo!()
} }
} }
impl From<LimboError> for JniError { impl From<TursoError> for JniError {
fn from(value: LimboError) -> Self { fn from(value: TursoError) -> Self {
match value { match value {
LimboError::CustomError(_) TursoError::CustomError(_)
| LimboError::InvalidDatabasePointer | TursoError::InvalidDatabasePointer
| LimboError::InvalidConnectionPointer | TursoError::InvalidConnectionPointer
| LimboError::JNIErrors(_) => { | TursoError::JNIErrors(_) => {
eprintln!("Error occurred: {:?}", value); eprintln!("Error occurred: {:?}", value);
JniError::Other(-1) 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 { 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_OK: i32 = 0; // Successful result
pub const SQLITE_ERROR: i32 = 1; // Generic error pub const SQLITE_ERROR: i32 = 1; // Generic error
@ -106,6 +106,6 @@ pub const SQLITE_BLOB: i32 = 4;
#[allow(dead_code)] #[allow(dead_code)]
pub const SQLITE_NULL: i32 = 5; pub const SQLITE_NULL: i32 = 5;
pub const LIMBO_FAILED_TO_PARSE_BYTE_ARRAY: i32 = 1100; pub const TURSO_FAILED_TO_PARSE_BYTE_ARRAY: i32 = 1100;
pub const LIMBO_FAILED_TO_PREPARE_STATEMENT: i32 = 1200; pub const TURSO_FAILED_TO_PREPARE_STATEMENT: i32 = 1200;
pub const LIMBO_ETC: i32 = 9999; pub const TURSO_ETC: i32 = 9999;

View file

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

View file

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

View file

@ -1,5 +1,5 @@
use crate::errors::{LimboError, Result, LIMBO_ETC}; use crate::errors::{Result, TursoError, TURSO_ETC};
use crate::limbo_connection::LimboConnection; use crate::turso_connection::TursoConnection;
use crate::utils::set_err_msg_and_throw_exception; use crate::utils::set_err_msg_and_throw_exception;
use jni::objects::{JByteArray, JObject}; use jni::objects::{JByteArray, JObject};
use jni::sys::{jint, jlong}; use jni::sys::{jint, jlong};
@ -7,14 +7,14 @@ use jni::JNIEnv;
use std::sync::Arc; use std::sync::Arc;
use turso_core::Database; use turso_core::Database;
struct LimboDB { struct TursoDB {
db: Arc<Database>, db: Arc<Database>,
io: Arc<dyn turso_core::IO>, io: Arc<dyn turso_core::IO>,
} }
impl LimboDB { impl TursoDB {
pub fn new(db: Arc<Database>, io: Arc<dyn turso_core::IO>) -> Self { pub fn new(db: Arc<Database>, io: Arc<dyn turso_core::IO>) -> Self {
LimboDB { db, io } TursoDB { db, io }
} }
#[allow(clippy::wrong_self_convention)] #[allow(clippy::wrong_self_convention)]
@ -23,21 +23,21 @@ impl LimboDB {
} }
pub fn drop(ptr: jlong) { 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 { if ptr == 0 {
Err(LimboError::InvalidDatabasePointer) Err(TursoError::InvalidDatabasePointer)
} else { } else {
unsafe { Ok(&mut *(ptr as *mut LimboDB)) } unsafe { Ok(&mut *(ptr as *mut TursoDB)) }
} }
} }
#[no_mangle] #[no_mangle]
#[allow(clippy::arc_with_non_send_sync)] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
file_path_byte_arr: JByteArray<'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() { let io = match turso_core::PlatformIO::new() {
Ok(io) => Arc::new(io), Ok(io) => Arc::new(io),
Err(e) => { 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; 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(bytes) => match String::from_utf8(bytes) {
Ok(s) => s, Ok(s) => s,
Err(e) => { 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; return -1;
} }
}, },
Err(e) => { 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; 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) { let db = match Database::open_file(io.clone(), &path, false, false) {
Ok(db) => db, Ok(db) => db,
Err(e) => { 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; return -1;
} }
}; };
LimboDB::new(db, io).to_ptr() TursoDB::new(db, io).to_ptr()
} }
#[no_mangle] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
db_pointer: jlong, db_pointer: jlong,
) -> jlong { ) -> jlong {
let db = match to_limbo_db(db_pointer) { let db = match to_turso_db(db_pointer) {
Ok(db) => db, Ok(db) => db,
Err(e) => { 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; 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() conn.to_ptr()
} }
#[no_mangle] #[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>, _env: JNIEnv<'local>,
_obj: JObject<'local>, _obj: JObject<'local>,
db_pointer: jlong, db_pointer: jlong,
) { ) {
LimboDB::drop(db_pointer); TursoDB::drop(db_pointer);
} }
#[no_mangle] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
error_code: jint, 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::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 crate::utils::set_err_msg_and_throw_exception;
use jni::objects::{JByteArray, JObject, JObjectArray, JString, JValue}; use jni::objects::{JByteArray, JObject, JObjectArray, JString, JValue};
use jni::sys::{jdouble, jint, jlong}; 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_BUSY: i32 = 50;
pub const STEP_RESULT_ID_ERROR: i32 = 60; pub const STEP_RESULT_ID_ERROR: i32 = 60;
pub struct LimboStatement { pub struct TursoStatement {
pub(crate) stmt: Statement, pub(crate) stmt: Statement,
pub(crate) connection: LimboConnection, pub(crate) connection: TursoConnection,
} }
impl LimboStatement { impl TursoStatement {
pub fn new(stmt: Statement, connection: LimboConnection) -> Self { pub fn new(stmt: Statement, connection: TursoConnection) -> Self {
LimboStatement { stmt, connection } TursoStatement { stmt, connection }
} }
#[allow(clippy::wrong_self_convention)] #[allow(clippy::wrong_self_convention)]
@ -32,71 +32,71 @@ impl LimboStatement {
} }
pub fn drop(ptr: jlong) { 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 { if ptr == 0 {
Err(LimboError::InvalidConnectionPointer) Err(TursoError::InvalidConnectionPointer)
} else { } else {
unsafe { Ok(&mut *(ptr as *mut LimboStatement)) } unsafe { Ok(&mut *(ptr as *mut TursoStatement)) }
} }
} }
#[no_mangle] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
) -> JObject<'local> { ) -> JObject<'local> {
let stmt = match to_limbo_statement(stmt_ptr) { let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(e) => { 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 to_limbo_step_result(&mut env, STEP_RESULT_ID_ERROR, None); return to_turso_step_result(&mut env, STEP_RESULT_ID_ERROR, None);
} }
}; };
loop { loop {
let step_result = match stmt.stmt.step() { let step_result = match stmt.stmt.step() {
Ok(result) => result, 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 { match step_result {
StepResult::Row => { StepResult::Row => {
let row = stmt.stmt.row().unwrap(); let row = stmt.stmt.row().unwrap();
return match row_to_obj_array(&mut env, row) { 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) => { 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());
to_limbo_step_result(&mut env, STEP_RESULT_ID_ERROR, None) to_turso_step_result(&mut env, STEP_RESULT_ID_ERROR, None)
} }
}; };
} }
StepResult::IO => { StepResult::IO => {
if let Err(e) = stmt.connection.io.run_once() { if let Err(e) = stmt.connection.io.run_once() {
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 to_limbo_step_result(&mut env, STEP_RESULT_ID_ERROR, None); 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 => { 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] #[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>, _env: JNIEnv<'local>,
_obj: JObject<'local>, _obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
) { ) {
LimboStatement::drop(stmt_ptr); TursoStatement::drop(stmt_ptr);
} }
fn row_to_obj_array<'local>( fn row_to_obj_array<'local>(
@ -126,12 +126,12 @@ fn row_to_obj_array<'local>(
} }
#[no_mangle] #[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>, mut env: JNIEnv<'local>,
_obj: JObject<'local>, _obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
) -> JObject<'local> { ) -> 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 num_columns = stmt.stmt.num_columns();
let obj_arr: JObjectArray = env let obj_arr: JObjectArray = env
.new_object_array(num_columns as i32, "java/lang/String", JObject::null()) .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] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
position: jint, position: jint,
) -> jint { ) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) { let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(e) => { Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string()); 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] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
position: jint, position: jint,
value: jlong, value: jlong,
) -> jint { ) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) { let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(e) => { Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string()); 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] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
position: jint, position: jint,
value: jdouble, value: jdouble,
) -> jint { ) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) { let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(e) => { Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string()); 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] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
position: jint, position: jint,
value: JString<'local>, value: JString<'local>,
) -> jint { ) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) { let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(e) => { Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string()); 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] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
position: jint, position: jint,
value: JByteArray<'local>, value: JByteArray<'local>,
) -> jint { ) -> jint {
let stmt = match to_limbo_statement(stmt_ptr) { let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(e) => { Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string()); 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] #[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>, mut env: JNIEnv<'local>,
obj: JObject<'local>, obj: JObject<'local>,
stmt_ptr: jlong, stmt_ptr: jlong,
) -> jlong { ) -> jlong {
let stmt = match to_limbo_statement(stmt_ptr) { let stmt = match to_turso_statement(stmt_ptr) {
Ok(stmt) => stmt, Ok(stmt) => stmt,
Err(e) => { Err(e) => {
set_err_msg_and_throw_exception(&mut env, obj, SQLITE_ERROR, e.to_string()); 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() 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 /// 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. /// appropriate constructor arguments.
/// ///
/// # Arguments /// # Arguments
@ -298,9 +298,9 @@ pub extern "system" fn Java_tech_turso_core_LimboStatement_totalChanges<'local>(
/// ///
/// # Returns /// # 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 /// a null `JObject` is returned
fn to_limbo_step_result<'local>( fn to_turso_step_result<'local>(
env: &mut JNIEnv<'local>, env: &mut JNIEnv<'local>,
id: i32, id: i32,
result: Option<JObject<'local>>, result: Option<JObject<'local>>,
@ -309,12 +309,12 @@ fn to_limbo_step_result<'local>(
if let Some(res) = result { if let Some(res) = result {
ctor_args.push(JValue::Object(&res)); ctor_args.push(JValue::Object(&res));
env.new_object( env.new_object(
"tech/turso/core/LimboStepResult", "tech/turso/core/TursoStepResult",
"(I[Ljava/lang/Object;)V", "(I[Ljava/lang/Object;)V",
&ctor_args, &ctor_args,
) )
} else { } 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()) .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::objects::{JByteArray, JObject};
use jni::JNIEnv; use jni::JNIEnv;
@ -8,9 +8,9 @@ pub(crate) fn utf8_byte_arr_to_str(
) -> crate::errors::Result<String> { ) -> crate::errors::Result<String> {
let bytes = env let bytes = env
.convert_byte_array(bytes) .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(|_| { 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) Ok(str)
} }
@ -18,7 +18,7 @@ pub(crate) fn utf8_byte_arr_to_str(
/// Sets the error message and throws a Java exception. /// Sets the error message and throws a Java exception.
/// ///
/// This function converts the provided error message to a byte array and calls the /// 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 /// # Parameters
/// - `env`: The JNI environment. /// - `env`: The JNI environment.
@ -41,7 +41,7 @@ pub fn set_err_msg_and_throw_exception<'local>(
.expect("Failed to convert to byte array"); .expect("Failed to convert to byte array");
match env.call_method( match env.call_method(
obj, obj,
"throwLimboException", "throwTursoException",
"(I[B)V", "(I[B)V",
&[err_code.into(), (&error_message_bytes).into()], &[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 java.util.Properties;
import tech.turso.annotations.Nullable; import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck; import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboPropertiesHolder; import tech.turso.core.TursoPropertiesHolder;
import tech.turso.jdbc4.JDBC4Connection; import tech.turso.jdbc4.JDBC4Connection;
import tech.turso.utils.Logger; import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory; import tech.turso.utils.LoggerFactory;
public final class JDBC implements Driver { public final class JDBC implements Driver {
private static final Logger logger = LoggerFactory.getLogger(JDBC.class); 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 { static {
try { try {
@ -33,7 +34,7 @@ public final class JDBC implements Driver {
} }
private static boolean isValidURL(String url) { 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) { private static String extractAddress(String url) {
@ -53,17 +54,17 @@ public final class JDBC implements Driver {
@Override @Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
return LimboConfig.getDriverPropertyInfo(); return TursoConfig.getDriverPropertyInfo();
} }
@Override @Override
public int getMajorVersion() { public int getMajorVersion() {
return Integer.parseInt(LimboPropertiesHolder.getDriverVersion().split("\\.")[0]); return Integer.parseInt(TursoPropertiesHolder.getDriverVersion().split("\\.")[0]);
} }
@Override @Override
public int getMinorVersion() { public int getMinorVersion() {
return Integer.parseInt(LimboPropertiesHolder.getDriverVersion().split("\\.")[1]); return Integer.parseInt(TursoPropertiesHolder.getDriverVersion().split("\\.")[1]);
} }
@Override @Override

View file

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

View file

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

View file

@ -2,8 +2,8 @@ package tech.turso;
import tech.turso.core.SqliteCode; import tech.turso.core.SqliteCode;
/** Limbo error code. Superset of SQLite3 error code. */ /** Turso error code. Superset of SQLite3 error code. */
public enum LimboErrorCode { public enum TursoErrorCode {
SQLITE_OK(SqliteCode.SQLITE_OK, "Successful result"), SQLITE_OK(SqliteCode.SQLITE_OK, "Successful result"),
SQLITE_ERROR(SqliteCode.SQLITE_ERROR, "SQL error or missing database"), SQLITE_ERROR(SqliteCode.SQLITE_ERROR, "SQL error or missing database"),
SQLITE_INTERNAL(SqliteCode.SQLITE_INTERNAL, "An internal logic error in SQLite"), 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"), SQLITE_NULL(SqliteCode.SQLITE_NULL, "Null type"),
UNKNOWN_ERROR(-1, "Unknown error"), UNKNOWN_ERROR(-1, "Unknown error"),
LIMBO_FAILED_TO_PARSE_BYTE_ARRAY(1100, "Failed to parse ut8 byte array"), TURSO_FAILED_TO_PARSE_BYTE_ARRAY(1100, "Failed to parse ut8 byte array"),
LIMBO_FAILED_TO_PREPARE_STATEMENT(1200, "Failed to prepare statement"), TURSO_FAILED_TO_PREPARE_STATEMENT(1200, "Failed to prepare statement"),
LIMBO_ETC(9999, "Unclassified error"); TURSO_ETC(9999, "Unclassified error");
public final int code; public final int code;
public final String message; public final String message;
@ -48,14 +48,14 @@ public enum LimboErrorCode {
* @param code Error code * @param code Error code
* @param message Message for the error. * @param message Message for the error.
*/ */
LimboErrorCode(int code, String message) { TursoErrorCode(int code, String message) {
this.code = code; this.code = code;
this.message = message; this.message = message;
} }
public static LimboErrorCode getErrorCode(int errorCode) { public static TursoErrorCode getErrorCode(int errorCode) {
for (LimboErrorCode limboErrorCode : LimboErrorCode.values()) { for (TursoErrorCode tursoErrorCode : TursoErrorCode.values()) {
if (errorCode == limboErrorCode.code) return limboErrorCode; if (errorCode == tursoErrorCode.code) return tursoErrorCode;
} }
return UNKNOWN_ERROR; return UNKNOWN_ERROR;
@ -63,6 +63,6 @@ public enum LimboErrorCode {
@Override @Override
public String toString() { 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.sql.SQLException;
import java.util.Properties; import java.util.Properties;
import tech.turso.annotations.NativeInvocation; import tech.turso.annotations.NativeInvocation;
import tech.turso.utils.LimboExceptionUtils;
import tech.turso.utils.Logger; import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory; import tech.turso.utils.LoggerFactory;
import tech.turso.utils.TursoExceptionUtils;
public final class LimboConnection { public final class TursoConnection {
private static final Logger logger = LoggerFactory.getLogger(LimboConnection.class);
private static final Logger logger = LoggerFactory.getLogger(TursoConnection.class);
private final String url; private final String url;
private final long connectionPtr; private final long connectionPtr;
private final LimboDB database; private final TursoDB database;
private boolean closed; private boolean closed;
public LimboConnection(String url, String filePath) throws SQLException { public TursoConnection(String url, String filePath) throws SQLException {
this(url, filePath, new Properties()); 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 * @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.url = url;
this.database = open(url, filePath, properties); this.database = open(url, filePath, properties);
this.connectionPtr = this.database.connect(); 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 { throws SQLException {
return LimboDBFactory.open(url, filePath, properties); return TursoDBFactory.open(url, filePath, properties);
} }
public void checkOpen() throws SQLException { public void checkOpen() throws SQLException {
@ -61,7 +62,7 @@ public final class LimboConnection {
return closed; return closed;
} }
public LimboDB getDatabase() { public TursoDB getDatabase() {
return database; return database;
} }
@ -72,18 +73,18 @@ public final class LimboConnection {
* @return Pointer to statement. * @return Pointer to statement.
* @throws SQLException if a database access error occurs. * @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); logger.trace("DriverManager [{}] [SQLite EXEC] {}", Thread.currentThread().getName(), sql);
byte[] sqlBytes = stringToUtf8ByteArray(sql); byte[] sqlBytes = stringToUtf8ByteArray(sql);
if (sqlBytes == null) { if (sqlBytes == null) {
throw new SQLException("Failed to convert " + sql + " into bytes"); 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; 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 * Checks whether the type, concurrency, and holdability settings for a {@link ResultSet} are
* supported by the SQLite interface. Supported settings are: * supported by the SQLite interface. Supported settings are:
@ -117,8 +118,8 @@ public final class LimboConnection {
* @param errorCode Error code. * @param errorCode Error code.
* @param errorMessageBytes Error message. * @param errorMessageBytes Error message.
*/ */
@NativeInvocation(invokedFrom = "limbo_connection.rs") @NativeInvocation(invokedFrom = "turso_connection.rs")
private void throwLimboException(int errorCode, byte[] errorMessageBytes) throws SQLException { private void throwTursoException(int errorCode, byte[] errorMessageBytes) throws SQLException {
LimboExceptionUtils.throwLimboException(errorCode, errorMessageBytes); TursoExceptionUtils.throwTursoException(errorCode, errorMessageBytes);
} }
} }

View file

@ -7,16 +7,17 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.sql.SQLException; import java.sql.SQLException;
import tech.turso.LimboErrorCode; import tech.turso.TursoErrorCode;
import tech.turso.annotations.NativeInvocation; import tech.turso.annotations.NativeInvocation;
import tech.turso.annotations.VisibleForTesting; import tech.turso.annotations.VisibleForTesting;
import tech.turso.utils.LimboExceptionUtils;
import tech.turso.utils.Logger; import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory; import tech.turso.utils.LoggerFactory;
import tech.turso.utils.TursoExceptionUtils;
/** This class provides a thin JNI layer over the SQLite3 C API. */ /** This class provides a thin JNI layer over the SQLite3 C API. */
public final class LimboDB implements AutoCloseable { public final class TursoDB implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(LimboDB.class);
private static final Logger logger = LoggerFactory.getLogger(TursoDB.class);
// Pointer to database instance // Pointer to database instance
private long dbPointer; private long dbPointer;
private boolean isOpen; private boolean isOpen;
@ -39,10 +40,10 @@ public final class LimboDB implements AutoCloseable {
* extensions. * extensions.
*/ */
enum Architecture { enum Architecture {
MACOS_ARM64("libs/macos_arm64/lib_limbo_java.dylib", ".dylib"), MACOS_ARM64("libs/macos_arm64/lib_turso_java.dylib", ".dylib"),
MACOS_X86("libs/macos_x86/lib_limbo_java.dylib", ".dylib"), MACOS_X86("libs/macos_x86/lib_turso_java.dylib", ".dylib"),
LINUX_X86("libs/linux_x86/lib_limbo_java.so", ".so"), LINUX_X86("libs/linux_x86/lib_turso_java.so", ".so"),
WINDOWS("libs/windows/lib_limbo_java.dll", ".dll"), WINDOWS("libs/windows/lib_turso_java.dll", ".dll"),
UNSUPPORTED("", ""); UNSUPPORTED("", "");
private final String libPath; 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 * 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 * 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 * 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. * 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. * 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. * @return true if the library was successfully loaded, false otherwise.
*/ */
private static boolean loadFromSystemPath() { private static boolean loadFromSystemPath() {
try { try {
System.loadLibrary("_limbo_java"); System.loadLibrary("_turso_java");
return true; return true;
} catch (Throwable t) { } catch (Throwable t) {
logger.info("Unable to load from default path: {}", String.valueOf(t)); logger.info("Unable to load from default path: {}", String.valueOf(t));
@ -148,7 +149,7 @@ public final class LimboDB implements AutoCloseable {
} }
try { try {
InputStream is = LimboDB.class.getClassLoader().getResourceAsStream(arch.getLibPath()); InputStream is = TursoDB.class.getClassLoader().getResourceAsStream(arch.getLibPath());
assert is != null; assert is != null;
File file = convertInputStreamToFile(is, arch); File file = convertInputStreamToFile(is, arch);
System.load(file.getPath()); 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 * @param filePath e.g. path to file
*/ */
public static LimboDB create(String url, String filePath) throws SQLException { public static TursoDB create(String url, String filePath) throws SQLException {
return new LimboDB(url, filePath); return new TursoDB(url, filePath);
} }
// TODO: receive config as argument // TODO: receive config as argument
private LimboDB(String url, String filePath) { private TursoDB(String url, String filePath) {
this.url = url; this.url = url;
this.filePath = filePath; this.filePath = filePath;
} }
@ -208,14 +209,14 @@ public final class LimboDB implements AutoCloseable {
private void open0(String filePath, int openFlags) throws SQLException { private void open0(String filePath, int openFlags) throws SQLException {
if (isOpen) { if (isOpen) {
throw LimboExceptionUtils.buildLimboException( throw TursoExceptionUtils.buildTursoException(
LimboErrorCode.LIMBO_ETC.code, "Already opened"); TursoErrorCode.TURSO_ETC.code, "Already opened");
} }
byte[] filePathBytes = stringToUtf8ByteArray(filePath); byte[] filePathBytes = stringToUtf8ByteArray(filePath);
if (filePathBytes == null) { if (filePathBytes == null) {
throw LimboExceptionUtils.buildLimboException( throw TursoExceptionUtils.buildTursoException(
LimboErrorCode.LIMBO_ETC.code, TursoErrorCode.TURSO_ETC.code,
"File path cannot be converted to byteArray. File name: " + filePath); "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 errorCode Error code.
* @param errorMessageBytes Error message. * @param errorMessageBytes Error message.
*/ */
@NativeInvocation(invokedFrom = "limbo_db.rs") @NativeInvocation(invokedFrom = "turso_db.rs")
private void throwLimboException(int errorCode, byte[] errorMessageBytes) throws SQLException { private void throwTursoException(int errorCode, byte[] errorMessageBytes) throws SQLException {
LimboExceptionUtils.throwLimboException(errorCode, errorMessageBytes); TursoExceptionUtils.throwTursoException(errorCode, errorMessageBytes);
} }
} }

View file

@ -5,12 +5,12 @@ import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* Factory class for managing and creating instances of {@link LimboDB}. This class ensures that * Factory class for managing and creating instances of {@link TursoDB}. This class ensures that
* multiple instances of {@link LimboDB} with the same URL are not created. * 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<>(); new ConcurrentHashMap<>();
/** /**
@ -20,11 +20,11 @@ public final class LimboDBFactory {
* @param url the URL of the database * @param url the URL of the database
* @param filePath the path to the database file * @param filePath the path to the database file
* @param properties additional properties for the database connection * @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 SQLException if there is an error opening the connection
* @throws IllegalArgumentException if the fileName is empty * @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 { throws SQLException {
if (databaseHolder.containsKey(url)) { if (databaseHolder.containsKey(url)) {
return databaseHolder.get(url); return databaseHolder.get(url);
@ -34,10 +34,10 @@ public final class LimboDBFactory {
throw new IllegalArgumentException("filePath should not be empty"); throw new IllegalArgumentException("filePath should not be empty");
} }
final LimboDB database; final TursoDB database;
try { try {
LimboDB.load(); TursoDB.load();
database = LimboDB.create(url, filePath); database = TursoDB.create(url, filePath);
} catch (Exception e) { } catch (Exception e) {
throw new SQLException("Error opening connection", 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.Logger;
import tech.turso.utils.LoggerFactory; import tech.turso.utils.LoggerFactory;
public class LimboPropertiesHolder { public class TursoPropertiesHolder {
private static final Logger logger = LoggerFactory.getLogger(LimboPropertiesHolder.class);
private static final Logger logger = LoggerFactory.getLogger(TursoPropertiesHolder.class);
private static String driverName = ""; private static String driverName = "";
private static String driverVersion = ""; private static String driverVersion = "";
static { static {
try (InputStream limboJdbcPropStream = try (InputStream tursoJdbcPropStream =
JDBC4DatabaseMetaData.class.getClassLoader().getResourceAsStream("limbo-jdbc.properties")) { JDBC4DatabaseMetaData.class
if (limboJdbcPropStream == null) { .getClassLoader()
throw new IOException("Cannot load limbo-jdbc.properties from jar"); .getResourceAsStream("turso-jdbc.properties"); ) {
if (tursoJdbcPropStream == null) {
throw new IOException("Cannot load turso-jdbc.properties from jar");
} }
final Properties properties = new Properties(); final Properties properties = new Properties();
properties.load(limboJdbcPropStream); properties.load(tursoJdbcPropStream);
driverName = properties.getProperty("driverName"); driverName = properties.getProperty("driverName");
driverVersion = properties.getProperty("driverVersion"); driverVersion = properties.getProperty("driverVersion");
} catch (IOException e) { } catch (IOException e) {

View file

@ -7,17 +7,17 @@ import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory; 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. * 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. * 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 // Name of the columns
private String[] columnNames = new String[0]; private String[] columnNames = new String[0];
@ -31,13 +31,13 @@ public final class LimboResultSet {
private int row = 0; private int row = 0;
private boolean pastLastRow = false; private boolean pastLastRow = false;
@Nullable private LimboStepResult lastStepResult; @Nullable private TursoStepResult lastStepResult;
public static LimboResultSet of(LimboStatement statement) { public static TursoResultSet of(TursoStatement statement) {
return new LimboResultSet(statement); return new TursoResultSet(statement);
} }
private LimboResultSet(LimboStatement statement) { private TursoResultSet(TursoStatement statement) {
this.open = true; this.open = true;
this.statement = statement; 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 * 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. * 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 * When a call to the <code>next</code> method returns <code>false</code>, the cursor is
* positioned after the last row. * 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. * cursor can only move forward.
*/ */
public boolean next() throws SQLException { public boolean next() throws SQLException {
@ -157,7 +157,7 @@ public final class LimboResultSet {
@Override @Override
public String toString() { public String toString() {
return "LimboResultSet{" return ("tursoResultSet{"
+ "statement=" + "statement="
+ statement + statement
+ ", isEmptyResultSet=" + ", isEmptyResultSet="
@ -172,6 +172,6 @@ public final class LimboResultSet {
+ pastLastRow + pastLastRow
+ ", lastResult=" + ", lastResult="
+ lastStepResult + lastStepResult
+ '}'; + '}');
} }
} }

View file

@ -3,36 +3,37 @@ package tech.turso.core;
import java.sql.SQLException; import java.sql.SQLException;
import tech.turso.annotations.NativeInvocation; import tech.turso.annotations.NativeInvocation;
import tech.turso.annotations.Nullable; import tech.turso.annotations.Nullable;
import tech.turso.utils.LimboExceptionUtils;
import tech.turso.utils.Logger; import tech.turso.utils.Logger;
import tech.turso.utils.LoggerFactory; 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 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> * the reading of another, each must have been generated by different <code>TursoStatement</code>
* objects. All execution method in the <code>LimboStatement</code> implicitly close the current * 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. * <code>resultSet</code> object of the statement if an open one exists.
*/ */
public final class LimboStatement { public final class TursoStatement {
private static final Logger log = LoggerFactory.getLogger(LimboStatement.class);
private static final Logger log = LoggerFactory.getLogger(TursoStatement.class);
private final String sql; private final String sql;
private final long statementPointer; private final long statementPointer;
private final LimboResultSet resultSet; private final TursoResultSet resultSet;
private boolean closed; private boolean closed;
// TODO: what if the statement we ran was DDL, update queries and etc. Should we still create a // TODO: what if the statement we ran was DDL, update queries and etc. Should we still create a
// resultSet? // resultSet?
public LimboStatement(String sql, long statementPointer) { public TursoStatement(String sql, long statementPointer) {
this.sql = sql; this.sql = sql;
this.statementPointer = statementPointer; this.statementPointer = statementPointer;
this.resultSet = LimboResultSet.of(this); this.resultSet = TursoResultSet.of(this);
log.debug("Creating statement with sql: {}", this.sql); log.debug("Creating statement with sql: {}", this.sql);
} }
public LimboResultSet getResultSet() { public TursoResultSet getResultSet() {
return resultSet; return resultSet;
} }
@ -46,8 +47,8 @@ public final class LimboStatement {
return resultSet.hasLastStepReturnedRow(); return resultSet.hasLastStepReturnedRow();
} }
LimboStepResult step() throws SQLException { TursoStepResult step() throws SQLException {
final LimboStepResult result = step(this.statementPointer); final TursoStepResult result = step(this.statementPointer);
if (result == null) { if (result == null) {
throw new SQLException("step() returned null, which is only returned when an error occurs"); 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 * Because turso supports async I/O, it is possible to return a {@link TursoStepResult} with
* {@link LimboStepResult#STEP_RESULT_ID_ROW}. However, this is handled by the native side, so you * {@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 LimboStepResult#STEP_RESULT_ID_ROW}. * can expect that this method will not return a {@link TursoStepResult#STEP_RESULT_ID_ROW}.
*/ */
@Nullable @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. * Throws formatted SQLException with error code and message.
@ -69,9 +70,9 @@ public final class LimboStatement {
* @param errorCode Error code. * @param errorCode Error code.
* @param errorMessageBytes Error message. * @param errorMessageBytes Error message.
*/ */
@NativeInvocation(invokedFrom = "limbo_statement.rs") @NativeInvocation(invokedFrom = "turso_statement.rs")
private void throwLimboException(int errorCode, byte[] errorMessageBytes) throws SQLException { private void throwTursoException(int errorCode, byte[] errorMessageBytes) throws SQLException {
LimboExceptionUtils.throwLimboException(errorCode, errorMessageBytes); TursoExceptionUtils.throwTursoException(errorCode, errorMessageBytes);
} }
/** /**
@ -90,8 +91,8 @@ public final class LimboStatement {
private native void _close(long statementPointer); private native void _close(long statementPointer);
/** /**
* Initializes the column metadata, such as the names of the columns. Since {@link LimboStatement} * Initializes the column metadata, such as the names of the columns. Since {@link tursoStatement}
* can only have a single {@link LimboResultSet}, it is appropriate to place the initialization of * can only have a single {@link tursoResultSet}, it is appropriate to place the initialization of
* column metadata here. * column metadata here.
* *
* @throws SQLException if a database access error occurs while retrieving column names * @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 * 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, * <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. * 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; private native long totalChanges(long statementPointer) throws SQLException;
/** /**
* Checks if the statement is closed. * Checks if the statement is closed.
* *
@ -240,12 +242,12 @@ public final class LimboStatement {
@Override @Override
public String toString() { public String toString() {
return "LimboStatement{" return ("tursoStatement{"
+ "statementPointer=" + "statementPointer="
+ statementPointer + statementPointer
+ ", sql='" + ", sql='"
+ sql + sql
+ '\'' + '\''
+ '}'; + '}');
} }
} }

View file

@ -4,8 +4,9 @@ import java.util.Arrays;
import tech.turso.annotations.NativeInvocation; import tech.turso.annotations.NativeInvocation;
import tech.turso.annotations.Nullable; import tech.turso.annotations.Nullable;
/** Represents the step result of limbo's statement's step function. */ /** Represents the step result of turso's statement's step function. */
public final class LimboStepResult { public final class TursoStepResult {
private static final int STEP_RESULT_ID_ROW = 10; 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_IO = 20;
private static final int STEP_RESULT_ID_DONE = 30; 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_BUSY = 50;
private static final int STEP_RESULT_ID_ERROR = 60; private static final int STEP_RESULT_ID_ERROR = 60;
// Identifier for limbo's StepResult // Identifier for Turso's StepResult
private final int stepResultId; private final int stepResultId;
@Nullable private final Object[] result; @Nullable private final Object[] result;
@NativeInvocation(invokedFrom = "limbo_statement.rs") @NativeInvocation(invokedFrom = "turso_statement.rs")
public LimboStepResult(int stepResultId) { public TursoStepResult(int stepResultId) {
this.stepResultId = stepResultId; this.stepResultId = stepResultId;
this.result = null; this.result = null;
} }
@NativeInvocation(invokedFrom = "limbo_statement.rs") @NativeInvocation(invokedFrom = "turso_statement.rs")
public LimboStepResult(int stepResultId, Object[] result) { public TursoStepResult(int stepResultId, Object[] result) {
this.stepResultId = stepResultId; this.stepResultId = stepResultId;
this.result = result; this.result = result;
} }
@ -41,10 +43,10 @@ public final class LimboStepResult {
public boolean isInInvalidState() { public boolean isInInvalidState() {
// current implementation doesn't allow STEP_RESULT_ID_IO to be returned // 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_INTERRUPT
|| stepResultId == STEP_RESULT_ID_BUSY || stepResultId == STEP_RESULT_ID_BUSY
|| stepResultId == STEP_RESULT_ID_ERROR; || stepResultId == STEP_RESULT_ID_ERROR);
} }
@Nullable @Nullable
@ -54,12 +56,12 @@ public final class LimboStepResult {
@Override @Override
public String toString() { public String toString() {
return "LimboStepResult{" return ("tursoStepResult{"
+ "stepResultName=" + "stepResultName="
+ getStepResultName() + getStepResultName()
+ ", result=" + ", result="
+ Arrays.toString(result) + Arrays.toString(result)
+ '}'; + '}');
} }
private String getStepResultName() { 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.Properties;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import tech.turso.annotations.SkipNullableCheck; import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboConnection; import tech.turso.core.TursoConnection;
import tech.turso.core.LimboStatement; import tech.turso.core.TursoStatement;
public final class JDBC4Connection implements Connection { public final class JDBC4Connection implements Connection {
private final LimboConnection connection; private final TursoConnection connection;
private Map<String, Class<?>> typeMap = new HashMap<>(); private Map<String, Class<?>> typeMap = new HashMap<>();
public JDBC4Connection(String url, String filePath) throws SQLException { 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 { 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); return connection.prepare(sql);
} }
@ -154,7 +154,7 @@ public final class JDBC4Connection implements Connection {
public void setHoldability(int holdability) throws SQLException { public void setHoldability(int holdability) throws SQLException {
connection.checkOpen(); connection.checkOpen();
if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT) { 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( public CallableStatement prepareCall(
String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException { throws SQLException {
throw new SQLException("Limbo does not support stored procedures"); throw new SQLException("turso does not support stored procedures");
} }
@Override @Override

View file

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

View file

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

View file

@ -24,13 +24,13 @@ import java.util.Calendar;
import java.util.Map; import java.util.Map;
import tech.turso.annotations.Nullable; import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck; import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboResultSet; import tech.turso.core.TursoResultSet;
public final class JDBC4ResultSet implements ResultSet, ResultSetMetaData { 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; this.resultSet = resultSet;
} }

View file

@ -10,15 +10,16 @@ import java.sql.Statement;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import tech.turso.annotations.Nullable; import tech.turso.annotations.Nullable;
import tech.turso.annotations.SkipNullableCheck; import tech.turso.annotations.SkipNullableCheck;
import tech.turso.core.LimboResultSet; import tech.turso.core.TursoResultSet;
import tech.turso.core.LimboStatement; import tech.turso.core.TursoStatement;
public class JDBC4Statement implements Statement { public class JDBC4Statement implements Statement {
private final JDBC4Connection connection; 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 // field to manage JDBC4Statement lifecycle
private boolean closed; private boolean closed;
private boolean closeOnCompletion; private boolean closeOnCompletion;
@ -76,7 +77,7 @@ public class JDBC4Statement implements Statement {
execute(sql); execute(sql);
requireNonNull(statement, "statement should not be null after running execute method"); requireNonNull(statement, "statement should not be null after running execute method");
final LimboResultSet resultSet = statement.getResultSet(); final TursoResultSet resultSet = statement.getResultSet();
resultSet.consumeAll(); resultSet.consumeAll();
return (int) (statement.totalChanges() - previousTotalChanges); return (int) (statement.totalChanges() - previousTotalChanges);

View file

@ -3,21 +3,22 @@ package tech.turso.utils;
import static tech.turso.utils.ByteArrayUtils.utf8ByteBufferToString; import static tech.turso.utils.ByteArrayUtils.utf8ByteBufferToString;
import java.sql.SQLException; import java.sql.SQLException;
import tech.turso.LimboErrorCode; import tech.turso.TursoErrorCode;
import tech.turso.annotations.Nullable; 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. * Throws formatted SQLException with error code and message.
* *
* @param errorCode Error code. * @param errorCode Error code.
* @param errorMessageBytes Error message. * @param errorMessageBytes Error message.
*/ */
public static void throwLimboException(int errorCode, byte[] errorMessageBytes) public static void throwTursoException(int errorCode, byte[] errorMessageBytes)
throws SQLException { throws SQLException {
String errorMessage = utf8ByteBufferToString(errorMessageBytes); 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 errorCode Error code.
* @param errorMessage Error message. * @param errorMessage Error message.
*/ */
public static LimboException buildLimboException(int errorCode, @Nullable String errorMessage) public static TursoException buildTursoException(int errorCode, @Nullable String errorMessage)
throws SQLException { throws SQLException {
LimboErrorCode code = LimboErrorCode.getErrorCode(errorCode); TursoErrorCode code = TursoErrorCode.getErrorCode(errorCode);
String msg; String msg;
if (code == LimboErrorCode.UNKNOWN_ERROR) { if (code == TursoErrorCode.UNKNOWN_ERROR) {
msg = String.format("%s:%s (%s)", code, errorCode, errorMessage); msg = String.format("%s:%s (%s)", code, errorCode, errorMessage);
} else { } else {
msg = String.format("%s (%s)", code, errorMessage); 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 # find a way to relate driverVersion with project.version defined in gradle.properties
driverVersion=0.0.1-SNAPSHOT driverVersion=0.0.1-SNAPSHOT

View file

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

View file

@ -22,26 +22,26 @@ class JDBCTest {
@Test @Test
void non_null_connection_is_returned_when_valid_url_is_passed() throws Exception { void non_null_connection_is_returned_when_valid_url_is_passed() throws Exception {
String fileUrl = TestUtils.createTempFile(); 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(); assertThat(connection).isNotNull();
} }
@Test @Test
void connection_can_be_retrieved_from_DriverManager() throws SQLException { 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(); assertThat(connection).isNotNull();
} }
} }
@Test @Test
void retrieve_version() { void retrieve_version() {
assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:sqlite:").getMajorVersion()); assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:turso:").getMajorVersion());
assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:sqlite:").getMinorVersion()); assertDoesNotThrow(() -> DriverManager.getDriver("jdbc:turso:").getMinorVersion());
} }
@Test @Test
void all_driver_property_info_should_have_a_description() throws Exception { 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)) assertThat(driver.getPropertyInfo(null, null))
.allSatisfy((info) -> assertThat(info.description).isNotNull()); .allSatisfy((info) -> assertThat(info.description).isNotNull());
} }

View file

@ -6,6 +6,6 @@ import java.nio.file.Files;
public class TestUtils { public class TestUtils {
/** Create temporary file and returns the path. */ /** Create temporary file and returns the path. */
public static String createTempFile() throws IOException { 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 org.junit.jupiter.api.Test;
import tech.turso.TestUtils; import tech.turso.TestUtils;
class LimboDBFactoryTest { class TursoDBFactoryTest {
@Test @Test
void single_database_should_be_created_when_urls_are_same() throws Exception { void single_database_should_be_created_when_urls_are_same() throws Exception {
String filePath = TestUtils.createTempFile(); String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath; String url = "jdbc:turso:" + filePath;
LimboDB db1 = LimboDBFactory.open(url, filePath, new Properties()); TursoDB db1 = TursoDBFactory.open(url, filePath, new Properties());
LimboDB db2 = LimboDBFactory.open(url, filePath, new Properties()); TursoDB db2 = TursoDBFactory.open(url, filePath, new Properties());
assertEquals(db1, db2); assertEquals(db1, db2);
} }
@ -22,10 +22,10 @@ class LimboDBFactoryTest {
void multiple_databases_should_be_created_when_urls_differ() throws Exception { void multiple_databases_should_be_created_when_urls_differ() throws Exception {
String filePath1 = TestUtils.createTempFile(); String filePath1 = TestUtils.createTempFile();
String filePath2 = TestUtils.createTempFile(); String filePath2 = TestUtils.createTempFile();
String url1 = "jdbc:sqlite:" + filePath1; String url1 = "jdbc:turso:" + filePath1;
String url2 = "jdbc:sqlite:" + filePath2; String url2 = "jdbc:turso:" + filePath2;
LimboDB db1 = LimboDBFactory.open(url1, filePath1, new Properties()); TursoDB db1 = TursoDBFactory.open(url1, filePath1, new Properties());
LimboDB db2 = LimboDBFactory.open(url2, filePath2, new Properties()); TursoDB db2 = TursoDBFactory.open(url2, filePath2, new Properties());
assertNotEquals(db1, db2); assertNotEquals(db1, db2);
} }
} }

View file

@ -6,25 +6,25 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import java.sql.SQLException; import java.sql.SQLException;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import tech.turso.LimboErrorCode;
import tech.turso.TestUtils; 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 @Test
void db_should_open_normally() throws Exception { void db_should_open_normally() throws Exception {
LimboDB.load(); TursoDB.load();
String dbPath = TestUtils.createTempFile(); String dbPath = TestUtils.createTempFile();
LimboDB db = LimboDB.create("jdbc:sqlite" + dbPath, dbPath); TursoDB db = TursoDB.create("jdbc:turso" + dbPath, dbPath);
db.open(0); db.open(0);
} }
@Test @Test
void db_should_close_normally() throws Exception { void db_should_close_normally() throws Exception {
LimboDB.load(); TursoDB.load();
String dbPath = TestUtils.createTempFile(); String dbPath = TestUtils.createTempFile();
LimboDB db = LimboDB.create("jdbc:sqlite" + dbPath, dbPath); TursoDB db = TursoDB.create("jdbc:turso" + dbPath, dbPath);
db.open(0); db.open(0);
db.close(); db.close();
@ -33,9 +33,9 @@ public class LimboDBTest {
@Test @Test
void should_throw_exception_when_opened_twice() throws Exception { void should_throw_exception_when_opened_twice() throws Exception {
LimboDB.load(); TursoDB.load();
String dbPath = TestUtils.createTempFile(); String dbPath = TestUtils.createTempFile();
LimboDB db = LimboDB.create("jdbc:sqlite:" + dbPath, dbPath); TursoDB db = TursoDB.create("jdbc:turso:" + dbPath, dbPath);
db.open(0); db.open(0);
assertThatThrownBy(() -> db.open(0)).isInstanceOf(SQLException.class); assertThatThrownBy(() -> db.open(0)).isInstanceOf(SQLException.class);
@ -43,17 +43,17 @@ public class LimboDBTest {
@Test @Test
void throwJavaException_should_throw_appropriate_java_exception() throws Exception { void throwJavaException_should_throw_appropriate_java_exception() throws Exception {
LimboDB.load(); TursoDB.load();
String dbPath = TestUtils.createTempFile(); 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 { try {
db.throwJavaException(limboExceptionCode); db.throwJavaException(tursoExceptionCode);
} catch (Exception e) { } catch (Exception e) {
assertThat(e).isInstanceOf(LimboException.class); assertThat(e).isInstanceOf(TursoException.class);
LimboException limboException = (LimboException) e; TursoException tursoException = (TursoException) e;
assertThat(limboException.getResultCode().code).isEqualTo(limboExceptionCode); 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.TestUtils;
import tech.turso.jdbc4.JDBC4Connection; import tech.turso.jdbc4.JDBC4Connection;
class LimboStatementTest { class TursoStatementTest {
private JDBC4Connection connection; private JDBC4Connection connection;
@BeforeEach @BeforeEach
void setUp() throws Exception { void setUp() throws Exception {
String filePath = TestUtils.createTempFile(); String filePath = TestUtils.createTempFile();
String url = "jdbc:sqlite:" + filePath; String url = "jdbc:turso:" + filePath;
connection = new JDBC4Connection(url, filePath, new Properties()); connection = new JDBC4Connection(url, filePath, new Properties());
} }
@Test @Test
void closing_statement_closes_related_resources() throws Exception { void closing_statement_closes_related_resources() throws Exception {
LimboStatement stmt = connection.prepare("SELECT 1;"); TursoStatement stmt = connection.prepare("SELECT 1;");
stmt.execute(); stmt.execute();
stmt.close(); stmt.close();
@ -38,9 +38,9 @@ class LimboStatementTest {
runSql("CREATE TABLE users (name TEXT, age INT, country TEXT);"); runSql("CREATE TABLE users (name TEXT, age INT, country TEXT);");
runSql("INSERT INTO users VALUES ('seonwoo', 30, 'KR');"); 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(); stmt.initializeColumnMetadata();
final LimboResultSet rs = stmt.getResultSet(); final TursoResultSet rs = stmt.getResultSet();
final String[] columnNames = rs.getColumnNames(); final String[] columnNames = rs.getColumnNames();
assertEquals("name", columnNames[0]); assertEquals("name", columnNames[0]);
@ -51,12 +51,12 @@ class LimboStatementTest {
@Test @Test
void test_bindNull() throws Exception { void test_bindNull() throws Exception {
runSql("CREATE TABLE test (col1 TEXT);"); 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.bindNull(1);
stmt.execute(); stmt.execute();
stmt.close(); stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;"); TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute(); selectStmt.execute();
assertNull(selectStmt.getResultSet().get(1)); assertNull(selectStmt.getResultSet().get(1));
selectStmt.close(); selectStmt.close();
@ -65,12 +65,12 @@ class LimboStatementTest {
@Test @Test
void test_bindLong() throws Exception { void test_bindLong() throws Exception {
runSql("CREATE TABLE test (col1 BIGINT);"); 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.bindLong(1, 123456789L);
stmt.execute(); stmt.execute();
stmt.close(); stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;"); TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute(); selectStmt.execute();
assertEquals(123456789L, selectStmt.getResultSet().get(1)); assertEquals(123456789L, selectStmt.getResultSet().get(1));
selectStmt.close(); selectStmt.close();
@ -79,12 +79,12 @@ class LimboStatementTest {
@Test @Test
void test_bindDouble() throws Exception { void test_bindDouble() throws Exception {
runSql("CREATE TABLE test (col1 DOUBLE);"); 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.bindDouble(1, 3.14);
stmt.execute(); stmt.execute();
stmt.close(); stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;"); TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute(); selectStmt.execute();
assertEquals(3.14, selectStmt.getResultSet().get(1)); assertEquals(3.14, selectStmt.getResultSet().get(1));
selectStmt.close(); selectStmt.close();
@ -93,12 +93,12 @@ class LimboStatementTest {
@Test @Test
void test_bindText() throws Exception { void test_bindText() throws Exception {
runSql("CREATE TABLE test (col1 TEXT);"); 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.bindText(1, "hello");
stmt.execute(); stmt.execute();
stmt.close(); stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;"); TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute(); selectStmt.execute();
assertEquals("hello", selectStmt.getResultSet().get(1)); assertEquals("hello", selectStmt.getResultSet().get(1));
selectStmt.close(); selectStmt.close();
@ -107,20 +107,20 @@ class LimboStatementTest {
@Test @Test
void test_bindBlob() throws Exception { void test_bindBlob() throws Exception {
runSql("CREATE TABLE test (col1 BLOB);"); 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}; byte[] blob = {1, 2, 3, 4, 5};
stmt.bindBlob(1, blob); stmt.bindBlob(1, blob);
stmt.execute(); stmt.execute();
stmt.close(); stmt.close();
LimboStatement selectStmt = connection.prepare("SELECT col1 FROM test;"); TursoStatement selectStmt = connection.prepare("SELECT col1 FROM test;");
selectStmt.execute(); selectStmt.execute();
assertArrayEquals(blob, (byte[]) selectStmt.getResultSet().get(1)); assertArrayEquals(blob, (byte[]) selectStmt.getResultSet().get(1));
selectStmt.close(); selectStmt.close();
} }
private void runSql(String sql) throws Exception { private void runSql(String sql) throws Exception {
LimboStatement stmt = connection.prepare(sql); TursoStatement stmt = connection.prepare(sql);
while (stmt.execute()) { while (stmt.execute()) {
stmt.execute(); stmt.execute();
} }

View file

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

View file

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

View file

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

View file

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

View file

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