Matrix/utils/database/transactionDatabaseConnector.go

120 lines
2.1 KiB
Go
Raw Normal View History

2020-10-01 15:45:57 +00:00
package database
2020-09-30 08:28:49 +00:00
import (
"database/sql"
2020-10-01 15:45:57 +00:00
"fmt"
"log"
2020-09-30 08:28:49 +00:00
"nutfactory.org/Matrix/entities/transaction"
)
2020-10-01 15:45:57 +00:00
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
}
2020-09-30 08:28:49 +00:00
statement.Exec()
2020-10-01 15:45:57 +00:00
//TODO: Test Queries
return
2020-09-30 08:28:49 +00:00
}
2020-10-01 15:45:57 +00:00
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
}
2020-09-30 08:28:49 +00:00
2020-10-01 15:45:57 +00:00
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
2020-09-30 08:28:49 +00:00
}
2020-10-01 15:45:57 +00:00
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()
2020-09-30 08:28:49 +00:00
2020-10-01 15:45:57 +00:00
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
2020-09-30 08:28:49 +00:00
}
2020-10-01 15:45:57 +00:00
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()
2020-09-30 08:28:49 +00:00
2020-10-01 15:45:57 +00:00
_, err = stmt.Exec(transaction.Origin, transaction.Timestamp, transaction.Id)
if err != nil {
return
}
tx.Commit()
return
2020-09-30 08:28:49 +00:00
}
2020-10-01 15:45:57 +00:00
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
}
2020-09-30 08:28:49 +00:00
2020-10-01 15:45:57 +00:00
tx.Commit()
return
2020-09-30 08:28:49 +00:00
}