-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
lib.rs
477 lines (434 loc) · 15.9 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#![feature(abi_vectorcall)]
extern crate ext_php_rs;
#[allow(non_snake_case, deprecated, unused_attributes)]
#[cfg_attr(windows, feature(abi_vectorcall))]
extern crate lazy_static;
pub mod generator;
pub mod hooks;
pub mod providers;
pub mod result;
pub mod statement;
pub mod transaction;
pub mod utils;
use crate::generator::LibSQLIterator;
use crate::result::FetchResult;
use crate::result::LibSQLResult;
use crate::statement::LibSQLStatement;
use crate::transaction::LibSQLTransaction;
use ext_php_rs::prelude::*;
use ext_php_rs::types::Zval;
use hooks::load_extensions::ExtensionParams;
use std::{path::Path, collections::HashMap, sync::Mutex};
use utils::{
config_value::ConfigValue,
query_params::QueryParameters,
runtime::{get_mode, parse_dsn},
};
lazy_static::lazy_static! {
static ref CONNECTION_REGISTRY: Mutex<HashMap<String, libsql::Connection>> = Mutex::new(HashMap::new());
static ref TRANSACTION_REGISTRY: Mutex<HashMap<String, libsql::Transaction>> = Mutex::new(HashMap::new());
static ref STATEMENT_REGISTRY: Mutex<HashMap<String, libsql::Statement>> = Mutex::new(HashMap::new());
}
pub const LIBSQL_PHP_VERSION: &str = "1.4.2";
/// Represents the flag for opening a database in read-only mode.
pub const LIBSQL_OPEN_READONLY: i32 = 1;
/// Represents the flag for opening a database in read-write mode.
pub const LIBSQL_OPEN_READWRITE: i32 = 2;
/// Represents the flag for creating a new database if it does not exist.
pub const LIBSQL_OPEN_CREATE: i32 = 4;
pub const LIBSQL_ASSOC: i32 = 1;
pub const LIBSQL_NUM: i32 = 2;
pub const LIBSQL_BOTH: i32 = 3;
pub const LIBSQL_ALL: i32 = 4;
pub const LIBSQL_LAZY: i32 = 5;
/// Struct representing LibSQL PHP Class.
#[php_class]
struct LibSQL {
/// Property representing the connection mode.
#[prop]
mode: String,
/// Property representing the connection ID.
conn_id: String,
/// Property representing the Database object.
db: Option<libsql::Database>,
conn: libsql::Connection,
}
#[php_impl]
impl LibSQL {
/// Represents the flag for opening a database in read-only mode.
const OPEN_READONLY: i32 = 1;
/// Represents the flag for opening a database in read-write mode.
const OPEN_READWRITE: i32 = 2;
/// Represents the flag for creating a new database if it does not exist.
const OPEN_CREATE: i32 = 4;
const LIBSQL_ASSOC: i32 = 1;
const LIBSQL_NUM: i32 = 2;
const LIBSQL_BOTH: i32 = 3;
const LIBSQL_ALL: i32 = 4;
const LIBSQL_LAZY: i32 = 5;
/// Constructs a new `LibSQLConnection` object.
///
/// # Arguments
///
/// * `config` - The configuration value for the connection.
/// * `flags` - Optional flags for the connection.
/// * `encryption_key` - Optional encryption key for the connection.
///
/// # Returns
///
/// A `Result` containing the constructed `LibSQLConnection` object or a `PhpException` if an error occurs.
pub fn __construct(
config: ConfigValue,
flags: Option<i32>,
encryption_key: Option<String>,
) -> Result<Self, PhpException> {
let db_flags = flags.unwrap_or(6);
let encryption_key = encryption_key.unwrap_or_default();
let (url, auth_token, sync_url, sync_interval, read_your_writes): (
String,
String,
String,
std::time::Duration,
bool,
) = match config {
ConfigValue::String(dsn) => {
let dsn_parsed = match parse_dsn(&dsn) {
Some(dsn) => match (dsn.dbname.is_empty(), dsn.auth_token.is_empty()) {
(false, true) => Some((
dsn.dbname,
"".to_string(),
"".to_string(),
std::time::Duration::from_secs(5),
true,
)),
(false, false) => Some((
dsn.dbname,
dsn.auth_token,
"".to_string(),
std::time::Duration::from_secs(5),
true,
)),
(true, true) => None,
(true, false) => None,
},
None => None,
};
dsn_parsed.ok_or_else(|| PhpException::default("Failed to parse DSN".into()))?
}
ConfigValue::Array(config) => {
let url = config
.get("url")
.and_then(|v| v.to_string())
.unwrap_or_default();
let auth_token = config
.get("authToken")
.and_then(|v| v.to_string())
.unwrap_or_default();
let sync_url = config
.get("syncUrl")
.and_then(|v| v.to_string())
.unwrap_or_default();
let sync_interval = config
.get("syncInterval")
.and_then(|s| s.to_long())
.map(std::time::Duration::from_secs)
.unwrap_or_else(|| std::time::Duration::from_secs(5));
let read_your_writes = config
.get("read_your_writes")
.and_then(|v| v.to_bool())
.unwrap_or(true);
(url, auth_token, sync_url, sync_interval, read_your_writes)
}
};
if url.is_empty() {
return Err(PhpException::default("URL is not defined!".into()));
}
let mode = get_mode(
Some(url.clone()),
Some(auth_token.clone()),
Some(sync_url.clone()),
);
let (conn, db) = match mode.as_str() {
"local" => {
let conn = providers::local::create_local_connection(
url,
Some(db_flags),
Some(encryption_key),
);
(conn, None)
}
"remote" => {
let conn = providers::remote::create_remote_connection(url, auth_token);
(conn, None)
}
"remote_replica" => {
let cleared_url = if url.starts_with("file:") {
url.strip_prefix("file:").unwrap().to_string()
} else {
url.clone()
};
let (db, conn) = providers::remote_replica::create_remote_replica_connection(
cleared_url.clone(),
auth_token.clone(),
sync_url.clone(),
sync_interval.clone(),
read_your_writes.clone(),
Some(encryption_key),
);
(conn, Some(db))
}
_ => return Err(PhpException::default("Mode is not available!".into())),
};
let conn_id = uuid::Uuid::new_v4().to_string();
CONNECTION_REGISTRY
.lock()
.unwrap()
.insert(conn_id.clone(), conn.clone());
Ok(Self { mode, conn_id, db, conn })
}
/// Retrieves the version of the LibSQL library.
///
/// # Returns
///
/// Returns a string representing the version of the LibSQL library.
pub fn version() -> String {
hooks::version::get_version()
}
/// Retrieves the number of changes made by the last executed statement.
///
/// # Returns
///
/// Returns the number of changes made as a result of the last executed statement.
pub fn changes(&self) -> Result<u64, PhpException> {
hooks::changes::get_changes(self.conn_id.to_string())
}
/// Checks if autocommit mode is enabled for the connection.
///
/// # Returns
///
/// Returns `true` if autocommit mode is enabled, otherwise `false`.
pub fn is_autocommit(&self) -> Result<bool, PhpException> {
hooks::is_autocommit::get_is_autocommit(self.conn_id.to_string())
}
/// Retrieves the total number of changes made by the connection.
///
/// # Returns
///
/// Returns the total number of changes made by the connection.
pub fn total_changes(&self) -> Result<u64, PhpException> {
Ok(self.conn.total_changes())
}
/// Retrieves the rowid of the last inserted row.
///
/// # Returns
///
/// Returns the rowid of the last inserted row.
pub fn last_inserted_id(&self) -> Result<i64, PhpException> {
Ok(self.conn.last_insert_rowid())
}
/// Executes a SQL statement.
///
/// # Arguments
///
/// * `stmt` - The SQL statement to execute.
/// * `parameters` - Parameters to bind to the statement.
///
/// # Returns
///
/// Returns the number of rows affected by the execution of the statement.
pub fn execute(
&self,
stmt: &str,
parameters: Option<QueryParameters>,
) -> Result<u64, PhpException> {
hooks::use_exec::exec(self.conn_id.to_string(), stmt, parameters)
}
/// Executes a batch of SQL statements.
///
/// # Arguments
///
/// * `stmt` - The batch of SQL statements to execute.
///
/// # Returns
///
/// Returns `true` if the execution is successful, otherwise `false`.
pub fn execute_batch(&self, stmt: &str) -> Result<bool, PhpException> {
hooks::use_exec_batch::exec_batch(self.conn_id.to_string(), stmt)
}
/// Executes a SQL query and returns the result.
///
/// # Arguments
///
/// * `stmt` - The SQL query to execute.
/// * `parameters` - Parameters to bind to the query.
///
/// # Returns
///
/// Returns the result of the query execution.
pub fn query(
&self,
stmt: &str,
parameters: Option<QueryParameters>,
) -> Result<LibSQLResult, PhpException> {
LibSQLResult::__construct(self.conn_id.to_string(), stmt, parameters)
}
/// Initiates a transaction with the specified behavior.
///
/// # Arguments
///
/// * `behavior` - The behavior of the transaction.
///
/// # Returns
///
/// Returns a `LibSQLTransaction` instance representing the transaction.
pub fn transaction(&self, behavior: Option<String>) -> Result<LibSQLTransaction, PhpException> {
let tx_behavior = behavior
.as_deref()
.map(|s| s.to_uppercase())
.unwrap_or_else(|| "DEFERRED".to_string());
LibSQLTransaction::__construct(self.conn_id.clone(), tx_behavior)
}
/// Prepares a SQL statement for execution.
///
/// # Arguments
///
/// * `sql` - The SQL statement to prepare.
///
/// # Returns
///
/// Returns a `LibSQLStatement` instance representing the prepared statement.
pub fn prepare(&self, sql: &str) -> Result<LibSQLStatement, PhpException> {
LibSQLStatement::__construct(self.conn_id.clone(), sql)
}
/// Closes the database connection.
///
/// # Returns
///
/// Returns `Ok(())` if the connection is closed successfully, otherwise returns a `PhpException`.
pub fn close(&self) -> Result<(), PhpException> {
hooks::close::disconnect(self.conn_id.to_string())
}
/// Synchronizes the database for remote replica connections.
///
/// This function attempts to synchronize the database if the connection mode is
/// set to `remote_replica`. It uses asynchronous execution to perform the sync operation
/// and returns an appropriate result based on the success or failure of the sync process.
///
/// # Returns
///
/// A `Result` containing:
/// - `()`: An empty tuple on successful synchronization.
/// - `PhpException`: An exception in case of failure.
///
/// # Errors
///
/// This function returns a `PhpException` in the following cases:
/// - If the mode is not `remote_replica`.
/// - If the database connection is not available for synchronization.
/// - If the synchronization operation fails.
///
/// # Panics
///
/// This function will not panic.
pub fn sync(&self) -> Result<(), PhpException> {
if self.mode == "remote_replica" {
match &self.db {
Some(db) => utils::runtime::runtime().block_on(async {
db.sync()
.await
.map_err(|e| PhpException::default(format!("Sync failed: {}", e)))?;
Ok(())
}),
None => Err(PhpException::default(
"Database connection is not available for sync".to_string(),
)),
}
} else {
Err(PhpException::default(format!(
"{} mode does not support sync",
self.mode
)))
}
}
pub fn enable_load_extension(&self, onoff: Option<bool>) -> Result<(), PhpException> {
hooks::load_extensions::enable_load_extension(self.conn_id.to_string(), onoff)
}
pub fn load_extensions(
&self,
extension_paths: Option<ExtensionParams>
) -> Result<(), PhpException> {
let entry_point = None;
match extension_paths {
Some(ExtensionParams::String(extension)) => {
hooks::load_extensions::load_extension(self.conn_id.to_string(), Path::new(&extension), entry_point).unwrap();
},
Some(ExtensionParams::Array(extensions)) => {
for extension in extensions {
hooks::load_extensions::load_extension(
self.conn_id.to_string(),
Path::new(&extension),
entry_point,
).unwrap();
}
},
None => Err(PhpException::default(
"No extension paths provided".to_string()
)).unwrap(),
}
Ok(())
}
}
// The function to display extension info in phpinfo().
pub extern "C" fn libsql_php_extension_info(_module: *mut ext_php_rs::zend::ModuleEntry) {
unsafe {
// Start the PHP info table.
ext_php_rs::ffi::php_info_print_table_start();
// Add rows to the PHP info table.
ext_php_rs::ffi::php_info_print_table_row(
2,
"LibSQL Support\0".as_ptr() as *const i8,
"Enabled\0".as_ptr() as *const i8,
);
ext_php_rs::ffi::php_info_print_table_row(
2,
"LibSQL Local Connection Support\0".as_ptr() as *const i8,
"Enabled\0".as_ptr() as *const i8,
);
ext_php_rs::ffi::php_info_print_table_row(
2,
"LibSQL In-Memory Connection Support\0".as_ptr() as *const i8,
"Enabled\0".as_ptr() as *const i8,
);
ext_php_rs::ffi::php_info_print_table_row(
2,
"LibSQL Remote Connection Support\0".as_ptr() as *const i8,
"Enabled\0".as_ptr() as *const i8,
);
ext_php_rs::ffi::php_info_print_table_row(
2,
"LibSQL Remote Replica Connection Support\0".as_ptr() as *const i8,
"Enabled\0".as_ptr() as *const i8,
);
ext_php_rs::ffi::php_info_print_table_row(
2,
"LibSQL PHP version\0".as_ptr() as *const i8,
"1.4.2\0".as_ptr() as *const i8,
);
ext_php_rs::ffi::php_info_print_table_row(
2,
"Author\0".as_ptr() as *const i8,
"Imam Ali Mustofa <darkterminal@duck.com>\0".as_ptr() as *const i8,
);
ext_php_rs::ffi::php_info_print_table_row(
2,
"GitHub\0".as_ptr() as *const i8,
"https://github.com/tursodatabase/turso-client-php\0".as_ptr() as *const i8,
);
// End the PHP info table.
ext_php_rs::ffi::php_info_print_table_end();
}
}
#[php_module]
pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
module.info_function(libsql_php_extension_info)
}