Matrix/entities/event/transactionDatabaseConnector.go
2020-10-17 12:07:39 +02:00

103 lines
1.8 KiB
Go

package event
import (
"fmt"
"git.nutfactory.org/hoernschen/Matrix/utils/database"
)
func CreateTransaction(transaction *Transaction) (err error) {
sqlStmt := fmt.Sprintf(`INSERT INTO txn
(id, origin, timestamp)
VALUES
(?, ?, ?)`)
tx, err := database.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 {
tx.Rollback()
return
}
tx.Commit()
return
}
func ReadTransaction(id string) (foundTransaction *Transaction, err error) {
queryStmt := fmt.Sprintf(`SELECT id, origin, timestamp
FROM txn
WHERE id = '%s'`, id)
rows, err := database.DB.Query(queryStmt)
if err != nil {
return
}
defer rows.Close()
if rows.Next() {
foundTransaction = &Transaction{}
err = rows.Scan(&foundTransaction.Id, &foundTransaction.Origin, &foundTransaction.Timestamp)
if err != nil {
return
}
foundTransaction.PDUS, err = ReadEventsFromTransaction(foundTransaction.Id)
}
return
}
func UpdateTransaction(transaction *Transaction) (err error) {
sqlStmt := fmt.Sprintf(`UPDATE txn SET
origin = ?,
timestamp = ?
WHERE id = ?`)
tx, err := database.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 {
tx.Rollback()
return
}
tx.Commit()
return
}
func DeleteTransaction(id string) (err error) {
queryStmt := fmt.Sprintf(`DELETE FROM txn
WHERE id = '%s'`, id)
tx, err := database.DB.Begin()
if err != nil {
return
}
_, err = tx.Exec(queryStmt)
if err != nil {
tx.Rollback()
return
}
tx.Commit()
return
}