Skip to content

Commit

Permalink
Add TinyGo SQLite to the API guide
Browse files Browse the repository at this point in the history
Signed-off-by: Adam Reese <adam@reese.io>
  • Loading branch information
adamreese committed Sep 12, 2023
1 parent 6b97a17 commit 529f667
Showing 1 changed file with 55 additions and 1 deletion.
56 changes: 55 additions & 1 deletion content/spin/sqlite-api-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,61 @@ def handle_request(request):

{{ startTab "TinyGo"}}

The Go SDK doesn't currently surface the SQLite API.
The Go SDK is implemented as a driver for the standard library's [database/sql](https://pkg.go.dev/database/sql) interface.

```go
package main

import (
"encoding/json"
"net/http"

spinhttp "github.com/fermyon/spin/sdk/go/http"
"github.com/fermyon/spin/sdk/go/sqlite"
)

type Todo struct {
ID string
Description string
Due string
}

func init() {
spinhttp.Handle(func(w http.ResponseWriter, r *http.Request) {
db := sqlite.Open("default")
defer db.Close()

_, err := db.Exec("INSERT INTO todos (description, due) VALUES (?, ?)", "Try out Spin SQLite", "Friday")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

rows, err := db.Query("SELECT id, description, due FROM todos")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

var todos []*Todo
for rows.Next() {
var todo Todo
if err := rows.Scan(&todo.ID, &todo.Description, &todo.Due); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
todos = append(todos, &todo)
}
json.NewEncoder(w).Encode(todos)
})
}

func main() {}
```

**General Notes**

A convince function `sqlite.Open()` is provided to create a database connection. Because the `http.Handle` function is inside the `init()` function the Spin SQLite driver cannot be initialized the same way as other drivers using [sql.Open](https://pkg.go.dev/database/sql#Open).

{{ blockEnd }}

Expand Down

0 comments on commit 529f667

Please # to comment.