implement sqlite transactions

This commit is contained in:
yggverse 2024-10-06 00:43:35 +03:00
parent d5101a6465
commit 271acd50ed
8 changed files with 213 additions and 119 deletions

View file

@ -1,38 +1,33 @@
use sqlite::{Connection, Error};
use std::sync::Arc;
use sqlite::{Error, Transaction};
pub struct Table {
pub id: i64,
// pub time: i64,
}
pub struct Database {
connection: Arc<Connection>,
// nothing yet..
}
impl Database {
pub fn init(connection: Arc<Connection>) -> Result<Database, Error> {
connection.execute(
pub fn init(tx: &Transaction) -> Result<Database, Error> {
tx.execute(
"CREATE TABLE IF NOT EXISTS `app`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`time` INTEGER NOT NULL DEFAULT (UNIXEPOCH('NOW'))
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
)",
[],
)?;
Ok(Self { connection })
Ok(Self {})
}
pub fn add(&self) -> Result<usize, Error> {
self.connection
.execute("INSERT INTO `app` DEFAULT VALUES", [])
pub fn add(&self, tx: &Transaction) -> Result<usize, Error> {
tx.execute("INSERT INTO `app` DEFAULT VALUES", [])
}
pub fn records(&self) -> Result<Vec<Table>, Error> {
let mut statement = self.connection.prepare("SELECT `id` FROM `app`")?;
let result = statement.query_map([], |row| Ok(Table { id: row.get(0)? }))?;
pub fn records(&self, tx: &Transaction) -> Result<Vec<Table>, Error> {
let mut stmt = tx.prepare("SELECT `id` FROM `app`")?;
let result = stmt.query_map([], |row| Ok(Table { id: row.get(0)? }))?;
let mut records = Vec::new();
@ -44,12 +39,11 @@ impl Database {
Ok(records)
}
pub fn delete(&self, id: &i64) -> Result<usize, Error> {
self.connection
.execute("DELETE FROM `app` WHERE `id` = ?", [id])
pub fn delete(&self, tx: &Transaction, id: &i64) -> Result<usize, Error> {
tx.execute("DELETE FROM `app` WHERE `id` = ?", [id])
}
pub fn last_insert_id(&self) -> i64 {
self.connection.last_insert_rowid()
pub fn last_insert_id(&self, tx: &Transaction) -> i64 {
tx.last_insert_rowid()
}
}