Skip to content

Commit

Permalink
Merge pull request #105 from syumai/support-sql-open-on-d1
Browse files Browse the repository at this point in the history
support sql.Open for D1
  • Loading branch information
syumai authored Apr 16, 2024
2 parents 01783f2 + d37e160 commit 482b281
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 31 deletions.
6 changes: 3 additions & 3 deletions _examples/d1-blog-server/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ deploy:
init-db:
wrangler d1 execute d1-blog-server --file=./schema.sql

.PHONY: init-db-preview
init-db-preview:
wrangler d1 execute d1-blog-server-preview --file=./schema.sql
.PHONY: init-db-local
init-db-local:
wrangler d1 execute d1-blog-server --file=./schema.sql --local
6 changes: 3 additions & 3 deletions _examples/d1-blog-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ This project requires these tools to be installed globally.

```
# development
make init-db-preview # initialize preview DB (remove all rows)
make dev # run dev server
make build # build Go Wasm binary
make init-db-local # initialize local DB (remove all rows)
make dev # run dev server
make build # build Go Wasm binary
# production
make init-db # initialize production DB (remove all rows)
Expand Down
34 changes: 14 additions & 20 deletions _examples/d1-blog-server/app/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,27 @@ import (
"time"

"github.com/syumai/workers/_examples/d1-blog-server/app/model"
"github.com/syumai/workers/cloudflare/d1"
_ "github.com/syumai/workers/cloudflare/d1" // register driver
)

type articleHandler struct{}
type articleHandler struct {
db *sql.DB
}

var _ http.Handler = (*articleHandler)(nil)

func NewArticleHandler() http.Handler {
return &articleHandler{}
func NewArticleHandler(db *sql.DB) http.Handler {
return &articleHandler{
db: db,
}
}

func (h *articleHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// initialize DB.
// D1 connector requires request's context to initialize DB.
c, err := d1.OpenConnector("BlogDB")
if err != nil {
h.handleErr(w, http.StatusInternalServerError, fmt.Sprintf("failed to initialize DB: %v", err))
}
// use sql.OpenDB instead of sql.Open.
db := sql.OpenDB(c)

switch req.Method {
case http.MethodGet:
h.listArticles(w, req, db)
h.listArticles(w, req)
return
case http.MethodPost:
h.createArticle(w, req, db)
h.createArticle(w, req)
return
}
w.WriteHeader(http.StatusNotFound)
Expand All @@ -51,7 +44,7 @@ func (h *articleHandler) handleErr(w http.ResponseWriter, status int, msg string
w.Write([]byte(msg))
}

func (h *articleHandler) createArticle(w http.ResponseWriter, req *http.Request, db *sql.DB) {
func (h *articleHandler) createArticle(w http.ResponseWriter, req *http.Request) {
var createArticleReq model.CreateArticleRequest
if err := json.NewDecoder(req.Body).Decode(&createArticleReq); err != nil {
h.handleErr(w, http.StatusBadRequest,
Expand All @@ -66,7 +59,7 @@ func (h *articleHandler) createArticle(w http.ResponseWriter, req *http.Request,
CreatedAt: uint64(now),
}

result, err := db.Exec(`
result, err := h.db.Exec(`
INSERT INTO articles (title, body, created_at)
VALUES (?, ?, ?)
`, article.Title, article.Body, article.CreatedAt)
Expand Down Expand Up @@ -95,12 +88,13 @@ VALUES (?, ?, ?)
}
}

func (h *articleHandler) listArticles(w http.ResponseWriter, req *http.Request, db *sql.DB) {
rows, err := db.Query(`
func (h *articleHandler) listArticles(w http.ResponseWriter, req *http.Request) {
rows, err := h.db.Query(`
SELECT id, title, body, created_at FROM articles
ORDER BY created_at DESC;
`)
if err != nil {
fmt.Printf("err: %v\n", err)
h.handleErr(w, http.StatusInternalServerError,
"failed to load article")
return
Expand Down
9 changes: 8 additions & 1 deletion _examples/d1-blog-server/main.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
package main

import (
"database/sql"
"log"
"net/http"

"github.com/syumai/workers"
"github.com/syumai/workers/_examples/d1-blog-server/app"
_ "github.com/syumai/workers/cloudflare/d1" // register driver
)

func main() {
http.Handle("/articles", app.NewArticleHandler())
db, err := sql.Open("d1", "BlogDB")
if err != nil {
log.Fatalf("error opening DB: %s", err.Error())
}
http.Handle("/articles", app.NewArticleHandler(db))
workers.Serve(nil) // use http.DefaultServeMux
}
2 changes: 1 addition & 1 deletion _examples/d1-blog-server/wrangler.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "d1-blog-server"
main = "./build/worker.mjs"
compatibility_date = "2023-01-09"
compatibility_date = "2024-04-15"

[build]
command = "make build"
Expand Down
10 changes: 7 additions & 3 deletions cloudflare/d1/driver.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package d1

import (
"context"
"database/sql"
"database/sql/driver"
"errors"
)

func init() {
Expand All @@ -16,6 +16,10 @@ var (
_ driver.Driver = (*Driver)(nil)
)

func (d *Driver) Open(string) (driver.Conn, error) {
return nil, errors.New("d1: Open is not supported. use d1.OpenConnector and sql.OpenDB instead")
func (d *Driver) Open(name string) (driver.Conn, error) {
connector, err := OpenConnector(name)
if err != nil {
return nil, err
}
return connector.Connect(context.Background())
}

0 comments on commit 482b281

Please sign in to comment.