sqlite3_vtable_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file.
  5. // +build vtable
  6. package sqlite3
  7. import (
  8. "database/sql"
  9. "errors"
  10. "fmt"
  11. "os"
  12. "reflect"
  13. "strings"
  14. "testing"
  15. )
  16. type testModule struct {
  17. t *testing.T
  18. intarray []int
  19. }
  20. type testVTab struct {
  21. intarray []int
  22. }
  23. type testVTabCursor struct {
  24. vTab *testVTab
  25. index int
  26. }
  27. func (m testModule) Create(c *SQLiteConn, args []string) (VTab, error) {
  28. if len(args) != 6 {
  29. m.t.Fatal("six arguments expected")
  30. }
  31. if args[0] != "test" {
  32. m.t.Fatal("module name")
  33. }
  34. if args[1] != "main" {
  35. m.t.Fatal("db name")
  36. }
  37. if args[2] != "vtab" {
  38. m.t.Fatal("table name")
  39. }
  40. if args[3] != "'1'" {
  41. m.t.Fatal("first arg")
  42. }
  43. if args[4] != "2" {
  44. m.t.Fatal("second arg")
  45. }
  46. if args[5] != "three" {
  47. m.t.Fatal("third argsecond arg")
  48. }
  49. err := c.DeclareVTab("CREATE TABLE x(test TEXT)")
  50. if err != nil {
  51. return nil, err
  52. }
  53. return &testVTab{m.intarray}, nil
  54. }
  55. func (m testModule) Connect(c *SQLiteConn, args []string) (VTab, error) {
  56. return m.Create(c, args)
  57. }
  58. func (m testModule) DestroyModule() {}
  59. func (v *testVTab) BestIndex(cst []InfoConstraint, ob []InfoOrderBy) (*IndexResult, error) {
  60. used := make([]bool, 0, len(cst))
  61. for range cst {
  62. used = append(used, false)
  63. }
  64. return &IndexResult{
  65. Used: used,
  66. IdxNum: 0,
  67. IdxStr: "test-index",
  68. AlreadyOrdered: true,
  69. EstimatedCost: 100,
  70. EstimatedRows: 200,
  71. }, nil
  72. }
  73. func (v *testVTab) Disconnect() error {
  74. return nil
  75. }
  76. func (v *testVTab) Destroy() error {
  77. return nil
  78. }
  79. func (v *testVTab) Open() (VTabCursor, error) {
  80. return &testVTabCursor{v, 0}, nil
  81. }
  82. func (vc *testVTabCursor) Close() error {
  83. return nil
  84. }
  85. func (vc *testVTabCursor) Filter(idxNum int, idxStr string, vals []interface{}) error {
  86. vc.index = 0
  87. return nil
  88. }
  89. func (vc *testVTabCursor) Next() error {
  90. vc.index++
  91. return nil
  92. }
  93. func (vc *testVTabCursor) EOF() bool {
  94. return vc.index >= len(vc.vTab.intarray)
  95. }
  96. func (vc *testVTabCursor) Column(c *SQLiteContext, col int) error {
  97. if col != 0 {
  98. return fmt.Errorf("column index out of bounds: %d", col)
  99. }
  100. c.ResultInt(vc.vTab.intarray[vc.index])
  101. return nil
  102. }
  103. func (vc *testVTabCursor) Rowid() (int64, error) {
  104. return int64(vc.index), nil
  105. }
  106. func TestCreateModule(t *testing.T) {
  107. tempFilename := TempFilename(t)
  108. defer os.Remove(tempFilename)
  109. intarray := []int{1, 2, 3}
  110. sql.Register("sqlite3_TestCreateModule", &SQLiteDriver{
  111. ConnectHook: func(conn *SQLiteConn) error {
  112. return conn.CreateModule("test", testModule{t, intarray})
  113. },
  114. })
  115. db, err := sql.Open("sqlite3_TestCreateModule", tempFilename)
  116. if err != nil {
  117. t.Fatalf("could not open db: %v", err)
  118. }
  119. _, err = db.Exec("CREATE VIRTUAL TABLE vtab USING test('1', 2, three)")
  120. if err != nil {
  121. t.Fatalf("could not create vtable: %v", err)
  122. }
  123. var i, value int
  124. rows, err := db.Query("SELECT rowid, * FROM vtab WHERE test = '3'")
  125. if err != nil {
  126. t.Fatalf("couldn't select from virtual table: %v", err)
  127. }
  128. for rows.Next() {
  129. rows.Scan(&i, &value)
  130. if intarray[i] != value {
  131. t.Fatalf("want %v but %v", intarray[i], value)
  132. }
  133. }
  134. _, err = db.Exec("DROP TABLE vtab")
  135. if err != nil {
  136. t.Fatalf("couldn't drop virtual table: %v", err)
  137. }
  138. }
  139. func TestVUpdate(t *testing.T) {
  140. tempFilename := TempFilename(t)
  141. defer os.Remove(tempFilename)
  142. // create module
  143. updateMod := &vtabUpdateModule{t, make(map[string]*vtabUpdateTable)}
  144. // register module
  145. sql.Register("sqlite3_TestVUpdate", &SQLiteDriver{
  146. ConnectHook: func(conn *SQLiteConn) error {
  147. return conn.CreateModule("updatetest", updateMod)
  148. },
  149. })
  150. // connect
  151. db, err := sql.Open("sqlite3_TestVUpdate", tempFilename)
  152. if err != nil {
  153. t.Fatalf("could not open db: %v", err)
  154. }
  155. // create test table
  156. _, err = db.Exec(`CREATE VIRTUAL TABLE vt USING updatetest(f1 integer, f2 text, f3 text)`)
  157. if err != nil {
  158. t.Fatalf("could not create updatetest vtable vt, got: %v", err)
  159. }
  160. // check that table is defined properly
  161. if len(updateMod.tables) != 1 {
  162. t.Fatalf("expected exactly 1 table to exist, got: %d", len(updateMod.tables))
  163. }
  164. if _, ok := updateMod.tables["vt"]; !ok {
  165. t.Fatalf("expected table `vt` to exist in tables")
  166. }
  167. // check nothing in updatetest
  168. rows, err := db.Query(`select * from vt`)
  169. if err != nil {
  170. t.Fatalf("could not query vt, got: %v", err)
  171. }
  172. i, err := getRowCount(rows)
  173. if err != nil {
  174. t.Fatalf("expected no error, got: %v", err)
  175. }
  176. if i != 0 {
  177. t.Fatalf("expected no rows in vt, got: %d", i)
  178. }
  179. _, err = db.Exec(`delete from vt where f1 = 'yes'`)
  180. if err != nil {
  181. t.Fatalf("expected error on delete, got nil")
  182. }
  183. // test bad column name
  184. _, err = db.Exec(`insert into vt (f4) values('a')`)
  185. if err == nil {
  186. t.Fatalf("expected error on insert, got nil")
  187. }
  188. // insert to vt
  189. res, err := db.Exec(`insert into vt (f1, f2, f3) values (115, 'b', 'c'), (116, 'd', 'e')`)
  190. if err != nil {
  191. t.Fatalf("expected no error on insert, got: %v", err)
  192. }
  193. n, err := res.RowsAffected()
  194. if err != nil {
  195. t.Fatalf("expected no error, got: %v", err)
  196. }
  197. if n != 2 {
  198. t.Fatalf("expected 1 row affected, got: %d", n)
  199. }
  200. // check vt table
  201. vt := updateMod.tables["vt"]
  202. if len(vt.data) != 2 {
  203. t.Fatalf("expected table vt to have exactly 2 rows, got: %d", len(vt.data))
  204. }
  205. if !reflect.DeepEqual(vt.data[0], []interface{}{int64(115), "b", "c"}) {
  206. t.Fatalf("expected table vt entry 0 to be [115 b c], instead: %v", vt.data[0])
  207. }
  208. if !reflect.DeepEqual(vt.data[1], []interface{}{int64(116), "d", "e"}) {
  209. t.Fatalf("expected table vt entry 1 to be [116 d e], instead: %v", vt.data[1])
  210. }
  211. // query vt
  212. var f1 int
  213. var f2, f3 string
  214. err = db.QueryRow(`select * from vt where f1 = 115`).Scan(&f1, &f2, &f3)
  215. if err != nil {
  216. t.Fatalf("expected no error on vt query, got: %v", err)
  217. }
  218. // check column values
  219. if f1 != 115 || f2 != "b" || f3 != "c" {
  220. t.Errorf("expected f1==115, f2==b, f3==c, got: %d, %q, %q", f1, f2, f3)
  221. }
  222. // update vt
  223. res, err = db.Exec(`update vt set f1=117, f2='f' where f3='e'`)
  224. if err != nil {
  225. t.Fatalf("expected no error, got: %v", err)
  226. }
  227. n, err = res.RowsAffected()
  228. if err != nil {
  229. t.Fatalf("expected no error, got: %v", err)
  230. }
  231. if n != 1 {
  232. t.Fatalf("expected exactly one row updated, got: %d", n)
  233. }
  234. // check vt table
  235. if len(vt.data) != 2 {
  236. t.Fatalf("expected table vt to have exactly 2 rows, got: %d", len(vt.data))
  237. }
  238. if !reflect.DeepEqual(vt.data[0], []interface{}{int64(115), "b", "c"}) {
  239. t.Fatalf("expected table vt entry 0 to be [115 b c], instead: %v", vt.data[0])
  240. }
  241. if !reflect.DeepEqual(vt.data[1], []interface{}{int64(117), "f", "e"}) {
  242. t.Fatalf("expected table vt entry 1 to be [117 f e], instead: %v", vt.data[1])
  243. }
  244. // delete from vt
  245. res, err = db.Exec(`delete from vt where f1 = 117`)
  246. if err != nil {
  247. t.Fatalf("expected no error, got: %v", err)
  248. }
  249. n, err = res.RowsAffected()
  250. if err != nil {
  251. t.Fatalf("expected no error, got: %v", err)
  252. }
  253. if n != 1 {
  254. t.Fatalf("expected exactly one row deleted, got: %d", n)
  255. }
  256. // check vt table
  257. if len(vt.data) != 1 {
  258. t.Fatalf("expected table vt to have exactly 1 row, got: %d", len(vt.data))
  259. }
  260. if !reflect.DeepEqual(vt.data[0], []interface{}{int64(115), "b", "c"}) {
  261. t.Fatalf("expected table vt entry 0 to be [115 b c], instead: %v", vt.data[0])
  262. }
  263. // check updatetest has 1 result
  264. rows, err = db.Query(`select * from vt`)
  265. if err != nil {
  266. t.Fatalf("could not query vt, got: %v", err)
  267. }
  268. i, err = getRowCount(rows)
  269. if err != nil {
  270. t.Fatalf("expected no error, got: %v", err)
  271. }
  272. if i != 1 {
  273. t.Fatalf("expected 1 row in vt, got: %d", i)
  274. }
  275. }
  276. func getRowCount(rows *sql.Rows) (int, error) {
  277. var i int
  278. for rows.Next() {
  279. i++
  280. }
  281. return i, nil
  282. }
  283. type vtabUpdateModule struct {
  284. t *testing.T
  285. tables map[string]*vtabUpdateTable
  286. }
  287. func (m *vtabUpdateModule) Create(c *SQLiteConn, args []string) (VTab, error) {
  288. if len(args) < 2 {
  289. return nil, errors.New("must declare at least one column")
  290. }
  291. // get database name, table name, and column declarations ...
  292. dbname, tname, decls := args[1], args[2], args[3:]
  293. // extract column names + types from parameters declarations
  294. cols, typs := make([]string, len(decls)), make([]string, len(decls))
  295. for i := 0; i < len(decls); i++ {
  296. n, typ := decls[i], ""
  297. if j := strings.IndexAny(n, " \t\n"); j != -1 {
  298. typ, n = strings.TrimSpace(n[j+1:]), n[:j]
  299. }
  300. cols[i], typs[i] = n, typ
  301. }
  302. // declare table
  303. err := c.DeclareVTab(fmt.Sprintf(`CREATE TABLE "%s"."%s" (%s)`, dbname, tname, strings.Join(decls, ",")))
  304. if err != nil {
  305. return nil, err
  306. }
  307. // create table
  308. vtab := &vtabUpdateTable{m.t, dbname, tname, cols, typs, make([][]interface{}, 0)}
  309. m.tables[tname] = vtab
  310. return vtab, nil
  311. }
  312. func (m *vtabUpdateModule) Connect(c *SQLiteConn, args []string) (VTab, error) {
  313. return m.Create(c, args)
  314. }
  315. func (m *vtabUpdateModule) DestroyModule() {}
  316. type vtabUpdateTable struct {
  317. t *testing.T
  318. db string
  319. name string
  320. cols []string
  321. typs []string
  322. data [][]interface{}
  323. }
  324. func (t *vtabUpdateTable) Open() (VTabCursor, error) {
  325. return &vtabUpdateCursor{t, 0}, nil
  326. }
  327. func (t *vtabUpdateTable) BestIndex(cst []InfoConstraint, ob []InfoOrderBy) (*IndexResult, error) {
  328. return &IndexResult{Used: make([]bool, len(cst))}, nil
  329. }
  330. func (t *vtabUpdateTable) Disconnect() error {
  331. return nil
  332. }
  333. func (t *vtabUpdateTable) Destroy() error {
  334. return nil
  335. }
  336. func (t *vtabUpdateTable) Insert(id interface{}, vals []interface{}) (int64, error) {
  337. var i int64
  338. if id == nil {
  339. i, t.data = int64(len(t.data)), append(t.data, vals)
  340. return i, nil
  341. }
  342. var ok bool
  343. i, ok = id.(int64)
  344. if !ok {
  345. return 0, fmt.Errorf("id is invalid type: %T", id)
  346. }
  347. t.data[i] = vals
  348. return i, nil
  349. }
  350. func (t *vtabUpdateTable) Update(id interface{}, vals []interface{}) error {
  351. i, ok := id.(int64)
  352. if !ok {
  353. return fmt.Errorf("id is invalid type: %T", id)
  354. }
  355. if int(i) >= len(t.data) || i < 0 {
  356. return fmt.Errorf("invalid row id %d", i)
  357. }
  358. t.data[int(i)] = vals
  359. return nil
  360. }
  361. func (t *vtabUpdateTable) Delete(id interface{}) error {
  362. i, ok := id.(int64)
  363. if !ok {
  364. return fmt.Errorf("id is invalid type: %T", id)
  365. }
  366. if int(i) >= len(t.data) || i < 0 {
  367. return fmt.Errorf("invalid row id %d", i)
  368. }
  369. t.data = append(t.data[:i], t.data[i+1:]...)
  370. return nil
  371. }
  372. type vtabUpdateCursor struct {
  373. t *vtabUpdateTable
  374. i int
  375. }
  376. func (c *vtabUpdateCursor) Column(ctxt *SQLiteContext, col int) error {
  377. switch x := c.t.data[c.i][col].(type) {
  378. case []byte:
  379. ctxt.ResultBlob(x)
  380. case bool:
  381. ctxt.ResultBool(x)
  382. case float64:
  383. ctxt.ResultDouble(x)
  384. case int:
  385. ctxt.ResultInt(x)
  386. case int64:
  387. ctxt.ResultInt64(x)
  388. case nil:
  389. ctxt.ResultNull()
  390. case string:
  391. ctxt.ResultText(x)
  392. default:
  393. ctxt.ResultText(fmt.Sprintf("%v", x))
  394. }
  395. return nil
  396. }
  397. func (c *vtabUpdateCursor) Filter(ixNum int, ixName string, vals []interface{}) error {
  398. return nil
  399. }
  400. func (c *vtabUpdateCursor) Next() error {
  401. c.i++
  402. return nil
  403. }
  404. func (c *vtabUpdateCursor) EOF() bool {
  405. return c.i >= len(c.t.data)
  406. }
  407. func (c *vtabUpdateCursor) Rowid() (int64, error) {
  408. return int64(c.i), nil
  409. }
  410. func (c *vtabUpdateCursor) Close() error {
  411. return nil
  412. }