Add simple db transaction controller

This commit is contained in:
2024-06-12 09:23:24 +02:00
parent 2d81d03bbd
commit b4d8543a5f
3 changed files with 51 additions and 0 deletions

View File

@@ -10,6 +10,8 @@
import { cn } from '$lib/utils' import { cn } from '$lib/utils'
import { location } from 'svelte-spa-router' import { location } from 'svelte-spa-router'
import { dbStateStore } from '$lib/store/dbState'
import { DBService } from '$lib/database'
// You can structure your links however you'd like, but I like to keep them in an array of objects // You can structure your links however you'd like, but I like to keep them in an array of objects
type Link = { type Link = {
@@ -43,6 +45,9 @@
class="flex space-x-4 text-xl font-bold select-none" class="flex space-x-4 text-xl font-bold select-none"
on:dragstart|preventDefault on:dragstart|preventDefault
> >
<div class:text-amber-500="{$dbStateStore.transacting}" on:click={DBService.Begin} class="cursor-pointer">T</div>
<div class:text-emerald-600={$dbStateStore.transacting} on:click={DBService.Commit} class="cursor-pointer">C</div>
<div class:text-red-700={$dbStateStore.transacting} on:click={DBService.Rollback} class="cursor-pointer">R</div>
{#each links as { href, label }} {#each links as { href, label }}
<a <a
use:link use:link

View File

@@ -1,3 +1,30 @@
import Database from 'tauri-plugin-sql-api' import Database from 'tauri-plugin-sql-api'
import { dbStateStore } from '$lib/store/dbState'
export const db = await Database.load('sqlite:food.db') export const db = await Database.load('sqlite:food.db')
const DBService = {
Begin() {
dbStateStore.update((state) => {
state.transacting = true
return state
})
return db.execute('begin transaction')
},
Commit() {
dbStateStore.update((state) => {
state.transacting = false
return state
})
return db.execute('commit')
},
Rollback() {
dbStateStore.update((state) => {
state.transacting = false
return state
})
return db.execute('rollback')
}
}
export { DBService }

19
src/lib/store/dbState.ts Normal file
View File

@@ -0,0 +1,19 @@
import { writable } from 'svelte/store'
type DBState = {
transacting: boolean
}
function createStore() {
const state = {
transacting: false
}
const { subscribe, update, set } = writable(state)
return {
subscribe,
update,
set
}
}
export const dbStateStore = createStore()