You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package stemdb
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
type Book struct {
|
|
ID int
|
|
Author string
|
|
Seria string
|
|
Title string
|
|
Deleted bool
|
|
Selected bool
|
|
}
|
|
|
|
var dbx *sqlx.DB
|
|
|
|
func Connect() *sqlx.DB {
|
|
db, err := sqlx.Open("mysql", "itman:X753951x@(xigmanas:3306)/stem")
|
|
checkError("open db", err)
|
|
dbx = db
|
|
return db
|
|
}
|
|
|
|
// возвращает список всех книг
|
|
// возможно использование фильтров в query, типа: ?deleted=deleted&selected=not selected
|
|
func ListAllBooks(options ...string) ([]Book, error) {
|
|
cmd := `
|
|
SELECT
|
|
id, author, seria, title,
|
|
deleted, selected
|
|
FROM
|
|
book
|
|
`
|
|
// блок условий
|
|
where := ""
|
|
if options != nil {
|
|
where = "WHERE 1=1"
|
|
for _, o := range options {
|
|
if o != "" {
|
|
where += fmt.Sprintf(" AND %s", o)
|
|
}
|
|
}
|
|
}
|
|
|
|
//fmt.Printf("where: %s\n", where)
|
|
var books []Book
|
|
err := dbx.Select(&books, cmd+where)
|
|
//checkError("ListBooks", err)
|
|
return books, err
|
|
}
|
|
|
|
// поскольку это отдельный пакет, то приходится дублировать
|
|
// ============================ разные утилиты ==========================
|
|
|
|
// Проверяет наличие ошибки
|
|
func checkError(src string, err error) {
|
|
if err != nil {
|
|
fmt.Printf("[db] (%s): %s\n", src, err)
|
|
os.Exit(1)
|
|
}
|
|
}
|