Still migrating to postgres, have to check that everything works and fix stuff
This commit is contained in:
+2
-4
@@ -1,8 +1,6 @@
|
||||
# DOING
|
||||
Adding the field `Calculated` to `Share` to avoid computing what each user owes
|
||||
everytime due to the fractional cents problem
|
||||
Make a script for the current migration to compute the Calculated value with
|
||||
our rules
|
||||
Migrating to postgres
|
||||
Refactor how the models access the database (move the Tx creation to the models)
|
||||
|
||||
# TODO
|
||||
- [ ] On the categories page, add a column of how many times a given category is
|
||||
|
||||
+3
-2
@@ -17,12 +17,13 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// TODO MOVE THIS REGISTERED FUNCTIONS SOMEWHER ELSE
|
||||
// This can be set in the compilation command - in the Makefile
|
||||
var (
|
||||
ginMode = "debug"
|
||||
tmplFuncMap = template.FuncMap{
|
||||
"formatDate": func(ts int64) string {
|
||||
return time.Unix(ts, 0).Format("02-Jan-2006")
|
||||
"formatDate": func(t time.Time) string {
|
||||
return t.Format("02-Jan-2006")
|
||||
},
|
||||
"formatPrice": func(v decimal.Decimal) string {
|
||||
return fmt.Sprintf("%s", v.Round(2).StringFixed(2))
|
||||
|
||||
+6
-2
@@ -1,6 +1,10 @@
|
||||
assets: "./assets/"
|
||||
port: 8081
|
||||
dbpath: "./data/data.db"
|
||||
dbsys: "sqlite3"
|
||||
postgres:
|
||||
user: expuser
|
||||
pass: exppass
|
||||
db: expdb
|
||||
host: 127.0.0.1
|
||||
port: 5431
|
||||
migrations_path: "file://expenses/db/migrations/"
|
||||
mig_custom_scripts: "./expenses/db/migrations/custom/"
|
||||
|
||||
+13
-6
@@ -7,13 +7,20 @@ import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type PostgresConfig struct {
|
||||
Host string `yaml:"host"`
|
||||
Port string `yaml:"port"`
|
||||
DB string `yaml:"db"`
|
||||
User string `yaml:"user"`
|
||||
Pass string `yaml:"pass"`
|
||||
}
|
||||
|
||||
type Configuration struct {
|
||||
AssetsDir string `yaml:"assets"`
|
||||
Port string `yaml:"port"`
|
||||
DBSys string `yaml:"dbsys"`
|
||||
DBPath string `yaml:"dbpath"`
|
||||
MigrationsPath string `yaml:"migrations_path"`
|
||||
MigCustomScript string `yaml:"mig_custom_scripts"`
|
||||
AssetsDir string `yaml:"assets"`
|
||||
Port string `yaml:"port"`
|
||||
PgCfg *PostgresConfig `yaml:"postgres"`
|
||||
MigrationsPath string `yaml:"migrations_path"`
|
||||
MigCustomScript string `yaml:"mig_custom_scripts"`
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import psycopg2
|
||||
from psycopg2 import Error
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
class DB():
|
||||
@@ -24,6 +25,34 @@ class DB():
|
||||
raise error
|
||||
|
||||
|
||||
def convert_to_date(timestamp):
|
||||
dt = datetime.fromtimestamp(int(timestamp))
|
||||
dt = dt.replace(hour=0)
|
||||
dt = dt.replace(minute=0)
|
||||
dt = dt.replace(second=0)
|
||||
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def migrate_dates():
|
||||
expDateIdx = 7
|
||||
creationDateIdx = 8
|
||||
|
||||
newFile = open("./new_expenses.csv", "w")
|
||||
|
||||
with open("./expenses.csv.bk", "r") as f:
|
||||
for l in f:
|
||||
fields = l.strip().split(',')
|
||||
exp = fields[expDateIdx]
|
||||
creation = fields[creationDateIdx]
|
||||
|
||||
exp = convert_to_date(exp)
|
||||
creation = convert_to_date(creation) if creation != -1 else convert_to_date(exp)
|
||||
|
||||
fields[expDateIdx] = exp
|
||||
fields[creationDateIdx] = creation
|
||||
newFile.write(','.join(fields) + "\n")
|
||||
|
||||
|
||||
def get_data(filePath):
|
||||
rows = []
|
||||
with open(filePath, "r") as f:
|
||||
@@ -37,7 +66,7 @@ def get_data(filePath):
|
||||
def truncate_table(db, m):
|
||||
print("Truncating table:", m["table"])
|
||||
try:
|
||||
db.runQuery(f"TRUNCATE TABLE {m["table"]} CASCADE", [])
|
||||
db.runQuery(f"TRUNCATE TABLE \"{m["table"]}\" CASCADE", [])
|
||||
except (Exception, Error) as error:
|
||||
raise error
|
||||
|
||||
@@ -54,8 +83,8 @@ def mig_data(db, m):
|
||||
print("Running migration for table:", m["table"])
|
||||
|
||||
values = ','.join(['%s'] * len(m["headers"]))
|
||||
fields = ','.join(m["headers"])
|
||||
query = f"INSERT INTO {m["table"]} ({fields}) VALUES({values})"
|
||||
fields = ','.join([f"\"{h}\"" for h in m["headers"]])
|
||||
query = f"INSERT INTO \"{m["table"]}\" ({fields}) VALUES({values})"
|
||||
|
||||
try:
|
||||
data = get_data(m["csvFile"])
|
||||
@@ -65,62 +94,66 @@ def mig_data(db, m):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
dbObj = DB("expuser", "exppass", "expdb", "127.0.0.1", "5431")
|
||||
except (Exception, Error) as error:
|
||||
print("Threw error:", error)
|
||||
exit(0)
|
||||
if False:
|
||||
migrate_dates()
|
||||
|
||||
migs = [
|
||||
{
|
||||
"table": "schema_migrations",
|
||||
"csvFile": "./schema_migrations.csv",
|
||||
"headers": ["version", "dirty"],
|
||||
},
|
||||
{
|
||||
"table": "categories",
|
||||
"csvFile": "./categories.csv",
|
||||
"headers": ["CategoryID", "CategoryName"],
|
||||
},
|
||||
{
|
||||
"table": "users",
|
||||
"csvFile": "./users.csv",
|
||||
"headers": ["UserID", "UserName", "UserPass"],
|
||||
},
|
||||
{
|
||||
"table": "stores",
|
||||
"csvFile": "./stores.csv",
|
||||
"headers": ["StoreID", "StoreName"],
|
||||
},
|
||||
{
|
||||
"table": "expenseTypes",
|
||||
"csvFile": "./expenseTypes.csv",
|
||||
"headers": ["TypeID", "TypeName"],
|
||||
},
|
||||
{
|
||||
"table": "expenses",
|
||||
"csvFile": "./expenses.csv",
|
||||
"headers": ["ExpID", "Description", "Value", "StoreID",
|
||||
"CategoryID", "OwnerUserID", "TypeID", "ExpDate",
|
||||
"CreationDate", "PaidOff", "SharesEven"],
|
||||
},
|
||||
{
|
||||
"table": "expensesShares",
|
||||
"csvFile": "./expensesShares.csv",
|
||||
"headers": ["ExpShareID", "ExpID", "UserID", "Share", "Calculated"],
|
||||
},
|
||||
{
|
||||
"table": "expensesPayments",
|
||||
"csvFile": "./expensesPayments.csv",
|
||||
"headers": ["ExpPaymID", "ExpID", "UserID", "Payed"],
|
||||
},
|
||||
]
|
||||
|
||||
for m in migs:
|
||||
truncate_table(dbObj, m)
|
||||
|
||||
for m in migs:
|
||||
if True:
|
||||
try:
|
||||
mig_data(dbObj, m)
|
||||
dbObj = DB("expuser", "exppass", "expdb", "127.0.0.1", "5431")
|
||||
except (Exception, Error) as error:
|
||||
print("failed to migrate data:", error)
|
||||
print("Threw error:", error)
|
||||
exit(0)
|
||||
|
||||
migs = [
|
||||
{
|
||||
"table": "schema_migrations",
|
||||
"csvFile": "./schema_migrations.csv",
|
||||
"headers": ["version", "dirty"],
|
||||
},
|
||||
{
|
||||
"table": "categories",
|
||||
"csvFile": "./categories.csv",
|
||||
"headers": ["CategoryID", "CategoryName"],
|
||||
},
|
||||
{
|
||||
"table": "users",
|
||||
"csvFile": "./users.csv",
|
||||
"headers": ["UserID", "UserName", "UserPass"],
|
||||
},
|
||||
{
|
||||
"table": "stores",
|
||||
"csvFile": "./stores.csv",
|
||||
"headers": ["StoreID", "StoreName"],
|
||||
},
|
||||
{
|
||||
"table": "expenseTypes",
|
||||
"csvFile": "./expenseTypes.csv",
|
||||
"headers": ["TypeID", "TypeName"],
|
||||
},
|
||||
{
|
||||
"table": "expenses",
|
||||
"csvFile": "./expenses.csv",
|
||||
"headers": ["ExpID", "Description", "Value", "StoreID",
|
||||
"CategoryID", "OwnerUserID", "TypeID", "ExpDate",
|
||||
"CreationDate", "PaidOff", "SharesEven"],
|
||||
},
|
||||
{
|
||||
"table": "expensesShares",
|
||||
"csvFile": "./expensesShares.csv",
|
||||
"headers": ["ExpShareID", "ExpID", "UserID", "Share", "Calculated"],
|
||||
},
|
||||
{
|
||||
"table": "expensesPayments",
|
||||
"csvFile": "./expensesPayments.csv",
|
||||
"headers": ["ExpPaymID", "ExpID", "UserID", "Payed"],
|
||||
},
|
||||
]
|
||||
|
||||
for m in migs:
|
||||
truncate_table(dbObj, m)
|
||||
|
||||
for m in migs:
|
||||
try:
|
||||
mig_data(dbObj, m)
|
||||
except (Exception, Error) as error:
|
||||
print("failed to migrate data:", error)
|
||||
|
||||
+16
-21
@@ -1,15 +1,15 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"context"
|
||||
"expenses/config"
|
||||
"log"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
"log"
|
||||
)
|
||||
|
||||
type ExpensesApp struct {
|
||||
DB *sql.DB
|
||||
DB *pgx.Conn
|
||||
Lua *lua.LState
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ var (
|
||||
App *ExpensesApp
|
||||
)
|
||||
|
||||
func NewExpenseApp(db *sql.DB, luaVM *lua.LState) *ExpensesApp {
|
||||
func NewExpenseApp(db *pgx.Conn, luaVM *lua.LState) *ExpensesApp {
|
||||
return &ExpensesApp{
|
||||
DB: db,
|
||||
Lua: luaVM,
|
||||
@@ -25,19 +25,12 @@ func NewExpenseApp(db *sql.DB, luaVM *lua.LState) *ExpensesApp {
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) Close() {
|
||||
a.DB.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
a.DB.Close(ctx)
|
||||
a.Lua.Close()
|
||||
}
|
||||
|
||||
func openDB(sys string, path string, extra string) (*sql.DB, error) {
|
||||
db, err := sql.Open(sys, "file:"+path+extra)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func StartLuaVM() (*lua.LState, error) {
|
||||
L := lua.NewState()
|
||||
App.registerLuaBinds(L)
|
||||
@@ -46,14 +39,16 @@ func StartLuaVM() (*lua.LState, error) {
|
||||
|
||||
func StartApp() error {
|
||||
config.SetConfig("./config.yaml")
|
||||
cfg := config.GetInstance()
|
||||
// cfg := config.GetInstance()
|
||||
|
||||
migDB, err := openDB(cfg.DBSys, cfg.DBPath, "")
|
||||
ctx := context.Background()
|
||||
pgStr := "port=5431 host=127.0.0.1 user=expuser dbname=expdb password=exppass"
|
||||
conn, err := pgx.Connect(ctx, pgStr)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to open migration DB: %v", err)
|
||||
}
|
||||
|
||||
App = NewExpenseApp(migDB, nil)
|
||||
App = NewExpenseApp(conn, nil)
|
||||
|
||||
luaVM, err := StartLuaVM()
|
||||
if err != nil {
|
||||
@@ -61,17 +56,17 @@ func StartApp() error {
|
||||
}
|
||||
App.Lua = luaVM
|
||||
|
||||
err = RunMigrations(migDB, luaVM)
|
||||
err = RunMigrations(conn, luaVM)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to apply migrations: %v", err)
|
||||
}
|
||||
App.Close()
|
||||
|
||||
db, err := openDB(cfg.DBSys, cfg.DBPath, "?_foreign_keys=on")
|
||||
conn, err = pgx.Connect(ctx, pgStr)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to open DB: %v", err)
|
||||
}
|
||||
App = NewExpenseApp(db, luaVM)
|
||||
App = NewExpenseApp(conn, luaVM)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+7
-2
@@ -4,6 +4,11 @@ import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func ParseID(s string) (int64, error) {
|
||||
return strconv.ParseInt(s, 10, 16)
|
||||
func ParseID(s string) (int32, error) {
|
||||
res, err := strconv.ParseInt(s, 10, 16)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return int32(res), nil
|
||||
}
|
||||
|
||||
+47
-18
@@ -1,70 +1,99 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
mod "expenses/expenses/models"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func GetAllCategories() ([]mod.Category, error) {
|
||||
return mod.GetAllCategories()
|
||||
func (a *ExpensesApp) GetAllCategories() ([]mod.Category, error) {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return []mod.Category{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
expenses, err := mod.GetAllCategories(a.DB, tx)
|
||||
if err != nil {
|
||||
return []mod.Category{}, err
|
||||
}
|
||||
|
||||
return expenses, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func GetCategory(id int64) (mod.Category, error) {
|
||||
return mod.GetCategory(id)
|
||||
func (a *ExpensesApp) GetCategory(id int32) (mod.Category, error) {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return mod.Category{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
category, err := mod.GetCategory(a.DB, tx, id)
|
||||
if err != nil {
|
||||
return mod.Category{}, err
|
||||
}
|
||||
|
||||
return category, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) CreateCategory(name string) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
newCat := mod.Category{
|
||||
CategoryName: name,
|
||||
}
|
||||
|
||||
err = newCat.Insert(tx)
|
||||
err = newCat.Insert(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) UpdateCategory(id int64, name string) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) UpdateCategory(id int32, name string) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
cat := mod.Category{
|
||||
CategoryID: id,
|
||||
CategoryName: name,
|
||||
}
|
||||
err = cat.Update()
|
||||
err = cat.Update(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) DeleteCategory(id int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) DeleteCategory(id int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
cat := mod.Category{
|
||||
CategoryID: id,
|
||||
}
|
||||
|
||||
err = cat.Delete()
|
||||
err = cat.Delete(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
-- 0001_initial.down.sql
|
||||
|
||||
DROP TABLE IF EXISTS expensesShares;
|
||||
DROP TABLE IF EXISTS expensesPayments;
|
||||
DROP TABLE IF EXISTS stores;
|
||||
DROP TABLE IF EXISTS categories;
|
||||
DROP TABLE IF EXISTS expenseTypes;
|
||||
DROP TABLE IF EXISTS users;
|
||||
DROP TABLE IF EXISTS expenses;
|
||||
@@ -1,62 +0,0 @@
|
||||
-- 0001_initial.up.sql
|
||||
|
||||
CREATE TABLE expenses (
|
||||
"ExpID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"Description" text NOT NULL,
|
||||
"Value" float NOT NULL DEFAULT 0,
|
||||
"StoreID" int NOT NULL DEFAULT 0,
|
||||
"CategoryID" int NOT NULL DEFAULT 0,
|
||||
"OwnerUserID" int NOT NULL DEFAULT 0,
|
||||
"TypeID" int NOT NULL DEFAULT 0,
|
||||
"ExpDate" int NOT NULL DEFAULT -1,
|
||||
"CreationDate" int NOT NULL DEFAULT -1,
|
||||
FOREIGN KEY(StoreID) REFERENCES stores(StoreID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(CategoryID) REFERENCES categories(CategoryID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(OwnerUserID) REFERENCES users(UserID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(TypeID) REFERENCES expensetypes(TypeID) ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE TABLE stores(
|
||||
"StoreID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"StoreName" text NOT NULL
|
||||
);
|
||||
-- Create a default store for NoStore
|
||||
INSERT INTO stores (StoreID, StoreName) VALUES(0, 'No Store');
|
||||
|
||||
CREATE TABLE categories(
|
||||
"CategoryID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"CategoryName" text NOT NULL
|
||||
);
|
||||
-- Create a default category for NoCategory
|
||||
INSERT INTO categories (CategoryID, CategoryName) VALUES(0, 'No Category');
|
||||
|
||||
CREATE TABLE "expenseTypes"(
|
||||
"TypeID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"TypeName" text NOT NULL
|
||||
);
|
||||
-- Create a default category for NoCategory
|
||||
INSERT INTO expensetypes (TypeID, TypeName) VALUES(0, 'expense');
|
||||
|
||||
CREATE TABLE users(
|
||||
"UserID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"UserName" text NOT NULL,
|
||||
"UserPass" text NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "expensesShares"(
|
||||
"ExpShareID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"ExpID" int NOT NULL,
|
||||
"UserID" int NOT NULL,
|
||||
"Share" float NOT NULL DEFAULT 0.5,
|
||||
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE TABLE "expensesPayments"(
|
||||
"ExpPaymID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"ExpID" int NOT NULL,
|
||||
"UserID" int NOT NULL,
|
||||
"Payed" float NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
);
|
||||
@@ -1,47 +0,0 @@
|
||||
-- 0002_change_floats_to_decimal.down.sql
|
||||
|
||||
-- expenses
|
||||
CREATE TABLE expenses_old (
|
||||
"ExpID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"Description" text NOT NULL,
|
||||
"Value" float NOT NULL DEFAULT 0,
|
||||
"StoreID" int NOT NULL DEFAULT 0,
|
||||
"CategoryID" int NOT NULL DEFAULT 0,
|
||||
"OwnerUserID" int NOT NULL DEFAULT 0,
|
||||
"TypeID" int NOT NULL DEFAULT 0,
|
||||
"ExpDate" int NOT NULL DEFAULT -1,
|
||||
"CreationDate" int NOT NULL DEFAULT -1,
|
||||
FOREIGN KEY(StoreID) REFERENCES stores(StoreID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(CategoryID) REFERENCES categories(CategoryID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(OwnerUserID) REFERENCES users(UserID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(TypeID) REFERENCES expensetypes(TypeID) ON DELETE RESTRICT
|
||||
);
|
||||
INSERT INTO expenses_old SELECT * FROM expenses;
|
||||
DROP TABLE expenses;
|
||||
ALTER TABLE expenses_old RENAME TO expenses;
|
||||
|
||||
-- expensesShares
|
||||
CREATE TABLE expensesShares_old (
|
||||
"ExpShareID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"ExpID" int NOT NULL,
|
||||
"UserID" int NOT NULL,
|
||||
"Share" float NOT NULL DEFAULT 0.5,
|
||||
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
);
|
||||
INSERT INTO expensesShares_old SELECT * FROM expensesShares;
|
||||
DROP TABLE expensesShares;
|
||||
ALTER TABLE expensesShares_old RENAME TO expensesShares;
|
||||
|
||||
-- expensesPayments
|
||||
CREATE TABLE expensesPayments_old (
|
||||
"ExpPaymID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"ExpID" int NOT NULL,
|
||||
"UserID" int NOT NULL,
|
||||
"Payed" float NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
);
|
||||
INSERT INTO expensesPayments_old SELECT * FROM expensesPayments;
|
||||
DROP TABLE expensesPayments;
|
||||
ALTER TABLE expensesPayments_old RENAME TO expensesPayments;
|
||||
@@ -1,47 +0,0 @@
|
||||
-- 0002_change_floats_to_decimal.up.sql
|
||||
|
||||
-- expenses
|
||||
CREATE TABLE expenses_new (
|
||||
"ExpID" INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
"Description" TEXT NOT NULL,
|
||||
"Value" TEXT NOT NULL DEFAULT 0,
|
||||
"StoreID" int NOT NULL DEFAULT 0,
|
||||
"CategoryID" int NOT NULL DEFAULT 0,
|
||||
"OwnerUserID" int NOT NULL DEFAULT 0,
|
||||
"TypeID" int NOT NULL DEFAULT 0,
|
||||
"ExpDate" int NOT NULL DEFAULT -1,
|
||||
"CreationDate" int NOT NULL DEFAULT -1,
|
||||
FOREIGN KEY(StoreID) REFERENCES stores(StoreID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(CategoryID) REFERENCES categories(CategoryID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(OwnerUserID) REFERENCES users(UserID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(TypeID) REFERENCES expensetypes(TypeID) ON DELETE RESTRICT
|
||||
);
|
||||
INSERT INTO expenses_new SELECT * FROM expenses;
|
||||
DROP TABLE expenses;
|
||||
ALTER TABLE expenses_new RENAME TO expenses;
|
||||
|
||||
-- expensesShares
|
||||
CREATE TABLE expensesShares_new (
|
||||
"ExpShareID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"ExpID" int NOT NULL,
|
||||
"UserID" int NOT NULL,
|
||||
"Share" TEXT NOT NULL DEFAULT 0.5,
|
||||
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
);
|
||||
INSERT INTO expensesShares_new SELECT * FROM expensesShares;
|
||||
DROP TABLE expensesShares;
|
||||
ALTER TABLE expensesShares_new RENAME TO expensesShares;
|
||||
|
||||
-- expensesPayments
|
||||
CREATE TABLE expensesPayments_new (
|
||||
"ExpPaymID" integer PRIMARY KEY AUTOINCREMENT,
|
||||
"ExpID" int NOT NULL,
|
||||
"UserID" int NOT NULL,
|
||||
"Payed" TEXT NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY(ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
);
|
||||
INSERT INTO expensesPayments_new SELECT * FROM expensesPayments;
|
||||
DROP TABLE expensesPayments;
|
||||
ALTER TABLE expensesPayments_new RENAME TO expensesPayments;
|
||||
@@ -1,4 +0,0 @@
|
||||
-- 0003_add_paidOff_column.down.sql
|
||||
|
||||
ALTER TABLE expenses DROP COLUMN "PaidOff";
|
||||
ALTER TABLE expenses DROP COLUMN "SharesEven";
|
||||
@@ -1,27 +0,0 @@
|
||||
-- 0003_add_paidOff_column.up.sql
|
||||
|
||||
ALTER TABLE expenses ADD COLUMN "PaidOff" BOOL DEFAULT FALSE;
|
||||
ALTER TABLE expenses ADD COLUMN "SharesEven" BOOL DEFAULT FALSE;
|
||||
|
||||
-- Update the SharesEven column
|
||||
UPDATE expenses
|
||||
SET SharesEven = TRUE
|
||||
WHERE ExpID IN (
|
||||
SELECT e.ExpID
|
||||
FROM expenses e
|
||||
JOIN expensesPayments p ON p.ExpID = e.ExpID
|
||||
GROUP BY e.ExpID
|
||||
HAVING ROUND(SUM(CAST(p.Payed AS REAL)), 2) == e.Value
|
||||
);
|
||||
|
||||
-- Update the PaidOff column
|
||||
UPDATE expenses
|
||||
SET "PaidOff" = TRUE
|
||||
WHERE ExpID IN (
|
||||
SELECT p.ExpID as ExpID
|
||||
FROM expensesPayments AS p
|
||||
JOIN expenses as e
|
||||
ON e.ExpID = p.ExpID
|
||||
GROUP BY p.ExpId
|
||||
HAVING ROUND(CAST(e.Value AS REAL),2) == ROUND(SUM(CAST(p.Payed AS REAL)), 2)
|
||||
);
|
||||
@@ -1,3 +0,0 @@
|
||||
-- 0004_calculated_share.down.sql
|
||||
|
||||
ALTER TABLE "expensesShares" DROP COLUMN "Calculated";
|
||||
@@ -1,3 +0,0 @@
|
||||
-- 0004_calculated_share.up.sql
|
||||
|
||||
ALTER TABLE "expensesShares" ADD COLUMN "Calculated" TEXT NOT NULL DEFAULT 0;
|
||||
@@ -1,130 +0,0 @@
|
||||
-- This scripts needs to do 2 things:
|
||||
-- Update the expenses where the owner doesn't have shares or payments to have
|
||||
-- some of his because of how the normalization function works
|
||||
-- Normalize the shares and update the expense
|
||||
|
||||
local json = require("json")
|
||||
|
||||
local info = debug.getinfo(1, 'S')
|
||||
print("Running ", info.source)
|
||||
|
||||
local function printTable(t)
|
||||
for key, value in pairs(t) do
|
||||
if type(value) == "table" then
|
||||
printTable(value)
|
||||
else
|
||||
print(key, ":", value)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function isOwnerInShares(exp)
|
||||
for _, share in pairs(exp.Shares) do
|
||||
if share.User.UserID == exp.Owner.UserID then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
local function isOwnerInPayments(exp)
|
||||
for _, paym in pairs(exp.Payments) do
|
||||
if paym.User.UserID == exp.Owner.UserID then
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
local function insertOwnerShare(exp)
|
||||
local share = {
|
||||
User = exp.Owner,
|
||||
Share = 0,
|
||||
}
|
||||
|
||||
local ok, err = InsertShare(json.encode(share), exp.ExpID)
|
||||
return ok, err
|
||||
end
|
||||
|
||||
local function insertOwnerPayment(exp)
|
||||
local payment = {
|
||||
User = exp.Owner,
|
||||
PayedAmount = 0,
|
||||
}
|
||||
|
||||
local ok, err = InsertPayment(json.encode(payment), exp.ExpID)
|
||||
return ok, err
|
||||
end
|
||||
|
||||
local function validateSharesAndPayments(exp)
|
||||
if not isOwnerInShares(exp) then
|
||||
local ok, err = insertOwnerShare(exp)
|
||||
if not ok then
|
||||
print("Error inserting owner share: ", err)
|
||||
return false
|
||||
end
|
||||
print("Inserted share in expense: ", exp.ExpID)
|
||||
end
|
||||
|
||||
if not isOwnerInPayments(exp) then
|
||||
local ok, err = insertOwnerPayment(exp)
|
||||
if not ok then
|
||||
print("Error inserting owner payment: ", err)
|
||||
return false
|
||||
end
|
||||
print("Inserted payment in expense: ", exp.ExpID)
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
local function requiresUpdate(exp, normalized)
|
||||
return exp ~= normalized
|
||||
end
|
||||
|
||||
---@diagnostic disable-next-line: undefined-global
|
||||
local ok, data = GetAllExpenses()
|
||||
if not ok or data == nil then
|
||||
print("Error:", data)
|
||||
return
|
||||
end
|
||||
|
||||
for i = 1, #data do
|
||||
local eJson = data[i].expense
|
||||
local e = json.decode(eJson)
|
||||
|
||||
local res = validateSharesAndPayments(e)
|
||||
if not res then
|
||||
goto continue
|
||||
end
|
||||
|
||||
-- if we inserted shares and payments we need to update the expense here
|
||||
local updatedEJson
|
||||
ok, updatedEJson = GetExpense(e.ExpID)
|
||||
if not ok then
|
||||
goto continue
|
||||
end
|
||||
|
||||
local normalizedExpense
|
||||
ok, normalizedExpense = NormalizeShare(updatedEJson)
|
||||
if not ok then
|
||||
print("Failed to normalize share: ", normalizedExpense)
|
||||
goto continue
|
||||
end
|
||||
|
||||
local newExp = json.decode(updatedEJson)
|
||||
local normalized = json.decode(normalizedExpense)
|
||||
if requiresUpdate(updatedEJson, normalizedExpense) then
|
||||
local err
|
||||
ok, err = UpdateExpense(normalizedExpense)
|
||||
if not ok then
|
||||
print("Failed to update expense ", normalized.ExpID, ": ", err)
|
||||
goto continue
|
||||
end
|
||||
print("Updated expense ", normalized.ExpID)
|
||||
end
|
||||
|
||||
::continue::
|
||||
end
|
||||
@@ -2,13 +2,13 @@
|
||||
SELECT * FROM categories;
|
||||
|
||||
-- name: GetCategory :one
|
||||
SELECT * FROM categories WHERE "CategoryID" = ?;
|
||||
SELECT * FROM categories WHERE "CategoryID" = $1;
|
||||
|
||||
-- name: UpdateCategory :execresult
|
||||
UPDATE categories SET "CategoryName" = ? WHERE "CategoryID" = ?;
|
||||
UPDATE categories SET "CategoryName" = $1 WHERE "CategoryID" = $2;
|
||||
|
||||
-- name: DeleteCategory :execresult
|
||||
DELETE FROM categories WHERE "CategoryID" = ?;
|
||||
DELETE FROM categories WHERE "CategoryID" = $1;
|
||||
|
||||
-- name: InsertCategory :execresult
|
||||
INSERT INTO categories("CategoryName") VALUES(?)
|
||||
INSERT INTO categories("CategoryName") VALUES($1);
|
||||
|
||||
@@ -7,17 +7,17 @@ SELECT
|
||||
sqlc.embed(types)
|
||||
FROM expenses
|
||||
JOIN
|
||||
Stores ON stores.StoreID = expenses.StoreID
|
||||
Stores ON stores."StoreID" = expenses."StoreID"
|
||||
JOIN
|
||||
Categories ON categories.CategoryID = expenses.CategoryID
|
||||
Categories ON categories."CategoryID" = expenses."CategoryID"
|
||||
JOIN
|
||||
Users ON UserID = OwnerUserId
|
||||
Users ON users."UserID" = expenses."OwnerUserID"
|
||||
JOIN
|
||||
"expenseTypes" as types ON types.TypeID = expenses.TypeID
|
||||
"expenseTypes" as types ON types."TypeID" = expenses."TypeID"
|
||||
WHERE
|
||||
(sqlc.narg(startDate) IS NULL OR expenses."ExpDate" >= sqlc.narg(startDate))
|
||||
(sqlc.narg(StartDate)::timestamp IS NULL OR expenses."ExpDate" >= sqlc.narg(StartDate)::timestamp)
|
||||
AND
|
||||
(sqlc.narg(endDate) IS NULL OR expenses."ExpDate" <= sqlc.narg(endDate));
|
||||
(sqlc.narg(EndDate)::timestamp IS NULL OR expenses."ExpDate" <= sqlc.narg(EndDate)::timestamp);
|
||||
|
||||
-- name: GetExpense :one
|
||||
SELECT
|
||||
@@ -28,17 +28,17 @@ SELECT
|
||||
sqlc.embed(types)
|
||||
FROM expenses
|
||||
JOIN
|
||||
Stores ON stores.StoreID = expenses.StoreID
|
||||
Stores ON stores."StoreID" = expenses."StoreID"
|
||||
JOIN
|
||||
Categories ON categories.CategoryID = expenses.CategoryID
|
||||
Categories ON categories."CategoryID" = expenses."CategoryID"
|
||||
JOIN
|
||||
Users ON "UserID" = "OwnerUserId"
|
||||
Users ON "UserID" = "OwnerUserID"
|
||||
JOIN
|
||||
"expenseTypes" as types ON types.TypeID = expenses.TypeID
|
||||
"expenseTypes" as types ON types."TypeID" = expenses."TypeID"
|
||||
WHERE
|
||||
"ExpID" = ?;
|
||||
expenses."ExpID" = $1;
|
||||
|
||||
-- name: InsertExpense :execresult
|
||||
-- name: InsertExpense :one
|
||||
INSERT INTO expenses(
|
||||
"Description",
|
||||
"Value",
|
||||
@@ -51,21 +51,22 @@ INSERT INTO expenses(
|
||||
"SharesEven",
|
||||
"CreationDate"
|
||||
)
|
||||
VALUES(?, ?, ? , ?, ?, ?, ?, ?, ?, ?);
|
||||
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING "ExpID";
|
||||
|
||||
-- name: DeleteExpense :execresult
|
||||
DELETE FROM expenses WHERE "ExpID" = ?;
|
||||
DELETE FROM expenses WHERE "ExpID" = $1;
|
||||
|
||||
-- name: UpdateExpense :execresult
|
||||
UPDATE expenses
|
||||
SET
|
||||
"Description" = ?,
|
||||
"Value" = ?,
|
||||
"StoreID" = ?,
|
||||
"CategoryID" = ?,
|
||||
"TypeID" = ?,
|
||||
"OwnerUserID" = ?,
|
||||
"PaidOff" = ?,
|
||||
"SharesEven" = ?,
|
||||
"ExpDate" = ?
|
||||
WHERE "ExpID" = ?;
|
||||
"Description" = $1,
|
||||
"Value" = $2,
|
||||
"StoreID" = $3,
|
||||
"CategoryID" = $4,
|
||||
"TypeID" = $5,
|
||||
"OwnerUserID" = $6,
|
||||
"PaidOff" = $7,
|
||||
"SharesEven" = $8,
|
||||
"ExpDate" = $9
|
||||
WHERE "ExpID" = $10;
|
||||
|
||||
@@ -5,7 +5,7 @@ FROM
|
||||
"expensesPayments" as payments
|
||||
JOIN
|
||||
users as users ON users.UserID = payments.UserID
|
||||
WHERE "ExpID" = ?;
|
||||
WHERE "ExpID" = $1;
|
||||
|
||||
-- name: GetExpensePaymentByUser :one
|
||||
SELECT
|
||||
@@ -15,19 +15,19 @@ FROM
|
||||
JOIN
|
||||
users as users ON users.UserID = payments.UserID
|
||||
WHERE
|
||||
"ExpID" = ? AND users."UserID" = ?;
|
||||
"ExpID" = $1 AND users."UserID" = $2;
|
||||
|
||||
|
||||
-- name: InsertPayment :execresult
|
||||
INSERT INTO "expensesPayments"(
|
||||
"ExpID", "UserID", "Payed"
|
||||
)
|
||||
VALUES(?, ?, ?);
|
||||
VALUES($1, $2, $3);
|
||||
|
||||
-- name: UpdatePayment :execresult
|
||||
UPDATE expensesPayments
|
||||
SET "UserID" = ?, "Payed" = ?
|
||||
WHERE "ExpPaymID" = ?;
|
||||
UPDATE "expensesPayments"
|
||||
SET "UserID" = $1, "Payed" = $2
|
||||
WHERE "ExpPaymID" = $3;
|
||||
|
||||
-- name: DeletePayment :execresult
|
||||
DELETE FROM "expensesPayments" WHERE "ExpPaymID" = ?;
|
||||
DELETE FROM "expensesPayments" WHERE "ExpPaymID" = $1;
|
||||
|
||||
@@ -5,18 +5,18 @@ FROM
|
||||
"expensesShares" as shares
|
||||
JOIN
|
||||
users as users ON users.UserID = shares.UserID
|
||||
WHERE "ExpID" = ?;
|
||||
WHERE "ExpID" = $1;
|
||||
|
||||
-- name: InsertShare :execresult
|
||||
INSERT INTO "expensesShares"(
|
||||
"ExpID", "UserID", "Share", "Calculated"
|
||||
)
|
||||
VALUES(?, ?, ?, ?);
|
||||
VALUES($1, $2, $3, $4);
|
||||
|
||||
-- name: UpdateShare :execresult
|
||||
UPDATE expensesShares
|
||||
SET "UserID" = ?, "Share" = ?, "Calculated" = ?
|
||||
WHERE "ExpShareID" = ?;
|
||||
UPDATE "expensesShares"
|
||||
SET "UserID" = $1, "Share" = $2, "Calculated" = $3
|
||||
WHERE "ExpShareID" = $4;
|
||||
|
||||
-- name: DeleteShare :execresult
|
||||
DELETE FROM "expensesShares" where "ExpShareID" = ?;
|
||||
DELETE FROM "expensesShares" where "ExpShareID" = $1;
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
SELECT * FROM stores;
|
||||
|
||||
-- name: GetStore :one
|
||||
SELECT * FROM stores WHERE "StoreID" = ?;
|
||||
SELECT * FROM stores WHERE "StoreID" = $1;
|
||||
|
||||
-- name: InsertStore :execresult
|
||||
INSERT INTO stores("StoreName") VALUES(?);
|
||||
INSERT INTO stores("StoreName") VALUES($1);
|
||||
|
||||
-- name: UpdateStore :execresult
|
||||
UPDATE stores SET "StoreName" = ? WHERE "StoreID" = ?;
|
||||
UPDATE stores SET "StoreName" = $1 WHERE "StoreID" = $2;
|
||||
|
||||
-- name: DeleteStore :execresult
|
||||
DELETE FROM stores WHERE "StoreID" = ?;
|
||||
DELETE FROM stores WHERE "StoreID" = $1;
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
SELECT * FROM "expenseTypes";
|
||||
|
||||
-- name: GetType :one
|
||||
SELECT * FROM "expenseTypes" WHERE "TypeID" = ?;
|
||||
SELECT * FROM "expenseTypes" WHERE "TypeID" = $1;
|
||||
|
||||
-- name: InsertType :execresult
|
||||
INSERT INTO "expenseTypes"("TypeName") VALUES(?);
|
||||
INSERT INTO "expenseTypes"("TypeName") VALUES($1);
|
||||
|
||||
-- name: UpdateType :execresult
|
||||
UPDATE expenseTypes SET "TypeName" = ? WHERE "TypeID" = ?;
|
||||
UPDATE "expenseTypes" SET "TypeName" = $1 WHERE "TypeID" = $2;
|
||||
|
||||
-- name: DeleteType :execresult
|
||||
DELETE FROM "expenseTypes" WHERE "TypeID" = ?;
|
||||
DELETE FROM "expenseTypes" WHERE "TypeID" = $1;
|
||||
|
||||
@@ -7,23 +7,24 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
const deleteCategory = `-- name: DeleteCategory :execresult
|
||||
DELETE FROM categories WHERE "CategoryID" = ?
|
||||
DELETE FROM categories WHERE "CategoryID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteCategory(ctx context.Context, categoryid int64) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, deleteCategory, categoryid)
|
||||
func (q *Queries) DeleteCategory(ctx context.Context, categoryid int32) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, deleteCategory, categoryid)
|
||||
}
|
||||
|
||||
const getCategories = `-- name: GetCategories :many
|
||||
SELECT CategoryID, CategoryName FROM categories
|
||||
SELECT "CategoryID", "CategoryName" FROM categories
|
||||
`
|
||||
|
||||
func (q *Queries) GetCategories(ctx context.Context) ([]Category, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getCategories)
|
||||
rows, err := q.db.Query(ctx, getCategories)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -36,9 +37,6 @@ func (q *Queries) GetCategories(ctx context.Context) ([]Category, error) {
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -46,33 +44,33 @@ func (q *Queries) GetCategories(ctx context.Context) ([]Category, error) {
|
||||
}
|
||||
|
||||
const getCategory = `-- name: GetCategory :one
|
||||
SELECT CategoryID, CategoryName FROM categories WHERE "CategoryID" = ?
|
||||
SELECT "CategoryID", "CategoryName" FROM categories WHERE "CategoryID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetCategory(ctx context.Context, categoryid int64) (Category, error) {
|
||||
row := q.db.QueryRowContext(ctx, getCategory, categoryid)
|
||||
func (q *Queries) GetCategory(ctx context.Context, categoryid int32) (Category, error) {
|
||||
row := q.db.QueryRow(ctx, getCategory, categoryid)
|
||||
var i Category
|
||||
err := row.Scan(&i.CategoryID, &i.CategoryName)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertCategory = `-- name: InsertCategory :execresult
|
||||
INSERT INTO categories("CategoryName") VALUES(?)
|
||||
INSERT INTO categories("CategoryName") VALUES($1)
|
||||
`
|
||||
|
||||
func (q *Queries) InsertCategory(ctx context.Context, categoryname string) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, insertCategory, categoryname)
|
||||
func (q *Queries) InsertCategory(ctx context.Context, categoryname string) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, insertCategory, categoryname)
|
||||
}
|
||||
|
||||
const updateCategory = `-- name: UpdateCategory :execresult
|
||||
UPDATE categories SET "CategoryName" = ? WHERE "CategoryID" = ?
|
||||
UPDATE categories SET "CategoryName" = $1 WHERE "CategoryID" = $2
|
||||
`
|
||||
|
||||
type UpdateCategoryParams struct {
|
||||
CategoryName string
|
||||
CategoryID int64
|
||||
CategoryID int32
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateCategory(ctx context.Context, arg UpdateCategoryParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, updateCategory, arg.CategoryName, arg.CategoryID)
|
||||
func (q *Queries) UpdateCategory(ctx context.Context, arg UpdateCategoryParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, updateCategory, arg.CategoryName, arg.CategoryID)
|
||||
}
|
||||
|
||||
@@ -6,14 +6,15 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
|
||||
PrepareContext(context.Context, string) (*sql.Stmt, error)
|
||||
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
|
||||
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
@@ -24,7 +25,7 @@ type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx *sql.Tx) *Queries {
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
|
||||
@@ -7,35 +7,37 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteExpense = `-- name: DeleteExpense :execresult
|
||||
DELETE FROM expenses WHERE "ExpID" = ?
|
||||
DELETE FROM expenses WHERE "ExpID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteExpense(ctx context.Context, expid int64) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, deleteExpense, expid)
|
||||
func (q *Queries) DeleteExpense(ctx context.Context, expid int32) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, deleteExpense, expid)
|
||||
}
|
||||
|
||||
const getExpense = `-- name: GetExpense :one
|
||||
SELECT
|
||||
expenses.ExpID, expenses.Description, expenses.Value, expenses.StoreID, expenses.CategoryID, expenses.OwnerUserID, expenses.TypeID, expenses.ExpDate, expenses.CreationDate, expenses.PaidOff, expenses.SharesEven,
|
||||
stores.StoreID, stores.StoreName,
|
||||
categories.CategoryID, categories.CategoryName,
|
||||
users.UserID, users.UserName, users.UserPass,
|
||||
types.TypeID, types.TypeName
|
||||
expenses."ExpID", expenses."Description", expenses."Value", expenses."StoreID", expenses."CategoryID", expenses."OwnerUserID", expenses."TypeID", expenses."ExpDate", expenses."CreationDate", expenses."PaidOff", expenses."SharesEven",
|
||||
stores."StoreID", stores."StoreName",
|
||||
categories."CategoryID", categories."CategoryName",
|
||||
users."UserID", users."UserName", users."UserPass",
|
||||
types."TypeID", types."TypeName"
|
||||
FROM expenses
|
||||
JOIN
|
||||
Stores ON stores.StoreID = expenses.StoreID
|
||||
Stores ON stores."StoreID" = expenses."StoreID"
|
||||
JOIN
|
||||
Categories ON categories.CategoryID = expenses.CategoryID
|
||||
Categories ON categories."CategoryID" = expenses."CategoryID"
|
||||
JOIN
|
||||
Users ON "UserID" = "OwnerUserId"
|
||||
Users ON "UserID" = "OwnerUserID"
|
||||
JOIN
|
||||
"expenseTypes" as types ON types.TypeID = expenses.TypeID
|
||||
"expenseTypes" as types ON types."TypeID" = expenses."TypeID"
|
||||
WHERE
|
||||
"ExpID" = ?
|
||||
expenses."ExpID" = $1
|
||||
`
|
||||
|
||||
type GetExpenseRow struct {
|
||||
@@ -46,8 +48,8 @@ type GetExpenseRow struct {
|
||||
ExpenseType ExpenseType
|
||||
}
|
||||
|
||||
func (q *Queries) GetExpense(ctx context.Context, expid int64) (GetExpenseRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getExpense, expid)
|
||||
func (q *Queries) GetExpense(ctx context.Context, expid int32) (GetExpenseRow, error) {
|
||||
row := q.db.QueryRow(ctx, getExpense, expid)
|
||||
var i GetExpenseRow
|
||||
err := row.Scan(
|
||||
&i.Expense.ExpID,
|
||||
@@ -76,29 +78,29 @@ func (q *Queries) GetExpense(ctx context.Context, expid int64) (GetExpenseRow, e
|
||||
|
||||
const getExpenses = `-- name: GetExpenses :many
|
||||
SELECT
|
||||
expenses.ExpID, expenses.Description, expenses.Value, expenses.StoreID, expenses.CategoryID, expenses.OwnerUserID, expenses.TypeID, expenses.ExpDate, expenses.CreationDate, expenses.PaidOff, expenses.SharesEven,
|
||||
stores.StoreID, stores.StoreName,
|
||||
categories.CategoryID, categories.CategoryName,
|
||||
users.UserID, users.UserName, users.UserPass,
|
||||
types.TypeID, types.TypeName
|
||||
expenses."ExpID", expenses."Description", expenses."Value", expenses."StoreID", expenses."CategoryID", expenses."OwnerUserID", expenses."TypeID", expenses."ExpDate", expenses."CreationDate", expenses."PaidOff", expenses."SharesEven",
|
||||
stores."StoreID", stores."StoreName",
|
||||
categories."CategoryID", categories."CategoryName",
|
||||
users."UserID", users."UserName", users."UserPass",
|
||||
types."TypeID", types."TypeName"
|
||||
FROM expenses
|
||||
JOIN
|
||||
Stores ON stores.StoreID = expenses.StoreID
|
||||
Stores ON stores."StoreID" = expenses."StoreID"
|
||||
JOIN
|
||||
Categories ON categories.CategoryID = expenses.CategoryID
|
||||
Categories ON categories."CategoryID" = expenses."CategoryID"
|
||||
JOIN
|
||||
Users ON UserID = OwnerUserId
|
||||
Users ON users."UserID" = expenses."OwnerUserID"
|
||||
JOIN
|
||||
"expenseTypes" as types ON types.TypeID = expenses.TypeID
|
||||
"expenseTypes" as types ON types."TypeID" = expenses."TypeID"
|
||||
WHERE
|
||||
(?1 IS NULL OR expenses."ExpDate" >= ?1)
|
||||
($1::timestamp IS NULL OR expenses."ExpDate" >= $1::timestamp)
|
||||
AND
|
||||
(?2 IS NULL OR expenses."ExpDate" <= ?2)
|
||||
($2::timestamp IS NULL OR expenses."ExpDate" <= $2::timestamp)
|
||||
`
|
||||
|
||||
type GetExpensesParams struct {
|
||||
Startdate interface{}
|
||||
Enddate interface{}
|
||||
Startdate pgtype.Timestamp
|
||||
Enddate pgtype.Timestamp
|
||||
}
|
||||
|
||||
type GetExpensesRow struct {
|
||||
@@ -110,7 +112,7 @@ type GetExpensesRow struct {
|
||||
}
|
||||
|
||||
func (q *Queries) GetExpenses(ctx context.Context, arg GetExpensesParams) ([]GetExpensesRow, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getExpenses, arg.Startdate, arg.Enddate)
|
||||
rows, err := q.db.Query(ctx, getExpenses, arg.Startdate, arg.Enddate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -144,16 +146,13 @@ func (q *Queries) GetExpenses(ctx context.Context, arg GetExpensesParams) ([]Get
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const insertExpense = `-- name: InsertExpense :execresult
|
||||
const insertExpense = `-- name: InsertExpense :one
|
||||
INSERT INTO expenses(
|
||||
"Description",
|
||||
"Value",
|
||||
@@ -166,24 +165,25 @@ INSERT INTO expenses(
|
||||
"SharesEven",
|
||||
"CreationDate"
|
||||
)
|
||||
VALUES(?, ?, ? , ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING "ExpID"
|
||||
`
|
||||
|
||||
type InsertExpenseParams struct {
|
||||
Description string
|
||||
Value string
|
||||
StoreID int64
|
||||
CategoryID int64
|
||||
TypeID int64
|
||||
OwnerUserID int64
|
||||
ExpDate int64
|
||||
PaidOff bool
|
||||
SharesEven bool
|
||||
CreationDate int64
|
||||
Value pgtype.Numeric
|
||||
StoreID int32
|
||||
CategoryID int32
|
||||
TypeID int32
|
||||
OwnerUserID int32
|
||||
ExpDate pgtype.Timestamp
|
||||
PaidOff pgtype.Bool
|
||||
SharesEven pgtype.Bool
|
||||
CreationDate pgtype.Timestamp
|
||||
}
|
||||
|
||||
func (q *Queries) InsertExpense(ctx context.Context, arg InsertExpenseParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, insertExpense,
|
||||
func (q *Queries) InsertExpense(ctx context.Context, arg InsertExpenseParams) (int32, error) {
|
||||
row := q.db.QueryRow(ctx, insertExpense,
|
||||
arg.Description,
|
||||
arg.Value,
|
||||
arg.StoreID,
|
||||
@@ -195,38 +195,41 @@ func (q *Queries) InsertExpense(ctx context.Context, arg InsertExpenseParams) (s
|
||||
arg.SharesEven,
|
||||
arg.CreationDate,
|
||||
)
|
||||
var ExpID int32
|
||||
err := row.Scan(&ExpID)
|
||||
return ExpID, err
|
||||
}
|
||||
|
||||
const updateExpense = `-- name: UpdateExpense :execresult
|
||||
UPDATE expenses
|
||||
SET
|
||||
"Description" = ?,
|
||||
"Value" = ?,
|
||||
"StoreID" = ?,
|
||||
"CategoryID" = ?,
|
||||
"TypeID" = ?,
|
||||
"OwnerUserID" = ?,
|
||||
"PaidOff" = ?,
|
||||
"SharesEven" = ?,
|
||||
"ExpDate" = ?
|
||||
WHERE "ExpID" = ?
|
||||
"Description" = $1,
|
||||
"Value" = $2,
|
||||
"StoreID" = $3,
|
||||
"CategoryID" = $4,
|
||||
"TypeID" = $5,
|
||||
"OwnerUserID" = $6,
|
||||
"PaidOff" = $7,
|
||||
"SharesEven" = $8,
|
||||
"ExpDate" = $9
|
||||
WHERE "ExpID" = $10
|
||||
`
|
||||
|
||||
type UpdateExpenseParams struct {
|
||||
Description string
|
||||
Value string
|
||||
StoreID int64
|
||||
CategoryID int64
|
||||
TypeID int64
|
||||
OwnerUserID int64
|
||||
PaidOff bool
|
||||
SharesEven bool
|
||||
ExpDate int64
|
||||
ExpID int64
|
||||
Value pgtype.Numeric
|
||||
StoreID int32
|
||||
CategoryID int32
|
||||
TypeID int32
|
||||
OwnerUserID int32
|
||||
PaidOff pgtype.Bool
|
||||
SharesEven pgtype.Bool
|
||||
ExpDate pgtype.Timestamp
|
||||
ExpID int32
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateExpense(ctx context.Context, arg UpdateExpenseParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, updateExpense,
|
||||
func (q *Queries) UpdateExpense(ctx context.Context, arg UpdateExpenseParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, updateExpense,
|
||||
arg.Description,
|
||||
arg.Value,
|
||||
arg.StoreID,
|
||||
|
||||
@@ -4,52 +4,61 @@
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type Category struct {
|
||||
CategoryID int64
|
||||
CategoryID int32
|
||||
CategoryName string
|
||||
}
|
||||
|
||||
type Expense struct {
|
||||
ExpID int64
|
||||
ExpID int32
|
||||
Description string
|
||||
Value string
|
||||
StoreID int64
|
||||
CategoryID int64
|
||||
OwnerUserID int64
|
||||
TypeID int64
|
||||
ExpDate int64
|
||||
CreationDate int64
|
||||
PaidOff bool
|
||||
SharesEven bool
|
||||
Value pgtype.Numeric
|
||||
StoreID int32
|
||||
CategoryID int32
|
||||
OwnerUserID int32
|
||||
TypeID int32
|
||||
ExpDate pgtype.Timestamp
|
||||
CreationDate pgtype.Timestamp
|
||||
PaidOff pgtype.Bool
|
||||
SharesEven pgtype.Bool
|
||||
}
|
||||
|
||||
type ExpenseType struct {
|
||||
TypeID int64
|
||||
TypeID int32
|
||||
TypeName string
|
||||
}
|
||||
|
||||
type ExpensesPayment struct {
|
||||
ExpPaymID int64
|
||||
ExpID int64
|
||||
UserID int64
|
||||
Payed string
|
||||
ExpPaymID int32
|
||||
ExpID int32
|
||||
UserID int32
|
||||
Payed pgtype.Numeric
|
||||
}
|
||||
|
||||
type ExpensesShare struct {
|
||||
ExpShareID int64
|
||||
ExpID int64
|
||||
UserID int64
|
||||
Share string
|
||||
Calculated string
|
||||
ExpShareID int32
|
||||
ExpID int32
|
||||
UserID int32
|
||||
Share pgtype.Numeric
|
||||
Calculated pgtype.Numeric
|
||||
}
|
||||
|
||||
type SchemaMigration struct {
|
||||
Version int64
|
||||
Dirty pgtype.Bool
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
StoreID int64
|
||||
StoreID int32
|
||||
StoreName string
|
||||
}
|
||||
|
||||
type User struct {
|
||||
UserID int64
|
||||
UserID int32
|
||||
UserName string
|
||||
UserPass string
|
||||
}
|
||||
|
||||
@@ -7,31 +7,33 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deletePayment = `-- name: DeletePayment :execresult
|
||||
DELETE FROM "expensesPayments" WHERE "ExpPaymID" = ?
|
||||
DELETE FROM "expensesPayments" WHERE "ExpPaymID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeletePayment(ctx context.Context, exppaymid int64) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, deletePayment, exppaymid)
|
||||
func (q *Queries) DeletePayment(ctx context.Context, exppaymid int32) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, deletePayment, exppaymid)
|
||||
}
|
||||
|
||||
const getExpensePaymentByUser = `-- name: GetExpensePaymentByUser :one
|
||||
SELECT
|
||||
payments.ExpPaymID, payments.ExpID, payments.UserID, payments.Payed, users.UserID, users.UserName, users.UserPass
|
||||
payments."ExpPaymID", payments."ExpID", payments."UserID", payments."Payed", users."UserID", users."UserName", users."UserPass"
|
||||
FROM
|
||||
"expensesPayments" as payments
|
||||
JOIN
|
||||
users as users ON users.UserID = payments.UserID
|
||||
WHERE
|
||||
"ExpID" = ? AND users."UserID" = ?
|
||||
"ExpID" = $1 AND users."UserID" = $2
|
||||
`
|
||||
|
||||
type GetExpensePaymentByUserParams struct {
|
||||
ExpID int64
|
||||
UserID int64
|
||||
ExpID int32
|
||||
UserID int32
|
||||
}
|
||||
|
||||
type GetExpensePaymentByUserRow struct {
|
||||
@@ -40,7 +42,7 @@ type GetExpensePaymentByUserRow struct {
|
||||
}
|
||||
|
||||
func (q *Queries) GetExpensePaymentByUser(ctx context.Context, arg GetExpensePaymentByUserParams) (GetExpensePaymentByUserRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getExpensePaymentByUser, arg.ExpID, arg.UserID)
|
||||
row := q.db.QueryRow(ctx, getExpensePaymentByUser, arg.ExpID, arg.UserID)
|
||||
var i GetExpensePaymentByUserRow
|
||||
err := row.Scan(
|
||||
&i.ExpensesPayment.ExpPaymID,
|
||||
@@ -56,12 +58,12 @@ func (q *Queries) GetExpensePaymentByUser(ctx context.Context, arg GetExpensePay
|
||||
|
||||
const getPayments = `-- name: GetPayments :many
|
||||
SELECT
|
||||
payments.ExpPaymID, payments.ExpID, payments.UserID, payments.Payed, users.UserID, users.UserName, users.UserPass
|
||||
payments."ExpPaymID", payments."ExpID", payments."UserID", payments."Payed", users."UserID", users."UserName", users."UserPass"
|
||||
FROM
|
||||
"expensesPayments" as payments
|
||||
JOIN
|
||||
users as users ON users.UserID = payments.UserID
|
||||
WHERE "ExpID" = ?
|
||||
WHERE "ExpID" = $1
|
||||
`
|
||||
|
||||
type GetPaymentsRow struct {
|
||||
@@ -69,8 +71,8 @@ type GetPaymentsRow struct {
|
||||
User User
|
||||
}
|
||||
|
||||
func (q *Queries) GetPayments(ctx context.Context, expid int64) ([]GetPaymentsRow, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getPayments, expid)
|
||||
func (q *Queries) GetPayments(ctx context.Context, expid int32) ([]GetPaymentsRow, error) {
|
||||
rows, err := q.db.Query(ctx, getPayments, expid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -91,9 +93,6 @@ func (q *Queries) GetPayments(ctx context.Context, expid int64) ([]GetPaymentsRo
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -104,31 +103,31 @@ const insertPayment = `-- name: InsertPayment :execresult
|
||||
INSERT INTO "expensesPayments"(
|
||||
"ExpID", "UserID", "Payed"
|
||||
)
|
||||
VALUES(?, ?, ?)
|
||||
VALUES($1, $2, $3)
|
||||
`
|
||||
|
||||
type InsertPaymentParams struct {
|
||||
ExpID int64
|
||||
UserID int64
|
||||
Payed string
|
||||
ExpID int32
|
||||
UserID int32
|
||||
Payed pgtype.Numeric
|
||||
}
|
||||
|
||||
func (q *Queries) InsertPayment(ctx context.Context, arg InsertPaymentParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, insertPayment, arg.ExpID, arg.UserID, arg.Payed)
|
||||
func (q *Queries) InsertPayment(ctx context.Context, arg InsertPaymentParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, insertPayment, arg.ExpID, arg.UserID, arg.Payed)
|
||||
}
|
||||
|
||||
const updatePayment = `-- name: UpdatePayment :execresult
|
||||
UPDATE expensesPayments
|
||||
SET "UserID" = ?, "Payed" = ?
|
||||
WHERE "ExpPaymID" = ?
|
||||
UPDATE "expensesPayments"
|
||||
SET "UserID" = $1, "Payed" = $2
|
||||
WHERE "ExpPaymID" = $3
|
||||
`
|
||||
|
||||
type UpdatePaymentParams struct {
|
||||
UserID int64
|
||||
Payed string
|
||||
ExpPaymID int64
|
||||
UserID int32
|
||||
Payed pgtype.Numeric
|
||||
ExpPaymID int32
|
||||
}
|
||||
|
||||
func (q *Queries) UpdatePayment(ctx context.Context, arg UpdatePaymentParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, updatePayment, arg.UserID, arg.Payed, arg.ExpPaymID)
|
||||
func (q *Queries) UpdatePayment(ctx context.Context, arg UpdatePaymentParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, updatePayment, arg.UserID, arg.Payed, arg.ExpPaymID)
|
||||
}
|
||||
|
||||
@@ -7,25 +7,27 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteShare = `-- name: DeleteShare :execresult
|
||||
DELETE FROM "expensesShares" where "ExpShareID" = ?
|
||||
DELETE FROM "expensesShares" where "ExpShareID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteShare(ctx context.Context, expshareid int64) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, deleteShare, expshareid)
|
||||
func (q *Queries) DeleteShare(ctx context.Context, expshareid int32) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, deleteShare, expshareid)
|
||||
}
|
||||
|
||||
const getShares = `-- name: GetShares :many
|
||||
SELECT
|
||||
shares.ExpShareID, shares.ExpID, shares.UserID, shares.Share, shares.Calculated, users.UserID, users.UserName, users.UserPass
|
||||
shares."ExpShareID", shares."ExpID", shares."UserID", shares."Share", shares."Calculated", users."UserID", users."UserName", users."UserPass"
|
||||
FROM
|
||||
"expensesShares" as shares
|
||||
JOIN
|
||||
users as users ON users.UserID = shares.UserID
|
||||
WHERE "ExpID" = ?
|
||||
WHERE "ExpID" = $1
|
||||
`
|
||||
|
||||
type GetSharesRow struct {
|
||||
@@ -33,8 +35,8 @@ type GetSharesRow struct {
|
||||
User User
|
||||
}
|
||||
|
||||
func (q *Queries) GetShares(ctx context.Context, expid int64) ([]GetSharesRow, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getShares, expid)
|
||||
func (q *Queries) GetShares(ctx context.Context, expid int32) ([]GetSharesRow, error) {
|
||||
rows, err := q.db.Query(ctx, getShares, expid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -56,9 +58,6 @@ func (q *Queries) GetShares(ctx context.Context, expid int64) ([]GetSharesRow, e
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -69,18 +68,18 @@ const insertShare = `-- name: InsertShare :execresult
|
||||
INSERT INTO "expensesShares"(
|
||||
"ExpID", "UserID", "Share", "Calculated"
|
||||
)
|
||||
VALUES(?, ?, ?, ?)
|
||||
VALUES($1, $2, $3, $4)
|
||||
`
|
||||
|
||||
type InsertShareParams struct {
|
||||
ExpID int64
|
||||
UserID int64
|
||||
Share string
|
||||
Calculated string
|
||||
ExpID int32
|
||||
UserID int32
|
||||
Share pgtype.Numeric
|
||||
Calculated pgtype.Numeric
|
||||
}
|
||||
|
||||
func (q *Queries) InsertShare(ctx context.Context, arg InsertShareParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, insertShare,
|
||||
func (q *Queries) InsertShare(ctx context.Context, arg InsertShareParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, insertShare,
|
||||
arg.ExpID,
|
||||
arg.UserID,
|
||||
arg.Share,
|
||||
@@ -89,20 +88,20 @@ func (q *Queries) InsertShare(ctx context.Context, arg InsertShareParams) (sql.R
|
||||
}
|
||||
|
||||
const updateShare = `-- name: UpdateShare :execresult
|
||||
UPDATE expensesShares
|
||||
SET "UserID" = ?, "Share" = ?, "Calculated" = ?
|
||||
WHERE "ExpShareID" = ?
|
||||
UPDATE "expensesShares"
|
||||
SET "UserID" = $1, "Share" = $2, "Calculated" = $3
|
||||
WHERE "ExpShareID" = $4
|
||||
`
|
||||
|
||||
type UpdateShareParams struct {
|
||||
UserID int64
|
||||
Share string
|
||||
Calculated string
|
||||
ExpShareID int64
|
||||
UserID int32
|
||||
Share pgtype.Numeric
|
||||
Calculated pgtype.Numeric
|
||||
ExpShareID int32
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateShare(ctx context.Context, arg UpdateShareParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, updateShare,
|
||||
func (q *Queries) UpdateShare(ctx context.Context, arg UpdateShareParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, updateShare,
|
||||
arg.UserID,
|
||||
arg.Share,
|
||||
arg.Calculated,
|
||||
|
||||
@@ -7,34 +7,35 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
const deleteStore = `-- name: DeleteStore :execresult
|
||||
DELETE FROM stores WHERE "StoreID" = ?
|
||||
DELETE FROM stores WHERE "StoreID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteStore(ctx context.Context, storeid int64) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, deleteStore, storeid)
|
||||
func (q *Queries) DeleteStore(ctx context.Context, storeid int32) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, deleteStore, storeid)
|
||||
}
|
||||
|
||||
const getStore = `-- name: GetStore :one
|
||||
SELECT StoreID, StoreName FROM stores WHERE "StoreID" = ?
|
||||
SELECT "StoreID", "StoreName" FROM stores WHERE "StoreID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetStore(ctx context.Context, storeid int64) (Store, error) {
|
||||
row := q.db.QueryRowContext(ctx, getStore, storeid)
|
||||
func (q *Queries) GetStore(ctx context.Context, storeid int32) (Store, error) {
|
||||
row := q.db.QueryRow(ctx, getStore, storeid)
|
||||
var i Store
|
||||
err := row.Scan(&i.StoreID, &i.StoreName)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getStores = `-- name: GetStores :many
|
||||
SELECT StoreID, StoreName FROM stores
|
||||
SELECT "StoreID", "StoreName" FROM stores
|
||||
`
|
||||
|
||||
func (q *Queries) GetStores(ctx context.Context) ([]Store, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getStores)
|
||||
rows, err := q.db.Query(ctx, getStores)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -47,9 +48,6 @@ func (q *Queries) GetStores(ctx context.Context) ([]Store, error) {
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -57,22 +55,22 @@ func (q *Queries) GetStores(ctx context.Context) ([]Store, error) {
|
||||
}
|
||||
|
||||
const insertStore = `-- name: InsertStore :execresult
|
||||
INSERT INTO stores("StoreName") VALUES(?)
|
||||
INSERT INTO stores("StoreName") VALUES($1)
|
||||
`
|
||||
|
||||
func (q *Queries) InsertStore(ctx context.Context, storename string) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, insertStore, storename)
|
||||
func (q *Queries) InsertStore(ctx context.Context, storename string) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, insertStore, storename)
|
||||
}
|
||||
|
||||
const updateStore = `-- name: UpdateStore :execresult
|
||||
UPDATE stores SET "StoreName" = ? WHERE "StoreID" = ?
|
||||
UPDATE stores SET "StoreName" = $1 WHERE "StoreID" = $2
|
||||
`
|
||||
|
||||
type UpdateStoreParams struct {
|
||||
StoreName string
|
||||
StoreID int64
|
||||
StoreID int32
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateStore(ctx context.Context, arg UpdateStoreParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, updateStore, arg.StoreName, arg.StoreID)
|
||||
func (q *Queries) UpdateStore(ctx context.Context, arg UpdateStoreParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, updateStore, arg.StoreName, arg.StoreID)
|
||||
}
|
||||
|
||||
@@ -7,34 +7,35 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
const deleteType = `-- name: DeleteType :execresult
|
||||
DELETE FROM "expenseTypes" WHERE "TypeID" = ?
|
||||
DELETE FROM "expenseTypes" WHERE "TypeID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteType(ctx context.Context, typeid int64) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, deleteType, typeid)
|
||||
func (q *Queries) DeleteType(ctx context.Context, typeid int32) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, deleteType, typeid)
|
||||
}
|
||||
|
||||
const getType = `-- name: GetType :one
|
||||
SELECT TypeID, TypeName FROM "expenseTypes" WHERE "TypeID" = ?
|
||||
SELECT "TypeID", "TypeName" FROM "expenseTypes" WHERE "TypeID" = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetType(ctx context.Context, typeid int64) (ExpenseType, error) {
|
||||
row := q.db.QueryRowContext(ctx, getType, typeid)
|
||||
func (q *Queries) GetType(ctx context.Context, typeid int32) (ExpenseType, error) {
|
||||
row := q.db.QueryRow(ctx, getType, typeid)
|
||||
var i ExpenseType
|
||||
err := row.Scan(&i.TypeID, &i.TypeName)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getTypes = `-- name: GetTypes :many
|
||||
SELECT TypeID, TypeName FROM "expenseTypes"
|
||||
SELECT "TypeID", "TypeName" FROM "expenseTypes"
|
||||
`
|
||||
|
||||
func (q *Queries) GetTypes(ctx context.Context) ([]ExpenseType, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getTypes)
|
||||
rows, err := q.db.Query(ctx, getTypes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -47,9 +48,6 @@ func (q *Queries) GetTypes(ctx context.Context) ([]ExpenseType, error) {
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -57,22 +55,22 @@ func (q *Queries) GetTypes(ctx context.Context) ([]ExpenseType, error) {
|
||||
}
|
||||
|
||||
const insertType = `-- name: InsertType :execresult
|
||||
INSERT INTO "expenseTypes"("TypeName") VALUES(?)
|
||||
INSERT INTO "expenseTypes"("TypeName") VALUES($1)
|
||||
`
|
||||
|
||||
func (q *Queries) InsertType(ctx context.Context, typename string) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, insertType, typename)
|
||||
func (q *Queries) InsertType(ctx context.Context, typename string) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, insertType, typename)
|
||||
}
|
||||
|
||||
const updateType = `-- name: UpdateType :execresult
|
||||
UPDATE expenseTypes SET "TypeName" = ? WHERE "TypeID" = ?
|
||||
UPDATE "expenseTypes" SET "TypeName" = $1 WHERE "TypeID" = $2
|
||||
`
|
||||
|
||||
type UpdateTypeParams struct {
|
||||
TypeName string
|
||||
TypeID int64
|
||||
TypeID int32
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateType(ctx context.Context, arg UpdateTypeParams) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, updateType, arg.TypeName, arg.TypeID)
|
||||
func (q *Queries) UpdateType(ctx context.Context, arg UpdateTypeParams) (pgconn.CommandTag, error) {
|
||||
return q.db.Exec(ctx, updateType, arg.TypeName, arg.TypeID)
|
||||
}
|
||||
|
||||
@@ -10,11 +10,11 @@ import (
|
||||
)
|
||||
|
||||
const getUsers = `-- name: GetUsers :many
|
||||
SELECT UserID, UserName, UserPass FROM users
|
||||
SELECT "UserID", "UserName", "UserPass" FROM users
|
||||
`
|
||||
|
||||
func (q *Queries) GetUsers(ctx context.Context) ([]User, error) {
|
||||
rows, err := q.db.QueryContext(ctx, getUsers)
|
||||
rows, err := q.db.Query(ctx, getUsers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -27,9 +27,6 @@ func (q *Queries) GetUsers(ctx context.Context) ([]User, error) {
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+40
-40
@@ -3,61 +3,61 @@
|
||||
-- This should only be a workaround :c
|
||||
|
||||
CREATE TABLE categories (
|
||||
CategoryID SERIAL PRIMARY KEY,
|
||||
CategoryName TEXT NOT NULL
|
||||
"CategoryID" SERIAL PRIMARY KEY,
|
||||
"CategoryName" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE expenseTypes (
|
||||
TypeID SERIAL PRIMARY KEY,
|
||||
TypeName TEXT NOT NULL
|
||||
CREATE TABLE "expenseTypes" (
|
||||
"TypeID" SERIAL PRIMARY KEY,
|
||||
"TypeName" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE stores (
|
||||
StoreID SERIAL PRIMARY KEY,
|
||||
StoreName TEXT NOT NULL
|
||||
"StoreID" SERIAL PRIMARY KEY,
|
||||
"StoreName" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
UserID SERIAL PRIMARY KEY,
|
||||
UserName TEXT NOT NULL,
|
||||
UserPass TEXT NOT NULL
|
||||
"UserID" SERIAL PRIMARY KEY,
|
||||
"UserName" TEXT NOT NULL,
|
||||
"UserPass" TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE expenses (
|
||||
ExpID SERIAL PRIMARY KEY,
|
||||
Description TEXT NOT NULL,
|
||||
Value NUMERIC(12,2) NOT NULL DEFAULT 0,
|
||||
StoreID INT NOT NULL DEFAULT 0,
|
||||
CategoryID INT NOT NULL DEFAULT 0,
|
||||
OwnerUserID INT NOT NULL DEFAULT 0,
|
||||
TypeID INT NOT NULL DEFAULT 0,
|
||||
ExpDate BIGINT NOT NULL DEFAULT -1,
|
||||
CreationDate BIGINT NOT NULL DEFAULT -1,
|
||||
PaidOff BOOLEAN DEFAULT FALSE,
|
||||
SharesEven BOOLEAN DEFAULT FALSE,
|
||||
FOREIGN KEY (StoreID) REFERENCES stores(StoreID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY (CategoryID) REFERENCES categories(CategoryID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY (OwnerUserID) REFERENCES users(UserID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY (TypeID) REFERENCES expenseTypes(TypeID) ON DELETE RESTRICT
|
||||
"ExpID" SERIAL PRIMARY KEY,
|
||||
"Description" TEXT NOT NULL,
|
||||
"Value" NUMERIC(12,2) NOT NULL DEFAULT 0,
|
||||
"StoreID" INT NOT NULL DEFAULT 0,
|
||||
"CategoryID" INT NOT NULL DEFAULT 0,
|
||||
"OwnerUserID" INT NOT NULL DEFAULT 0,
|
||||
"TypeID" INT NOT NULL DEFAULT 0,
|
||||
"ExpDate" TIMESTAMP NOT NULL,
|
||||
"CreationDate" TIMESTAMP NOT NULL,
|
||||
"PaidOff" BOOLEAN DEFAULT FALSE,
|
||||
"SharesEven" BOOLEAN DEFAULT FALSE,
|
||||
FOREIGN KEY ("StoreID") REFERENCES stores("StoreID") ON DELETE RESTRICT,
|
||||
FOREIGN KEY ("CategoryID") REFERENCES categories("CategoryID") ON DELETE RESTRICT,
|
||||
FOREIGN KEY ("OwnerUserID") REFERENCES users("UserID") ON DELETE RESTRICT,
|
||||
FOREIGN KEY ("TypeID") REFERENCES "expenseTypes"("TypeID") ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE TABLE expensesPayments (
|
||||
ExpPaymID SERIAL PRIMARY KEY,
|
||||
ExpID INT NOT NULL,
|
||||
UserID INT NOT NULL,
|
||||
Payed NUMERIC(12,2) NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY (UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
CREATE TABLE "expensesPayments" (
|
||||
"ExpPaymID" SERIAL PRIMARY KEY,
|
||||
"ExpID" INT NOT NULL,
|
||||
"UserID" INT NOT NULL,
|
||||
"Payed" NUMERIC(12,2) NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY ("ExpID") REFERENCES expenses("ExpID") ON DELETE RESTRICT,
|
||||
FOREIGN KEY ("UserID") REFERENCES users("UserID") ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE TABLE expensesShares (
|
||||
ExpShareID SERIAL PRIMARY KEY,
|
||||
ExpID INT NOT NULL,
|
||||
UserID INT NOT NULL,
|
||||
Share NUMERIC(6,2) NOT NULL DEFAULT 0.5,
|
||||
Calculated NUMERIC(12,2) NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (ExpID) REFERENCES expenses(ExpID) ON DELETE RESTRICT,
|
||||
FOREIGN KEY (UserID) REFERENCES users(UserID) ON DELETE RESTRICT
|
||||
CREATE TABLE "expensesShares" (
|
||||
"ExpShareID" SERIAL PRIMARY KEY,
|
||||
"ExpID" INT NOT NULL,
|
||||
"UserID" INT NOT NULL,
|
||||
"Share" NUMERIC(6,2) NOT NULL DEFAULT 0.5,
|
||||
"Calculated" NUMERIC(12,2) NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY ("ExpID") REFERENCES expenses("ExpID") ON DELETE RESTRICT,
|
||||
FOREIGN KEY ("UserID") REFERENCES users("UserID") ON DELETE RESTRICT
|
||||
);
|
||||
|
||||
CREATE TABLE schema_migrations (
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
version: "2"
|
||||
sql:
|
||||
- engine: "sqlite"
|
||||
- engine: "postgresql"
|
||||
queries: "queries/"
|
||||
schema: "schema.sql"
|
||||
gen:
|
||||
go:
|
||||
sql_package: "pgx/v5"
|
||||
package: "repository"
|
||||
out: "repository"
|
||||
rename:
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
mod "expenses/expenses/models"
|
||||
"sort"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
dec "github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
@@ -143,28 +145,29 @@ func CalculateDebts(e *mod.Expense) (mod.Debts, error) {
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) settleDebt(payment mod.ExpensePayment,
|
||||
credit mod.ExpensePayment, eId int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
credit mod.ExpensePayment, eId int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
credit.PayedAmount = credit.PayedAmount.Sub(payment.PayedAmount)
|
||||
|
||||
err = payment.Insert(tx, eId)
|
||||
err = payment.Insert(a.DB, tx, eId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = credit.Update(tx)
|
||||
err = credit.Update(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) ProcessDebt(expID int64, debt mod.Debt) error {
|
||||
func (a *ExpensesApp) ProcessDebt(expID int32, debt mod.Debt) error {
|
||||
// We have to balance the debtor and creditor payments
|
||||
payment := mod.ExpensePayment{
|
||||
User: mod.User{
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
mod "expenses/expenses/models"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
dec "github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
@@ -45,71 +48,75 @@ func ParseFormPayments(userIDs []string, paymentsIDs []string,
|
||||
return payments, nil
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) GetExpensePaymentByUserID(eId int64, uId int64,
|
||||
func (a *ExpensesApp) GetExpensePaymentByUserID(eId int32, uId int32,
|
||||
) (mod.ExpensePayment, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return mod.ExpensePayment{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
payment, err := mod.GetExpensePaymentByUserID(tx, eId, uId)
|
||||
payment, err := mod.GetExpensePaymentByUserID(a.DB, tx, eId, uId)
|
||||
|
||||
return payment, tx.Commit()
|
||||
return payment, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// insertPayment allows us to insert a payment manually
|
||||
// for now its private, need to figure out if it needs to be public
|
||||
func (a *ExpensesApp) insertPayment(payment mod.ExpensePayment, eIdx int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) insertPayment(payment mod.ExpensePayment, eIdx int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
err = payment.Insert(tx, eIdx)
|
||||
err = payment.Insert(a.DB, tx, eIdx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) DeletePayment(id int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) DeletePayment(id int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
payment := mod.ExpensePayment{
|
||||
ExpPaymID: id,
|
||||
}
|
||||
|
||||
err = payment.Delete(tx)
|
||||
err = payment.Delete(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) UpdatePayment(payment mod.ExpensePayment) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
err = payment.Update(tx)
|
||||
err = payment.Update(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) AddPayment(expID int64, userID int64, sum dec.Decimal) error {
|
||||
func (a *ExpensesApp) AddPayment(expID int32, userID int32, sum dec.Decimal) error {
|
||||
payment := mod.ExpensePayment{
|
||||
User: mod.User{
|
||||
UserID: userID,
|
||||
|
||||
@@ -2,7 +2,6 @@ package expenses
|
||||
|
||||
import (
|
||||
mod "expenses/expenses/models"
|
||||
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
@@ -15,7 +14,7 @@ func (a *ExpensesApp) luaInsertPayment(L *lua.LState) int {
|
||||
return returnWithError(L, err.Error())
|
||||
}
|
||||
|
||||
err = a.insertPayment(*payment, int64(expenseID))
|
||||
err = a.insertPayment(*payment, int32(expenseID))
|
||||
if err != nil {
|
||||
return returnWithError(L, err.Error())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
mod "expenses/expenses/models"
|
||||
"github.com/jackc/pgx/v5"
|
||||
dec "github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
@@ -68,36 +70,38 @@ func (a *ExpensesApp) NormalizeShares(e *mod.Expense) error {
|
||||
|
||||
// insertShare allows us to insert a share manually
|
||||
// for now its private, need to figure out if it needs to be public
|
||||
func (a *ExpensesApp) insertShare(share *mod.Share, eIdx int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) insertShare(share *mod.Share, eIdx int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
err = share.Insert(tx, eIdx)
|
||||
err = share.Insert(a.DB, tx, eIdx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) DeleteShare(id int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) DeleteShare(id int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
share := mod.Share{
|
||||
ExpShareID: id,
|
||||
}
|
||||
|
||||
err = share.Delete(tx)
|
||||
err = share.Delete(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ func (a *ExpensesApp) luaInsertShare(L *lua.LState) int {
|
||||
return returnWithError(L, err.Error())
|
||||
}
|
||||
|
||||
err = a.insertShare(share, int64(expenseID))
|
||||
err = a.insertShare(share, int32(expenseID))
|
||||
if err != nil {
|
||||
return returnWithError(L, err.Error())
|
||||
}
|
||||
|
||||
+53
-36
@@ -1,23 +1,30 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
mod "expenses/expenses/models"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
func (a *ExpensesApp) GetAllExpenses() ([]mod.Expense, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return []mod.Expense{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
expenses, err := mod.GetAllExpenses(tx)
|
||||
expenses, err := mod.GetAllExpenses(a.DB, tx)
|
||||
if err != nil {
|
||||
return []mod.Expense{}, err
|
||||
}
|
||||
|
||||
return expenses, tx.Commit()
|
||||
return expenses, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) GetExpensesRanged(startDate string, endDate string) ([]mod.Expense, error) {
|
||||
@@ -26,69 +33,75 @@ func (a *ExpensesApp) GetExpensesRanged(startDate string, endDate string) ([]mod
|
||||
log.Printf("error startDate: %v", err)
|
||||
return []mod.Expense{}, nil
|
||||
}
|
||||
start := startDateTime.Unix()
|
||||
|
||||
endDateTime, err := time.ParseInLocation("02-Jan-2006 15:04:05", endDate, time.UTC)
|
||||
if err != nil {
|
||||
log.Printf("error endDate: %v", err)
|
||||
return []mod.Expense{}, nil
|
||||
}
|
||||
end := endDateTime.Unix()
|
||||
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return []mod.Expense{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
expenses, err := mod.GetExpensesRange(tx, start, end)
|
||||
expenses, err := mod.GetExpensesRange(a.DB, tx, startDateTime, endDateTime)
|
||||
|
||||
return expenses, tx.Commit()
|
||||
return expenses, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) GetExpense(id int64) (mod.Expense, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) GetExpense(id int32) (mod.Expense, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return mod.Expense{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
expense, err := mod.GetExpense(tx, id)
|
||||
expense, err := mod.GetExpense(a.DB, tx, id)
|
||||
if err != nil {
|
||||
return mod.Expense{}, err
|
||||
}
|
||||
|
||||
return expense, tx.Commit()
|
||||
return expense, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) LoadExpenseShares(e *mod.Expense) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
err = e.GetShares(tx)
|
||||
err = e.GetShares(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) LoadExpensePayments(e *mod.Expense) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
err = e.GetPayments(tx)
|
||||
err = e.GetPayments(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) LoadExpenseDebts(e *mod.Expense) error {
|
||||
@@ -98,23 +111,24 @@ func (a *ExpensesApp) LoadExpenseDebts(e *mod.Expense) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) DeleteExpense(id int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) DeleteExpense(id int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
expense := mod.Expense{
|
||||
ExpID: id,
|
||||
}
|
||||
|
||||
err = expense.Delete()
|
||||
err = expense.Delete(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func mapShares(e *mod.Expense) map[mod.User]decimal.Decimal {
|
||||
@@ -176,35 +190,38 @@ func (a *ExpensesApp) analyzeExpense(e *mod.Expense) {
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) NewExpense(exp mod.Expense) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
a.analyzeExpense(&exp)
|
||||
|
||||
err = exp.Insert(tx)
|
||||
err = exp.Insert(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) UpdateExpense(exp mod.Expense) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
a.analyzeExpense(&exp)
|
||||
|
||||
err = exp.Update(tx)
|
||||
err = exp.Update(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
mod "expenses/expenses/models"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
@@ -21,13 +22,16 @@ func (a *ExpensesApp) prepareExpense(exp *mod.Expense) error {
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) luaGetAllExpenses(L *lua.LState) int {
|
||||
tx, err := a.DB.Begin()
|
||||
// TODO
|
||||
// It makes no sense this repeats this db thing
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return returnWithError(L, err.Error())
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
expenses, err := mod.GetAllExpenses(tx)
|
||||
expenses, err := mod.GetAllExpenses(a.DB, tx)
|
||||
|
||||
tbl := L.NewTable()
|
||||
for _, e := range expenses {
|
||||
@@ -54,13 +58,16 @@ func (a *ExpensesApp) luaGetAllExpenses(L *lua.LState) int {
|
||||
func (a *ExpensesApp) luaGetExpense(L *lua.LState) int {
|
||||
expId := L.CheckInt(1)
|
||||
|
||||
tx, err := a.DB.Begin()
|
||||
// TODO
|
||||
// This also doesnt make sense
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.Begin(ctx)
|
||||
if err != nil {
|
||||
return returnWithError(L, err.Error())
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
expense, err := mod.GetExpense(tx, int64(expId))
|
||||
expense, err := mod.GetExpense(a.DB, tx, int32(expId))
|
||||
if err != nil {
|
||||
return returnWithError(L, err.Error())
|
||||
}
|
||||
|
||||
+14
-10
@@ -1,27 +1,31 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"expenses/config"
|
||||
mig "github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
"github.com/jackc/pgx/v5"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
mig "github.com/golang-migrate/migrate/v4"
|
||||
"github.com/golang-migrate/migrate/v4/database/sqlite3"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
lua "github.com/yuin/gopher-lua"
|
||||
)
|
||||
|
||||
const LAST_GO_MIGRATION = 3
|
||||
|
||||
func prepareMigrator(db *sql.DB) (*mig.Migrate, error) {
|
||||
func prepareMigrator(db *pgx.Conn) (*mig.Migrate, error) {
|
||||
cfg := config.GetInstance()
|
||||
|
||||
driver, err := sqlite3.WithInstance(db, &sqlite3.Config{})
|
||||
m, err := mig.NewWithDatabaseInstance(cfg.MigrationsPath, "sqlite3", driver)
|
||||
m, err := mig.New(cfg.MigrationsPath,
|
||||
"postgres://"+cfg.PgCfg.User+":"+cfg.PgCfg.Pass+"@"+cfg.PgCfg.Host+":"+
|
||||
cfg.PgCfg.Port+"/"+cfg.PgCfg.DB+"?sslmode=disable",
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, err
|
||||
}
|
||||
@@ -92,7 +96,7 @@ func runCustomMigrationLogic(ver uint) {
|
||||
}
|
||||
}
|
||||
|
||||
func RunMigrations(db *sql.DB, lua *lua.LState) error {
|
||||
func RunMigrations(db *pgx.Conn, lua *lua.LState) error {
|
||||
m, err := prepareMigrator(db)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -2,16 +2,14 @@ package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
config "expenses/config"
|
||||
repo "expenses/expenses/db/repository"
|
||||
experr "expenses/expenses/errors"
|
||||
"fmt"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type Category struct {
|
||||
CategoryID int64 `json:"CategoryID"`
|
||||
CategoryID int32 `json:"CategoryID"`
|
||||
CategoryName string `json:"CategoryName"`
|
||||
}
|
||||
|
||||
@@ -22,17 +20,10 @@ func NewCategory() Category {
|
||||
}
|
||||
}
|
||||
|
||||
func GetAllCategories() ([]Category, error) {
|
||||
cfg := config.GetInstance()
|
||||
func GetAllCategories(db repo.DBTX, tx pgx.Tx) ([]Category, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
db, err := sql.Open(cfg.DBSys, cfg.DBPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
queries := repo.New(db)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
categories, err := queries.GetCategories(ctx)
|
||||
if err != nil {
|
||||
return []Category{}, nil
|
||||
@@ -41,75 +32,53 @@ func GetAllCategories() ([]Category, error) {
|
||||
return MapRepoCategories(categories), nil
|
||||
}
|
||||
|
||||
func GetCategory(catID int64) (Category, error) {
|
||||
cfg := config.GetInstance()
|
||||
func GetCategory(db repo.DBTX, tx pgx.Tx, catID int32) (Category, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
db, err := sql.Open(cfg.DBSys, cfg.DBPath)
|
||||
if err != nil {
|
||||
return Category{}, err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
queries := repo.New(db)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
category, err := queries.GetCategory(ctx, catID)
|
||||
|
||||
return MapRepoCategory(category), err
|
||||
}
|
||||
|
||||
func (cat *Category) Insert(tx *sql.Tx) error {
|
||||
func (cat *Category) Insert(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.InsertCategory(ctx, cat.CategoryName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cat *Category) Delete() error {
|
||||
cfg := config.GetInstance()
|
||||
func (cat *Category) Delete(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
db, err := sql.Open(cfg.DBSys, "file:"+cfg.DBPath+"?_foreign_keys=on")
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.DeleteCategory(ctx, cat.CategoryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
queries := repo.New(db)
|
||||
res, err := queries.DeleteCategory(ctx, cat.CategoryID)
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return experr.ErrNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cat *Category) Update() error {
|
||||
cfg := config.GetInstance()
|
||||
func (cat *Category) Update(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
db, err := sql.Open(cfg.DBSys, "file:"+cfg.DBPath+"?_foreign_keys=on")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
queries := repo.New(db)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.UpdateCategory(ctx, repo.UpdateCategoryParams{
|
||||
CategoryName: cat.CategoryName,
|
||||
CategoryID: cat.CategoryID,
|
||||
@@ -118,10 +87,8 @@ func (cat *Category) Update() error {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return experr.ErrNotFound
|
||||
}
|
||||
|
||||
|
||||
+219
-182
@@ -3,30 +3,30 @@ package models
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"expenses/config"
|
||||
repo "expenses/expenses/db/repository"
|
||||
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
type Expense struct {
|
||||
ExpID int64 `json:"ExpID"`
|
||||
ExpID int32 `json:"ExpID"`
|
||||
Description string `json:"Description"`
|
||||
Value decimal.Decimal `json:"Value"`
|
||||
Store Store `json:"Store"`
|
||||
Type Type `json:"Type"`
|
||||
Category Category `json:"Category"`
|
||||
Owner User `json:"Owner"`
|
||||
Date int64 `json:"Date"`
|
||||
Date time.Time `json:"Date"`
|
||||
Payments []ExpensePayment `json:"Payments"`
|
||||
Shares []Share `json:"Shares"`
|
||||
Debts Debts `json:"Debts"`
|
||||
PaidOff bool `json:"PaidOff"`
|
||||
SharesEven bool `json:"SharesEven"`
|
||||
CreationDate int64 `json:"CreationDate"`
|
||||
CreationDate time.Time `json:"CreationDate"`
|
||||
}
|
||||
|
||||
func NewExpense() Expense {
|
||||
@@ -37,12 +37,12 @@ func NewExpense() Expense {
|
||||
Store: NewStore(),
|
||||
Category: NewCategory(),
|
||||
Owner: NewUser(),
|
||||
Date: 0,
|
||||
Date: time.Now(),
|
||||
Payments: []ExpensePayment{},
|
||||
Shares: []Share{},
|
||||
PaidOff: false,
|
||||
SharesEven: false,
|
||||
CreationDate: 0,
|
||||
CreationDate: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,183 +55,15 @@ func ExpenseFromJSON(data []byte) (*Expense, error) {
|
||||
return &expense, err
|
||||
}
|
||||
|
||||
func GetAllExpenses(tx *sql.Tx) ([]Expense, error) {
|
||||
func GetAllExpenses(db repo.DBTX, tx pgx.Tx) ([]Expense, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
expenses, err := queries.GetExpenses(ctx, repo.GetExpensesParams{
|
||||
Startdate: nil,
|
||||
Enddate: nil,
|
||||
})
|
||||
if err != nil {
|
||||
return []Expense{}, err
|
||||
}
|
||||
var start pgtype.Timestamp
|
||||
start.Valid = false
|
||||
var end pgtype.Timestamp
|
||||
end.Valid = false
|
||||
|
||||
return mapRepoGetExpensesRows(expenses), nil
|
||||
}
|
||||
|
||||
func GetExpense(tx *sql.Tx, expID int64) (Expense, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
expense, err := queries.GetExpense(ctx, expID)
|
||||
if err != nil {
|
||||
return Expense{}, err
|
||||
}
|
||||
|
||||
return mapRepoGetExpenseRow(expense), nil
|
||||
}
|
||||
|
||||
func (exp *Expense) Insert(tx *sql.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
res, err := queries.InsertExpense(ctx, repo.InsertExpenseParams{
|
||||
Description: exp.Description,
|
||||
Value: exp.Value.String(),
|
||||
StoreID: exp.Store.StoreID,
|
||||
CategoryID: exp.Category.CategoryID,
|
||||
TypeID: exp.Type.TypeID,
|
||||
OwnerUserID: exp.Owner.UserID,
|
||||
ExpDate: exp.Date,
|
||||
PaidOff: exp.PaidOff,
|
||||
SharesEven: exp.SharesEven,
|
||||
CreationDate: exp.CreationDate,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
expenseID, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve last inserted expense ID: %v", err)
|
||||
}
|
||||
|
||||
exp.ExpID = expenseID
|
||||
|
||||
err = exp.InsertShares(tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = exp.InsertPayments(tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (exp *Expense) InsertShares(tx *sql.Tx) error {
|
||||
for _, share := range exp.Shares {
|
||||
err := share.Insert(tx, exp.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (exp *Expense) InsertPayments(tx *sql.Tx) error {
|
||||
for _, paym := range exp.Payments {
|
||||
err := paym.Insert(tx, exp.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Expense) Update(tx *sql.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
res, err := queries.UpdateExpense(ctx, repo.UpdateExpenseParams{
|
||||
ExpID: e.ExpID,
|
||||
Description: e.Description,
|
||||
Value: e.Value.String(),
|
||||
StoreID: e.Store.StoreID,
|
||||
CategoryID: e.Category.CategoryID,
|
||||
TypeID: e.Type.TypeID,
|
||||
OwnerUserID: e.Owner.UserID,
|
||||
PaidOff: e.PaidOff,
|
||||
SharesEven: e.SharesEven,
|
||||
ExpDate: e.Date,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, share := range e.Shares {
|
||||
if share.ExpShareID == -1 {
|
||||
err := share.Insert(tx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
share.Update(tx)
|
||||
}
|
||||
}
|
||||
|
||||
for _, paym := range e.Payments {
|
||||
if paym.ExpPaymID == -1 {
|
||||
err := paym.Insert(tx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
paym.Update(tx)
|
||||
}
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were updated")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Expense) Delete() error {
|
||||
cfg := config.GetInstance()
|
||||
ctx := context.Background()
|
||||
|
||||
db, err := sql.Open(cfg.DBSys, cfg.DBPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
queries := repo.New(db)
|
||||
res, err := queries.DeleteExpense(ctx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SHITTY QUERIES THAT I NEED TO PUT IN SOMEWHERE MORE OGRANHJASLD
|
||||
func GetExpensesRange(tx *sql.Tx, start int64, end int64) ([]Expense, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
expenses, err := queries.GetExpenses(ctx, repo.GetExpensesParams{
|
||||
Startdate: start,
|
||||
Enddate: end,
|
||||
@@ -242,3 +74,208 @@ func GetExpensesRange(tx *sql.Tx, start int64, end int64) ([]Expense, error) {
|
||||
|
||||
return mapRepoGetExpensesRows(expenses), nil
|
||||
}
|
||||
|
||||
func GetExpense(db repo.DBTX, tx pgx.Tx, expID int32) (Expense, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
expense, err := queries.GetExpense(ctx, expID)
|
||||
if err != nil {
|
||||
return Expense{}, err
|
||||
}
|
||||
|
||||
return mapRepoGetExpenseRow(expense), nil
|
||||
}
|
||||
|
||||
func (exp *Expense) Insert(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
value, err := decimalToNumeric(exp.Value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paidOff, err := boolToPgBool(exp.PaidOff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sharesEven, err := boolToPgBool(exp.SharesEven)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
expDate, err := timeToTimestamp(exp.Date)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
creationDate, err := timeToTimestamp(exp.CreationDate)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
lastInsertedID, err := queries.InsertExpense(ctx, repo.InsertExpenseParams{
|
||||
Description: exp.Description,
|
||||
Value: value,
|
||||
StoreID: exp.Store.StoreID,
|
||||
CategoryID: exp.Category.CategoryID,
|
||||
TypeID: exp.Type.TypeID,
|
||||
OwnerUserID: exp.Owner.UserID,
|
||||
ExpDate: expDate,
|
||||
PaidOff: paidOff,
|
||||
SharesEven: sharesEven,
|
||||
CreationDate: creationDate,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
exp.ExpID = lastInsertedID
|
||||
|
||||
err = exp.InsertShares(db, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = exp.InsertPayments(db, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (exp *Expense) InsertShares(db repo.DBTX, tx pgx.Tx) error {
|
||||
for _, share := range exp.Shares {
|
||||
err := share.Insert(db, tx, exp.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (exp *Expense) InsertPayments(db repo.DBTX, tx pgx.Tx) error {
|
||||
for _, paym := range exp.Payments {
|
||||
err := paym.Insert(db, tx, exp.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Expense) Update(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
value, err := decimalToNumeric(e.Value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paidOff, err := boolToPgBool(e.PaidOff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sharesEven, err := boolToPgBool(e.SharesEven)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
expDate, err := timeToTimestamp(e.Date)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.UpdateExpense(ctx, repo.UpdateExpenseParams{
|
||||
ExpID: e.ExpID,
|
||||
Description: e.Description,
|
||||
Value: value,
|
||||
StoreID: e.Store.StoreID,
|
||||
CategoryID: e.Category.CategoryID,
|
||||
TypeID: e.Type.TypeID,
|
||||
OwnerUserID: e.Owner.UserID,
|
||||
PaidOff: paidOff,
|
||||
SharesEven: sharesEven,
|
||||
ExpDate: expDate,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, share := range e.Shares {
|
||||
if share.ExpShareID == -1 {
|
||||
err := share.Insert(db, tx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
share.Update(db, tx)
|
||||
}
|
||||
}
|
||||
|
||||
for _, paym := range e.Payments {
|
||||
if paym.ExpPaymID == -1 {
|
||||
err := paym.Insert(db, tx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
paym.Update(db, tx)
|
||||
}
|
||||
}
|
||||
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were updated")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Expense) Delete(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.DeleteExpense(ctx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SHITTY QUERIES THAT I NEED TO PUT IN SOMEWHERE MORE OGRANHJASLD
|
||||
func GetExpensesRange(db repo.DBTX, tx pgx.Tx, start time.Time, end time.Time) ([]Expense, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
startPg, err := timeToTimestamp(start)
|
||||
if err != nil {
|
||||
return []Expense{}, err
|
||||
}
|
||||
|
||||
endPg, err := timeToTimestamp(end)
|
||||
if err != nil {
|
||||
return []Expense{}, err
|
||||
}
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
expenses, err := queries.GetExpenses(ctx, repo.GetExpensesParams{
|
||||
Startdate: startPg,
|
||||
Enddate: endPg,
|
||||
})
|
||||
if err != nil {
|
||||
return []Expense{}, err
|
||||
}
|
||||
|
||||
return mapRepoGetExpensesRows(expenses), nil
|
||||
}
|
||||
|
||||
@@ -2,12 +2,10 @@ package models
|
||||
|
||||
import (
|
||||
repo "expenses/expenses/db/repository"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
func mapRepoGetPaymentsRow(s repo.GetPaymentsRow) ExpensePayment {
|
||||
payed, _ := decimal.NewFromString(s.ExpensesPayment.Payed)
|
||||
payed := pgNumericToDecimal(s.ExpensesPayment.Payed)
|
||||
|
||||
return ExpensePayment{
|
||||
ExpPaymID: s.ExpensesPayment.ExpPaymID,
|
||||
@@ -28,7 +26,7 @@ func mapRepoGetPaymentsRows(ep []repo.GetPaymentsRow) []ExpensePayment {
|
||||
}
|
||||
|
||||
func mapRepoGetPaymentRow(s repo.GetExpensePaymentByUserRow) ExpensePayment {
|
||||
payed, _ := decimal.NewFromString(s.ExpensesPayment.Payed)
|
||||
payed := pgNumericToDecimal(s.ExpensesPayment.Payed)
|
||||
|
||||
return ExpensePayment{
|
||||
ExpPaymID: s.ExpensesPayment.ExpPaymID,
|
||||
|
||||
@@ -4,16 +4,14 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
repo "expenses/expenses/db/repository"
|
||||
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
type ExpensePayment struct {
|
||||
ExpPaymID int64
|
||||
ExpPaymID int32
|
||||
User User
|
||||
PayedAmount decimal.Decimal
|
||||
}
|
||||
@@ -25,10 +23,10 @@ func PaymentFromJSON(data []byte) (*ExpensePayment, error) {
|
||||
return &payment, err
|
||||
}
|
||||
|
||||
func (e *Expense) GetPayments(tx *sql.Tx) error {
|
||||
func (e *Expense) GetPayments(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
payments, err := queries.GetPayments(ctx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -38,11 +36,11 @@ func (e *Expense) GetPayments(tx *sql.Tx) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetExpensePaymentByUserID(tx *sql.Tx, eId int64, uId int64,
|
||||
func GetExpensePaymentByUserID(db repo.DBTX, tx pgx.Tx, eId int32, uId int32,
|
||||
) (ExpensePayment, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
payment, err := queries.GetExpensePaymentByUser(ctx, repo.GetExpensePaymentByUserParams{
|
||||
ExpID: eId,
|
||||
UserID: uId,
|
||||
@@ -54,65 +52,69 @@ func GetExpensePaymentByUserID(tx *sql.Tx, eId int64, uId int64,
|
||||
return mapRepoGetPaymentRow(payment), nil
|
||||
}
|
||||
|
||||
func (p *ExpensePayment) Insert(tx *sql.Tx, expID int64) error {
|
||||
func (p *ExpensePayment) Insert(db repo.DBTX, tx pgx.Tx, expID int32) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
payed, err := decimalToNumeric(p.PayedAmount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.InsertPayment(ctx, repo.InsertPaymentParams{
|
||||
ExpID: expID,
|
||||
UserID: p.User.UserID,
|
||||
Payed: p.PayedAmount.String(),
|
||||
Payed: payed,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *ExpensePayment) Update(tx *sql.Tx) error {
|
||||
func (p *ExpensePayment) Update(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
payed, err := decimalToNumeric(p.PayedAmount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.UpdatePayment(ctx, repo.UpdatePaymentParams{
|
||||
ExpPaymID: p.ExpPaymID,
|
||||
Payed: p.PayedAmount.String(),
|
||||
Payed: payed,
|
||||
UserID: p.User.UserID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *ExpensePayment) Delete(tx *sql.Tx) error {
|
||||
func (p *ExpensePayment) Delete(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.DeletePayment(ctx, p.ExpPaymID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,14 @@ package models
|
||||
|
||||
import (
|
||||
repo "expenses/expenses/db/repository"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
func mapRepoGetExpenseRow(e repo.GetExpenseRow) Expense {
|
||||
value, _ := decimal.NewFromString(e.Expense.Value)
|
||||
value := pgNumericToDecimal(e.Expense.Value)
|
||||
paidOff := pgBoolToBool(e.Expense.PaidOff)
|
||||
sharesEven := pgBoolToBool(e.Expense.SharesEven)
|
||||
expDate := pgTimestampToTime(e.Expense.ExpDate)
|
||||
creationDate := pgTimestampToTime(e.Expense.CreationDate)
|
||||
|
||||
return Expense{
|
||||
ExpID: e.Expense.ExpID,
|
||||
@@ -29,17 +31,21 @@ func mapRepoGetExpenseRow(e repo.GetExpenseRow) Expense {
|
||||
UserID: e.User.UserID,
|
||||
UserName: e.User.UserName,
|
||||
},
|
||||
Date: e.Expense.ExpDate,
|
||||
Date: expDate,
|
||||
Shares: []Share{},
|
||||
Payments: []ExpensePayment{},
|
||||
PaidOff: e.Expense.PaidOff,
|
||||
SharesEven: e.Expense.SharesEven,
|
||||
CreationDate: e.Expense.CreationDate,
|
||||
PaidOff: paidOff,
|
||||
SharesEven: sharesEven,
|
||||
CreationDate: creationDate,
|
||||
}
|
||||
}
|
||||
|
||||
func mapRepoGetExpenseRowMulti(e repo.GetExpensesRow) Expense {
|
||||
value, _ := decimal.NewFromString(e.Expense.Value)
|
||||
value := pgNumericToDecimal(e.Expense.Value)
|
||||
paidOff := pgBoolToBool(e.Expense.PaidOff)
|
||||
sharesEven := pgBoolToBool(e.Expense.SharesEven)
|
||||
expDate := pgTimestampToTime(e.Expense.ExpDate)
|
||||
creationDate := pgTimestampToTime(e.Expense.CreationDate)
|
||||
|
||||
return Expense{
|
||||
ExpID: e.Expense.ExpID,
|
||||
@@ -61,12 +67,12 @@ func mapRepoGetExpenseRowMulti(e repo.GetExpensesRow) Expense {
|
||||
UserID: e.User.UserID,
|
||||
UserName: e.User.UserName,
|
||||
},
|
||||
Date: e.Expense.ExpDate,
|
||||
Date: expDate,
|
||||
Shares: []Share{},
|
||||
Payments: []ExpensePayment{},
|
||||
PaidOff: e.Expense.PaidOff,
|
||||
SharesEven: e.Expense.SharesEven,
|
||||
CreationDate: e.Expense.CreationDate,
|
||||
PaidOff: paidOff,
|
||||
SharesEven: sharesEven,
|
||||
CreationDate: creationDate,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,18 +2,17 @@ package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"expenses/expenses/db/repository"
|
||||
repo "expenses/expenses/db/repository"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
dec "github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
type Share struct {
|
||||
ExpShareID int64 `json:"ExpShareID"`
|
||||
ExpShareID int32 `json:"ExpShareID"`
|
||||
User User `json:"User"`
|
||||
Share dec.Decimal `json:"Share"`
|
||||
Calculated dec.Decimal `json:"Calculated"`
|
||||
@@ -45,10 +44,10 @@ func (sh Shares) Equal(other Shares) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (e *Expense) GetShares(tx *sql.Tx) error {
|
||||
func (e *Expense) GetShares(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repository.New(tx)
|
||||
queries := repository.New(db).WithTx(tx)
|
||||
shares, err := queries.GetShares(ctx, e.ExpID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -58,67 +57,79 @@ func (e *Expense) GetShares(tx *sql.Tx) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sh *Share) Insert(tx *sql.Tx, expID int64) error {
|
||||
func (sh *Share) Insert(db repo.DBTX, tx pgx.Tx, expID int32) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
share, err := decimalToNumeric(sh.Share)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
calculated, err := decimalToNumeric(sh.Calculated)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.InsertShare(ctx, repo.InsertShareParams{
|
||||
ExpID: expID,
|
||||
Share: sh.Share.String(),
|
||||
Share: share,
|
||||
UserID: sh.User.UserID,
|
||||
Calculated: sh.Calculated.String(),
|
||||
Calculated: calculated,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sh *Share) Update(tx *sql.Tx) error {
|
||||
func (sh *Share) Update(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
share, err := decimalToNumeric(sh.Share)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
calculated, err := decimalToNumeric(sh.Calculated)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.UpdateShare(ctx, repo.UpdateShareParams{
|
||||
ExpShareID: sh.ExpShareID,
|
||||
Share: sh.Share.String(),
|
||||
Share: share,
|
||||
UserID: sh.User.UserID,
|
||||
Calculated: sh.Calculated.String(),
|
||||
Calculated: calculated,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sh *Share) Delete(tx *sql.Tx) error {
|
||||
func (sh *Share) Delete(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.DeleteShare(ctx, sh.ExpShareID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
|
||||
@@ -2,13 +2,11 @@ package models
|
||||
|
||||
import (
|
||||
repo "expenses/expenses/db/repository"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
)
|
||||
|
||||
func mapRepoGetSharesRow(s repo.GetSharesRow) Share {
|
||||
share, _ := decimal.NewFromString(s.ExpensesShare.Share)
|
||||
calculated, _ := decimal.NewFromString(s.ExpensesShare.Calculated)
|
||||
share := pgNumericToDecimal(s.ExpensesShare.Share)
|
||||
calculated := pgNumericToDecimal(s.ExpensesShare.Calculated)
|
||||
|
||||
return Share{
|
||||
ExpShareID: s.ExpensesShare.ExpShareID,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
dec "github.com/shopspring/decimal"
|
||||
"time"
|
||||
)
|
||||
|
||||
func decimalToNumeric(d dec.Decimal) (pgtype.Numeric, error) {
|
||||
var num pgtype.Numeric
|
||||
err := num.Scan(d.Truncate(2).String())
|
||||
if err != nil {
|
||||
return pgtype.Numeric{}, err
|
||||
}
|
||||
num.Valid = true
|
||||
|
||||
return num, nil
|
||||
}
|
||||
|
||||
func boolToPgBool(v bool) (pgtype.Bool, error) {
|
||||
var b pgtype.Bool
|
||||
err := b.Scan(v)
|
||||
if err != nil {
|
||||
return pgtype.Bool{}, err
|
||||
}
|
||||
b.Valid = true
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func timeToTimestamp(t time.Time) (pgtype.Timestamp, error) {
|
||||
var ts pgtype.Timestamp
|
||||
err := ts.Scan(t)
|
||||
if err != nil {
|
||||
return pgtype.Timestamp{}, err
|
||||
}
|
||||
|
||||
return ts, nil
|
||||
}
|
||||
|
||||
func pgNumericToDecimal(n pgtype.Numeric) dec.Decimal {
|
||||
return dec.NewFromBigInt(n.Int, n.Exp)
|
||||
}
|
||||
|
||||
func pgBoolToBool(n pgtype.Bool) bool {
|
||||
return n.Bool
|
||||
}
|
||||
|
||||
func pgTimestampToTime(ts pgtype.Timestamp) time.Time {
|
||||
return ts.Time
|
||||
}
|
||||
@@ -4,15 +4,13 @@ import (
|
||||
"context"
|
||||
repo "expenses/expenses/db/repository"
|
||||
experr "expenses/expenses/errors"
|
||||
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
StoreID int64 `json:"StoreID"`
|
||||
StoreID int32 `json:"StoreID"`
|
||||
StoreName string `json:"StoreName"`
|
||||
}
|
||||
|
||||
@@ -23,10 +21,10 @@ func NewStore() Store {
|
||||
}
|
||||
}
|
||||
|
||||
func GetAllStores(tx *sql.Tx) ([]Store, error) {
|
||||
func GetAllStores(db repo.DBTX, tx pgx.Tx) ([]Store, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
storeList, err := queries.GetStores(ctx)
|
||||
if err != nil {
|
||||
return []Store{}, err
|
||||
@@ -35,10 +33,10 @@ func GetAllStores(tx *sql.Tx) ([]Store, error) {
|
||||
return mapRepoStores(storeList), nil
|
||||
}
|
||||
|
||||
func GetStore(tx *sql.Tx, storeID int64) (Store, error) {
|
||||
func GetStore(db repo.DBTX, tx pgx.Tx, storeID int32) (Store, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
store, err := queries.GetStore(ctx, storeID)
|
||||
if err != nil {
|
||||
return Store{}, err
|
||||
@@ -47,51 +45,49 @@ func GetStore(tx *sql.Tx, storeID int64) (Store, error) {
|
||||
return mapRepoStore(store), nil
|
||||
}
|
||||
|
||||
func (s *Store) Insert(tx *sql.Tx) error {
|
||||
func (s *Store) Insert(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.InsertStore(ctx, s.StoreName)
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
}
|
||||
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Update(tx *sql.Tx) error {
|
||||
func (s *Store) Update(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
res, err := queries.UpdateStore(ctx, repo.UpdateStoreParams{
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
_, err := queries.UpdateStore(ctx, repo.UpdateStoreParams{
|
||||
StoreID: s.StoreID,
|
||||
StoreName: s.StoreName,
|
||||
})
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
return experr.ErrNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Delete(tx *sql.Tx) error {
|
||||
func (s *Store) Delete(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.DeleteStore(ctx, s.StoreID)
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
}
|
||||
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return experr.ErrNotFound
|
||||
}
|
||||
|
||||
|
||||
+18
-26
@@ -4,15 +4,13 @@ import (
|
||||
"context"
|
||||
repo "expenses/expenses/db/repository"
|
||||
experr "expenses/expenses/errors"
|
||||
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type Type struct {
|
||||
TypeID int64 `json:"TypeID"`
|
||||
TypeID int32 `json:"TypeID"`
|
||||
TypeName string `json:"TypeName"`
|
||||
}
|
||||
|
||||
@@ -23,10 +21,10 @@ func NewType() Type {
|
||||
}
|
||||
}
|
||||
|
||||
func GetAllTypes(tx *sql.Tx) ([]Type, error) {
|
||||
func GetAllTypes(db repo.DBTX, tx pgx.Tx) ([]Type, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
typeList, err := queries.GetTypes(ctx)
|
||||
if err != nil {
|
||||
return []Type{}, err
|
||||
@@ -35,10 +33,10 @@ func GetAllTypes(tx *sql.Tx) ([]Type, error) {
|
||||
return mapRepoTypes(typeList), nil
|
||||
}
|
||||
|
||||
func GetType(tx *sql.Tx, typID int64) (Type, error) {
|
||||
func GetType(db repo.DBTX, tx pgx.Tx, typID int32) (Type, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
typ, err := queries.GetType(ctx, typID)
|
||||
if err != nil {
|
||||
return Type{}, err
|
||||
@@ -47,10 +45,10 @@ func GetType(tx *sql.Tx, typID int64) (Type, error) {
|
||||
return mapRepoType(typ), nil
|
||||
}
|
||||
|
||||
func (typ *Type) Insert(tx *sql.Tx) error {
|
||||
func (typ *Type) Insert(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.InsertType(ctx, typ.TypeName)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -59,39 +57,35 @@ func (typ *Type) Insert(tx *sql.Tx) error {
|
||||
// TODO
|
||||
// Move all theses things outside of this, I'll handle it wherever I'm doing
|
||||
// logics
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("no rows were created")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (typ *Type) Delete(tx *sql.Tx) error {
|
||||
func (typ *Type) Delete(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.DeleteType(ctx, typ.TypeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return experr.ErrNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (typ *Type) Update(tx *sql.Tx) error {
|
||||
func (typ *Type) Update(db repo.DBTX, tx pgx.Tx) error {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
res, err := queries.UpdateType(ctx, repo.UpdateTypeParams{
|
||||
TypeID: typ.TypeID,
|
||||
TypeName: typ.TypeName,
|
||||
@@ -100,10 +94,8 @@ func (typ *Type) Update(tx *sql.Tx) error {
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
} else if rowsAffected == 0 {
|
||||
rowsAffected := res.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return experr.ErrNotFound
|
||||
}
|
||||
|
||||
|
||||
@@ -2,14 +2,13 @@ package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
repo "expenses/expenses/db/repository"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
UserID int64 `json:"UserID"`
|
||||
UserID int32 `json:"UserID"`
|
||||
UserName string `json:"UserName"`
|
||||
}
|
||||
|
||||
@@ -20,10 +19,10 @@ func NewUser() User {
|
||||
}
|
||||
}
|
||||
|
||||
func GetAllUsers(tx *sql.Tx) ([]User, error) {
|
||||
func GetAllUsers(db repo.DBTX, tx pgx.Tx) ([]User, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
queries := repo.New(tx)
|
||||
queries := repo.New(db).WithTx(tx)
|
||||
userList, err := queries.GetUsers(ctx)
|
||||
if err != nil {
|
||||
return []User{}, err
|
||||
|
||||
+31
-23
@@ -1,89 +1,97 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
mod "expenses/expenses/models"
|
||||
)
|
||||
|
||||
func (a *ExpensesApp) GetAllStores() ([]mod.Store, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return []mod.Store{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
stores, err := mod.GetAllStores(tx)
|
||||
stores, err := mod.GetAllStores(a.DB, tx)
|
||||
if err != nil {
|
||||
return []mod.Store{}, err
|
||||
}
|
||||
|
||||
return stores, tx.Commit()
|
||||
return stores, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) GetStore(id int64) (mod.Store, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) GetStore(id int32) (mod.Store, error) {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return mod.Store{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
store, err := mod.GetStore(tx, id)
|
||||
store, err := mod.GetStore(a.DB, tx, id)
|
||||
if err != nil {
|
||||
return mod.Store{}, err
|
||||
}
|
||||
|
||||
return store, tx.Commit()
|
||||
return store, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) NewStore(name string) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
newStore := mod.Store{
|
||||
StoreName: name,
|
||||
}
|
||||
|
||||
err = newStore.Insert(tx)
|
||||
return tx.Commit()
|
||||
err = newStore.Insert(a.DB, tx)
|
||||
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) UpdateStore(id int64, name string) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) UpdateStore(id int32, name string) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
store := mod.Store{
|
||||
StoreID: id,
|
||||
StoreName: name,
|
||||
}
|
||||
|
||||
err = store.Update(tx)
|
||||
err = store.Update(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) DeleteStore(id int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) DeleteStore(id int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
store := mod.Store{
|
||||
StoreID: id,
|
||||
}
|
||||
|
||||
err = store.Delete(tx)
|
||||
err = store.Delete(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
+30
-23
@@ -1,93 +1,100 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
mod "expenses/expenses/models"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (a *ExpensesApp) GetAllTypes() ([]mod.Type, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return []mod.Type{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
types, err := mod.GetAllTypes(tx)
|
||||
types, err := mod.GetAllTypes(a.DB, tx)
|
||||
if err != nil {
|
||||
return []mod.Type{}, err
|
||||
}
|
||||
|
||||
return types, tx.Commit()
|
||||
return types, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) GetType(id int64) (mod.Type, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) GetType(id int32) (mod.Type, error) {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return mod.Type{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
typ, err := mod.GetType(tx, id)
|
||||
typ, err := mod.GetType(a.DB, tx, id)
|
||||
if err != nil {
|
||||
return mod.Type{}, err
|
||||
}
|
||||
|
||||
return typ, tx.Commit()
|
||||
return typ, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) NewType(name string) error {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
newTyp := mod.Type{
|
||||
TypeName: name,
|
||||
}
|
||||
|
||||
err = newTyp.Insert(tx)
|
||||
err = newTyp.Insert(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) DeleteType(id int64) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) DeleteType(id int32) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
typ := mod.Type{
|
||||
TypeID: id,
|
||||
}
|
||||
|
||||
err = typ.Delete(tx)
|
||||
err = typ.Delete(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (a *ExpensesApp) UpdateType(id int64, name string) error {
|
||||
tx, err := a.DB.Begin()
|
||||
func (a *ExpensesApp) UpdateType(id int32, name string) error {
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
newTyp := mod.Type{
|
||||
TypeID: id,
|
||||
TypeName: name,
|
||||
}
|
||||
|
||||
err = newTyp.Update(tx)
|
||||
err = newTyp.Update(a.DB, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
package expenses
|
||||
|
||||
import (
|
||||
"context"
|
||||
mod "expenses/expenses/models"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (a *ExpensesApp) GetAllUsers() ([]mod.User, error) {
|
||||
tx, err := a.DB.Begin()
|
||||
ctx := context.Background()
|
||||
tx, err := a.DB.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return []mod.User{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
users, err := mod.GetAllUsers(tx)
|
||||
users, err := mod.GetAllUsers(a.DB, tx)
|
||||
if err != nil {
|
||||
return []mod.User{}, err
|
||||
}
|
||||
|
||||
return users, tx.Commit()
|
||||
|
||||
return users, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ go 1.24.4
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.10.1
|
||||
github.com/golang-migrate/migrate/v4 v4.18.3
|
||||
github.com/jackc/pgx/v5 v5.5.4
|
||||
github.com/layeh/gopher-json v0.0.0-20201124131017-552bb3c4c3bf
|
||||
github.com/mattn/go-sqlite3 v1.14.28
|
||||
github.com/shopspring/decimal v1.2.0
|
||||
@@ -27,9 +28,12 @@ require (
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
|
||||
+60
-1
@@ -1,3 +1,7 @@
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
@@ -10,12 +14,28 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dhui/dktest v0.4.5 h1:uUfYBIVREmj/Rw6MvgmqNAYzTiKOHJak+enB5Di73MM=
|
||||
github.com/dhui/dktest v0.4.5/go.mod h1:tmcyeHDKagvlDrz7gDKq4UAJOLIfVZYkfD5OnHDwcCo=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v27.2.0+incompatible h1:Rk9nIVdfH3+Vz4cyI/uhbINhEZ/oLmc+CBXmH6fbNk4=
|
||||
github.com/docker/docker v27.2.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
|
||||
github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
|
||||
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
@@ -26,6 +46,8 @@ github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBEx
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=
|
||||
github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
@@ -38,12 +60,24 @@ github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+l
|
||||
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.5.4 h1:Xp2aQS8uXButQdnCMWNmvx6UysWQQC+u1EoizjguY+8=
|
||||
github.com/jackc/pgx/v5 v5.5.4/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/layeh/gopher-json v0.0.0-20201124131017-552bb3c4c3bf h1:bg6J/5S/AeTz7K9i/luJRj31BJ8f+LgYwKQBSOZxSEM=
|
||||
github.com/layeh/gopher-json v0.0.0-20201124131017-552bb3c4c3bf/go.mod h1:E/q28EyUVBgBQnONAVPIdwvEsv4Ve0vaCA9JWim4+3I=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
@@ -54,15 +88,29 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A=
|
||||
github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
|
||||
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
|
||||
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
|
||||
@@ -88,6 +136,14 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
|
||||
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
|
||||
go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8=
|
||||
go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc=
|
||||
go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8=
|
||||
go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4=
|
||||
go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ=
|
||||
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
@@ -97,6 +153,8 @@ golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
|
||||
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
|
||||
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
|
||||
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
||||
golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
|
||||
golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||
@@ -107,8 +165,9 @@ golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSm
|
||||
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -4,12 +4,9 @@ import (
|
||||
"database/sql"
|
||||
exp "expenses/expenses"
|
||||
experr "expenses/expenses/errors"
|
||||
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -18,7 +15,7 @@ const (
|
||||
)
|
||||
|
||||
func categoriesGlobalPage(c *gin.Context) {
|
||||
categories, err := exp.GetAllCategories()
|
||||
categories, err := exp.App.GetAllCategories()
|
||||
if err != nil {
|
||||
ServerErrorView(c, "The server too makes mistakes")
|
||||
return
|
||||
@@ -33,13 +30,13 @@ func categoriesGlobalPage(c *gin.Context) {
|
||||
}
|
||||
|
||||
func categoryPage(c *gin.Context) {
|
||||
categoryID, err := strconv.ParseInt(c.Param("id"), 10, 16)
|
||||
categoryID, err := exp.ParseID(c.Param("id"))
|
||||
if err != nil {
|
||||
NotFoundView(c, "No such category")
|
||||
return
|
||||
}
|
||||
|
||||
category, err := exp.GetCategory(categoryID)
|
||||
category, err := exp.App.GetCategory(categoryID)
|
||||
if err == sql.ErrNoRows {
|
||||
NotFoundView(c, fmt.Sprintf("Could not find category `%d`", categoryID))
|
||||
return
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
experr "expenses/expenses/errors"
|
||||
mod "expenses/expenses/models"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"net/http"
|
||||
|
||||
@@ -32,6 +33,7 @@ func expensesPartial(c *gin.Context) {
|
||||
func ExpensesGlobalPage(c *gin.Context) {
|
||||
expenses, err := exp.App.GetAllExpenses()
|
||||
if err != nil {
|
||||
log.Panicln("error:", err)
|
||||
c.Header("HX-Redirect", "/500")
|
||||
return
|
||||
}
|
||||
@@ -75,7 +77,7 @@ func expensePage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
categories, err := exp.GetAllCategories()
|
||||
categories, err := exp.App.GetAllCategories()
|
||||
if err != nil {
|
||||
ServerErrorView(c, "failed to fetch categories")
|
||||
return
|
||||
@@ -120,7 +122,7 @@ func expensePage(c *gin.Context) {
|
||||
}
|
||||
|
||||
func newExpensePage(c *gin.Context) {
|
||||
categories, err := exp.GetAllCategories()
|
||||
categories, err := exp.App.GetAllCategories()
|
||||
if err != nil {
|
||||
ServerErrorView(c, "failed to fetch categories")
|
||||
return
|
||||
|
||||
@@ -33,7 +33,6 @@ func expenseFromForm(c *gin.Context) (*mod.Expense, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
date := formattedDate.Unix()
|
||||
|
||||
newValue := c.PostForm("expense-value")
|
||||
value, err := decimal.NewFromString(newValue)
|
||||
@@ -70,7 +69,7 @@ func expenseFromForm(c *gin.Context) (*mod.Expense, error) {
|
||||
|
||||
newExp := mod.Expense{
|
||||
Description: newDescription,
|
||||
Date: date,
|
||||
Date: formattedDate,
|
||||
Value: value,
|
||||
Type: mod.Type{
|
||||
TypeID: typID,
|
||||
@@ -86,7 +85,7 @@ func expenseFromForm(c *gin.Context) (*mod.Expense, error) {
|
||||
// This needs to be dynamic - to be added once we have logins and whatnot
|
||||
UserID: 1,
|
||||
},
|
||||
CreationDate: time.Now().Unix(),
|
||||
CreationDate: time.Now(),
|
||||
Shares: shares,
|
||||
Payments: payments,
|
||||
}
|
||||
|
||||
+1
-4
@@ -5,10 +5,7 @@ import (
|
||||
exp "expenses/expenses"
|
||||
experr "expenses/expenses/errors"
|
||||
"fmt"
|
||||
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -32,7 +29,7 @@ func storesGlobalPage(c *gin.Context) {
|
||||
}
|
||||
|
||||
func storePage(c *gin.Context) {
|
||||
storeID, err := strconv.ParseInt(c.Param("id"), 10, 16)
|
||||
storeID, err := exp.ParseID(c.Param("id"))
|
||||
if err != nil {
|
||||
NotFoundView(c, "didn't find request store")
|
||||
return
|
||||
|
||||
+1
-4
@@ -4,11 +4,8 @@ import (
|
||||
"database/sql"
|
||||
exp "expenses/expenses"
|
||||
experr "expenses/expenses/errors"
|
||||
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -32,7 +29,7 @@ func typesGlobalPage(c *gin.Context) {
|
||||
}
|
||||
|
||||
func typePage(c *gin.Context) {
|
||||
typeID, err := strconv.ParseInt(c.Param("id"), 10, 16)
|
||||
typeID, err := exp.ParseID(c.Param("id"))
|
||||
if err != nil {
|
||||
NotFoundView(c, "requested type doesn't exist")
|
||||
return
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
schema.sql
|
||||
.env
|
||||
pgsql-data-dev/
|
||||
|
||||
Reference in New Issue
Block a user