buntdb.go 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375
  1. // Package buntdb implements a low-level in-memory key/value store in pure Go.
  2. // It persists to disk, is ACID compliant, and uses locking for multiple
  3. // readers and a single writer. Bunt is ideal for projects that need a
  4. // dependable database, and favor speed over data size.
  5. package buntdb
  6. import (
  7. "bufio"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "os"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/tidwall/btree"
  18. "github.com/tidwall/gjson"
  19. "github.com/tidwall/grect"
  20. "github.com/tidwall/match"
  21. "github.com/tidwall/rtred"
  22. )
  23. var (
  24. // ErrTxNotWritable is returned when performing a write operation on a
  25. // read-only transaction.
  26. ErrTxNotWritable = errors.New("tx not writable")
  27. // ErrTxClosed is returned when committing or rolling back a transaction
  28. // that has already been committed or rolled back.
  29. ErrTxClosed = errors.New("tx closed")
  30. // ErrNotFound is returned when an item or index is not in the database.
  31. ErrNotFound = errors.New("not found")
  32. // ErrInvalid is returned when the database file is an invalid format.
  33. ErrInvalid = errors.New("invalid database")
  34. // ErrDatabaseClosed is returned when the database is closed.
  35. ErrDatabaseClosed = errors.New("database closed")
  36. // ErrIndexExists is returned when an index already exists in the database.
  37. ErrIndexExists = errors.New("index exists")
  38. // ErrInvalidOperation is returned when an operation cannot be completed.
  39. ErrInvalidOperation = errors.New("invalid operation")
  40. // ErrInvalidSyncPolicy is returned for an invalid SyncPolicy value.
  41. ErrInvalidSyncPolicy = errors.New("invalid sync policy")
  42. // ErrShrinkInProcess is returned when a shrink operation is in-process.
  43. ErrShrinkInProcess = errors.New("shrink is in-process")
  44. // ErrPersistenceActive is returned when post-loading data from an database
  45. // not opened with Open(":memory:").
  46. ErrPersistenceActive = errors.New("persistence active")
  47. // ErrTxIterating is returned when Set or Delete are called while iterating.
  48. ErrTxIterating = errors.New("tx is iterating")
  49. )
  50. // DB represents a collection of key-value pairs that persist on disk.
  51. // Transactions are used for all forms of data access to the DB.
  52. type DB struct {
  53. mu sync.RWMutex // the gatekeeper for all fields
  54. file *os.File // the underlying file
  55. buf []byte // a buffer to write to
  56. keys *btree.BTree // a tree of all item ordered by key
  57. exps *btree.BTree // a tree of items ordered by expiration
  58. idxs map[string]*index // the index trees.
  59. insIdxs []*index // a reuse buffer for gathering indexes
  60. flushes int // a count of the number of disk flushes
  61. closed bool // set when the database has been closed
  62. config Config // the database configuration
  63. persist bool // do we write to disk
  64. shrinking bool // when an aof shrink is in-process.
  65. lastaofsz int // the size of the last shrink aof size
  66. }
  67. // SyncPolicy represents how often data is synced to disk.
  68. type SyncPolicy int
  69. const (
  70. // Never is used to disable syncing data to disk.
  71. // The faster and less safe method.
  72. Never SyncPolicy = 0
  73. // EverySecond is used to sync data to disk every second.
  74. // It's pretty fast and you can lose 1 second of data if there
  75. // is a disaster.
  76. // This is the recommended setting.
  77. EverySecond = 1
  78. // Always is used to sync data after every write to disk.
  79. // Slow. Very safe.
  80. Always = 2
  81. )
  82. // Config represents database configuration options. These
  83. // options are used to change various behaviors of the database.
  84. type Config struct {
  85. // SyncPolicy adjusts how often the data is synced to disk.
  86. // This value can be Never, EverySecond, or Always.
  87. // The default is EverySecond.
  88. SyncPolicy SyncPolicy
  89. // AutoShrinkPercentage is used by the background process to trigger
  90. // a shrink of the aof file when the size of the file is larger than the
  91. // percentage of the result of the previous shrunk file.
  92. // For example, if this value is 100, and the last shrink process
  93. // resulted in a 100mb file, then the new aof file must be 200mb before
  94. // a shrink is triggered.
  95. AutoShrinkPercentage int
  96. // AutoShrinkMinSize defines the minimum size of the aof file before
  97. // an automatic shrink can occur.
  98. AutoShrinkMinSize int
  99. // AutoShrinkDisabled turns off automatic background shrinking
  100. AutoShrinkDisabled bool
  101. // OnExpired is used to custom handle the deletion option when a key
  102. // has been expired.
  103. OnExpired func(keys []string)
  104. // OnExpiredSync will be called inside the same transaction that is
  105. // performing the deletion of expired items. If OnExpired is present then
  106. // this callback will not be called. If this callback is present, then the
  107. // deletion of the timeed-out item is the explicit responsibility of this
  108. // callback.
  109. OnExpiredSync func(key, value string, tx *Tx) error
  110. }
  111. // exctx is a simple b-tree context for ordering by expiration.
  112. type exctx struct {
  113. db *DB
  114. }
  115. // Open opens a database at the provided path.
  116. // If the file does not exist then it will be created automatically.
  117. func Open(path string) (*DB, error) {
  118. db := &DB{}
  119. // initialize trees and indexes
  120. db.keys = btreeNew(lessCtx(nil))
  121. db.exps = btreeNew(lessCtx(&exctx{db}))
  122. db.idxs = make(map[string]*index)
  123. // initialize default configuration
  124. db.config = Config{
  125. SyncPolicy: EverySecond,
  126. AutoShrinkPercentage: 100,
  127. AutoShrinkMinSize: 32 * 1024 * 1024,
  128. }
  129. // turn off persistence for pure in-memory
  130. db.persist = path != ":memory:"
  131. if db.persist {
  132. var err error
  133. // hardcoding 0666 as the default mode.
  134. db.file, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0666)
  135. if err != nil {
  136. return nil, err
  137. }
  138. // load the database from disk
  139. if err := db.load(); err != nil {
  140. // close on error, ignore close error
  141. _ = db.file.Close()
  142. return nil, err
  143. }
  144. }
  145. // start the background manager.
  146. go db.backgroundManager()
  147. return db, nil
  148. }
  149. // Close releases all database resources.
  150. // All transactions must be closed before closing the database.
  151. func (db *DB) Close() error {
  152. db.mu.Lock()
  153. defer db.mu.Unlock()
  154. if db.closed {
  155. return ErrDatabaseClosed
  156. }
  157. db.closed = true
  158. if db.persist {
  159. db.file.Sync() // do a sync but ignore the error
  160. if err := db.file.Close(); err != nil {
  161. return err
  162. }
  163. }
  164. // Let's release all references to nil. This will help both with debugging
  165. // late usage panics and it provides a hint to the garbage collector
  166. db.keys, db.exps, db.idxs, db.file = nil, nil, nil, nil
  167. return nil
  168. }
  169. // Save writes a snapshot of the database to a writer. This operation blocks all
  170. // writes, but not reads. This can be used for snapshots and backups for pure
  171. // in-memory databases using the ":memory:". Database that persist to disk
  172. // can be snapshotted by simply copying the database file.
  173. func (db *DB) Save(wr io.Writer) error {
  174. var err error
  175. db.mu.RLock()
  176. defer db.mu.RUnlock()
  177. // use a buffered writer and flush every 4MB
  178. var buf []byte
  179. now := time.Now()
  180. // iterated through every item in the database and write to the buffer
  181. btreeAscend(db.keys, func(item interface{}) bool {
  182. dbi := item.(*dbItem)
  183. buf = dbi.writeSetTo(buf, now)
  184. if len(buf) > 1024*1024*4 {
  185. // flush when buffer is over 4MB
  186. _, err = wr.Write(buf)
  187. if err != nil {
  188. return false
  189. }
  190. buf = buf[:0]
  191. }
  192. return true
  193. })
  194. if err != nil {
  195. return err
  196. }
  197. // one final flush
  198. if len(buf) > 0 {
  199. _, err = wr.Write(buf)
  200. if err != nil {
  201. return err
  202. }
  203. }
  204. return nil
  205. }
  206. // Load loads commands from reader. This operation blocks all reads and writes.
  207. // Note that this can only work for fully in-memory databases opened with
  208. // Open(":memory:").
  209. func (db *DB) Load(rd io.Reader) error {
  210. db.mu.Lock()
  211. defer db.mu.Unlock()
  212. if db.persist {
  213. // cannot load into databases that persist to disk
  214. return ErrPersistenceActive
  215. }
  216. _, err := db.readLoad(rd, time.Now())
  217. return err
  218. }
  219. // index represents a b-tree or r-tree index and also acts as the
  220. // b-tree/r-tree context for itself.
  221. type index struct {
  222. btr *btree.BTree // contains the items
  223. rtr *rtred.RTree // contains the items
  224. name string // name of the index
  225. pattern string // a required key pattern
  226. less func(a, b string) bool // less comparison function
  227. rect func(item string) (min, max []float64) // rect from string function
  228. db *DB // the origin database
  229. opts IndexOptions // index options
  230. }
  231. // match matches the pattern to the key
  232. func (idx *index) match(key string) bool {
  233. if idx.pattern == "*" {
  234. return true
  235. }
  236. if idx.opts.CaseInsensitiveKeyMatching {
  237. for i := 0; i < len(key); i++ {
  238. if key[i] >= 'A' && key[i] <= 'Z' {
  239. key = strings.ToLower(key)
  240. break
  241. }
  242. }
  243. }
  244. return match.Match(key, idx.pattern)
  245. }
  246. // clearCopy creates a copy of the index, but with an empty dataset.
  247. func (idx *index) clearCopy() *index {
  248. // copy the index meta information
  249. nidx := &index{
  250. name: idx.name,
  251. pattern: idx.pattern,
  252. db: idx.db,
  253. less: idx.less,
  254. rect: idx.rect,
  255. opts: idx.opts,
  256. }
  257. // initialize with empty trees
  258. if nidx.less != nil {
  259. nidx.btr = btreeNew(lessCtx(nidx))
  260. }
  261. if nidx.rect != nil {
  262. nidx.rtr = rtred.New(nidx)
  263. }
  264. return nidx
  265. }
  266. // rebuild rebuilds the index
  267. func (idx *index) rebuild() {
  268. // initialize trees
  269. if idx.less != nil {
  270. idx.btr = btreeNew(lessCtx(idx))
  271. }
  272. if idx.rect != nil {
  273. idx.rtr = rtred.New(idx)
  274. }
  275. // iterate through all keys and fill the index
  276. btreeAscend(idx.db.keys, func(item interface{}) bool {
  277. dbi := item.(*dbItem)
  278. if !idx.match(dbi.key) {
  279. // does not match the pattern, continue
  280. return true
  281. }
  282. if idx.less != nil {
  283. idx.btr.Set(dbi)
  284. }
  285. if idx.rect != nil {
  286. idx.rtr.Insert(dbi)
  287. }
  288. return true
  289. })
  290. }
  291. // CreateIndex builds a new index and populates it with items.
  292. // The items are ordered in an b-tree and can be retrieved using the
  293. // Ascend* and Descend* methods.
  294. // An error will occur if an index with the same name already exists.
  295. //
  296. // When a pattern is provided, the index will be populated with
  297. // keys that match the specified pattern. This is a very simple pattern
  298. // match where '*' matches on any number characters and '?' matches on
  299. // any one character.
  300. // The less function compares if string 'a' is less than string 'b'.
  301. // It allows for indexes to create custom ordering. It's possible
  302. // that the strings may be textual or binary. It's up to the provided
  303. // less function to handle the content format and comparison.
  304. // There are some default less function that can be used such as
  305. // IndexString, IndexBinary, etc.
  306. func (db *DB) CreateIndex(name, pattern string,
  307. less ...func(a, b string) bool) error {
  308. return db.Update(func(tx *Tx) error {
  309. return tx.CreateIndex(name, pattern, less...)
  310. })
  311. }
  312. // ReplaceIndex builds a new index and populates it with items.
  313. // The items are ordered in an b-tree and can be retrieved using the
  314. // Ascend* and Descend* methods.
  315. // If a previous index with the same name exists, that index will be deleted.
  316. func (db *DB) ReplaceIndex(name, pattern string,
  317. less ...func(a, b string) bool) error {
  318. return db.Update(func(tx *Tx) error {
  319. err := tx.CreateIndex(name, pattern, less...)
  320. if err != nil {
  321. if err == ErrIndexExists {
  322. err := tx.DropIndex(name)
  323. if err != nil {
  324. return err
  325. }
  326. return tx.CreateIndex(name, pattern, less...)
  327. }
  328. return err
  329. }
  330. return nil
  331. })
  332. }
  333. // CreateSpatialIndex builds a new index and populates it with items.
  334. // The items are organized in an r-tree and can be retrieved using the
  335. // Intersects method.
  336. // An error will occur if an index with the same name already exists.
  337. //
  338. // The rect function converts a string to a rectangle. The rectangle is
  339. // represented by two arrays, min and max. Both arrays may have a length
  340. // between 1 and 20, and both arrays must match in length. A length of 1 is a
  341. // one dimensional rectangle, and a length of 4 is a four dimension rectangle.
  342. // There is support for up to 20 dimensions.
  343. // The values of min must be less than the values of max at the same dimension.
  344. // Thus min[0] must be less-than-or-equal-to max[0].
  345. // The IndexRect is a default function that can be used for the rect
  346. // parameter.
  347. func (db *DB) CreateSpatialIndex(name, pattern string,
  348. rect func(item string) (min, max []float64)) error {
  349. return db.Update(func(tx *Tx) error {
  350. return tx.CreateSpatialIndex(name, pattern, rect)
  351. })
  352. }
  353. // ReplaceSpatialIndex builds a new index and populates it with items.
  354. // The items are organized in an r-tree and can be retrieved using the
  355. // Intersects method.
  356. // If a previous index with the same name exists, that index will be deleted.
  357. func (db *DB) ReplaceSpatialIndex(name, pattern string,
  358. rect func(item string) (min, max []float64)) error {
  359. return db.Update(func(tx *Tx) error {
  360. err := tx.CreateSpatialIndex(name, pattern, rect)
  361. if err != nil {
  362. if err == ErrIndexExists {
  363. err := tx.DropIndex(name)
  364. if err != nil {
  365. return err
  366. }
  367. return tx.CreateSpatialIndex(name, pattern, rect)
  368. }
  369. return err
  370. }
  371. return nil
  372. })
  373. }
  374. // DropIndex removes an index.
  375. func (db *DB) DropIndex(name string) error {
  376. return db.Update(func(tx *Tx) error {
  377. return tx.DropIndex(name)
  378. })
  379. }
  380. // Indexes returns a list of index names.
  381. func (db *DB) Indexes() ([]string, error) {
  382. var names []string
  383. var err = db.View(func(tx *Tx) error {
  384. var err error
  385. names, err = tx.Indexes()
  386. return err
  387. })
  388. return names, err
  389. }
  390. // ReadConfig returns the database configuration.
  391. func (db *DB) ReadConfig(config *Config) error {
  392. db.mu.RLock()
  393. defer db.mu.RUnlock()
  394. if db.closed {
  395. return ErrDatabaseClosed
  396. }
  397. *config = db.config
  398. return nil
  399. }
  400. // SetConfig updates the database configuration.
  401. func (db *DB) SetConfig(config Config) error {
  402. db.mu.Lock()
  403. defer db.mu.Unlock()
  404. if db.closed {
  405. return ErrDatabaseClosed
  406. }
  407. switch config.SyncPolicy {
  408. default:
  409. return ErrInvalidSyncPolicy
  410. case Never, EverySecond, Always:
  411. }
  412. db.config = config
  413. return nil
  414. }
  415. // insertIntoDatabase performs inserts an item in to the database and updates
  416. // all indexes. If a previous item with the same key already exists, that item
  417. // will be replaced with the new one, and return the previous item.
  418. func (db *DB) insertIntoDatabase(item *dbItem) *dbItem {
  419. var pdbi *dbItem
  420. // Generate a list of indexes that this item will be inserted in to.
  421. idxs := db.insIdxs
  422. for _, idx := range db.idxs {
  423. if idx.match(item.key) {
  424. idxs = append(idxs, idx)
  425. }
  426. }
  427. prev := db.keys.Set(item)
  428. if prev != nil {
  429. // A previous item was removed from the keys tree. Let's
  430. // fully delete this item from all indexes.
  431. pdbi = prev.(*dbItem)
  432. if pdbi.opts != nil && pdbi.opts.ex {
  433. // Remove it from the expires tree.
  434. db.exps.Delete(pdbi)
  435. }
  436. for _, idx := range idxs {
  437. if idx.btr != nil {
  438. // Remove it from the btree index.
  439. idx.btr.Delete(pdbi)
  440. }
  441. if idx.rtr != nil {
  442. // Remove it from the rtree index.
  443. idx.rtr.Remove(pdbi)
  444. }
  445. }
  446. }
  447. if item.opts != nil && item.opts.ex {
  448. // The new item has eviction options. Add it to the
  449. // expires tree
  450. db.exps.Set(item)
  451. }
  452. for i, idx := range idxs {
  453. if idx.btr != nil {
  454. // Add new item to btree index.
  455. idx.btr.Set(item)
  456. }
  457. if idx.rtr != nil {
  458. // Add new item to rtree index.
  459. idx.rtr.Insert(item)
  460. }
  461. // clear the index
  462. idxs[i] = nil
  463. }
  464. // reuse the index list slice
  465. db.insIdxs = idxs[:0]
  466. // we must return the previous item to the caller.
  467. return pdbi
  468. }
  469. // deleteFromDatabase removes and item from the database and indexes. The input
  470. // item must only have the key field specified thus "&dbItem{key: key}" is all
  471. // that is needed to fully remove the item with the matching key. If an item
  472. // with the matching key was found in the database, it will be removed and
  473. // returned to the caller. A nil return value means that the item was not
  474. // found in the database
  475. func (db *DB) deleteFromDatabase(item *dbItem) *dbItem {
  476. var pdbi *dbItem
  477. prev := db.keys.Delete(item)
  478. if prev != nil {
  479. pdbi = prev.(*dbItem)
  480. if pdbi.opts != nil && pdbi.opts.ex {
  481. // Remove it from the exipres tree.
  482. db.exps.Delete(pdbi)
  483. }
  484. for _, idx := range db.idxs {
  485. if !idx.match(pdbi.key) {
  486. continue
  487. }
  488. if idx.btr != nil {
  489. // Remove it from the btree index.
  490. idx.btr.Delete(pdbi)
  491. }
  492. if idx.rtr != nil {
  493. // Remove it from the rtree index.
  494. idx.rtr.Remove(pdbi)
  495. }
  496. }
  497. }
  498. return pdbi
  499. }
  500. // backgroundManager runs continuously in the background and performs various
  501. // operations such as removing expired items and syncing to disk.
  502. func (db *DB) backgroundManager() {
  503. flushes := 0
  504. t := time.NewTicker(time.Second)
  505. defer t.Stop()
  506. for range t.C {
  507. var shrink bool
  508. // Open a standard view. This will take a full lock of the
  509. // database thus allowing for access to anything we need.
  510. var onExpired func([]string)
  511. var expired []*dbItem
  512. var onExpiredSync func(key, value string, tx *Tx) error
  513. err := db.Update(func(tx *Tx) error {
  514. onExpired = db.config.OnExpired
  515. if onExpired == nil {
  516. onExpiredSync = db.config.OnExpiredSync
  517. }
  518. if db.persist && !db.config.AutoShrinkDisabled {
  519. pos, err := db.file.Seek(0, 1)
  520. if err != nil {
  521. return err
  522. }
  523. aofsz := int(pos)
  524. if aofsz > db.config.AutoShrinkMinSize {
  525. prc := float64(db.config.AutoShrinkPercentage) / 100.0
  526. shrink = aofsz > db.lastaofsz+int(float64(db.lastaofsz)*prc)
  527. }
  528. }
  529. // produce a list of expired items that need removing
  530. btreeAscendLessThan(db.exps, &dbItem{
  531. opts: &dbItemOpts{ex: true, exat: time.Now()},
  532. }, func(item interface{}) bool {
  533. expired = append(expired, item.(*dbItem))
  534. return true
  535. })
  536. if onExpired == nil && onExpiredSync == nil {
  537. for _, itm := range expired {
  538. if _, err := tx.Delete(itm.key); err != nil {
  539. // it's ok to get a "not found" because the
  540. // 'Delete' method reports "not found" for
  541. // expired items.
  542. if err != ErrNotFound {
  543. return err
  544. }
  545. }
  546. }
  547. } else if onExpiredSync != nil {
  548. for _, itm := range expired {
  549. if err := onExpiredSync(itm.key, itm.val, tx); err != nil {
  550. return err
  551. }
  552. }
  553. }
  554. return nil
  555. })
  556. if err == ErrDatabaseClosed {
  557. break
  558. }
  559. // send expired event, if needed
  560. if onExpired != nil && len(expired) > 0 {
  561. keys := make([]string, 0, 32)
  562. for _, itm := range expired {
  563. keys = append(keys, itm.key)
  564. }
  565. onExpired(keys)
  566. }
  567. // execute a disk sync, if needed
  568. func() {
  569. db.mu.Lock()
  570. defer db.mu.Unlock()
  571. if db.persist && db.config.SyncPolicy == EverySecond &&
  572. flushes != db.flushes {
  573. _ = db.file.Sync()
  574. flushes = db.flushes
  575. }
  576. }()
  577. if shrink {
  578. if err = db.Shrink(); err != nil {
  579. if err == ErrDatabaseClosed {
  580. break
  581. }
  582. }
  583. }
  584. }
  585. }
  586. // Shrink will make the database file smaller by removing redundant
  587. // log entries. This operation does not block the database.
  588. func (db *DB) Shrink() error {
  589. db.mu.Lock()
  590. if db.closed {
  591. db.mu.Unlock()
  592. return ErrDatabaseClosed
  593. }
  594. if !db.persist {
  595. // The database was opened with ":memory:" as the path.
  596. // There is no persistence, and no need to do anything here.
  597. db.mu.Unlock()
  598. return nil
  599. }
  600. if db.shrinking {
  601. // The database is already in the process of shrinking.
  602. db.mu.Unlock()
  603. return ErrShrinkInProcess
  604. }
  605. db.shrinking = true
  606. defer func() {
  607. db.mu.Lock()
  608. db.shrinking = false
  609. db.mu.Unlock()
  610. }()
  611. fname := db.file.Name()
  612. tmpname := fname + ".tmp"
  613. // the endpos is used to return to the end of the file when we are
  614. // finished writing all of the current items.
  615. endpos, err := db.file.Seek(0, 2)
  616. if err != nil {
  617. return err
  618. }
  619. db.mu.Unlock()
  620. time.Sleep(time.Second / 4) // wait just a bit before starting
  621. f, err := os.Create(tmpname)
  622. if err != nil {
  623. return err
  624. }
  625. defer func() {
  626. _ = f.Close()
  627. _ = os.RemoveAll(tmpname)
  628. }()
  629. // we are going to read items in as chunks as to not hold up the database
  630. // for too long.
  631. var buf []byte
  632. pivot := ""
  633. done := false
  634. for !done {
  635. err := func() error {
  636. db.mu.RLock()
  637. defer db.mu.RUnlock()
  638. if db.closed {
  639. return ErrDatabaseClosed
  640. }
  641. done = true
  642. var n int
  643. now := time.Now()
  644. btreeAscendGreaterOrEqual(db.keys, &dbItem{key: pivot},
  645. func(item interface{}) bool {
  646. dbi := item.(*dbItem)
  647. // 1000 items or 64MB buffer
  648. if n > 1000 || len(buf) > 64*1024*1024 {
  649. pivot = dbi.key
  650. done = false
  651. return false
  652. }
  653. buf = dbi.writeSetTo(buf, now)
  654. n++
  655. return true
  656. },
  657. )
  658. if len(buf) > 0 {
  659. if _, err := f.Write(buf); err != nil {
  660. return err
  661. }
  662. buf = buf[:0]
  663. }
  664. return nil
  665. }()
  666. if err != nil {
  667. return err
  668. }
  669. }
  670. // We reached this far so all of the items have been written to a new tmp
  671. // There's some more work to do by appending the new line from the aof
  672. // to the tmp file and finally swap the files out.
  673. return func() error {
  674. // We're wrapping this in a function to get the benefit of a defered
  675. // lock/unlock.
  676. db.mu.Lock()
  677. defer db.mu.Unlock()
  678. if db.closed {
  679. return ErrDatabaseClosed
  680. }
  681. // We are going to open a new version of the aof file so that we do
  682. // not change the seek position of the previous. This may cause a
  683. // problem in the future if we choose to use syscall file locking.
  684. aof, err := os.Open(fname)
  685. if err != nil {
  686. return err
  687. }
  688. defer func() { _ = aof.Close() }()
  689. if _, err := aof.Seek(endpos, 0); err != nil {
  690. return err
  691. }
  692. // Just copy all of the new commands that have occurred since we
  693. // started the shrink process.
  694. if _, err := io.Copy(f, aof); err != nil {
  695. return err
  696. }
  697. // Close all files
  698. if err := aof.Close(); err != nil {
  699. return err
  700. }
  701. if err := f.Close(); err != nil {
  702. return err
  703. }
  704. if err := db.file.Close(); err != nil {
  705. return err
  706. }
  707. // Any failures below here are really bad. So just panic.
  708. if err := os.Rename(tmpname, fname); err != nil {
  709. panicErr(err)
  710. }
  711. db.file, err = os.OpenFile(fname, os.O_CREATE|os.O_RDWR, 0666)
  712. if err != nil {
  713. panicErr(err)
  714. }
  715. pos, err := db.file.Seek(0, 2)
  716. if err != nil {
  717. return err
  718. }
  719. db.lastaofsz = int(pos)
  720. return nil
  721. }()
  722. }
  723. func panicErr(err error) error {
  724. panic(fmt.Errorf("buntdb: %w", err))
  725. }
  726. // readLoad reads from the reader and loads commands into the database.
  727. // modTime is the modified time of the reader, should be no greater than
  728. // the current time.Now().
  729. // Returns the number of bytes of the last command read and the error if any.
  730. func (db *DB) readLoad(rd io.Reader, modTime time.Time) (n int64, err error) {
  731. defer func() {
  732. if err == io.EOF {
  733. err = io.ErrUnexpectedEOF
  734. }
  735. }()
  736. totalSize := int64(0)
  737. data := make([]byte, 4096)
  738. parts := make([]string, 0, 8)
  739. r := bufio.NewReader(rd)
  740. for {
  741. // peek at the first byte. If it's a 'nul' control character then
  742. // ignore it and move to the next byte.
  743. c, err := r.ReadByte()
  744. if err != nil {
  745. if err == io.EOF {
  746. err = nil
  747. }
  748. return totalSize, err
  749. }
  750. if c == 0 {
  751. // ignore nul control characters
  752. n += 1
  753. continue
  754. }
  755. if err := r.UnreadByte(); err != nil {
  756. return totalSize, err
  757. }
  758. // read a single command.
  759. // first we should read the number of parts that the of the command
  760. cmdByteSize := int64(0)
  761. line, err := r.ReadBytes('\n')
  762. if err != nil {
  763. return totalSize, err
  764. }
  765. if line[0] != '*' {
  766. return totalSize, ErrInvalid
  767. }
  768. cmdByteSize += int64(len(line))
  769. // convert the string number to and int
  770. var n int
  771. if len(line) == 4 && line[len(line)-2] == '\r' {
  772. if line[1] < '0' || line[1] > '9' {
  773. return totalSize, ErrInvalid
  774. }
  775. n = int(line[1] - '0')
  776. } else {
  777. if len(line) < 5 || line[len(line)-2] != '\r' {
  778. return totalSize, ErrInvalid
  779. }
  780. for i := 1; i < len(line)-2; i++ {
  781. if line[i] < '0' || line[i] > '9' {
  782. return totalSize, ErrInvalid
  783. }
  784. n = n*10 + int(line[i]-'0')
  785. }
  786. }
  787. // read each part of the command.
  788. parts = parts[:0]
  789. for i := 0; i < n; i++ {
  790. // read the number of bytes of the part.
  791. line, err := r.ReadBytes('\n')
  792. if err != nil {
  793. return totalSize, err
  794. }
  795. if line[0] != '$' {
  796. return totalSize, ErrInvalid
  797. }
  798. cmdByteSize += int64(len(line))
  799. // convert the string number to and int
  800. var n int
  801. if len(line) == 4 && line[len(line)-2] == '\r' {
  802. if line[1] < '0' || line[1] > '9' {
  803. return totalSize, ErrInvalid
  804. }
  805. n = int(line[1] - '0')
  806. } else {
  807. if len(line) < 5 || line[len(line)-2] != '\r' {
  808. return totalSize, ErrInvalid
  809. }
  810. for i := 1; i < len(line)-2; i++ {
  811. if line[i] < '0' || line[i] > '9' {
  812. return totalSize, ErrInvalid
  813. }
  814. n = n*10 + int(line[i]-'0')
  815. }
  816. }
  817. // resize the read buffer
  818. if len(data) < n+2 {
  819. dataln := len(data)
  820. for dataln < n+2 {
  821. dataln *= 2
  822. }
  823. data = make([]byte, dataln)
  824. }
  825. if _, err = io.ReadFull(r, data[:n+2]); err != nil {
  826. return totalSize, err
  827. }
  828. if data[n] != '\r' || data[n+1] != '\n' {
  829. return totalSize, ErrInvalid
  830. }
  831. // copy string
  832. parts = append(parts, string(data[:n]))
  833. cmdByteSize += int64(n + 2)
  834. }
  835. // finished reading the command
  836. if len(parts) == 0 {
  837. continue
  838. }
  839. if (parts[0][0] == 's' || parts[0][0] == 'S') &&
  840. (parts[0][1] == 'e' || parts[0][1] == 'E') &&
  841. (parts[0][2] == 't' || parts[0][2] == 'T') {
  842. // SET
  843. if len(parts) < 3 || len(parts) == 4 || len(parts) > 5 {
  844. return totalSize, ErrInvalid
  845. }
  846. if len(parts) == 5 {
  847. if strings.ToLower(parts[3]) != "ex" {
  848. return totalSize, ErrInvalid
  849. }
  850. ex, err := strconv.ParseUint(parts[4], 10, 64)
  851. if err != nil {
  852. return totalSize, err
  853. }
  854. now := time.Now()
  855. dur := (time.Duration(ex) * time.Second) - now.Sub(modTime)
  856. if dur > 0 {
  857. db.insertIntoDatabase(&dbItem{
  858. key: parts[1],
  859. val: parts[2],
  860. opts: &dbItemOpts{
  861. ex: true,
  862. exat: now.Add(dur),
  863. },
  864. })
  865. }
  866. } else {
  867. db.insertIntoDatabase(&dbItem{key: parts[1], val: parts[2]})
  868. }
  869. } else if (parts[0][0] == 'd' || parts[0][0] == 'D') &&
  870. (parts[0][1] == 'e' || parts[0][1] == 'E') &&
  871. (parts[0][2] == 'l' || parts[0][2] == 'L') {
  872. // DEL
  873. if len(parts) != 2 {
  874. return totalSize, ErrInvalid
  875. }
  876. db.deleteFromDatabase(&dbItem{key: parts[1]})
  877. } else if (parts[0][0] == 'f' || parts[0][0] == 'F') &&
  878. strings.ToLower(parts[0]) == "flushdb" {
  879. db.keys = btreeNew(lessCtx(nil))
  880. db.exps = btreeNew(lessCtx(&exctx{db}))
  881. db.idxs = make(map[string]*index)
  882. } else {
  883. return totalSize, ErrInvalid
  884. }
  885. totalSize += cmdByteSize
  886. }
  887. }
  888. // load reads entries from the append only database file and fills the database.
  889. // The file format uses the Redis append only file format, which is and a series
  890. // of RESP commands. For more information on RESP please read
  891. // http://redis.io/topics/protocol. The only supported RESP commands are DEL and
  892. // SET.
  893. func (db *DB) load() error {
  894. fi, err := db.file.Stat()
  895. if err != nil {
  896. return err
  897. }
  898. n, err := db.readLoad(db.file, fi.ModTime())
  899. if err != nil {
  900. if err == io.ErrUnexpectedEOF {
  901. // The db file has ended mid-command, which is allowed but the
  902. // data file should be truncated to the end of the last valid
  903. // command
  904. if err := db.file.Truncate(n); err != nil {
  905. return err
  906. }
  907. } else {
  908. return err
  909. }
  910. }
  911. if _, err := db.file.Seek(n, 0); err != nil {
  912. return err
  913. }
  914. var estaofsz int
  915. db.keys.Walk(func(items []interface{}) {
  916. for _, v := range items {
  917. estaofsz += v.(*dbItem).estAOFSetSize()
  918. }
  919. })
  920. db.lastaofsz += estaofsz
  921. return nil
  922. }
  923. // managed calls a block of code that is fully contained in a transaction.
  924. // This method is intended to be wrapped by Update and View
  925. func (db *DB) managed(writable bool, fn func(tx *Tx) error) (err error) {
  926. var tx *Tx
  927. tx, err = db.Begin(writable)
  928. if err != nil {
  929. return
  930. }
  931. defer func() {
  932. if err != nil {
  933. // The caller returned an error. We must rollback.
  934. _ = tx.Rollback()
  935. return
  936. }
  937. if writable {
  938. // Everything went well. Lets Commit()
  939. err = tx.Commit()
  940. } else {
  941. // read-only transaction can only roll back.
  942. err = tx.Rollback()
  943. }
  944. }()
  945. tx.funcd = true
  946. defer func() {
  947. tx.funcd = false
  948. }()
  949. err = fn(tx)
  950. return
  951. }
  952. // View executes a function within a managed read-only transaction.
  953. // When a non-nil error is returned from the function that error will be return
  954. // to the caller of View().
  955. //
  956. // Executing a manual commit or rollback from inside the function will result
  957. // in a panic.
  958. func (db *DB) View(fn func(tx *Tx) error) error {
  959. return db.managed(false, fn)
  960. }
  961. // Update executes a function within a managed read/write transaction.
  962. // The transaction has been committed when no error is returned.
  963. // In the event that an error is returned, the transaction will be rolled back.
  964. // When a non-nil error is returned from the function, the transaction will be
  965. // rolled back and the that error will be return to the caller of Update().
  966. //
  967. // Executing a manual commit or rollback from inside the function will result
  968. // in a panic.
  969. func (db *DB) Update(fn func(tx *Tx) error) error {
  970. return db.managed(true, fn)
  971. }
  972. // get return an item or nil if not found.
  973. func (db *DB) get(key string) *dbItem {
  974. item := db.keys.Get(&dbItem{key: key})
  975. if item != nil {
  976. return item.(*dbItem)
  977. }
  978. return nil
  979. }
  980. // Tx represents a transaction on the database. This transaction can either be
  981. // read-only or read/write. Read-only transactions can be used for retrieving
  982. // values for keys and iterating through keys and values. Read/write
  983. // transactions can set and delete keys.
  984. //
  985. // All transactions must be committed or rolled-back when done.
  986. type Tx struct {
  987. db *DB // the underlying database.
  988. writable bool // when false mutable operations fail.
  989. funcd bool // when true Commit and Rollback panic.
  990. wc *txWriteContext // context for writable transactions.
  991. }
  992. type txWriteContext struct {
  993. // rollback when deleteAll is called
  994. rbkeys *btree.BTree // a tree of all item ordered by key
  995. rbexps *btree.BTree // a tree of items ordered by expiration
  996. rbidxs map[string]*index // the index trees.
  997. rollbackItems map[string]*dbItem // details for rolling back tx.
  998. commitItems map[string]*dbItem // details for committing tx.
  999. itercount int // stack of iterators
  1000. rollbackIndexes map[string]*index // details for dropped indexes.
  1001. }
  1002. // DeleteAll deletes all items from the database.
  1003. func (tx *Tx) DeleteAll() error {
  1004. if tx.db == nil {
  1005. return ErrTxClosed
  1006. } else if !tx.writable {
  1007. return ErrTxNotWritable
  1008. } else if tx.wc.itercount > 0 {
  1009. return ErrTxIterating
  1010. }
  1011. // check to see if we've already deleted everything
  1012. if tx.wc.rbkeys == nil {
  1013. // we need to backup the live data in case of a rollback.
  1014. tx.wc.rbkeys = tx.db.keys
  1015. tx.wc.rbexps = tx.db.exps
  1016. tx.wc.rbidxs = tx.db.idxs
  1017. }
  1018. // now reset the live database trees
  1019. tx.db.keys = btreeNew(lessCtx(nil))
  1020. tx.db.exps = btreeNew(lessCtx(&exctx{tx.db}))
  1021. tx.db.idxs = make(map[string]*index)
  1022. // finally re-create the indexes
  1023. for name, idx := range tx.wc.rbidxs {
  1024. tx.db.idxs[name] = idx.clearCopy()
  1025. }
  1026. // always clear out the commits
  1027. tx.wc.commitItems = make(map[string]*dbItem)
  1028. return nil
  1029. }
  1030. // Begin opens a new transaction.
  1031. // Multiple read-only transactions can be opened at the same time but there can
  1032. // only be one read/write transaction at a time. Attempting to open a read/write
  1033. // transactions while another one is in progress will result in blocking until
  1034. // the current read/write transaction is completed.
  1035. //
  1036. // All transactions must be closed by calling Commit() or Rollback() when done.
  1037. func (db *DB) Begin(writable bool) (*Tx, error) {
  1038. tx := &Tx{
  1039. db: db,
  1040. writable: writable,
  1041. }
  1042. tx.lock()
  1043. if db.closed {
  1044. tx.unlock()
  1045. return nil, ErrDatabaseClosed
  1046. }
  1047. if writable {
  1048. // writable transactions have a writeContext object that
  1049. // contains information about changes to the database.
  1050. tx.wc = &txWriteContext{}
  1051. tx.wc.rollbackItems = make(map[string]*dbItem)
  1052. tx.wc.rollbackIndexes = make(map[string]*index)
  1053. if db.persist {
  1054. tx.wc.commitItems = make(map[string]*dbItem)
  1055. }
  1056. }
  1057. return tx, nil
  1058. }
  1059. // lock locks the database based on the transaction type.
  1060. func (tx *Tx) lock() {
  1061. if tx.writable {
  1062. tx.db.mu.Lock()
  1063. } else {
  1064. tx.db.mu.RLock()
  1065. }
  1066. }
  1067. // unlock unlocks the database based on the transaction type.
  1068. func (tx *Tx) unlock() {
  1069. if tx.writable {
  1070. tx.db.mu.Unlock()
  1071. } else {
  1072. tx.db.mu.RUnlock()
  1073. }
  1074. }
  1075. // rollbackInner handles the underlying rollback logic.
  1076. // Intended to be called from Commit() and Rollback().
  1077. func (tx *Tx) rollbackInner() {
  1078. // rollback the deleteAll if needed
  1079. if tx.wc.rbkeys != nil {
  1080. tx.db.keys = tx.wc.rbkeys
  1081. tx.db.idxs = tx.wc.rbidxs
  1082. tx.db.exps = tx.wc.rbexps
  1083. }
  1084. for key, item := range tx.wc.rollbackItems {
  1085. tx.db.deleteFromDatabase(&dbItem{key: key})
  1086. if item != nil {
  1087. // When an item is not nil, we will need to reinsert that item
  1088. // into the database overwriting the current one.
  1089. tx.db.insertIntoDatabase(item)
  1090. }
  1091. }
  1092. for name, idx := range tx.wc.rollbackIndexes {
  1093. delete(tx.db.idxs, name)
  1094. if idx != nil {
  1095. // When an index is not nil, we will need to rebuilt that index
  1096. // this could be an expensive process if the database has many
  1097. // items or the index is complex.
  1098. tx.db.idxs[name] = idx
  1099. idx.rebuild()
  1100. }
  1101. }
  1102. }
  1103. // Commit writes all changes to disk.
  1104. // An error is returned when a write error occurs, or when a Commit() is called
  1105. // from a read-only transaction.
  1106. func (tx *Tx) Commit() error {
  1107. if tx.funcd {
  1108. panic("managed tx commit not allowed")
  1109. }
  1110. if tx.db == nil {
  1111. return ErrTxClosed
  1112. } else if !tx.writable {
  1113. return ErrTxNotWritable
  1114. }
  1115. var err error
  1116. if tx.db.persist && (len(tx.wc.commitItems) > 0 || tx.wc.rbkeys != nil) {
  1117. tx.db.buf = tx.db.buf[:0]
  1118. // write a flushdb if a deleteAll was called.
  1119. if tx.wc.rbkeys != nil {
  1120. tx.db.buf = append(tx.db.buf, "*1\r\n$7\r\nflushdb\r\n"...)
  1121. }
  1122. now := time.Now()
  1123. // Each committed record is written to disk
  1124. for key, item := range tx.wc.commitItems {
  1125. if item == nil {
  1126. tx.db.buf = (&dbItem{key: key}).writeDeleteTo(tx.db.buf)
  1127. } else {
  1128. tx.db.buf = item.writeSetTo(tx.db.buf, now)
  1129. }
  1130. }
  1131. // Flushing the buffer only once per transaction.
  1132. // If this operation fails then the write did failed and we must
  1133. // rollback.
  1134. var n int
  1135. n, err = tx.db.file.Write(tx.db.buf)
  1136. if err != nil {
  1137. if n > 0 {
  1138. // There was a partial write to disk.
  1139. // We are possibly out of disk space.
  1140. // Delete the partially written bytes from the data file by
  1141. // seeking to the previously known position and performing
  1142. // a truncate operation.
  1143. // At this point a syscall failure is fatal and the process
  1144. // should be killed to avoid corrupting the file.
  1145. pos, err := tx.db.file.Seek(-int64(n), 1)
  1146. if err != nil {
  1147. panicErr(err)
  1148. }
  1149. if err := tx.db.file.Truncate(pos); err != nil {
  1150. panicErr(err)
  1151. }
  1152. }
  1153. tx.rollbackInner()
  1154. }
  1155. if tx.db.config.SyncPolicy == Always {
  1156. _ = tx.db.file.Sync()
  1157. }
  1158. // Increment the number of flushes. The background syncing uses this.
  1159. tx.db.flushes++
  1160. }
  1161. // Unlock the database and allow for another writable transaction.
  1162. tx.unlock()
  1163. // Clear the db field to disable this transaction from future use.
  1164. tx.db = nil
  1165. return err
  1166. }
  1167. // Rollback closes the transaction and reverts all mutable operations that
  1168. // were performed on the transaction such as Set() and Delete().
  1169. //
  1170. // Read-only transactions can only be rolled back, not committed.
  1171. func (tx *Tx) Rollback() error {
  1172. if tx.funcd {
  1173. panic("managed tx rollback not allowed")
  1174. }
  1175. if tx.db == nil {
  1176. return ErrTxClosed
  1177. }
  1178. // The rollback func does the heavy lifting.
  1179. if tx.writable {
  1180. tx.rollbackInner()
  1181. }
  1182. // unlock the database for more transactions.
  1183. tx.unlock()
  1184. // Clear the db field to disable this transaction from future use.
  1185. tx.db = nil
  1186. return nil
  1187. }
  1188. // dbItemOpts holds various meta information about an item.
  1189. type dbItemOpts struct {
  1190. ex bool // does this item expire?
  1191. exat time.Time // when does this item expire?
  1192. }
  1193. type dbItem struct {
  1194. key, val string // the binary key and value
  1195. opts *dbItemOpts // optional meta information
  1196. keyless bool // keyless item for scanning
  1197. }
  1198. // estIntSize returns the string representions size.
  1199. // Has the same result as len(strconv.Itoa(x)).
  1200. func estIntSize(x int) int {
  1201. n := 1
  1202. if x < 0 {
  1203. n++
  1204. x *= -1
  1205. }
  1206. for x >= 10 {
  1207. n++
  1208. x /= 10
  1209. }
  1210. return n
  1211. }
  1212. func estArraySize(count int) int {
  1213. return 1 + estIntSize(count) + 2
  1214. }
  1215. func estBulkStringSize(s string) int {
  1216. return 1 + estIntSize(len(s)) + 2 + len(s) + 2
  1217. }
  1218. // estAOFSetSize returns an estimated number of bytes that this item will use
  1219. // when stored in the aof file.
  1220. func (dbi *dbItem) estAOFSetSize() int {
  1221. var n int
  1222. if dbi.opts != nil && dbi.opts.ex {
  1223. n += estArraySize(5)
  1224. n += estBulkStringSize("set")
  1225. n += estBulkStringSize(dbi.key)
  1226. n += estBulkStringSize(dbi.val)
  1227. n += estBulkStringSize("ex")
  1228. n += estBulkStringSize("99") // estimate two byte bulk string
  1229. } else {
  1230. n += estArraySize(3)
  1231. n += estBulkStringSize("set")
  1232. n += estBulkStringSize(dbi.key)
  1233. n += estBulkStringSize(dbi.val)
  1234. }
  1235. return n
  1236. }
  1237. func appendArray(buf []byte, count int) []byte {
  1238. buf = append(buf, '*')
  1239. buf = strconv.AppendInt(buf, int64(count), 10)
  1240. buf = append(buf, '\r', '\n')
  1241. return buf
  1242. }
  1243. func appendBulkString(buf []byte, s string) []byte {
  1244. buf = append(buf, '$')
  1245. buf = strconv.AppendInt(buf, int64(len(s)), 10)
  1246. buf = append(buf, '\r', '\n')
  1247. buf = append(buf, s...)
  1248. buf = append(buf, '\r', '\n')
  1249. return buf
  1250. }
  1251. // writeSetTo writes an item as a single SET record to the a bufio Writer.
  1252. func (dbi *dbItem) writeSetTo(buf []byte, now time.Time) []byte {
  1253. if dbi.opts != nil && dbi.opts.ex {
  1254. ex := dbi.opts.exat.Sub(now) / time.Second
  1255. buf = appendArray(buf, 5)
  1256. buf = appendBulkString(buf, "set")
  1257. buf = appendBulkString(buf, dbi.key)
  1258. buf = appendBulkString(buf, dbi.val)
  1259. buf = appendBulkString(buf, "ex")
  1260. buf = appendBulkString(buf, strconv.FormatUint(uint64(ex), 10))
  1261. } else {
  1262. buf = appendArray(buf, 3)
  1263. buf = appendBulkString(buf, "set")
  1264. buf = appendBulkString(buf, dbi.key)
  1265. buf = appendBulkString(buf, dbi.val)
  1266. }
  1267. return buf
  1268. }
  1269. // writeSetTo writes an item as a single DEL record to the a bufio Writer.
  1270. func (dbi *dbItem) writeDeleteTo(buf []byte) []byte {
  1271. buf = appendArray(buf, 2)
  1272. buf = appendBulkString(buf, "del")
  1273. buf = appendBulkString(buf, dbi.key)
  1274. return buf
  1275. }
  1276. // expired evaluates id the item has expired. This will always return false when
  1277. // the item does not have `opts.ex` set to true.
  1278. func (dbi *dbItem) expired() bool {
  1279. return dbi.opts != nil && dbi.opts.ex && time.Now().After(dbi.opts.exat)
  1280. }
  1281. // MaxTime from http://stackoverflow.com/questions/25065055#32620397
  1282. // This is a long time in the future. It's an imaginary number that is
  1283. // used for b-tree ordering.
  1284. var maxTime = time.Unix(1<<63-62135596801, 999999999)
  1285. // expiresAt will return the time when the item will expire. When an item does
  1286. // not expire `maxTime` is used.
  1287. func (dbi *dbItem) expiresAt() time.Time {
  1288. if dbi.opts == nil || !dbi.opts.ex {
  1289. return maxTime
  1290. }
  1291. return dbi.opts.exat
  1292. }
  1293. // Less determines if a b-tree item is less than another. This is required
  1294. // for ordering, inserting, and deleting items from a b-tree. It's important
  1295. // to note that the ctx parameter is used to help with determine which
  1296. // formula to use on an item. Each b-tree should use a different ctx when
  1297. // sharing the same item.
  1298. func (dbi *dbItem) Less(dbi2 *dbItem, ctx interface{}) bool {
  1299. switch ctx := ctx.(type) {
  1300. case *exctx:
  1301. // The expires b-tree formula
  1302. if dbi2.expiresAt().After(dbi.expiresAt()) {
  1303. return true
  1304. }
  1305. if dbi.expiresAt().After(dbi2.expiresAt()) {
  1306. return false
  1307. }
  1308. case *index:
  1309. if ctx.less != nil {
  1310. // Using an index
  1311. if ctx.less(dbi.val, dbi2.val) {
  1312. return true
  1313. }
  1314. if ctx.less(dbi2.val, dbi.val) {
  1315. return false
  1316. }
  1317. }
  1318. }
  1319. // Always fall back to the key comparison. This creates absolute uniqueness.
  1320. if dbi.keyless {
  1321. return false
  1322. } else if dbi2.keyless {
  1323. return true
  1324. }
  1325. return dbi.key < dbi2.key
  1326. }
  1327. func lessCtx(ctx interface{}) func(a, b interface{}) bool {
  1328. return func(a, b interface{}) bool {
  1329. return a.(*dbItem).Less(b.(*dbItem), ctx)
  1330. }
  1331. }
  1332. // Rect converts a string to a rectangle.
  1333. // An invalid rectangle will cause a panic.
  1334. func (dbi *dbItem) Rect(ctx interface{}) (min, max []float64) {
  1335. switch ctx := ctx.(type) {
  1336. case *index:
  1337. return ctx.rect(dbi.val)
  1338. }
  1339. return nil, nil
  1340. }
  1341. // SetOptions represents options that may be included with the Set() command.
  1342. type SetOptions struct {
  1343. // Expires indicates that the Set() key-value will expire
  1344. Expires bool
  1345. // TTL is how much time the key-value will exist in the database
  1346. // before being evicted. The Expires field must also be set to true.
  1347. // TTL stands for Time-To-Live.
  1348. TTL time.Duration
  1349. }
  1350. // GetLess returns the less function for an index. This is handy for
  1351. // doing ad-hoc compares inside a transaction.
  1352. // Returns ErrNotFound if the index is not found or there is no less
  1353. // function bound to the index
  1354. func (tx *Tx) GetLess(index string) (func(a, b string) bool, error) {
  1355. if tx.db == nil {
  1356. return nil, ErrTxClosed
  1357. }
  1358. idx, ok := tx.db.idxs[index]
  1359. if !ok || idx.less == nil {
  1360. return nil, ErrNotFound
  1361. }
  1362. return idx.less, nil
  1363. }
  1364. // GetRect returns the rect function for an index. This is handy for
  1365. // doing ad-hoc searches inside a transaction.
  1366. // Returns ErrNotFound if the index is not found or there is no rect
  1367. // function bound to the index
  1368. func (tx *Tx) GetRect(index string) (func(s string) (min, max []float64),
  1369. error) {
  1370. if tx.db == nil {
  1371. return nil, ErrTxClosed
  1372. }
  1373. idx, ok := tx.db.idxs[index]
  1374. if !ok || idx.rect == nil {
  1375. return nil, ErrNotFound
  1376. }
  1377. return idx.rect, nil
  1378. }
  1379. // Set inserts or replaces an item in the database based on the key.
  1380. // The opt params may be used for additional functionality such as forcing
  1381. // the item to be evicted at a specified time. When the return value
  1382. // for err is nil the operation succeeded. When the return value of
  1383. // replaced is true, then the operaton replaced an existing item whose
  1384. // value will be returned through the previousValue variable.
  1385. // The results of this operation will not be available to other
  1386. // transactions until the current transaction has successfully committed.
  1387. //
  1388. // Only a writable transaction can be used with this operation.
  1389. // This operation is not allowed during iterations such as Ascend* & Descend*.
  1390. func (tx *Tx) Set(key, value string, opts *SetOptions) (previousValue string,
  1391. replaced bool, err error) {
  1392. if tx.db == nil {
  1393. return "", false, ErrTxClosed
  1394. } else if !tx.writable {
  1395. return "", false, ErrTxNotWritable
  1396. } else if tx.wc.itercount > 0 {
  1397. return "", false, ErrTxIterating
  1398. }
  1399. item := &dbItem{key: key, val: value}
  1400. if opts != nil {
  1401. if opts.Expires {
  1402. // The caller is requesting that this item expires. Convert the
  1403. // TTL to an absolute time and bind it to the item.
  1404. item.opts = &dbItemOpts{ex: true, exat: time.Now().Add(opts.TTL)}
  1405. }
  1406. }
  1407. // Insert the item into the keys tree.
  1408. prev := tx.db.insertIntoDatabase(item)
  1409. // insert into the rollback map if there has not been a deleteAll.
  1410. if tx.wc.rbkeys == nil {
  1411. if prev == nil {
  1412. // An item with the same key did not previously exist. Let's
  1413. // create a rollback entry with a nil value. A nil value indicates
  1414. // that the entry should be deleted on rollback. When the value is
  1415. // *not* nil, that means the entry should be reverted.
  1416. if _, ok := tx.wc.rollbackItems[key]; !ok {
  1417. tx.wc.rollbackItems[key] = nil
  1418. }
  1419. } else {
  1420. // A previous item already exists in the database. Let's create a
  1421. // rollback entry with the item as the value. We need to check the
  1422. // map to see if there isn't already an item that matches the
  1423. // same key.
  1424. if _, ok := tx.wc.rollbackItems[key]; !ok {
  1425. tx.wc.rollbackItems[key] = prev
  1426. }
  1427. if !prev.expired() {
  1428. previousValue, replaced = prev.val, true
  1429. }
  1430. }
  1431. }
  1432. // For commits we simply assign the item to the map. We use this map to
  1433. // write the entry to disk.
  1434. if tx.db.persist {
  1435. tx.wc.commitItems[key] = item
  1436. }
  1437. return previousValue, replaced, nil
  1438. }
  1439. // Get returns a value for a key. If the item does not exist or if the item
  1440. // has expired then ErrNotFound is returned. If ignoreExpired is true, then
  1441. // the found value will be returned even if it is expired.
  1442. func (tx *Tx) Get(key string, ignoreExpired ...bool) (val string, err error) {
  1443. if tx.db == nil {
  1444. return "", ErrTxClosed
  1445. }
  1446. var ignore bool
  1447. if len(ignoreExpired) != 0 {
  1448. ignore = ignoreExpired[0]
  1449. }
  1450. item := tx.db.get(key)
  1451. if item == nil || (item.expired() && !ignore) {
  1452. // The item does not exists or has expired. Let's assume that
  1453. // the caller is only interested in items that have not expired.
  1454. return "", ErrNotFound
  1455. }
  1456. return item.val, nil
  1457. }
  1458. // Delete removes an item from the database based on the item's key. If the item
  1459. // does not exist or if the item has expired then ErrNotFound is returned.
  1460. //
  1461. // Only a writable transaction can be used for this operation.
  1462. // This operation is not allowed during iterations such as Ascend* & Descend*.
  1463. func (tx *Tx) Delete(key string) (val string, err error) {
  1464. if tx.db == nil {
  1465. return "", ErrTxClosed
  1466. } else if !tx.writable {
  1467. return "", ErrTxNotWritable
  1468. } else if tx.wc.itercount > 0 {
  1469. return "", ErrTxIterating
  1470. }
  1471. item := tx.db.deleteFromDatabase(&dbItem{key: key})
  1472. if item == nil {
  1473. return "", ErrNotFound
  1474. }
  1475. // create a rollback entry if there has not been a deleteAll call.
  1476. if tx.wc.rbkeys == nil {
  1477. if _, ok := tx.wc.rollbackItems[key]; !ok {
  1478. tx.wc.rollbackItems[key] = item
  1479. }
  1480. }
  1481. if tx.db.persist {
  1482. tx.wc.commitItems[key] = nil
  1483. }
  1484. // Even though the item has been deleted, we still want to check
  1485. // if it has expired. An expired item should not be returned.
  1486. if item.expired() {
  1487. // The item exists in the tree, but has expired. Let's assume that
  1488. // the caller is only interested in items that have not expired.
  1489. return "", ErrNotFound
  1490. }
  1491. return item.val, nil
  1492. }
  1493. // TTL returns the remaining time-to-live for an item.
  1494. // A negative duration will be returned for items that do not have an
  1495. // expiration.
  1496. func (tx *Tx) TTL(key string) (time.Duration, error) {
  1497. if tx.db == nil {
  1498. return 0, ErrTxClosed
  1499. }
  1500. item := tx.db.get(key)
  1501. if item == nil {
  1502. return 0, ErrNotFound
  1503. } else if item.opts == nil || !item.opts.ex {
  1504. return -1, nil
  1505. }
  1506. dur := time.Until(item.opts.exat)
  1507. if dur < 0 {
  1508. return 0, ErrNotFound
  1509. }
  1510. return dur, nil
  1511. }
  1512. // scan iterates through a specified index and calls user-defined iterator
  1513. // function for each item encountered.
  1514. // The desc param indicates that the iterator should descend.
  1515. // The gt param indicates that there is a greaterThan limit.
  1516. // The lt param indicates that there is a lessThan limit.
  1517. // The index param tells the scanner to use the specified index tree. An
  1518. // empty string for the index means to scan the keys, not the values.
  1519. // The start and stop params are the greaterThan, lessThan limits. For
  1520. // descending order, these will be lessThan, greaterThan.
  1521. // An error will be returned if the tx is closed or the index is not found.
  1522. func (tx *Tx) scan(desc, gt, lt bool, index, start, stop string,
  1523. iterator func(key, value string) bool) error {
  1524. if tx.db == nil {
  1525. return ErrTxClosed
  1526. }
  1527. // wrap a btree specific iterator around the user-defined iterator.
  1528. iter := func(item interface{}) bool {
  1529. dbi := item.(*dbItem)
  1530. return iterator(dbi.key, dbi.val)
  1531. }
  1532. var tr *btree.BTree
  1533. if index == "" {
  1534. // empty index means we will use the keys tree.
  1535. tr = tx.db.keys
  1536. } else {
  1537. idx := tx.db.idxs[index]
  1538. if idx == nil {
  1539. // index was not found. return error
  1540. return ErrNotFound
  1541. }
  1542. tr = idx.btr
  1543. if tr == nil {
  1544. return nil
  1545. }
  1546. }
  1547. // create some limit items
  1548. var itemA, itemB *dbItem
  1549. if gt || lt {
  1550. if index == "" {
  1551. itemA = &dbItem{key: start}
  1552. itemB = &dbItem{key: stop}
  1553. } else {
  1554. itemA = &dbItem{val: start}
  1555. itemB = &dbItem{val: stop}
  1556. if desc {
  1557. itemA.keyless = true
  1558. itemB.keyless = true
  1559. }
  1560. }
  1561. }
  1562. // execute the scan on the underlying tree.
  1563. if tx.wc != nil {
  1564. tx.wc.itercount++
  1565. defer func() {
  1566. tx.wc.itercount--
  1567. }()
  1568. }
  1569. if desc {
  1570. if gt {
  1571. if lt {
  1572. btreeDescendRange(tr, itemA, itemB, iter)
  1573. } else {
  1574. btreeDescendGreaterThan(tr, itemA, iter)
  1575. }
  1576. } else if lt {
  1577. btreeDescendLessOrEqual(tr, itemA, iter)
  1578. } else {
  1579. btreeDescend(tr, iter)
  1580. }
  1581. } else {
  1582. if gt {
  1583. if lt {
  1584. btreeAscendRange(tr, itemA, itemB, iter)
  1585. } else {
  1586. btreeAscendGreaterOrEqual(tr, itemA, iter)
  1587. }
  1588. } else if lt {
  1589. btreeAscendLessThan(tr, itemA, iter)
  1590. } else {
  1591. btreeAscend(tr, iter)
  1592. }
  1593. }
  1594. return nil
  1595. }
  1596. // Match returns true if the specified key matches the pattern. This is a very
  1597. // simple pattern matcher where '*' matches on any number characters and '?'
  1598. // matches on any one character.
  1599. func Match(key, pattern string) bool {
  1600. return match.Match(key, pattern)
  1601. }
  1602. // AscendKeys allows for iterating through keys based on the specified pattern.
  1603. func (tx *Tx) AscendKeys(pattern string,
  1604. iterator func(key, value string) bool) error {
  1605. if pattern == "" {
  1606. return nil
  1607. }
  1608. if pattern[0] == '*' {
  1609. if pattern == "*" {
  1610. return tx.Ascend("", iterator)
  1611. }
  1612. return tx.Ascend("", func(key, value string) bool {
  1613. if match.Match(key, pattern) {
  1614. if !iterator(key, value) {
  1615. return false
  1616. }
  1617. }
  1618. return true
  1619. })
  1620. }
  1621. min, max := match.Allowable(pattern)
  1622. return tx.AscendGreaterOrEqual("", min, func(key, value string) bool {
  1623. if key > max {
  1624. return false
  1625. }
  1626. if match.Match(key, pattern) {
  1627. if !iterator(key, value) {
  1628. return false
  1629. }
  1630. }
  1631. return true
  1632. })
  1633. }
  1634. // DescendKeys allows for iterating through keys based on the specified pattern.
  1635. func (tx *Tx) DescendKeys(pattern string,
  1636. iterator func(key, value string) bool) error {
  1637. if pattern == "" {
  1638. return nil
  1639. }
  1640. if pattern[0] == '*' {
  1641. if pattern == "*" {
  1642. return tx.Descend("", iterator)
  1643. }
  1644. return tx.Descend("", func(key, value string) bool {
  1645. if match.Match(key, pattern) {
  1646. if !iterator(key, value) {
  1647. return false
  1648. }
  1649. }
  1650. return true
  1651. })
  1652. }
  1653. min, max := match.Allowable(pattern)
  1654. return tx.DescendLessOrEqual("", max, func(key, value string) bool {
  1655. if key < min {
  1656. return false
  1657. }
  1658. if match.Match(key, pattern) {
  1659. if !iterator(key, value) {
  1660. return false
  1661. }
  1662. }
  1663. return true
  1664. })
  1665. }
  1666. // Ascend calls the iterator for every item in the database within the range
  1667. // [first, last], until iterator returns false.
  1668. // When an index is provided, the results will be ordered by the item values
  1669. // as specified by the less() function of the defined index.
  1670. // When an index is not provided, the results will be ordered by the item key.
  1671. // An invalid index will return an error.
  1672. func (tx *Tx) Ascend(index string,
  1673. iterator func(key, value string) bool) error {
  1674. return tx.scan(false, false, false, index, "", "", iterator)
  1675. }
  1676. // AscendGreaterOrEqual calls the iterator for every item in the database within
  1677. // the range [pivot, last], until iterator returns false.
  1678. // When an index is provided, the results will be ordered by the item values
  1679. // as specified by the less() function of the defined index.
  1680. // When an index is not provided, the results will be ordered by the item key.
  1681. // An invalid index will return an error.
  1682. func (tx *Tx) AscendGreaterOrEqual(index, pivot string,
  1683. iterator func(key, value string) bool) error {
  1684. return tx.scan(false, true, false, index, pivot, "", iterator)
  1685. }
  1686. // AscendLessThan calls the iterator for every item in the database within the
  1687. // range [first, pivot), until iterator returns false.
  1688. // When an index is provided, the results will be ordered by the item values
  1689. // as specified by the less() function of the defined index.
  1690. // When an index is not provided, the results will be ordered by the item key.
  1691. // An invalid index will return an error.
  1692. func (tx *Tx) AscendLessThan(index, pivot string,
  1693. iterator func(key, value string) bool) error {
  1694. return tx.scan(false, false, true, index, pivot, "", iterator)
  1695. }
  1696. // AscendRange calls the iterator for every item in the database within
  1697. // the range [greaterOrEqual, lessThan), until iterator returns false.
  1698. // When an index is provided, the results will be ordered by the item values
  1699. // as specified by the less() function of the defined index.
  1700. // When an index is not provided, the results will be ordered by the item key.
  1701. // An invalid index will return an error.
  1702. func (tx *Tx) AscendRange(index, greaterOrEqual, lessThan string,
  1703. iterator func(key, value string) bool) error {
  1704. return tx.scan(
  1705. false, true, true, index, greaterOrEqual, lessThan, iterator,
  1706. )
  1707. }
  1708. // Descend calls the iterator for every item in the database within the range
  1709. // [last, first], until iterator returns false.
  1710. // When an index is provided, the results will be ordered by the item values
  1711. // as specified by the less() function of the defined index.
  1712. // When an index is not provided, the results will be ordered by the item key.
  1713. // An invalid index will return an error.
  1714. func (tx *Tx) Descend(index string,
  1715. iterator func(key, value string) bool) error {
  1716. return tx.scan(true, false, false, index, "", "", iterator)
  1717. }
  1718. // DescendGreaterThan calls the iterator for every item in the database within
  1719. // the range [last, pivot), until iterator returns false.
  1720. // When an index is provided, the results will be ordered by the item values
  1721. // as specified by the less() function of the defined index.
  1722. // When an index is not provided, the results will be ordered by the item key.
  1723. // An invalid index will return an error.
  1724. func (tx *Tx) DescendGreaterThan(index, pivot string,
  1725. iterator func(key, value string) bool) error {
  1726. return tx.scan(true, true, false, index, pivot, "", iterator)
  1727. }
  1728. // DescendLessOrEqual calls the iterator for every item in the database within
  1729. // the range [pivot, first], until iterator returns false.
  1730. // When an index is provided, the results will be ordered by the item values
  1731. // as specified by the less() function of the defined index.
  1732. // When an index is not provided, the results will be ordered by the item key.
  1733. // An invalid index will return an error.
  1734. func (tx *Tx) DescendLessOrEqual(index, pivot string,
  1735. iterator func(key, value string) bool) error {
  1736. return tx.scan(true, false, true, index, pivot, "", iterator)
  1737. }
  1738. // DescendRange calls the iterator for every item in the database within
  1739. // the range [lessOrEqual, greaterThan), until iterator returns false.
  1740. // When an index is provided, the results will be ordered by the item values
  1741. // as specified by the less() function of the defined index.
  1742. // When an index is not provided, the results will be ordered by the item key.
  1743. // An invalid index will return an error.
  1744. func (tx *Tx) DescendRange(index, lessOrEqual, greaterThan string,
  1745. iterator func(key, value string) bool) error {
  1746. return tx.scan(
  1747. true, true, true, index, lessOrEqual, greaterThan, iterator,
  1748. )
  1749. }
  1750. // AscendEqual calls the iterator for every item in the database that equals
  1751. // pivot, until iterator returns false.
  1752. // When an index is provided, the results will be ordered by the item values
  1753. // as specified by the less() function of the defined index.
  1754. // When an index is not provided, the results will be ordered by the item key.
  1755. // An invalid index will return an error.
  1756. func (tx *Tx) AscendEqual(index, pivot string,
  1757. iterator func(key, value string) bool) error {
  1758. var err error
  1759. var less func(a, b string) bool
  1760. if index != "" {
  1761. less, err = tx.GetLess(index)
  1762. if err != nil {
  1763. return err
  1764. }
  1765. }
  1766. return tx.AscendGreaterOrEqual(index, pivot, func(key, value string) bool {
  1767. if less == nil {
  1768. if key != pivot {
  1769. return false
  1770. }
  1771. } else if less(pivot, value) {
  1772. return false
  1773. }
  1774. return iterator(key, value)
  1775. })
  1776. }
  1777. // DescendEqual calls the iterator for every item in the database that equals
  1778. // pivot, until iterator returns false.
  1779. // When an index is provided, the results will be ordered by the item values
  1780. // as specified by the less() function of the defined index.
  1781. // When an index is not provided, the results will be ordered by the item key.
  1782. // An invalid index will return an error.
  1783. func (tx *Tx) DescendEqual(index, pivot string,
  1784. iterator func(key, value string) bool) error {
  1785. var err error
  1786. var less func(a, b string) bool
  1787. if index != "" {
  1788. less, err = tx.GetLess(index)
  1789. if err != nil {
  1790. return err
  1791. }
  1792. }
  1793. return tx.DescendLessOrEqual(index, pivot, func(key, value string) bool {
  1794. if less == nil {
  1795. if key != pivot {
  1796. return false
  1797. }
  1798. } else if less(value, pivot) {
  1799. return false
  1800. }
  1801. return iterator(key, value)
  1802. })
  1803. }
  1804. // rect is used by Intersects and Nearby
  1805. type rect struct {
  1806. min, max []float64
  1807. }
  1808. func (r *rect) Rect(ctx interface{}) (min, max []float64) {
  1809. return r.min, r.max
  1810. }
  1811. // Nearby searches for rectangle items that are nearby a target rect.
  1812. // All items belonging to the specified index will be returned in order of
  1813. // nearest to farthest.
  1814. // The specified index must have been created by AddIndex() and the target
  1815. // is represented by the rect string. This string will be processed by the
  1816. // same bounds function that was passed to the CreateSpatialIndex() function.
  1817. // An invalid index will return an error.
  1818. // The dist param is the distance of the bounding boxes. In the case of
  1819. // simple 2D points, it's the distance of the two 2D points squared.
  1820. func (tx *Tx) Nearby(index, bounds string,
  1821. iterator func(key, value string, dist float64) bool) error {
  1822. if tx.db == nil {
  1823. return ErrTxClosed
  1824. }
  1825. if index == "" {
  1826. // cannot search on keys tree. just return nil.
  1827. return nil
  1828. }
  1829. // // wrap a rtree specific iterator around the user-defined iterator.
  1830. iter := func(item rtred.Item, dist float64) bool {
  1831. dbi := item.(*dbItem)
  1832. return iterator(dbi.key, dbi.val, dist)
  1833. }
  1834. idx := tx.db.idxs[index]
  1835. if idx == nil {
  1836. // index was not found. return error
  1837. return ErrNotFound
  1838. }
  1839. if idx.rtr == nil {
  1840. // not an r-tree index. just return nil
  1841. return nil
  1842. }
  1843. // execute the nearby search
  1844. var min, max []float64
  1845. if idx.rect != nil {
  1846. min, max = idx.rect(bounds)
  1847. }
  1848. // set the center param to false, which uses the box dist calc.
  1849. idx.rtr.KNN(&rect{min, max}, false, iter)
  1850. return nil
  1851. }
  1852. // Intersects searches for rectangle items that intersect a target rect.
  1853. // The specified index must have been created by AddIndex() and the target
  1854. // is represented by the rect string. This string will be processed by the
  1855. // same bounds function that was passed to the CreateSpatialIndex() function.
  1856. // An invalid index will return an error.
  1857. func (tx *Tx) Intersects(index, bounds string,
  1858. iterator func(key, value string) bool) error {
  1859. if tx.db == nil {
  1860. return ErrTxClosed
  1861. }
  1862. if index == "" {
  1863. // cannot search on keys tree. just return nil.
  1864. return nil
  1865. }
  1866. // wrap a rtree specific iterator around the user-defined iterator.
  1867. iter := func(item rtred.Item) bool {
  1868. dbi := item.(*dbItem)
  1869. return iterator(dbi.key, dbi.val)
  1870. }
  1871. idx := tx.db.idxs[index]
  1872. if idx == nil {
  1873. // index was not found. return error
  1874. return ErrNotFound
  1875. }
  1876. if idx.rtr == nil {
  1877. // not an r-tree index. just return nil
  1878. return nil
  1879. }
  1880. // execute the search
  1881. var min, max []float64
  1882. if idx.rect != nil {
  1883. min, max = idx.rect(bounds)
  1884. }
  1885. idx.rtr.Search(&rect{min, max}, iter)
  1886. return nil
  1887. }
  1888. // Len returns the number of items in the database
  1889. func (tx *Tx) Len() (int, error) {
  1890. if tx.db == nil {
  1891. return 0, ErrTxClosed
  1892. }
  1893. return tx.db.keys.Len(), nil
  1894. }
  1895. // IndexOptions provides an index with additional features or
  1896. // alternate functionality.
  1897. type IndexOptions struct {
  1898. // CaseInsensitiveKeyMatching allow for case-insensitive
  1899. // matching on keys when setting key/values.
  1900. CaseInsensitiveKeyMatching bool
  1901. }
  1902. // CreateIndex builds a new index and populates it with items.
  1903. // The items are ordered in an b-tree and can be retrieved using the
  1904. // Ascend* and Descend* methods.
  1905. // An error will occur if an index with the same name already exists.
  1906. //
  1907. // When a pattern is provided, the index will be populated with
  1908. // keys that match the specified pattern. This is a very simple pattern
  1909. // match where '*' matches on any number characters and '?' matches on
  1910. // any one character.
  1911. // The less function compares if string 'a' is less than string 'b'.
  1912. // It allows for indexes to create custom ordering. It's possible
  1913. // that the strings may be textual or binary. It's up to the provided
  1914. // less function to handle the content format and comparison.
  1915. // There are some default less function that can be used such as
  1916. // IndexString, IndexBinary, etc.
  1917. func (tx *Tx) CreateIndex(name, pattern string,
  1918. less ...func(a, b string) bool) error {
  1919. return tx.createIndex(name, pattern, less, nil, nil)
  1920. }
  1921. // CreateIndexOptions is the same as CreateIndex except that it allows
  1922. // for additional options.
  1923. func (tx *Tx) CreateIndexOptions(name, pattern string,
  1924. opts *IndexOptions,
  1925. less ...func(a, b string) bool) error {
  1926. return tx.createIndex(name, pattern, less, nil, opts)
  1927. }
  1928. // CreateSpatialIndex builds a new index and populates it with items.
  1929. // The items are organized in an r-tree and can be retrieved using the
  1930. // Intersects method.
  1931. // An error will occur if an index with the same name already exists.
  1932. //
  1933. // The rect function converts a string to a rectangle. The rectangle is
  1934. // represented by two arrays, min and max. Both arrays may have a length
  1935. // between 1 and 20, and both arrays must match in length. A length of 1 is a
  1936. // one dimensional rectangle, and a length of 4 is a four dimension rectangle.
  1937. // There is support for up to 20 dimensions.
  1938. // The values of min must be less than the values of max at the same dimension.
  1939. // Thus min[0] must be less-than-or-equal-to max[0].
  1940. // The IndexRect is a default function that can be used for the rect
  1941. // parameter.
  1942. func (tx *Tx) CreateSpatialIndex(name, pattern string,
  1943. rect func(item string) (min, max []float64)) error {
  1944. return tx.createIndex(name, pattern, nil, rect, nil)
  1945. }
  1946. // CreateSpatialIndexOptions is the same as CreateSpatialIndex except that
  1947. // it allows for additional options.
  1948. func (tx *Tx) CreateSpatialIndexOptions(name, pattern string,
  1949. opts *IndexOptions,
  1950. rect func(item string) (min, max []float64)) error {
  1951. return tx.createIndex(name, pattern, nil, rect, nil)
  1952. }
  1953. // createIndex is called by CreateIndex() and CreateSpatialIndex()
  1954. func (tx *Tx) createIndex(name string, pattern string,
  1955. lessers []func(a, b string) bool,
  1956. rect func(item string) (min, max []float64),
  1957. opts *IndexOptions,
  1958. ) error {
  1959. if tx.db == nil {
  1960. return ErrTxClosed
  1961. } else if !tx.writable {
  1962. return ErrTxNotWritable
  1963. } else if tx.wc.itercount > 0 {
  1964. return ErrTxIterating
  1965. }
  1966. if name == "" {
  1967. // cannot create an index without a name.
  1968. // an empty name index is designated for the main "keys" tree.
  1969. return ErrIndexExists
  1970. }
  1971. // check if an index with that name already exists.
  1972. if _, ok := tx.db.idxs[name]; ok {
  1973. // index with name already exists. error.
  1974. return ErrIndexExists
  1975. }
  1976. // genreate a less function
  1977. var less func(a, b string) bool
  1978. switch len(lessers) {
  1979. default:
  1980. // multiple less functions specified.
  1981. // create a compound less function.
  1982. less = func(a, b string) bool {
  1983. for i := 0; i < len(lessers)-1; i++ {
  1984. if lessers[i](a, b) {
  1985. return true
  1986. }
  1987. if lessers[i](b, a) {
  1988. return false
  1989. }
  1990. }
  1991. return lessers[len(lessers)-1](a, b)
  1992. }
  1993. case 0:
  1994. // no less function
  1995. case 1:
  1996. less = lessers[0]
  1997. }
  1998. var sopts IndexOptions
  1999. if opts != nil {
  2000. sopts = *opts
  2001. }
  2002. if sopts.CaseInsensitiveKeyMatching {
  2003. pattern = strings.ToLower(pattern)
  2004. }
  2005. // intialize new index
  2006. idx := &index{
  2007. name: name,
  2008. pattern: pattern,
  2009. less: less,
  2010. rect: rect,
  2011. db: tx.db,
  2012. opts: sopts,
  2013. }
  2014. idx.rebuild()
  2015. // save the index
  2016. tx.db.idxs[name] = idx
  2017. if tx.wc.rbkeys == nil {
  2018. // store the index in the rollback map.
  2019. if _, ok := tx.wc.rollbackIndexes[name]; !ok {
  2020. // we use nil to indicate that the index should be removed upon
  2021. // rollback.
  2022. tx.wc.rollbackIndexes[name] = nil
  2023. }
  2024. }
  2025. return nil
  2026. }
  2027. // DropIndex removes an index.
  2028. func (tx *Tx) DropIndex(name string) error {
  2029. if tx.db == nil {
  2030. return ErrTxClosed
  2031. } else if !tx.writable {
  2032. return ErrTxNotWritable
  2033. } else if tx.wc.itercount > 0 {
  2034. return ErrTxIterating
  2035. }
  2036. if name == "" {
  2037. // cannot drop the default "keys" index
  2038. return ErrInvalidOperation
  2039. }
  2040. idx, ok := tx.db.idxs[name]
  2041. if !ok {
  2042. return ErrNotFound
  2043. }
  2044. // delete from the map.
  2045. // this is all that is needed to delete an index.
  2046. delete(tx.db.idxs, name)
  2047. if tx.wc.rbkeys == nil {
  2048. // store the index in the rollback map.
  2049. if _, ok := tx.wc.rollbackIndexes[name]; !ok {
  2050. // we use a non-nil copy of the index without the data to indicate
  2051. // that the index should be rebuilt upon rollback.
  2052. tx.wc.rollbackIndexes[name] = idx.clearCopy()
  2053. }
  2054. }
  2055. return nil
  2056. }
  2057. // Indexes returns a list of index names.
  2058. func (tx *Tx) Indexes() ([]string, error) {
  2059. if tx.db == nil {
  2060. return nil, ErrTxClosed
  2061. }
  2062. names := make([]string, 0, len(tx.db.idxs))
  2063. for name := range tx.db.idxs {
  2064. names = append(names, name)
  2065. }
  2066. sort.Strings(names)
  2067. return names, nil
  2068. }
  2069. // Rect is helper function that returns a string representation
  2070. // of a rect. IndexRect() is the reverse function and can be used
  2071. // to generate a rect from a string.
  2072. func Rect(min, max []float64) string {
  2073. r := grect.Rect{Min: min, Max: max}
  2074. return r.String()
  2075. }
  2076. // Point is a helper function that converts a series of float64s
  2077. // to a rectangle for a spatial index.
  2078. func Point(coords ...float64) string {
  2079. return Rect(coords, coords)
  2080. }
  2081. // IndexRect is a helper function that converts string to a rect.
  2082. // Rect() is the reverse function and can be used to generate a string
  2083. // from a rect.
  2084. func IndexRect(a string) (min, max []float64) {
  2085. r := grect.Get(a)
  2086. return r.Min, r.Max
  2087. }
  2088. // IndexString is a helper function that return true if 'a' is less than 'b'.
  2089. // This is a case-insensitive comparison. Use the IndexBinary() for comparing
  2090. // case-sensitive strings.
  2091. func IndexString(a, b string) bool {
  2092. for i := 0; i < len(a) && i < len(b); i++ {
  2093. if a[i] >= 'A' && a[i] <= 'Z' {
  2094. if b[i] >= 'A' && b[i] <= 'Z' {
  2095. // both are uppercase, do nothing
  2096. if a[i] < b[i] {
  2097. return true
  2098. } else if a[i] > b[i] {
  2099. return false
  2100. }
  2101. } else {
  2102. // a is uppercase, convert a to lowercase
  2103. if a[i]+32 < b[i] {
  2104. return true
  2105. } else if a[i]+32 > b[i] {
  2106. return false
  2107. }
  2108. }
  2109. } else if b[i] >= 'A' && b[i] <= 'Z' {
  2110. // b is uppercase, convert b to lowercase
  2111. if a[i] < b[i]+32 {
  2112. return true
  2113. } else if a[i] > b[i]+32 {
  2114. return false
  2115. }
  2116. } else {
  2117. // neither are uppercase
  2118. if a[i] < b[i] {
  2119. return true
  2120. } else if a[i] > b[i] {
  2121. return false
  2122. }
  2123. }
  2124. }
  2125. return len(a) < len(b)
  2126. }
  2127. // IndexBinary is a helper function that returns true if 'a' is less than 'b'.
  2128. // This compares the raw binary of the string.
  2129. func IndexBinary(a, b string) bool {
  2130. return a < b
  2131. }
  2132. // IndexInt is a helper function that returns true if 'a' is less than 'b'.
  2133. func IndexInt(a, b string) bool {
  2134. ia, _ := strconv.ParseInt(a, 10, 64)
  2135. ib, _ := strconv.ParseInt(b, 10, 64)
  2136. return ia < ib
  2137. }
  2138. // IndexUint is a helper function that returns true if 'a' is less than 'b'.
  2139. // This compares uint64s that are added to the database using the
  2140. // Uint() conversion function.
  2141. func IndexUint(a, b string) bool {
  2142. ia, _ := strconv.ParseUint(a, 10, 64)
  2143. ib, _ := strconv.ParseUint(b, 10, 64)
  2144. return ia < ib
  2145. }
  2146. // IndexFloat is a helper function that returns true if 'a' is less than 'b'.
  2147. // This compares float64s that are added to the database using the
  2148. // Float() conversion function.
  2149. func IndexFloat(a, b string) bool {
  2150. ia, _ := strconv.ParseFloat(a, 64)
  2151. ib, _ := strconv.ParseFloat(b, 64)
  2152. return ia < ib
  2153. }
  2154. // IndexJSON provides for the ability to create an index on any JSON field.
  2155. // When the field is a string, the comparison will be case-insensitive.
  2156. // It returns a helper function used by CreateIndex.
  2157. func IndexJSON(path string) func(a, b string) bool {
  2158. return func(a, b string) bool {
  2159. return gjson.Get(a, path).Less(gjson.Get(b, path), false)
  2160. }
  2161. }
  2162. // IndexJSONCaseSensitive provides for the ability to create an index on
  2163. // any JSON field.
  2164. // When the field is a string, the comparison will be case-sensitive.
  2165. // It returns a helper function used by CreateIndex.
  2166. func IndexJSONCaseSensitive(path string) func(a, b string) bool {
  2167. return func(a, b string) bool {
  2168. return gjson.Get(a, path).Less(gjson.Get(b, path), true)
  2169. }
  2170. }
  2171. // Desc is a helper function that changes the order of an index.
  2172. func Desc(less func(a, b string) bool) func(a, b string) bool {
  2173. return func(a, b string) bool { return less(b, a) }
  2174. }
  2175. //// Wrappers around btree Ascend/Descend
  2176. func bLT(tr *btree.BTree, a, b interface{}) bool { return tr.Less(a, b) }
  2177. func bGT(tr *btree.BTree, a, b interface{}) bool { return tr.Less(b, a) }
  2178. // func bLTE(tr *btree.BTree, a, b interface{}) bool { return !tr.Less(b, a) }
  2179. // func bGTE(tr *btree.BTree, a, b interface{}) bool { return !tr.Less(a, b) }
  2180. // Ascend
  2181. func btreeAscend(tr *btree.BTree, iter func(item interface{}) bool) {
  2182. tr.Ascend(nil, iter)
  2183. }
  2184. func btreeAscendLessThan(tr *btree.BTree, pivot interface{},
  2185. iter func(item interface{}) bool,
  2186. ) {
  2187. tr.Ascend(nil, func(item interface{}) bool {
  2188. return bLT(tr, item, pivot) && iter(item)
  2189. })
  2190. }
  2191. func btreeAscendGreaterOrEqual(tr *btree.BTree, pivot interface{},
  2192. iter func(item interface{}) bool,
  2193. ) {
  2194. tr.Ascend(pivot, iter)
  2195. }
  2196. func btreeAscendRange(tr *btree.BTree, greaterOrEqual, lessThan interface{},
  2197. iter func(item interface{}) bool,
  2198. ) {
  2199. tr.Ascend(greaterOrEqual, func(item interface{}) bool {
  2200. return bLT(tr, item, lessThan) && iter(item)
  2201. })
  2202. }
  2203. // Descend
  2204. func btreeDescend(tr *btree.BTree, iter func(item interface{}) bool) {
  2205. tr.Descend(nil, iter)
  2206. }
  2207. func btreeDescendGreaterThan(tr *btree.BTree, pivot interface{},
  2208. iter func(item interface{}) bool,
  2209. ) {
  2210. tr.Descend(nil, func(item interface{}) bool {
  2211. return bGT(tr, item, pivot) && iter(item)
  2212. })
  2213. }
  2214. func btreeDescendRange(tr *btree.BTree, lessOrEqual, greaterThan interface{},
  2215. iter func(item interface{}) bool,
  2216. ) {
  2217. tr.Descend(lessOrEqual, func(item interface{}) bool {
  2218. return bGT(tr, item, greaterThan) && iter(item)
  2219. })
  2220. }
  2221. func btreeDescendLessOrEqual(tr *btree.BTree, pivot interface{},
  2222. iter func(item interface{}) bool,
  2223. ) {
  2224. tr.Descend(pivot, iter)
  2225. }
  2226. func btreeNew(less func(a, b interface{}) bool) *btree.BTree {
  2227. // Using NewNonConcurrent because we're managing our own locks.
  2228. return btree.NewNonConcurrent(less)
  2229. }