-
Notifications
You must be signed in to change notification settings - Fork 0
/
author_mysql.go
64 lines (43 loc) · 1.26 KB
/
author_mysql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package repository
import (
"database/sql"
"fmt"
"strconv"
book "github.com/aburtasov/books"
)
type AuthorMysql struct {
db *sql.DB
}
func NewAuthorMysql(db *sql.DB) *AuthorMysql {
return &AuthorMysql{db: db}
}
func (r *AuthorMysql) GetAuthor(bookTitle string) (book.Author, error) {
var id int
var author book.Author
query1 := fmt.Sprintf("SELECT author_id FROM %s WHERE title='%s'", booksTable, bookTitle)
if err := r.db.QueryRow(query1).Scan(&id); err != nil {
return book.Author{}, err
}
query2 := fmt.Sprintf("SELECT first_name,second_name FROM %s WHERE id='%d'", authorsTable, id)
if err := r.db.QueryRow(query2).Scan(&author.FirstName, &author.SecondName); err != nil {
return book.Author{}, err
}
return author, nil
}
func (r *AuthorMysql) AddAuthor(author book.Author) (book.Responce, error) {
var id int
tx, err := r.db.Begin()
if err != nil {
return book.Responce{}, err
}
query1 := fmt.Sprintf("INSERT INTO %s (first_name, second_name) VALUES ('%s','%s')", authorsTable, author.FirstName, author.SecondName)
tx.QueryRow(query1)
err = tx.QueryRow("SELECT LAST_INSERT_ID();").Scan(&id)
if err != nil {
tx.Rollback()
return book.Responce{}, err
}
tx.Commit()
strId := strconv.Itoa(id)
return book.Responce{Id: strId}, nil
}