Skip to content

Commit

Permalink
feat: changes to queries and debugging select errors
Browse files Browse the repository at this point in the history
  • Loading branch information
soulsam480 committed Oct 27, 2024
1 parent 1a72615 commit ec4e774
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 15 deletions.
2 changes: 1 addition & 1 deletion .lasso-marks-tracker
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
src/app/db/models/user.gleam
src/app/db/connection.gleam
src/app/controllers/sessions.gleam
4 changes: 2 additions & 2 deletions src/app/config.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ pub type Context {
Context(db: sqlight.Connection, user: Option(user.User))
}

pub fn context_with_connection(db: sqlight.Connection) {
Context(db, None)
pub fn acquire_context(db: sqlight.Connection, run: fn(Context) -> a) -> a {
run(Context(db, None))
}

pub fn set_user(ctx: Context, user: user.User) {
Expand Down
6 changes: 5 additions & 1 deletion src/app/controllers/sessions.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ fn handle_register(req: Request, ctx: config.Context) {
let my_user = user.insert_user(params, ctx.db)

case my_user {
Error(_) -> wisp.internal_server_error()
Error(e) -> {
wisp.log_error(e.message)

wisp.internal_server_error()
}

Ok(new_user) -> {
let user_obj =
Expand Down
4 changes: 2 additions & 2 deletions src/app/db/connection.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ pub fn get_db_path() -> String {
env.get_string_or("DATABASE", ":memory:")
}

pub fn with_connection(conn_fn: fn(sqlight.Connection) -> t) -> t {
sqlight.with_connection(get_db_path(), conn_fn)
pub fn with_connection(run: fn(sqlight.Connection) -> t) -> t {
sqlight.with_connection(get_db_path(), run)
}

pub fn run_query_with(
Expand Down
4 changes: 2 additions & 2 deletions src/app/db/migrations/1729363922_add_users.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
-- users
CREATE TABLE users (
id INTEGER PRIMARY KEY,
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE,
created_at TEXT NOT NULL,
Expand All @@ -9,7 +9,7 @@ CREATE TABLE users (

-- groups
CREATE TABLE groups (
id INTEGER PRIMARY KEY,
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
created_at TEXT NOT NULL,
deleted_at TEXT
Expand Down
7 changes: 7 additions & 0 deletions src/app/db/migrator.gleam
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import app/db/connection
import app/lib/logger
import feather
import feather/migrate as migrator

pub fn migrate_to_latest() {
logger.info("Fetching migrations...")

let assert Ok(migrations) = migrator.get_migrations("src/app/db/migrations")

logger.info("Acquiring connection...")

let assert Ok(connection) =
feather.connect(
feather.Config(..feather.default_config(), file: connection.get_db_path()),
)

logger.info("Running migrations...")

migrator.migrate(migrations, connection)
}
10 changes: 7 additions & 3 deletions src/app/db/models/user.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import app/db/connection
import app/db/models/helpers
import app/lib/generic_error
import cake
import cake/insert
import cake/select
Expand Down Expand Up @@ -35,14 +36,14 @@ fn decode_user(row: dynamic.Dynamic) {

fn get_user_props() {
select.new()
|> select.from_table("users")
|> select.selects([
select.col("users.id"),
select.col("users.name"),
select.col("users.email"),
select.col("users.password"),
select.col("users.created_at"),
])
|> select.from_table("users")
}

pub fn find_by_id(id: Int, conn: sqlight.Connection) {
Expand Down Expand Up @@ -96,10 +97,13 @@ pub fn insert_user(
columns: ["name", "email", "password"] |> helpers.with_created_at_column,
encoder: insertable_user_encoder,
)
|> insert.returning(["name", "email", "password", "id"])
|> insert.to_query
|> cake.to_write_query
|> connection.run_query_with(conn, decode_user)
|> result.map(fn(users) { users |> list.first })
|> result.replace_error(Nil)
|> result.map_error(fn(e) { generic_error.new(e) })
|> result.map(fn(users) {
users |> list.first |> result.replace_error(generic_error.new("empty user"))
})
|> result.flatten
}
6 changes: 4 additions & 2 deletions src/app/db/schema.sql
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
CREATE TABLE storch_migrations (id integer, applied integer);

CREATE TABLE users (
id INTEGER PRIMARY KEY,
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE,
created_at TEXT NOT NULL,
password TEXT NOT NULL
);

CREATE TABLE sqlite_sequence(name,seq);

CREATE TABLE groups (
id INTEGER PRIMARY KEY,
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
created_at TEXT NOT NULL,
deleted_at TEXT
Expand Down
12 changes: 12 additions & 0 deletions src/app/lib/generic_error.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import gleam/string

/// This defeats the whole purpose of error handling in gleam
/// but it somewhat helps with collecting all errors and then debugging
pub type GenericError {
GenericError(message: String)
}

/// create a new generic error which has ambiguos error inside
pub fn new(a) {
GenericError(a |> string.inspect)
}
5 changes: 5 additions & 0 deletions src/app/lib/logger.gleam
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import wisp

pub fn info(message: String) {
wisp.log_notice("[Okane]: " <> message)
}
7 changes: 5 additions & 2 deletions src/okane.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import app/router
import dot_env
import dot_env/env
import gleam/erlang/process
import gleam/io
import mist
import radiate
import wisp
Expand All @@ -20,6 +21,9 @@ pub fn main() {
let _ =
radiate.new()
|> radiate.add_dir(".")
|> radiate.on_reload(fn(_state, path) {
io.println("Change in " <> path <> ", reloading!")
})
|> radiate.start()

Nil
Expand All @@ -35,8 +39,7 @@ pub fn main() {
let assert Ok(_) = migrator.migrate_to_latest()

use db <- connection.with_connection()

let context = config.context_with_connection(db)
use context <- config.acquire_context(db)

// Start the Mist web server.
let assert Ok(_) =
Expand Down

0 comments on commit ec4e774

Please sign in to comment.