storage.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. // Copyright (c) 2014 ql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ql
  5. import (
  6. "fmt"
  7. "strings"
  8. )
  9. type storage interface {
  10. Acid() bool
  11. BeginTransaction() error
  12. Close() error
  13. Commit() error
  14. Create(data ...interface{}) (h int64, err error)
  15. CreateIndex(unique bool) (handle int64, x btreeIndex, err error)
  16. CreateTemp(asc bool) (bt temp, err error)
  17. Delete(h int64, blobCols ...*col) error //LATER split the nil blobCols case
  18. ID() (id int64, err error)
  19. Name() string
  20. OpenIndex(unique bool, handle int64) (btreeIndex, error) // Never called on the memory backend.
  21. Read(dst []interface{}, h int64, cols ...*col) (data []interface{}, err error)
  22. ResetID() (err error)
  23. Rollback() error
  24. Update(h int64, data ...interface{}) error
  25. UpdateRow(h int64, blobCols []*col, data ...interface{}) error
  26. Verify() (allocs int64, err error)
  27. }
  28. type btreeIterator interface {
  29. Next() (k, v []interface{}, err error)
  30. }
  31. type temp interface {
  32. BeginTransaction() error
  33. Create(data ...interface{}) (h int64, err error)
  34. Drop() (err error)
  35. Get(k []interface{}) (v []interface{}, err error)
  36. Read(dst []interface{}, h int64, cols ...*col) (data []interface{}, err error)
  37. SeekFirst() (e btreeIterator, err error)
  38. Set(k, v []interface{}) (err error)
  39. }
  40. type indexIterator interface {
  41. Next() (k []interface{}, h int64, err error)
  42. Prev() (k []interface{}, h int64, err error)
  43. }
  44. type btreeIndex interface {
  45. Clear() error // supports truncate table statement
  46. Create(indexedValues []interface{}, h int64) error // supports insert into statement
  47. Delete(indexedValues []interface{}, h int64) error // supports delete from statement
  48. Drop() error // supports drop table, drop index statements
  49. Seek(indexedValues []interface{}) (iter indexIterator, hit bool, err error) // supports where clause
  50. SeekFirst() (iter indexIterator, err error) // supports aggregate min / ascending order by
  51. SeekLast() (iter indexIterator, err error) // supports aggregate max / descending order by
  52. }
  53. type indexedCol struct { // Column name or id() index.
  54. name string
  55. unique bool
  56. x btreeIndex
  57. xroot int64
  58. }
  59. type index2 struct { // Expression list index.
  60. unique bool
  61. x btreeIndex
  62. xroot int64
  63. sources []string
  64. exprList []expression
  65. }
  66. func (x *index2) eval(ctx *execCtx, cols []*col, id int64, r []interface{}) ([]interface{}, error) {
  67. f, isFile := ctx.db.store.(*file)
  68. vlist := make([]interface{}, len(x.exprList))
  69. m := map[interface{}]interface{}{"$id": id}
  70. for _, col := range cols {
  71. ci := col.index
  72. v := interface{}(nil)
  73. if ci < len(r) {
  74. v = r[ci]
  75. }
  76. if b, ok := v.([]byte); ok && isFile {
  77. var err error
  78. if v, err = expand1(chunk{f: f, b: b}, nil); err != nil {
  79. return nil, err
  80. }
  81. }
  82. m[col.name] = v
  83. }
  84. for i, e := range x.exprList {
  85. v, err := e.eval(ctx, m)
  86. if err != nil {
  87. return nil, err
  88. }
  89. if ok, typ := isBlobType(v); ok {
  90. return nil, fmt.Errorf("value of a complex index cannot be of blob-like type: %v", typ)
  91. }
  92. vlist[i] = v
  93. }
  94. return vlist, nil
  95. }
  96. type indexKey struct {
  97. value []interface{}
  98. h int64
  99. }
  100. // storage fields
  101. // 0: next int64
  102. // 1: scols string
  103. // 2: hhead int64
  104. // 3: name string
  105. // 4: indices string - optional
  106. // 5: hxroots int64 - optional
  107. type table struct {
  108. cols []*col // logical
  109. cols0 []*col // physical
  110. h int64 //
  111. head int64 // head of the single linked record list
  112. hhead int64 // handle of the head of the single linked record list
  113. hxroots int64
  114. indices []*indexedCol
  115. indices2 map[string]*index2
  116. name string
  117. next int64 // single linked table list
  118. store storage
  119. tnext *table
  120. tprev *table
  121. xroots []interface{}
  122. constraints []*constraint
  123. defaults []expression
  124. }
  125. func (t *table) hasIndices() bool { return len(t.indices) != 0 || len(t.indices2) != 0 }
  126. func (t *table) constraintsAndDefaults(ctx *execCtx) error {
  127. if isSystemName[t.name] {
  128. return nil
  129. }
  130. _, ok := ctx.db.root.tables["__Column2"]
  131. if !ok {
  132. return nil
  133. }
  134. cols := t.cols
  135. constraints := make([]*constraint, len(cols))
  136. defaults := make([]expression, len(cols))
  137. arg := []interface{}{t.name}
  138. rs, err := selectColumn2.l[0].exec(&execCtx{db: ctx.db, arg: arg})
  139. if err != nil {
  140. return err
  141. }
  142. var rows [][]interface{}
  143. ok = false
  144. if err := rs.(recordset).do(
  145. &execCtx{db: ctx.db, arg: arg},
  146. func(id interface{}, data []interface{}) (more bool, err error) {
  147. rows = append(rows, data)
  148. return true, nil
  149. },
  150. ); err != nil {
  151. return err
  152. }
  153. for _, row := range rows {
  154. nm := row[0].(string)
  155. nonNull := row[1].(bool)
  156. cexpr := row[2].(string)
  157. dexpr := row[3].(string)
  158. for i, c := range cols {
  159. if c.name == nm {
  160. var co *constraint
  161. if nonNull || cexpr != "" {
  162. co = &constraint{}
  163. constraints[i] = co
  164. if cexpr != "" {
  165. if co.expr, err = ctx.db.str2expr(cexpr); err != nil {
  166. return fmt.Errorf("constraint %q: %v", cexpr, err)
  167. }
  168. }
  169. t.constraints = constraints
  170. }
  171. if dexpr != "" {
  172. if defaults[i], err = ctx.db.str2expr(dexpr); err != nil {
  173. return fmt.Errorf("constraint %q: %v", dexpr, err)
  174. }
  175. t.defaults = defaults
  176. }
  177. }
  178. }
  179. }
  180. return nil
  181. }
  182. func (t *table) checkConstraintsAndDefaults(ctx *execCtx, row []interface{}, m map[interface{}]interface{}) error {
  183. cols := t.cols
  184. if len(t.defaults) != 0 {
  185. // 1.
  186. for _, c := range cols {
  187. m[c.name] = row[c.index]
  188. }
  189. // 2.
  190. for i, c := range cols {
  191. val := row[c.index]
  192. expr := t.defaults[i]
  193. if val != nil || expr == nil {
  194. continue
  195. }
  196. dval, err := expr.eval(ctx, m)
  197. if err != nil {
  198. return err
  199. }
  200. row[c.index] = dval
  201. if err = typeCheck(row, []*col{c}); err != nil {
  202. return err
  203. }
  204. }
  205. }
  206. if len(t.constraints) != 0 {
  207. // 3.
  208. for _, c := range cols {
  209. m[c.name] = row[c.index]
  210. }
  211. // 4.
  212. for i, c := range cols {
  213. constraint := t.constraints[i]
  214. if constraint == nil {
  215. continue
  216. }
  217. val := row[c.index]
  218. expr := constraint.expr
  219. if expr == nil { // Constraint: NOT NULL
  220. if val == nil {
  221. return fmt.Errorf("column %s: constraint violation: NOT NULL", c.name)
  222. }
  223. continue
  224. }
  225. // Constraint is an expression
  226. cval, err := expr.eval(ctx, m)
  227. if err != nil {
  228. return err
  229. }
  230. if cval == nil {
  231. return fmt.Errorf("column %s: constraint violation: %s", c.name, expr)
  232. }
  233. bval, ok := cval.(bool)
  234. if !ok {
  235. return fmt.Errorf("column %s: non bool constraint expression: %s", c.name, expr)
  236. }
  237. if !bval {
  238. return fmt.Errorf("column %s: constraint violation: %s", c.name, expr)
  239. }
  240. }
  241. }
  242. return nil
  243. }
  244. func (t *table) clone() *table {
  245. r := &table{}
  246. *r = *t
  247. r.constraints = append([]*constraint(nil), t.constraints...)
  248. r.defaults = append([]expression(nil), t.defaults...)
  249. r.indices2 = nil
  250. if n := len(t.indices2); n != 0 {
  251. r.indices2 = make(map[string]*index2, n)
  252. for k, v := range t.indices2 {
  253. r.indices2[k] = v
  254. }
  255. }
  256. r.cols = make([]*col, len(t.cols))
  257. for i, v := range t.cols {
  258. c := &col{}
  259. *c = *v
  260. r.cols[i] = c
  261. }
  262. r.cols0 = make([]*col, len(t.cols0))
  263. for i, v := range t.cols0 {
  264. c := &col{}
  265. *c = *v
  266. r.cols0[i] = c
  267. }
  268. r.indices = make([]*indexedCol, len(t.indices))
  269. for i, v := range t.indices {
  270. if v != nil {
  271. c := &indexedCol{}
  272. *c = *v
  273. r.indices[i] = c
  274. }
  275. }
  276. r.xroots = make([]interface{}, len(t.xroots))
  277. copy(r.xroots, t.xroots)
  278. r.tnext, r.tprev = nil, nil
  279. return r
  280. }
  281. func (t *table) findIndexByColName(name string) (*col, *indexedCol) {
  282. for i, v := range t.indices {
  283. if v == nil {
  284. continue
  285. }
  286. if i == 0 {
  287. if name == "id()" {
  288. return idCol, v
  289. }
  290. continue
  291. }
  292. if c := t.cols[i-1]; c.name == name {
  293. return c, v
  294. }
  295. }
  296. return nil, nil
  297. }
  298. func (t *table) findIndexByName(name string) interface{} {
  299. for _, v := range t.indices {
  300. if v != nil && v.name == name {
  301. return v
  302. }
  303. }
  304. for k, v := range t.indices2 {
  305. if k == name {
  306. return v
  307. }
  308. }
  309. return nil
  310. }
  311. func (t *table) load() (err error) {
  312. data, err := t.store.Read(nil, t.h)
  313. if err != nil {
  314. return
  315. }
  316. var hasIndices bool
  317. switch n := len(data); n {
  318. case 4:
  319. case 6:
  320. hasIndices = true
  321. default:
  322. return fmt.Errorf("corrupted DB: table data len %d", n)
  323. }
  324. var ok bool
  325. if t.next, ok = data[0].(int64); !ok {
  326. return fmt.Errorf("corrupted DB: table data[0] of type %T", data[0])
  327. }
  328. scols, ok := data[1].(string)
  329. if !ok {
  330. return fmt.Errorf("corrupted DB: table data[1] of type %T", data[1])
  331. }
  332. if t.hhead, ok = data[2].(int64); !ok {
  333. return fmt.Errorf("corrupted DB: table data[2] of type %T", data[2])
  334. }
  335. if t.name, ok = data[3].(string); !ok {
  336. return fmt.Errorf("corrupted DB: table data[3] of type %T", data[3])
  337. }
  338. var head []interface{}
  339. if head, err = t.store.Read(nil, t.hhead); err != nil {
  340. return err
  341. }
  342. if len(head) != 1 {
  343. return fmt.Errorf("corrupted DB: table head data len %d", len(head))
  344. }
  345. if t.head, ok = head[0].(int64); !ok {
  346. return fmt.Errorf("corrupted DB: table head data[0] of type %T", head[0])
  347. }
  348. a := strings.Split(scols, "|")
  349. t.cols0 = make([]*col, len(a))
  350. for i, v := range a {
  351. if len(v) < 1 {
  352. return fmt.Errorf("corrupted DB: field info %q", v)
  353. }
  354. col := &col{name: v[1:], typ: int(v[0]), index: i}
  355. t.cols0[i] = col
  356. if col.name != "" {
  357. t.cols = append(t.cols, col)
  358. }
  359. }
  360. if !hasIndices {
  361. return
  362. }
  363. if t.hxroots, ok = data[5].(int64); !ok {
  364. return fmt.Errorf("corrupted DB: table data[5] of type %T", data[5])
  365. }
  366. xroots, err := t.store.Read(nil, t.hxroots)
  367. if err != nil {
  368. return err
  369. }
  370. if g, e := len(xroots), len(t.cols0)+1; g != e {
  371. return fmt.Errorf("corrupted DB: got %d index roots, expected %d", g, e)
  372. }
  373. indices, ok := data[4].(string)
  374. if !ok {
  375. return fmt.Errorf("corrupted DB: table data[4] of type %T", data[4])
  376. }
  377. a = strings.Split(indices, "|")
  378. if g, e := len(a), len(t.cols0)+1; g != e {
  379. return fmt.Errorf("corrupted DB: got %d index definitions, expected %d", g, e)
  380. }
  381. t.indices = make([]*indexedCol, len(a))
  382. for i, v := range a {
  383. if v == "" {
  384. continue
  385. }
  386. if len(v) < 2 {
  387. return fmt.Errorf("corrupted DB: invalid index definition %q", v)
  388. }
  389. nm := v[1:]
  390. h, ok := xroots[i].(int64)
  391. if !ok {
  392. return fmt.Errorf("corrupted DB: table index root of type %T", xroots[i])
  393. }
  394. if h == 0 {
  395. return fmt.Errorf("corrupted DB: missing root for index %s", nm)
  396. }
  397. unique := v[0] == 'u'
  398. x, err := t.store.OpenIndex(unique, h)
  399. if err != nil {
  400. return err
  401. }
  402. t.indices[i] = &indexedCol{nm, unique, x, h}
  403. }
  404. t.xroots = xroots
  405. return
  406. }
  407. func newTable(store storage, name string, next int64, cols []*col, tprev, tnext *table) (t *table, err error) {
  408. hhead, err := store.Create(int64(0))
  409. if err != nil {
  410. return
  411. }
  412. scols := cols2meta(cols)
  413. h, err := store.Create(next, scols, hhead, name)
  414. if err != nil {
  415. return
  416. }
  417. t = &table{
  418. cols0: cols,
  419. h: h,
  420. hhead: hhead,
  421. name: name,
  422. next: next,
  423. store: store,
  424. tnext: tnext,
  425. tprev: tprev,
  426. }
  427. return t.updateCols(), nil
  428. }
  429. func (t *table) blobCols() (r []*col) {
  430. for _, c := range t.cols0 {
  431. switch c.typ {
  432. case qBlob, qBigInt, qBigRat, qTime, qDuration:
  433. r = append(r, c)
  434. }
  435. }
  436. return
  437. }
  438. func (t *table) truncate() (err error) {
  439. h := t.head
  440. var rec []interface{}
  441. blobCols := t.blobCols()
  442. for h != 0 {
  443. rec, err := t.store.Read(rec, h)
  444. if err != nil {
  445. return err
  446. }
  447. nh := rec[0].(int64)
  448. if err = t.store.Delete(h, blobCols...); err != nil { //LATER remove double read for len(blobCols) != 0
  449. return err
  450. }
  451. h = nh
  452. }
  453. if err = t.store.Update(t.hhead, 0); err != nil {
  454. return
  455. }
  456. for _, v := range t.indices {
  457. if v == nil {
  458. continue
  459. }
  460. if err := v.x.Clear(); err != nil {
  461. return err
  462. }
  463. }
  464. for _, ix := range t.indices2 {
  465. if err := ix.x.Clear(); err != nil {
  466. return err
  467. }
  468. }
  469. t.head = 0
  470. return t.updated()
  471. }
  472. func (t *table) addIndex0(unique bool, indexName string, colIndex int) (int64, btreeIndex, error) {
  473. switch len(t.indices) {
  474. case 0:
  475. indices := make([]*indexedCol, len(t.cols0)+1)
  476. h, x, err := t.store.CreateIndex(unique)
  477. if err != nil {
  478. return -1, nil, err
  479. }
  480. indices[colIndex+1] = &indexedCol{indexName, unique, x, h}
  481. xroots := make([]interface{}, len(indices))
  482. xroots[colIndex+1] = h
  483. hx, err := t.store.Create(xroots...)
  484. if err != nil {
  485. return -1, nil, err
  486. }
  487. t.hxroots, t.xroots, t.indices = hx, xroots, indices
  488. return h, x, t.updated()
  489. default:
  490. ex := t.indices[colIndex+1]
  491. if ex != nil && ex.name != "" {
  492. colName := "id()"
  493. if colIndex >= 0 {
  494. colName = t.cols0[colIndex].name
  495. }
  496. return -1, nil, fmt.Errorf("column %s already has an index: %s", colName, ex.name)
  497. }
  498. h, x, err := t.store.CreateIndex(unique)
  499. if err != nil {
  500. return -1, nil, err
  501. }
  502. t.xroots[colIndex+1] = h
  503. if err := t.store.Update(t.hxroots, t.xroots...); err != nil {
  504. return -1, nil, err
  505. }
  506. t.indices[colIndex+1] = &indexedCol{indexName, unique, x, h}
  507. return h, x, t.updated()
  508. }
  509. }
  510. func (t *table) addIndex(unique bool, indexName string, colIndex int) (int64, error) {
  511. hx, x, err := t.addIndex0(unique, indexName, colIndex)
  512. if err != nil {
  513. return -1, err
  514. }
  515. // Must fill the new index.
  516. ncols := len(t.cols0)
  517. h, store := t.head, t.store
  518. for h != 0 {
  519. rec, err := store.Read(nil, h, t.cols...)
  520. if err != nil {
  521. return -1, err
  522. }
  523. if n := ncols + 2 - len(rec); n > 0 {
  524. rec = append(rec, make([]interface{}, n)...)
  525. }
  526. if err = x.Create([]interface{}{rec[colIndex+2]}, h); err != nil {
  527. return -1, err
  528. }
  529. h = rec[0].(int64)
  530. }
  531. return hx, nil
  532. }
  533. func (t *table) addIndex2(execCtx *execCtx, unique bool, indexName string, exprList []expression) (int64, error) {
  534. if _, ok := t.indices2[indexName]; ok {
  535. panic("internal error 009")
  536. }
  537. hx, x, err := t.store.CreateIndex(unique)
  538. if err != nil {
  539. return -1, err
  540. }
  541. var a []string
  542. for _, v := range exprList {
  543. a = append(a, v.String())
  544. }
  545. x2 := &index2{unique, x, hx, a, exprList}
  546. if t.indices2 == nil {
  547. t.indices2 = map[string]*index2{}
  548. }
  549. t.indices2[indexName] = x2
  550. // Must fill the new index.
  551. m := map[interface{}]interface{}{}
  552. h, store := t.head, t.store
  553. for h != 0 {
  554. rec, err := store.Read(nil, h, t.cols...)
  555. if err != nil {
  556. return -1, err
  557. }
  558. for _, col := range t.cols {
  559. ci := col.index
  560. v := interface{}(nil)
  561. if ci < len(rec) {
  562. v = rec[ci+2]
  563. }
  564. m[col.name] = v
  565. }
  566. id := rec[1].(int64)
  567. vlist, err := x2.eval(execCtx, t.cols, id, rec[2:])
  568. if err != nil {
  569. return -1, err
  570. }
  571. if err := x2.x.Create(vlist, h); err != nil {
  572. return -1, err
  573. }
  574. h = rec[0].(int64)
  575. }
  576. return hx, nil
  577. }
  578. func (t *table) dropIndex(xIndex int) error {
  579. t.xroots[xIndex] = 0
  580. if err := t.indices[xIndex].x.Drop(); err != nil {
  581. return err
  582. }
  583. t.indices[xIndex] = nil
  584. return t.updated()
  585. }
  586. func (t *table) updated() (err error) {
  587. switch {
  588. case len(t.indices) != 0:
  589. a := []string{}
  590. for _, v := range t.indices {
  591. if v == nil {
  592. a = append(a, "")
  593. continue
  594. }
  595. s := "n"
  596. if v.unique {
  597. s = "u"
  598. }
  599. a = append(a, s+v.name)
  600. }
  601. return t.store.Update(t.h, t.next, cols2meta(t.updateCols().cols0), t.hhead, t.name, strings.Join(a, "|"), t.hxroots)
  602. default:
  603. return t.store.Update(t.h, t.next, cols2meta(t.updateCols().cols0), t.hhead, t.name)
  604. }
  605. }
  606. // storage fields
  607. // 0: next record handle int64
  608. // 1: record id int64
  609. // 2...: data row
  610. func (t *table) addRecord(execCtx *execCtx, r []interface{}) (id int64, err error) {
  611. if id, err = t.store.ID(); err != nil {
  612. return
  613. }
  614. r = append([]interface{}{t.head, id}, r...)
  615. h, err := t.store.Create(r...)
  616. if err != nil {
  617. return
  618. }
  619. for i, v := range t.indices {
  620. if v == nil {
  621. continue
  622. }
  623. if err = v.x.Create([]interface{}{r[i+1]}, h); err != nil {
  624. return
  625. }
  626. }
  627. for _, ix := range t.indices2 {
  628. vlist, err := ix.eval(execCtx, t.cols, id, r[2:])
  629. if err != nil {
  630. return -1, err
  631. }
  632. if err := ix.x.Create(vlist, h); err != nil {
  633. return -1, err
  634. }
  635. }
  636. if err = t.store.Update(t.hhead, h); err != nil {
  637. return
  638. }
  639. t.head = h
  640. return
  641. }
  642. func (t *table) fieldNames() []string {
  643. r := make([]string, len(t.cols))
  644. for i, v := range t.cols {
  645. r[i] = v.name
  646. }
  647. return r
  648. }
  649. func (t *table) updateCols() *table {
  650. t.cols = t.cols[:0]
  651. for i, c := range t.cols0 {
  652. if c.name != "" {
  653. c.index = i
  654. t.cols = append(t.cols, c)
  655. }
  656. }
  657. return t
  658. }
  659. func (t *table) row0(ctx *execCtx, h int64) ([]interface{}, error) {
  660. rec, err := ctx.db.store.Read(nil, h, t.cols...)
  661. if err != nil {
  662. return nil, err
  663. }
  664. if d := len(t.cols) - (len(rec) - 2); d > 0 {
  665. rec = append(rec, make([]interface{}, d)...)
  666. }
  667. return rec, nil
  668. }
  669. func (t *table) row(ctx *execCtx, h int64) (int64, []interface{}, error) {
  670. rec, err := t.row0(ctx, h)
  671. if err != nil {
  672. return -1, nil, err
  673. }
  674. return rec[1].(int64), rec[2:], nil
  675. }
  676. // storage fields
  677. // 0: handle of first table in DB int64
  678. type root struct {
  679. head int64 // Single linked table list
  680. lastInsertID int64
  681. parent *root
  682. //rowsAffected int64 //LATER implement
  683. store storage
  684. tables map[string]*table
  685. thead *table
  686. }
  687. func newRoot(store storage) (r *root, err error) {
  688. data, err := store.Read(nil, 1)
  689. if err != nil {
  690. return
  691. }
  692. switch len(data) {
  693. case 0: // new empty DB, create empty table list
  694. if err = store.BeginTransaction(); err != nil {
  695. return
  696. }
  697. if err = store.Update(1, int64(0)); err != nil {
  698. store.Rollback()
  699. return
  700. }
  701. if err = store.Commit(); err != nil {
  702. return
  703. }
  704. return &root{
  705. store: store,
  706. tables: map[string]*table{},
  707. }, nil
  708. case 1: // existing DB, load tables
  709. if len(data) != 1 {
  710. return nil, fmt.Errorf("corrupted DB: root is an %d-scalar", len(data))
  711. }
  712. p, ok := data[0].(int64)
  713. if !ok {
  714. return nil, fmt.Errorf("corrupted DB: root head has type %T", data[0])
  715. }
  716. r := &root{
  717. head: p,
  718. store: store,
  719. tables: map[string]*table{},
  720. }
  721. var tprev *table
  722. for p != 0 {
  723. t := &table{
  724. h: p,
  725. store: store,
  726. tprev: tprev,
  727. }
  728. if r.thead == nil {
  729. r.thead = t
  730. }
  731. if tprev != nil {
  732. tprev.tnext = t
  733. }
  734. tprev = t
  735. if err = t.load(); err != nil {
  736. return nil, err
  737. }
  738. if r.tables[t.name] != nil { // duplicate
  739. return nil, fmt.Errorf("corrupted DB: duplicate table metadata for table %s", t.name)
  740. }
  741. r.tables[t.name] = t
  742. p = t.next
  743. }
  744. return r, nil
  745. default:
  746. return nil, errIncompatibleDBFormat
  747. }
  748. }
  749. func (r *root) findIndexByName(name string) (*table, interface{}) {
  750. for _, t := range r.tables {
  751. if i := t.findIndexByName(name); i != nil {
  752. return t, i
  753. }
  754. }
  755. return nil, nil
  756. }
  757. func (r *root) updated() (err error) {
  758. return r.store.Update(1, r.head)
  759. }
  760. func (r *root) createTable(name string, cols []*col) (t *table, err error) {
  761. if _, ok := r.tables[name]; ok {
  762. panic("internal error 065")
  763. }
  764. if t, err = newTable(r.store, name, r.head, cols, nil, r.thead); err != nil {
  765. return nil, err
  766. }
  767. if err = r.store.Update(1, t.h); err != nil {
  768. return nil, err
  769. }
  770. if p := r.thead; p != nil {
  771. p.tprev = t
  772. }
  773. r.tables[name], r.head, r.thead = t, t.h, t
  774. return
  775. }
  776. func (r *root) dropTable(t *table) (err error) {
  777. defer func() {
  778. if err != nil {
  779. return
  780. }
  781. delete(r.tables, t.name)
  782. }()
  783. if err = t.truncate(); err != nil {
  784. return
  785. }
  786. if err = t.store.Delete(t.hhead); err != nil {
  787. return
  788. }
  789. if err = t.store.Delete(t.h); err != nil {
  790. return
  791. }
  792. for _, v := range t.indices {
  793. if v != nil && v.x != nil {
  794. if err = v.x.Drop(); err != nil {
  795. return
  796. }
  797. }
  798. }
  799. for _, v := range t.indices2 {
  800. if err = v.x.Drop(); err != nil {
  801. return
  802. }
  803. }
  804. if h := t.hxroots; h != 0 {
  805. if err = t.store.Delete(h); err != nil {
  806. return
  807. }
  808. }
  809. switch {
  810. case t.tprev == nil && t.tnext == nil:
  811. r.head = 0
  812. r.thead = nil
  813. err = r.updated()
  814. return errSet(&err, r.store.ResetID())
  815. case t.tprev == nil && t.tnext != nil:
  816. next := t.tnext
  817. next.tprev = nil
  818. r.head = next.h
  819. r.thead = next
  820. if err = r.updated(); err != nil {
  821. return
  822. }
  823. return next.updated()
  824. case t.tprev != nil && t.tnext == nil: // last in list
  825. prev := t.tprev
  826. prev.next = 0
  827. prev.tnext = nil
  828. return prev.updated()
  829. default: //case t.tprev != nil && t.tnext != nil:
  830. prev, next := t.tprev, t.tnext
  831. prev.next = next.h
  832. prev.tnext = next
  833. next.tprev = prev
  834. if err = prev.updated(); err != nil {
  835. return
  836. }
  837. return next.updated()
  838. }
  839. }