/service/database/connection.go
Go | 107 lines | 65 code | 18 blank | 24 comment | 16 complexity | 339a21912c04e1cefafe4aed5a5ae1b5 MD5 | raw file
- package database
- import (
- "fmt"
- "strings"
- _ "github.com/mattn/go-sqlite3"
- "github.com/jmoiron/sqlx"
- )
- const FALLBACK_DB_FILE string = "./linksink.db"
- const DEFAULT_IDLE_CONNECTIONS int = 10
- const DEFAULT_OPEN_CONNECTIONS int = 10
- const DEFAULT_LIMIT int = 100
- var connection *sqlx.DB
- /*
- * Initializes a SQLite database
- */
- func InitializeDatabasePool(path string) (*sqlx.DB, error) {
- if connection != nil {
- return connection, nil
- }
- path = strings.TrimSpace(path)
- if len(path) == 0 {
- path = FALLBACK_DB_FILE
- }
- // Open database file
- db, err := sqlx.Open("sqlite3", path)
- if err != nil {
- return connection, err
- }
- // Initialize schema
- stmt := `
- CREATE TABLE IF NOT EXISTS links (
- id integer primary key,
- created DATETIME DEFAULT CURRENT_TIMESTAMP,
- label TEXT,
- href TEXT
- );
- `
- if _, err := db.Exec(stmt); err != nil {
- return connection, err
- }
- db.SetMaxIdleConns(DEFAULT_IDLE_CONNECTIONS)
- db.SetMaxOpenConns(DEFAULT_OPEN_CONNECTIONS)
- connection = db
- return connection, nil
- }
- /*
- * Return cached pool information and/or initialize a database at the
- * default file path.
- */
- func GetConnection() (*sqlx.DB, error) {
- return InitializeDatabasePool("")
- }
- /*
- * Conventience wrapper for executing transactions.
- *
- * Example:
- * func (s Service) DoSomething() error {
- * return Transaction(func (tx *sqlx.Tx) error {
- * if _, err := tx.Exec(...); err != nil {
- * return err
- * }
- * if _, err := tx.Exec(...); err != nil {
- * return err
- * }
- * })
- * }
- */
- func Transaction(fn func(*sqlx.Tx) error) (error) {
- tx, err := connection.Beginx()
- if err != nil {
- return err
- }
- defer func() {
- if p := recover(); p != nil {
- switch p := p.(type) {
- case error:
- err = p
- default:
- err = fmt.Errorf("%s", p)
- }
- }
- if err != nil {
- tx.Rollback()
- return
- }
- err = tx.Commit()
- }()
- return fn(tx)
- }