package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	// section: main
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		log.Fatal(err)
	}

	// Load some sample data
	if err := load(db); err != nil {
		log.Fatal(err)
	}

	// Get all users
	users, err := GetUsers(db)
	if err != nil {
		log.Fatal(db)
	}
	for _, u := range users {
		fmt.Printf("%+v\n", u)
	}
	// section: main
}

func load(db *sql.DB) error {
	_, err := db.Exec(`
		create table users(id int, name text);
		insert into users(id, name) values (1, 'Wilma'), (2, 'Fred'), (3, 'Betty'), (4, 'Barney');
	`)
	return err
}

// section: users
type User struct {
	ID   int
	Name string
}

func GetUsers(db *sql.DB) ([]User, error) {
	rows, err := db.Query("select * from users;")
	if err != nil {
		return nil, err
	}

	users := []User{}

	for rows.Next() {
		var u User
		if err := rows.Scan(&u.ID, &u.Name); err != nil {
			return nil, err
		}
		users = append(users, u)
	}
	return users, nil
}

// section: users

/*
// section: output
{ID:1 Name:Wilma}
{ID:2 Name:Fred}
{ID:3 Name:Betty}
{ID:4 Name:Barney}
// section: output


*/
