-
-
Notifications
You must be signed in to change notification settings - Fork 521
/
sqlite3.go
105 lines (91 loc) · 2.28 KB
/
sqlite3.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package sqlite3
import (
"context"
"database/sql"
_ "github.com/mattn/go-sqlite3" // sqlite3 driver
"github.com/tmc/langchaingo/tools/sqldatabase"
)
const EngineName = "sqlite3"
//nolint:gochecknoinits
func init() {
sqldatabase.RegisterEngine(EngineName, NewSQLite3)
}
var _ sqldatabase.Engine = SQLite3{}
// SQLite3 is a SQLite3 engine.
type SQLite3 struct {
db *sql.DB
}
// NewSQLite3 creates a new SQLite3 engine.
// The dsn is the data source name.(e.g. file:locked.sqlite?cache=shared).
func NewSQLite3(dsn string) (sqldatabase.Engine, error) { //nolint:ireturn
db, err := sql.Open(EngineName, dsn)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(1)
return &SQLite3{
db: db,
}, nil
}
func (m SQLite3) Dialect() string {
return EngineName
}
func (m SQLite3) Query(ctx context.Context, query string, args ...any) ([]string, [][]string, error) {
rows, err := m.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, nil, err
}
if err := rows.Err(); err != nil {
return nil, nil, err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return nil, nil, err
}
results := make([][]string, 0)
for rows.Next() {
row := make([]string, len(cols))
rowNullable := make([]sql.NullString, len(cols))
rowPtrs := make([]interface{}, len(cols))
for i := range row {
rowPtrs[i] = &rowNullable[i]
}
err = rows.Scan(rowPtrs...)
if err != nil {
return nil, nil, err
}
for i := range rowNullable {
row[i] = rowNullable[i].String
}
results = append(results, row)
}
return cols, results, nil
}
func (m SQLite3) TableNames(ctx context.Context) ([]string, error) {
_, result, err := m.Query(ctx, "SELECT name FROM sqlite_master WHERE type='table';")
if err != nil {
return nil, err
}
ret := make([]string, 0, len(result))
for _, row := range result {
ret = append(ret, row[0])
}
return ret, nil
}
func (m SQLite3) TableInfo(ctx context.Context, table string) (string, error) {
_, result, err := m.Query(ctx, "SELECT sql FROM sqlite_master WHERE type='table' AND name=?;", table)
if err != nil {
return "", err
}
if len(result) == 0 {
return "", sqldatabase.ErrTableNotFound
}
if len(result[0]) < 1 {
return "", sqldatabase.ErrInvalidResult
}
return result[0][0], nil
}
func (m SQLite3) Close() error {
return m.db.Close()
}