Matrix/utils/database/transactionDatabaseConnector.go
2020-10-01 17:45:57 +02:00

119 lines
2.1 KiB
Go

package database
import (
"database/sql"
"fmt"
"log"
"nutfactory.org/Matrix/entities/transaction"
)
func initTransactionTable(db *sql.DB) (err error) {
log.Printf("Init Transaction Table")
statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS txn (
id TEXT PRIMARY KEY,
origin TEXT,
timestamp INTEGER
)`)
if err != nil {
return
}
statement.Exec()
//TODO: Test Queries
return
}
func createTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO txn
(id, origin, timestamp)
VALUES
(?, ?, ?)`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(transaction.Id, transaction.Origin, transaction.Timestamp)
if err != nil {
return
}
tx.Commit()
return
}
func readTransaction(db *sql.DB, id string) (foundTransaction *transaction.Transaction, err error) {
queryStmt := fmt.Sprintf(`SELECT id, origin, timestamp
FROM txn
WHERE id = '%s'`, id)
rows, err := db.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundTransaction = &transaction.Transaction{}
err = rows.Scan(&foundTransaction.Id, &foundTransaction.Origin, &foundTransaction.Timestamp)
if err != nil {
return
}
foundTransaction.PDUS, err = ReadEventsFromTransaction(db, foundTransaction.Id)
}
return
}
func updateTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE txn SET
origin = ?,
timestamp = ?
WHERE id = ?`)
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare(sqlStmt)
if err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(transaction.Origin, transaction.Timestamp, transaction.Id)
if err != nil {
return
}
tx.Commit()
return
}
func deleteTransaction(db *sql.DB, id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM txn
WHERE id = '%s'`, id)
tx, err := db.Begin()
if err != nil {
return
}
_, err = db.Exec(queryStmt)
if err != nil {
return
}
tx.Commit()
return
}