Skip to content

Commit

Permalink
complete implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
amitsaha committed Jun 20, 2023
1 parent 54149a7 commit 7988c6e
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 25 deletions.
25 changes: 20 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
# WORK IN PROGRESS - go-sqlite-demo
# Project to demo SQLite + Go

A demo project to demo SQLite + Go
This repository contains an illustration of how to interact with a SQLite
database using `database/sql` and `https://pkg.go.dev/modernc.org/sqlite`.

- database/sql
- https://pkg.go.dev/modernc.org/sqlite
The example is intentionally chosen to match that of the official Go Project
tutorial, [Accessing a relational database](https://go.dev/doc/tutorial/database-access)
which uses MySQL as the database server.

## Why SQLite?

https://go.dev/doc/tutorial/database-access
SQLite is perfect for [many use cases](https://www.sqlite.org/whentouse.html).

My choice of using SQLite for this demo is that it is perfect to illustrate how
we can persist data to a SQL database from Go.

## Why modernc.org/sqlite?

It's CGO free which means, we don't have to worry about installation woes
(potential) on different operating systems and architecture

## Explanations of the code

See [this blog post](TBD).
51 changes: 37 additions & 14 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@ func initDatabase(dbPath string) error {
}
_, err = db.ExecContext(
context.Background(),
`CREATE TABLE IF NOT EXISTS album (id INTEGER, title TEXT NOT NULL, artist TEXT NOT NULL, price REAL NOT NULL)`,
`CREATE TABLE IF NOT EXISTS album (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
artist TEXT NOT NULL,
price REAL NOT NULL
)`,
)
if err != nil {
return err
Expand All @@ -42,31 +47,49 @@ func addAlbum(a *Album) (int64, error) {
context.Background(),
`INSERT INTO album (title, artist, price) VALUES (?,?,?);`, a.Title, a.Artist, a.Price,
)
rows, err := result.RowsAffected()
id, err := result.LastInsertId()
if err != nil {
return 0, err
}
return rows, nil
return id, nil
}

func albumsByArtist(artist string) ([]*AlbumDbRow, error) {
result, err := db.QueryContext(
func albumsByArtist(artist string) ([]AlbumDbRow, error) {

var albums []AlbumDbRow
rows, err := db.QueryContext(
context.Background(),
`INSERT INTO album (title, artist, price) VALUES (?,?,?);`, a.Title, a.Artist, a.Price,
`SELECT * FROM album WHERE artist=?;`, artist,
)
rows, err := result.RowsAffected()
if err != nil {
return 0, err
return nil, err
}
return rows, nil

return nil, nil
defer rows.Close()
for rows.Next() {
var album AlbumDbRow
if err := rows.Scan(
&album.ID, &album.Title, &album.Artist, &album.Price,
); err != nil {
return nil, err
}
albums = append(albums, album)
}
return albums, err
}

func albumByID(id int) (*AlbumDbRow, error) {
return nil, nil
func albumByID(id int) (AlbumDbRow, error) {
var album AlbumDbRow
row := db.QueryRowContext(
context.Background(),
`SELECT * FROM album WHERE id=?`, id,
)
err := row.Scan(&album.ID, &album.Title, &album.Artist, &album.Price)
if err != nil {
return album, err
}
return album, nil
}

func main() {
fmt.Println("HELLO")
fmt.Println("HELLO WORLD. Please run go test")
}
23 changes: 17 additions & 6 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ func TestInsertAndQueryData(t *testing.T) {
{"Blue Train", "John Coltrane", 56.99},
}

for _, album := range testData {
rowCnt, err := addAlbum(&album)
if rowCnt != 1 {
t.Fatalf("expected inserted row count: 1, got: %d", rowCnt)
for idx, album := range testData {
lastInsertId, err := addAlbum(&album)
if lastInsertId != int64(idx+1) {
t.Fatalf("expected inserted ID: %d, got: %d", idx+1, lastInsertId)
}
if err != nil {
t.Fatalf("error inserting row: %v", err)
Expand All @@ -40,8 +40,19 @@ func TestInsertAndQueryData(t *testing.T) {
t.Fatalf("error querying data: %v", err)
}

if !reflect.DeepEqual(gotAlbums, expectedAlbums) {
t.Fatalf("expected: %#v, got: %#v", expectedAlbums, gotAlbums)
if len(gotAlbums) != len(expectedAlbums) {
t.Fatalf("expected to get: %d albums as result, got: %d", len(expectedAlbums), len(gotAlbums))
}

gotAlbumMap := make(map[int]AlbumDbRow)
for _, a := range gotAlbums {
gotAlbumMap[a.ID] = a
}

for _, a := range expectedAlbums {
if _, ok := gotAlbumMap[a.ID]; !ok {
t.Error("expected to get album with ID:", a.ID)
}
}

expectedAlbum := AlbumDbRow{
Expand Down

0 comments on commit 7988c6e

Please sign in to comment.