github.com/tunedmystic/hound@v0.0.0-20200829043919-3822fec61e65/app/database/database.go (about) 1 package database 2 3 import ( 4 "fmt" 5 6 "github.com/jmoiron/sqlx" 7 _ "github.com/mattn/go-sqlite3" // sqlite 8 9 "github.com/tunedmystic/hound/app/config" 10 ) 11 12 // NewDB ... 13 func NewDB() *sqlx.DB { 14 config := config.GetConfig() 15 db := sqlx.MustOpen("sqlite3", config.DatabaseName) 16 return db 17 } 18 19 // CreateTables ... 20 func CreateTables(db *sqlx.DB) { 21 PerformCreateTables(db) 22 } 23 24 // GetArticles ... 25 func GetArticles(db *sqlx.DB) []*Article { 26 return PerformGetArticles(db) 27 } 28 29 // PerformCreateTables [internal] 30 var PerformCreateTables = func(db *sqlx.DB) { 31 sql := ` 32 CREATE TABLE IF NOT EXISTS article ( 33 id INTEGER PRIMARY KEY AUTOINCREMENT, 34 url VARCHAR(100) UNIQUE NOT NULL, 35 title VARCHAR(100) NOT NULL, 36 description VARCHAR(100), 37 published_at DATETIME NOT NULL, 38 created_at DATETIME NOT NULL 39 );` 40 41 db.MustExec(sql) 42 } 43 44 // PerformGetArticles [internal] 45 var PerformGetArticles = func(db *sqlx.DB) []*Article { 46 articles := []*Article{} 47 sql := `SELECT * FROM article;` 48 49 if err := db.Select(&articles, sql); err != nil { 50 fmt.Printf("Could not fetch articles: %v\n", err.Error()) 51 } 52 53 return articles 54 }