package stemdb import ( "fmt" "os" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) // The above type represents a book with properties such as ID, author, series, title, and flags for // deletion and selection. // @property {int} ID - The ID property is an integer that represents the unique identifier of a book. // @property {string} Author - The author of the book. // @property {string} Seria - The "Seria" property in the Book struct represents the series to which // the book belongs. It is a string that holds the name or identifier of the series. // @property {string} Title - The title of the book. // @property {bool} Deleted - The "Deleted" property is a boolean value that indicates whether the book // has been marked as deleted or not. If the value is true, it means the book has been deleted. If the // value is false, it means the book is not deleted. // @property {bool} Selected - The "Selected" property is a boolean value that indicates whether the // book is currently selected or not. It can be used to keep track of which books are currently being // interacted with or displayed in a user interface. type Book struct { ID int Author string Seria string Title string Deleted bool Selected bool } var dbx *sqlx.DB // The Connect function opens a connection to a MySQL database and returns the connection object. 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 // The function `ListAllBooks` retrieves a list of books from a database based on optional conditions. 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 } // поскольку это отдельный пакет, то приходится дублировать // ============================ разные утилиты ========================== // Проверяет наличие ошибки // The function "checkError" is used to print and exit the program if an error occurs. func checkError(src string, err error) { if err != nil { fmt.Printf("[db] (%s): %s\n", src, err) os.Exit(1) } }