aboutsummaryrefslogtreecommitdiff
path: root/src/database.gleam
diff options
context:
space:
mode:
authorFuwn <[email protected]>2024-05-14 06:37:52 +0000
committerFuwn <[email protected]>2024-05-14 06:37:52 +0000
commit71a9af2b1d79f2bdd70de171aa77e2f9ccd638a3 (patch)
treefc3dec26c9280af36357100e33a30bf29998b908 /src/database.gleam
downloadmayu-71a9af2b1d79f2bdd70de171aa77e2f9ccd638a3.tar.xz
mayu-71a9af2b1d79f2bdd70de171aa77e2f9ccd638a3.zip
feat: initial release
Diffstat (limited to 'src/database.gleam')
-rw-r--r--src/database.gleam87
1 files changed, 87 insertions, 0 deletions
diff --git a/src/database.gleam b/src/database.gleam
new file mode 100644
index 0000000..bba3b29
--- /dev/null
+++ b/src/database.gleam
@@ -0,0 +1,87 @@
+import birl
+import gleam/dynamic
+import sqlight
+
+pub type Counter {
+ Counter(name: String, num: Int, created_at: String, updated_at: String)
+}
+
+pub fn setup(connection) {
+ let _ =
+ sqlight.exec(
+ "pragma foreign_keys = on;
+
+ create table if not exists tb_count (
+ id integer primary key autoincrement not null unique,
+ name text not null unique,
+ num int not null default (0)
+ ) strict;",
+ connection,
+ )
+ let add_column = fn(name) {
+ let _ =
+ sqlight.exec(
+ "alter table tb_count add column "
+ <> name
+ <> " text default current_timestamp;",
+ connection,
+ )
+
+ Nil
+ }
+
+ add_column("created_at")
+ add_column("updated_at")
+
+ Nil
+}
+
+pub fn add_counter(connection, name) {
+ sqlight.query(
+ "insert into tb_count (name) values (?);",
+ with: [sqlight.text(name)],
+ on: connection,
+ expecting: dynamic.optional(dynamic.int),
+ )
+}
+
+pub fn get_counter(connection, name) {
+ let _ =
+ sqlight.query(
+ "insert or ignore into tb_count (name) values (?);",
+ with: [sqlight.text(name)],
+ on: connection,
+ expecting: dynamic.optional(dynamic.int),
+ )
+ let _ =
+ sqlight.query(
+ "update tb_count set num = num + 1, updated_at = ? where name = ?;",
+ with: [sqlight.text(birl.to_iso8601(birl.utc_now())), sqlight.text(name)],
+ on: connection,
+ expecting: dynamic.int,
+ )
+
+ case
+ sqlight.query(
+ "select name, num, created_at, updated_at from tb_count where name = ?;",
+ with: [sqlight.text(name)],
+ on: connection,
+ expecting: dynamic.tuple4(
+ dynamic.string,
+ dynamic.int,
+ dynamic.string,
+ dynamic.string,
+ ),
+ )
+ {
+ Ok([first_element]) -> {
+ Counter(
+ first_element.0,
+ first_element.1,
+ first_element.2,
+ first_element.3,
+ )
+ }
+ _ -> Counter(name, 0, "", "")
+ }
+}