github.com/emcfarlane/larking@v0.0.0-20220605172417-1704b45ee6c3/examples/library/impl.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  	"fmt"
     7  	"strconv"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/emcfarlane/larking/examples/library/apipb"
    12  )
    13  
    14  func createTables(db *sql.DB) error {
    15  	_, err := db.Exec(`
    16  CREATE TABLE IF NOT EXISTS books (
    17  	id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    18  	shelf_id TEXT NOT NULL,
    19  	title TEXT NOT NULL,
    20  	author TEXT NOT NULL,
    21  	cover_image TEXT NOT NULL,
    22  	create_time TIMESTAMP NOT NULL,
    23  	update_time TIMESTAMP NOT NULL
    24  );`)
    25  	return err
    26  }
    27  
    28  func (s *Server) GetBook(ctx context.Context, req *apipb.GetBookRequest) (*apipb.Book, error) {
    29  	ids := strings.Split(req.Name, "/")
    30  	shelfID, bookID := ids[1], ids[3]
    31  	id, err := strconv.Atoi(bookID)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	var (
    37  		book = apipb.Book{Name: req.Name}
    38  	)
    39  	if err := s.db.QueryRowContext(ctx, `
    40  SELECT title, author, cover_image 
    41  FROM books WHERE shelf_id = ? AND id = ?
    42  `, shelfID, id).Scan(
    43  		&book.Title, &book.Author, &book.CoverImage,
    44  	); err != nil {
    45  		return nil, err
    46  	}
    47  	return &book, nil
    48  
    49  }
    50  func (s *Server) CreateBook(ctx context.Context, req *apipb.CreateBookRequest) (*apipb.Book, error) {
    51  	t := time.Now()
    52  
    53  	ids := strings.Split(req.Parent, "/")
    54  	shelfID := ids[1]
    55  
    56  	var id int
    57  	if err := s.db.QueryRowContext(ctx, `
    58  INSERT INTO
    59  	books(shelf_id, title, author, cover_image, create_time, update_time)
    60  VALUES (?,?,?,?,?,?)
    61  RETURNING id
    62  `, shelfID, req.Book.Title, req.Book.Author, req.Book.CoverImage, t, t,
    63  	).Scan(&id); err != nil {
    64  		return nil, err
    65  	}
    66  	req.Book.Name = fmt.Sprintf("%s/books/%d", req.Parent, id)
    67  	return req.Book, nil
    68  }