Recount-Server/db/db.go

108 lines
2.6 KiB
Go

package db
import (
"fmt"
"database/sql"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog/log"
"nickiel.net/recount_server/types"
)
var DB_TYPE string;
var DB_SCHEMA string;
var DB_CONNECTION_STRING string;
func SetConstants(db_type string, db_schema string, db_conn_string string) {
DB_TYPE = db_type;
DB_SCHEMA = db_schema;
DB_CONNECTION_STRING = db_conn_string;
}
func GetTransactions(transactions *[]types.Transaction, resultCount int, pageNum int) error {
db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING)
if err != nil {
log.Fatal().
Err(err).
Msg("Fatal error in db_get_transactions\nCannot connect to server")
}
defer db.Close()
err = db.Select(transactions,
"SELECT trns_id, trns_amount, trns_description, "+
"trns_account, trns_bucket, trns_date "+
fmt.Sprintf("FROM %stransactions ORDER BY trns_id DESC ", DB_SCHEMA)+
fmt.Sprintf("LIMIT %d OFFSET %d",
resultCount, pageNum*resultCount))
if err != nil {
return err
}
return nil
}
func NewTransaction(transaction types.Transaction) error {
db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING)
if err != nil {
log.Fatal().
Err(err).
Msg("Fatal error in db_get_transactions\nCannot connect to server")
}
defer db.Close()
log.Debug().Msgf("%#v", transaction)
_, err = db.NamedExec(
fmt.Sprintf("INSERT INTO %stransactions", DB_SCHEMA)+
"(trns_amount, trns_description, trns_account, trns_bucket, trns_date)"+
"VALUES (:trns_amount, :trns_description, :trns_account, :trns_bucket, :trns_date)",
transaction)
if err != nil {
log.Fatal().
Err(err).
Msg("Could not exec insert db query")
}
return nil
}
func GetUserAccounts(userID int) ([]types.Account, error) {
user_accounts := make([]types.Account, 4);
user_accounts[0] = types.Account {
Id: 1,
DisplayName: sql.NullString {
String: "Savings",
Valid: true,
} ,
Description: sql.NullString {
String: "BECU Saving Account",
Valid: true,
},
};
user_accounts[1] = types.Account {
Id: 2,
DisplayName: sql.NullString {
String: "Svngs",
Valid: true,
} ,
Description: sql.NullString {
String: "BECU Saving Account",
Valid: true,
},
};
return user_accounts, nil;
}
func GetTransPaneEntries(userID int) ([]types.QuickTransactionType, error) {
transaction_types := make([]types.QuickTransactionType, 1);
transaction_types[0] = types.QuickTransactionType {
DisplayName: "Manual",
};
return transaction_types, nil;
}