From 0b0a3d24f667317ebc892f95a46c258dde8b1a46 Mon Sep 17 00:00:00 2001 From: Immanuel Onyeka Date: Wed, 16 Nov 2022 22:33:13 -0500 Subject: [PATCH] Query loan types --- migrations/0_29092022_create_main_tables.sql | 2 +- skouter.go | 45 +++++++++++++++++--- 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/migrations/0_29092022_create_main_tables.sql b/migrations/0_29092022_create_main_tables.sql index 4f91f3e..99c800f 100644 --- a/migrations/0_29092022_create_main_tables.sql +++ b/migrations/0_29092022_create_main_tables.sql @@ -52,7 +52,7 @@ CREATE TABLE loan_type ( id INT AUTO_INCREMENT, branch_id INT, user_id INT, - name VARCHAR(30), + name VARCHAR(30) NOT NULL, FOREIGN KEY (branch_id) REFERENCES branch(id), FOREIGN KEY (user_id) REFERENCES user(id), PRIMARY KEY (`id`) diff --git a/skouter.go b/skouter.go index 36f26e9..07ce163 100644 --- a/skouter.go +++ b/skouter.go @@ -18,8 +18,9 @@ type Page struct { } type LoanType struct { - user int - branch int + id int + user sql.NullInt64 + branch sql.NullInt64 name string } @@ -106,10 +107,43 @@ func match(path, pattern string, args *[]string) bool { return true } +func getLoanType(db *sql.DB, id int, isUser bool) ([]LoanType, error) { + var loans []LoanType + + // Should be changed to specify user + rows, err := + db.Query("SELECT * FROM loan_type WHERE user_id = ? " + + "OR (user_id = NULL AND branch_id = NULL)", id) + + if err != nil { + return nil, fmt.Errorf("loan_type error: %v", err) + } + + defer rows.Close() + + for rows.Next() { + var loan LoanType + + if err := rows.Scan( + &loan.user, + &loan.branch, + &loan.name) + err != nil { + log.Printf("Error occured fetching loan: %v", err) + return nil, fmt.Errorf("Error occured fetching loan: %v", err) + } + + loans = append(loans, loan) + } + + return loans, nil +} + // Fetch fees from the database func getFees(db *sql.DB, user int) ([]FeeTemplate, error) { var fees []FeeTemplate + // Should be changed to specify user rows, err := db.Query("SELECT * FROM fee_template") if err != nil { return nil, fmt.Errorf("Fee error %v", err) @@ -119,9 +153,6 @@ func getFees(db *sql.DB, user int) ([]FeeTemplate, error) { for rows.Next() { var fee FeeTemplate - // var fee = FeeTemplate{ ftype: map[string]uint8{ - // "Government": 0, "Title": 1, "Required": 2, "Lender": 3, "Other": 4, - // }} if err := rows.Scan( &fee.id, @@ -141,7 +172,7 @@ func getFees(db *sql.DB, user int) ([]FeeTemplate, error) { fees = append(fees, fee) } - fmt.Print("the fees: %v", fees) + // fmt.Print("the fees: %v", fees) return fees, nil } @@ -182,7 +213,7 @@ func main() { // maybe os.Exit(1) instead } - fmt.Print(getFees(db, 0)) + fmt.Print(getLoanType(db, 0, true)) http.Handle("/assets/", files) http.HandleFunc("/", route)