Added: creating database, sql tx repository

This commit is contained in:
Oliwier Adamczyk
2025-10-04 15:11:20 +02:00
parent 1aa78d10c5
commit fdd1c98e75
10 changed files with 159 additions and 1 deletions

View File

@@ -0,0 +1,14 @@
package db
import "database/sql"
type ITxRepository interface {
// Creates a new tx.
Begin() (*sql.Tx, error)
// Rollbacks tx's data or returns an error to the given error's pointer address.
RollbackOnError(*sql.Tx, *error)
// Applies changes to the database.
Commit(*sql.Tx) error
}

34
internal/db/repository.go Normal file
View File

@@ -0,0 +1,34 @@
package db
import (
"database/sql"
)
type TxRepository struct {
db *sql.DB
}
func NewTxRepository(instance *sql.DB) ITxRepository {
return &TxRepository{
db: instance,
}
}
func (t TxRepository) Begin() (*sql.Tx, error) {
tx, err := t.db.Begin()
if err != nil {
return nil, err
}
return tx, nil
}
func (TxRepository) RollbackOnError(tx *sql.Tx, errObserve *error) {
if *errObserve != nil {
tx.Rollback()
}
}
func (TxRepository) Commit(tx *sql.Tx) error {
return tx.Commit()
}

65
internal/db/setup.go Normal file
View File

@@ -0,0 +1,65 @@
package db
import (
"database/sql"
"os"
"scrap/internal/config"
"strings"
_ "github.com/mattn/go-sqlite3"
)
var dbInstance *sql.DB
func Setup() {
db, err := sql.Open("sqlite3", "./example.db")
if err != nil {
panic(err)
}
dbInstance = db
tableFilenames := getTableFilenames()
createTablesFromSQLFiles(tableFilenames)
}
func GetInstance() *sql.DB { return dbInstance }
func Close() { dbInstance.Close() }
func getTableFilenames() []string {
appConfig := config.GetAppConfig()
files, err := os.ReadDir(appConfig.SqlTablesDir)
if err != nil {
panic(err)
}
filenames := []string{}
for _, f := range files {
fName := f.Name()
if !strings.HasSuffix(fName, ".sql") {
continue
}
filenames = append(filenames, fName)
}
return filenames
}
func createTablesFromSQLFiles(filenames []string) {
appConfig := config.GetAppConfig()
for _, fName := range filenames {
tableBytes, err := os.ReadFile(appConfig.SqlTablesDir + fName)
if err != nil {
panic(err)
}
tableQuery := string(tableBytes)
if _, err = dbInstance.Exec(tableQuery); err != nil {
panic(err)
}
}
}