73 lines
1.3 KiB
Go
73 lines
1.3 KiB
Go
package mysqlite
|
|
|
|
import (
|
|
"fmt"
|
|
"zombiezen.com/go/sqlite"
|
|
)
|
|
|
|
type Query struct {
|
|
stmt *sqlite.Stmt
|
|
err error
|
|
}
|
|
|
|
func (d *Db) Query(query string) *Query {
|
|
stmt, remaining, err := d.Db.PrepareTransient(query)
|
|
if err != nil {
|
|
return &Query{err: err}
|
|
}
|
|
if remaining != 0 {
|
|
return &Query{err: fmt.Errorf("remaining bytes: %s", remaining)}
|
|
}
|
|
return &Query{stmt: stmt}
|
|
}
|
|
|
|
//func (q *Query) Args(args ...any) *Query {
|
|
// return q
|
|
//}
|
|
|
|
func (q *Query) Exec() error {
|
|
if q.stmt != nil {
|
|
defer q.stmt.Finalize()
|
|
}
|
|
if q.err != nil {
|
|
return q.err
|
|
}
|
|
rowReturned, err := q.stmt.Step()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if rowReturned {
|
|
return fmt.Errorf("row returned unexpectedly")
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (q *Query) ScanSingle(results ...any) error {
|
|
if q.stmt != nil {
|
|
defer q.stmt.Finalize()
|
|
}
|
|
if q.err != nil {
|
|
return q.err
|
|
}
|
|
rowReturned, err := q.stmt.Step()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !rowReturned {
|
|
return fmt.Errorf("did not return any rows")
|
|
}
|
|
|
|
for i, arg := range results {
|
|
if asString, ok := arg.(*string); ok {
|
|
*asString = q.stmt.ColumnText(i)
|
|
} else if asInt, ok := arg.(*int); ok {
|
|
*asInt = q.stmt.ColumnInt(i)
|
|
} else if asBool, ok := arg.(*bool); ok {
|
|
*asBool = q.stmt.ColumnBool(i)
|
|
} else {
|
|
return fmt.Errorf("unsupported column type at index %d", i)
|
|
}
|
|
}
|
|
return nil
|
|
}
|