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

@ -65,7 +65,7 @@ Guide and protocol draft
* column name for parental ID must have absolute namespace prefix, for example `app_browser_id` column for `app_browser_widget` table. For example, if the table has few parental keys, column set could be `id`, `parent_one_id`, `parent_two_id`, `some_data` * column name for parental ID must have absolute namespace prefix, for example `app_browser_id` column for `app_browser_widget` table. For example, if the table has few parental keys, column set could be `id`, `parent_one_id`, `parent_two_id`, `some_data`
* _todo_ * _todo_
* [ ] version control for auto-migrations * [ ] version control for auto-migrations
* [ ] transactions support for update operations * [x] transactions support for update operations
#### GTK #### GTK

View File

@ -13,7 +13,10 @@ use gtk::{
}; };
use sqlite::Connection; use sqlite::Connection;
use std::{path::PathBuf, sync::Arc}; use std::{
path::PathBuf,
sync::{Arc, RwLock},
};
const APPLICATION_ID: &str = "io.github.yggverse.Yoda"; const APPLICATION_ID: &str = "io.github.yggverse.Yoda";
@ -30,11 +33,32 @@ pub struct App {
impl App { impl App {
// Construct // Construct
pub fn new(profile_database_connection: Arc<Connection>, profile_path: PathBuf) -> Self { pub fn new(
profile_database_connection: Arc<RwLock<Connection>>,
profile_path: PathBuf,
) -> Self {
// Init database // Init database
let database = match Database::init(profile_database_connection.clone()) { let database = {
Ok(database) => Arc::new(database), // Init writable database connection
Err(error) => panic!("{error}"), // @TODO let mut connection = match profile_database_connection.write() {
Ok(connection) => connection,
Err(error) => todo!("{error}"),
};
// Init new transaction
let transaction = match connection.transaction() {
Ok(transaction) => transaction,
Err(error) => todo!("{error}"),
};
// Init database structure
match Database::init(&transaction) {
Ok(database) => match transaction.commit() {
Ok(_) => Arc::new(database),
Err(error) => todo!("{error}"),
},
Err(error) => todo!("{error}"),
}
}; };
// Init actions // Init actions
@ -82,7 +106,7 @@ impl App {
// Init components // Init components
let browser = Arc::new(Browser::new( let browser = Arc::new(Browser::new(
profile_database_connection, profile_database_connection.clone(),
profile_path, profile_path,
action_tool_debug.simple(), action_tool_debug.simple(),
action_tool_profile_directory.simple(), action_tool_profile_directory.simple(),
@ -110,15 +134,28 @@ impl App {
application.connect_startup({ application.connect_startup({
let browser = browser.clone(); let browser = browser.clone();
let database = database.clone(); let database = database.clone();
let profile_database_connection = profile_database_connection.clone();
move |this| { move |this| {
// Restore previous session from DB // Init readable connection
match database.records() { match profile_database_connection.read() {
Ok(records) => { Ok(connection) => {
for record in records { // Create transaction
browser.restore(&record.id); match connection.unchecked_transaction() {
Ok(transaction) => {
// Restore previous session from DB
match database.records(&transaction) {
Ok(records) => {
for record in records {
browser.restore(&transaction, &record.id);
}
}
Err(error) => todo!("{error}"),
}
}
Err(error) => todo!("{error}"),
} }
} }
Err(error) => panic!("{error}"), // @TODO Err(error) => todo!("{error}"),
} }
// Assign browser window to this application // Assign browser window to this application
@ -131,32 +168,52 @@ impl App {
application.connect_shutdown({ application.connect_shutdown({
// let browser = browser.clone(); // let browser = browser.clone();
let profile_database_connection = profile_database_connection.clone();
let database = database.clone(); let database = database.clone();
move |_| { move |_| {
// @TODO transaction? // Init writable connection
match database.records() { match profile_database_connection.write() {
Ok(records) => { Ok(mut connection) => {
// Cleanup previous session records // Create transaction
for record in records { match connection.transaction() {
match database.delete(&record.id) { Ok(transaction) => {
Ok(_) => { match database.records(&transaction) {
// Delegate clean action to childs Ok(records) => {
browser.clean(&record.id); // Cleanup previous session records
} for record in records {
Err(error) => panic!("{error}"), // @TODO match database.delete(&transaction, &record.id) {
} Ok(_) => {
} // Delegate clean action to childs
browser.clean(&transaction, &record.id);
}
Err(error) => todo!("{error}"),
}
}
// Save current session to DB // Save current session to DB
match database.add() { match database.add(&transaction) {
Ok(_) => { Ok(_) => {
// Delegate save action to childs // Delegate save action to childs
browser.save(&database.last_insert_id()); browser.save(
&transaction,
&database.last_insert_id(&transaction),
);
}
Err(error) => todo!("{error}"),
}
}
Err(error) => todo!("{error}"),
}
// Confirm changes
if let Err(error) = transaction.commit() {
todo!("{error}")
}
} }
Err(error) => panic!("{error}"), // @TODO Err(error) => todo!("{error}"),
} }
} }
Err(error) => panic!("{error}"), // @TODO Err(error) => todo!("{error}"),
} }
} }
}); });

View File

@ -5,6 +5,7 @@ mod window;
use database::Database; use database::Database;
use header::Header; use header::Header;
use sqlite::Transaction;
use widget::Widget; use widget::Widget;
use window::Window; use window::Window;
@ -13,7 +14,10 @@ use gtk::{
prelude::{ActionMapExt, GtkWindowExt}, prelude::{ActionMapExt, GtkWindowExt},
ApplicationWindow, ApplicationWindow,
}; };
use std::{path::PathBuf, sync::Arc}; use std::{
path::PathBuf,
sync::{Arc, RwLock},
};
pub struct Browser { pub struct Browser {
// Extras // Extras
@ -28,7 +32,7 @@ impl Browser {
// Construct // Construct
pub fn new( pub fn new(
// Extras // Extras
profile_database_connection: Arc<sqlite::Connection>, profile_database_connection: Arc<RwLock<sqlite::Connection>>,
profile_path: PathBuf, profile_path: PathBuf,
// Actions // Actions
action_tool_debug: Arc<SimpleAction>, action_tool_debug: Arc<SimpleAction>,
@ -45,9 +49,27 @@ impl Browser {
action_tab_pin: Arc<SimpleAction>, action_tab_pin: Arc<SimpleAction>,
) -> Browser { ) -> Browser {
// Init database // Init database
let database = match Database::init(profile_database_connection.clone()) { let database = {
Ok(database) => Arc::new(database), // Init writable database connection
Err(error) => panic!("{error}"), // @TODO let mut connection = match profile_database_connection.write() {
Ok(connection) => connection,
Err(error) => todo!("{error}"),
};
// Init new transaction
let transaction = match connection.transaction() {
Ok(transaction) => transaction,
Err(error) => todo!("{error}"),
};
// Init database structure
match Database::init(&transaction) {
Ok(database) => match transaction.commit() {
Ok(_) => Arc::new(database),
Err(error) => todo!("{error}"),
},
Err(error) => todo!("{error}"),
}
}; };
// Init components // Init components
@ -227,50 +249,54 @@ impl Browser {
} }
// Actions // Actions
pub fn clean(&self, app_id: &i64) { pub fn clean(&self, tx: &Transaction, app_id: &i64) {
match self.database.records(app_id) { match self.database.records(tx, app_id) {
Ok(records) => { Ok(records) => {
for record in records { for record in records {
match self.database.delete(&record.id) { match self.database.delete(tx, &record.id) {
Ok(_) => { Ok(_) => {
// Delegate clean action to childs // Delegate clean action to childs
// @TODO // @TODO
// self.header.clean(record.id); // self.header.clean(record.id);
// self.main.clean(record.id); // self.main.clean(record.id);
self.widget.clean(&record.id);
self.widget.clean(tx, &record.id);
} }
Err(error) => panic!("{error}"), // @TODO Err(error) => todo!("{error}"),
} }
} }
} }
Err(error) => panic!("{error}"), // @TODO Err(error) => todo!("{error}"),
} }
} }
pub fn restore(&self, app_id: &i64) { pub fn restore(&self, tx: &Transaction, app_id: &i64) {
match self.database.records(app_id) { match self.database.records(tx, app_id) {
Ok(records) => { Ok(records) => {
for record in records { for record in records {
// Delegate restore action to childs // Delegate restore action to childs
// @TODO // @TODO
// self.header.restore(record.id); // self.header.restore(record.id);
// self.window.restore(record.id); // self.window.restore(record.id);
self.widget.restore(&record.id);
self.widget.restore(tx, &record.id);
} }
} }
Err(error) => panic!("{error}"), // @TODO Err(error) => panic!("{error}"), // @TODO
} }
} }
pub fn save(&self, app_id: &i64) { pub fn save(&self, tx: &Transaction, app_id: &i64) {
match self.database.add(app_id) { match self.database.add(tx, app_id) {
Ok(_) => { Ok(_) => {
// Delegate save action to childs // Delegate save action to childs
let id = self.database.last_insert_id(); let id = self.database.last_insert_id(tx);
// @TODO // @TODO
// self.header.save(id); // self.header.save(id);
// self.window.save(id); // self.window.save(id);
self.widget.save(&id);
self.widget.save(tx, &id);
} }
Err(error) => panic!("{error}"), // @TODO Err(error) => panic!("{error}"), // @TODO
} }

View File

@ -1,5 +1,4 @@
use sqlite::{Connection, Error}; use sqlite::{Error, Transaction};
use std::sync::Arc;
pub struct Table { pub struct Table {
pub id: i64, pub id: i64,
@ -7,12 +6,12 @@ pub struct Table {
} }
pub struct Database { pub struct Database {
connection: Arc<Connection>, // nothing yet..
} }
impl Database { impl Database {
pub fn init(connection: Arc<Connection>) -> Result<Database, Error> { pub fn init(tx: &Transaction) -> Result<Database, Error> {
connection.execute( tx.execute(
"CREATE TABLE IF NOT EXISTS `app_browser` "CREATE TABLE IF NOT EXISTS `app_browser`
( (
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
@ -21,20 +20,17 @@ impl Database {
[], [],
)?; )?;
Ok(Self { connection }) Ok(Self {})
} }
pub fn add(&self, app_id: &i64) -> Result<usize, Error> { pub fn add(&self, tx: &Transaction, app_id: &i64) -> Result<usize, Error> {
self.connection tx.execute("INSERT INTO `app_browser` (`app_id`) VALUES (?)", [app_id])
.execute("INSERT INTO `app_browser` (`app_id`) VALUES (?)", [app_id])
} }
pub fn records(&self, app_id: &i64) -> Result<Vec<Table>, Error> { pub fn records(&self, tx: &Transaction, app_id: &i64) -> Result<Vec<Table>, Error> {
let mut statement = self let mut stmt = tx.prepare("SELECT `id`, `app_id` FROM `app_browser` WHERE `app_id` = ?")?;
.connection
.prepare("SELECT `id`, `app_id` FROM `app_browser` WHERE `app_id` = ?")?;
let result = statement.query_map([app_id], |row| { let result = stmt.query_map([app_id], |row| {
Ok(Table { Ok(Table {
id: row.get(0)?, id: row.get(0)?,
// app_id: row.get(1)?, not in use // app_id: row.get(1)?, not in use
@ -51,12 +47,11 @@ impl Database {
Ok(records) Ok(records)
} }
pub fn delete(&self, id: &i64) -> Result<usize, Error> { pub fn delete(&self, tx: &Transaction, id: &i64) -> Result<usize, Error> {
self.connection tx.execute("DELETE FROM `app_browser` WHERE `id` = ?", [id])
.execute("DELETE FROM `app_browser` WHERE `id` = ?", [id])
} }
pub fn last_insert_id(&self) -> i64 { pub fn last_insert_id(&self, tx: &Transaction) -> i64 {
self.connection.last_insert_rowid() tx.last_insert_rowid()
} }
} }

View File

@ -3,7 +3,8 @@ mod database;
use database::Database; use database::Database;
use gtk::{prelude::GtkWindowExt, ApplicationWindow, Box, HeaderBar}; use gtk::{prelude::GtkWindowExt, ApplicationWindow, Box, HeaderBar};
use std::sync::Arc; use sqlite::Transaction;
use std::sync::{Arc, RwLock};
// Default options // Default options
const DEFAULT_HEIGHT: i32 = 480; const DEFAULT_HEIGHT: i32 = 480;
@ -18,14 +19,32 @@ pub struct Widget {
impl Widget { impl Widget {
// Construct // Construct
pub fn new( pub fn new(
profile_database_connection: Arc<sqlite::Connection>, profile_database_connection: Arc<RwLock<sqlite::Connection>>,
titlebar: &HeaderBar, titlebar: &HeaderBar,
child: &Box, child: &Box,
) -> Self { ) -> Self {
// Init database // Init database
let database = match Database::init(profile_database_connection) { let database = {
Ok(database) => Arc::new(database), // Init writable database connection
Err(error) => panic!("{error}"), // @TODO let mut connection = match profile_database_connection.write() {
Ok(connection) => connection,
Err(error) => todo!("{error}"),
};
// Init new transaction
let transaction = match connection.transaction() {
Ok(transaction) => transaction,
Err(error) => todo!("{error}"),
};
// Init database structure
match Database::init(&transaction) {
Ok(database) => match transaction.commit() {
Ok(_) => Arc::new(database),
Err(error) => todo!("{error}"),
},
Err(error) => todo!("{error}"),
}
}; };
// Init GTK // Init GTK
@ -45,11 +64,11 @@ impl Widget {
} }
// Actions // Actions
pub fn clean(&self, app_browser_id: &i64) { pub fn clean(&self, tx: &Transaction, app_browser_id: &i64) {
match self.database.records(app_browser_id) { match self.database.records(tx, app_browser_id) {
Ok(records) => { Ok(records) => {
for record in records { for record in records {
match self.database.delete(&record.id) { match self.database.delete(tx, &record.id) {
Ok(_) => { Ok(_) => {
// Delegate clean action to childs // Delegate clean action to childs
// nothing yet.. // nothing yet..
@ -62,8 +81,8 @@ impl Widget {
} }
} }
pub fn restore(&self, app_browser_id: &i64) { pub fn restore(&self, tx: &Transaction, app_browser_id: &i64) {
match self.database.records(app_browser_id) { match self.database.records(tx, app_browser_id) {
Ok(records) => { Ok(records) => {
for record in records { for record in records {
// Restore widget // Restore widget
@ -79,8 +98,9 @@ impl Widget {
} }
} }
pub fn save(&self, app_browser_id: &i64) { pub fn save(&self, tx: &Transaction, app_browser_id: &i64) {
match self.database.add( match self.database.add(
tx,
app_browser_id, app_browser_id,
&self.application_window.default_width(), &self.application_window.default_width(),
&self.application_window.default_height(), &self.application_window.default_height(),

View File

@ -1,5 +1,4 @@
use sqlite::{Connection, Error}; use sqlite::{Error, Transaction};
use std::sync::Arc;
pub struct Table { pub struct Table {
pub id: i64, pub id: i64,
@ -10,12 +9,12 @@ pub struct Table {
} }
pub struct Database { pub struct Database {
connection: Arc<Connection>, // nothing yet..
} }
impl Database { impl Database {
pub fn init(connection: Arc<Connection>) -> Result<Database, Error> { pub fn init(tx: &Transaction) -> Result<Database, Error> {
connection.execute( tx.execute(
"CREATE TABLE IF NOT EXISTS `app_browser_widget` "CREATE TABLE IF NOT EXISTS `app_browser_widget`
( (
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
@ -27,17 +26,18 @@ impl Database {
[], [],
)?; )?;
Ok(Self { connection }) Ok(Self {})
} }
pub fn add( pub fn add(
&self, &self,
tx: &Transaction,
app_browser_id: &i64, app_browser_id: &i64,
default_width: &i32, default_width: &i32,
default_height: &i32, default_height: &i32,
is_maximized: &bool, is_maximized: &bool,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
self.connection.execute( tx.execute(
"INSERT INTO `app_browser_widget` ( "INSERT INTO `app_browser_widget` (
`app_browser_id`, `app_browser_id`,
`default_width`, `default_width`,
@ -56,8 +56,8 @@ impl Database {
) )
} }
pub fn records(&self, app_browser_id: &i64) -> Result<Vec<Table>, Error> { pub fn records(&self, tx: &Transaction, app_browser_id: &i64) -> Result<Vec<Table>, Error> {
let mut statement = self.connection.prepare( let mut stmt = tx.prepare(
"SELECT `id`, "SELECT `id`,
`app_browser_id`, `app_browser_id`,
`default_width`, `default_width`,
@ -65,7 +65,7 @@ impl Database {
`is_maximized` FROM `app_browser_widget` WHERE `app_browser_id` = ?", `is_maximized` FROM `app_browser_widget` WHERE `app_browser_id` = ?",
)?; )?;
let result = statement.query_map([app_browser_id], |row| { let result = stmt.query_map([app_browser_id], |row| {
Ok(Table { Ok(Table {
id: row.get(0)?, id: row.get(0)?,
// app_browser_id: row.get(1)?, not in use // app_browser_id: row.get(1)?, not in use
@ -85,13 +85,12 @@ impl Database {
Ok(records) Ok(records)
} }
pub fn delete(&self, id: &i64) -> Result<usize, Error> { pub fn delete(&self, tx: &Transaction, id: &i64) -> Result<usize, Error> {
self.connection tx.execute("DELETE FROM `app_browser_widget` WHERE `id` = ?", [id])
.execute("DELETE FROM `app_browser_widget` WHERE `id` = ?", [id])
} }
/* not in use /* not in use
pub fn last_insert_id(&self) -> i64 { pub fn last_insert_id(&self, tx: &Transaction) -> i64 {
self.connection.last_insert_rowid() tx.last_insert_rowid()
} */ } */
} }

View File

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

View File

@ -3,7 +3,10 @@ mod app;
use app::App; use app::App;
use gtk::glib::{user_config_dir, ExitCode}; use gtk::glib::{user_config_dir, ExitCode};
use sqlite::Connection; use sqlite::Connection;
use std::{fs::create_dir_all, sync::Arc}; use std::{
fs::create_dir_all,
sync::{Arc, RwLock},
};
const VENDOR: &str = "YGGverse"; const VENDOR: &str = "YGGverse";
const APP_ID: &str = "Yoda"; // env!("CARGO_PKG_NAME"); const APP_ID: &str = "Yoda"; // env!("CARGO_PKG_NAME");
@ -28,7 +31,7 @@ fn main() -> ExitCode {
// Init database connection // Init database connection
let profile_database_connection = match Connection::open(profile_database_path) { let profile_database_connection = match Connection::open(profile_database_path) {
Ok(connection) => Arc::new(connection), Ok(connection) => Arc::new(RwLock::new(connection)),
Err(error) => panic!("Failed to connect profile database: {error}"), Err(error) => panic!("Failed to connect profile database: {error}"),
}; };