-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
112 lines (91 loc) · 2.06 KB
/
driver.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
106
107
108
109
110
111
112
package nodb
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"strings"
"github.com/kr/pretty"
"github.com/snadrus/nodb/internal/base"
"github.com/snadrus/nodb/internal/sel"
"github.com/xwb1989/sqlparser"
)
type NoDBDriver struct{}
func (n NoDBDriver) Open(s string) (driver.Conn, error) {
if strings.ToLower(s) != "cache" {
return nil, errors.New("Unsupported")
}
ctx, cancel := context.WithCancel(context.Background())
return Conn{
Context: ctx,
Cancel: cancel,
}, nil
}
type Conn struct {
context.Context
Cancel context.CancelFunc
}
func (c Conn) Begin() (driver.Tx, error) {
return Tx{}, nil
}
type Tx struct{}
func (t Tx) Commit() error { return nil }
func (t Tx) Rollback() error { return nil }
func (c Conn) Close() error {
c.Cancel()
return nil
}
func (c Conn) Prepare(s string) (driver.Stmt, error) {
ctx, cancel := context.WithCancel(c.Context)
return Stmt{
Context: ctx,
Cancel: cancel,
S: s,
}, nil
}
type Stmt struct {
context.Context
Cancel context.CancelFunc
S string
}
func (s Stmt) Close() error {
s.Cancel()
return nil
}
func (s Stmt) NumInput() int {
return -1 // Default for We Don't Know
}
func (s Stmt) Exec(args []driver.Value) (driver.Result, error) {
return nil, errors.New("Exec not supported for Read-only system")
}
func (s Stmt) Query(args []driver.Value) (driver.Rows, error) {
if len(args) != 0 {
return nil, errors.New("Cannot take prepared statements yet, TODO")
}
tree, err := sqlparser.Parse(s.S)
if err != nil {
return nil, err
}
base.Debug(pretty.Sprint(tree))
switch tree.(type) {
case *sqlparser.Select:
return sel.DoAry(tree.(*sqlparser.Select), base.Obj(cache), s.Context)
default:
return nil, fmt.Errorf("Query type not supported")
}
}
// TODO add locking
var cache Obj
// Add a table ([]struct) or function to the database
func Add(key string, item interface{}) {
cache[key] = item
}
// Delete a user-added item from the database
func Delete(key string) {
delete(cache, key)
}
func init() {
cache = make(Obj)
sql.Register("nodb", &NoDBDriver{})
}