選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

buntdb.go 66KB

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