d1

package
v0.0.0-...-1d4b78d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2025 License: Apache-2.0 Imports: 13 Imported by: 0

README

Cloudflare D1 Driver

It is an unofficail sql.Driver, and gorm.Dialector for Cloudflare D1 datebase.

The original author doesn't update anymore, so I copied it and modified it.

NOTE

current support date types list.

  • ✅ Full support.
  • ⚠️ Part support.
  • ❌ Not support.
Go type D1 JSON Support Notes
bool String
int,int32,int64 Number ⚠️ auto convert to int64 if math.Trunc euqal.
float32,float64 Number
string String
[]byte String auto convert between unicode escape and bytes
time.Time String ⚠️ if column has prefix "time_".

Useage

example for sql.

package main

import (
	"database/sql"
	"fmt"

	d1 "github.com/kofj/gorm-driver-d1"
	_ "github.com/kofj/gorm-driver-d1/stdlib"
	log "github.com/sirupsen/logrus"
)

var (
	accountId  = "xxx-xxx-xx"
	apiToken   = "adcdef_xxx"
	datebaseId = "yyy-yyy-yyy"
)

func main() {
	db, err := sql.Open(d1.DriverName,
		fmt.Sprintf("d1://%s:%s@%s", accountId, apiToken, datebaseId),
	)
	if err != nil {
		log.WithError(err).Fatal("open database failed")
		return
	}
	rows, err := db.Query("PRAGMA table_info(users)")
	if err != nil {
		log.WithError(err).Error("query failed")
		return
	}
	for rows.Next() {
		var cid int
		var name, fieldType string
		err = rows.Scan(&cid, &name, &fieldType)
		if err != nil {
			log.WithError(err).Error("scan failed")
			return
		}
		log.WithField("cid", cid).WithField("name", name).WithField("type", fieldType).Info("scan result")
	}
}
db, err := gorm.Open(gormd1.Open(d.Setting.ToStr()), &gorm.Config{
    Logger: d.logger,
})
if err != nil {
    return errors.Join(err, ErrConnectDbFailed)
}

Documentation

Index

Constants

View Source
const (
	API_TOKEN apiOps
)
View Source
const DriverName = "d1"

Variables

View Source
var (
	ErrInvalidAPI = errors.New("invalid api")
	ErrClosed     = errors.New("d1: connection is closed")
	ErrEmptyDSN   = errors.New("dsn is empty")
	ErrShortDSN   = errors.New("dsn specified is impossibly short")
	ErrNotD1      = errors.New("dsn does not start with 'd1'")
	ErrInvalidDB  = errors.New("invalid database id")
)

Functions

func BytesToUnicodeEscapes

func BytesToUnicodeEscapes(b []byte) string

BytesToUnicodeEscapes 将 []byte 转换为 Unicode 转义序列字符串

func IsFullyUnicodeEscaped

func IsFullyUnicodeEscaped(s string) bool

func Trace

func Trace(pattern string, args ...interface{})

func TraceOff

func TraceOff()

TraceOff turns off tracing output. Once you call TraceOff(), no further info is sent to the io.Writer, unless it is TraceOn'd again.

func TraceOn

func TraceOn(w io.Writer)

TraceOn turns on tracing output to the io.Writer of your choice.

Trace output is very detailed and verbose, as you might expect.

Normally, you should run with tracing off, as it makes absolutely no concession to performance and is intended for debugging/dev use.

func UnescapeUnicode

func UnescapeUnicode(s string) ([]byte, error)

UnescapeUnicode 将包含Unicode转义序列的字符串转换为对应的[]byte。

Types

type Connection

type Connection struct {
	ID string //   generated in init()
	// contains filtered or unexported fields
}

func Open

func Open(dsn string) (conn *Connection, err error)

Open opens a new connection to the database. The dsn looks like:

d1://apiToken:accountId@databaseId?timeout=10

func (*Connection) Close

func (conn *Connection) Close()

Close will mark the connection as closed. It is safe to be called multiple times.

func (*Connection) VerifyApiTokenContext

func (c *Connection) VerifyApiTokenContext(ctx context.Context) (err error)

func (*Connection) WriteParameterizedContext

func (c *Connection) WriteParameterizedContext(ctx context.Context, stmt ParameterizedStatement) (resp D1Resp, err error)

type D1Resp

type D1Resp struct {
	Errors     []D1RespError        `json:"errors"`
	Messages   []D1RespMessage      `json:"messages"`
	Result     []*D1RespQueryResult `json:"result"`
	ResultInfo *D1RespResultInfo    `json:"result_info"`
	Success    bool                 `json:"success"`
	AuditlogId string               `json:"-"`
}

type D1RespError

type D1RespError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type D1RespMessage

type D1RespMessage struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Type    interface{} `json:"type"`
}

type D1RespQueryResult

type D1RespQueryResult struct {
	Meta    D1RespQueryResultMeta `json:"meta"`
	Results D1RespQueryResults    `json:"results"`
}

type D1RespQueryResultMeta

type D1RespQueryResultMeta struct {
	ChangedDb   bool    `json:"changed_db"`
	Changes     int64   `json:"changes"`
	Duration    float64 `json:"duration"`
	LastRowID   int64   `json:"last_row_id"`
	RowsRead    int64   `json:"rows_read"`
	RowsWritten int64   `json:"rows_written"`
	ServedBy    string  `json:"served_by"`
	SizeAfter   int64   `json:"size_after"`
}

type D1RespQueryResults

type D1RespQueryResults struct {
	Columns []string        `json:"columns"`
	Rows    [][]interface{} `json:"rows"`
}

type D1RespResultInfo

type D1RespResultInfo struct {
	Count      int `json:"count"`
	Page       int `json:"page"`
	PerPage    int `json:"per_page"`
	TotalCount int `json:"total_count"`
}

type ParameterizedStatement

type ParameterizedStatement struct {
	SQL    string        `json:"sql"`
	Params []interface{} `json:"params"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL