gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/mpackdb/MPackDB.hl

6.6 KB

  1. \* hl:mpackdb — the MessagePack file database. Construct it and it opens
  2. (the file root IS the constructor):
  3. db = new MPackDB(file = '/tmp/users.db', primaryKey = '*id',
  4. indexes = ['!email', 'age'])
  5. Key prefixes follow the JS API: `*name` auto-increment number pk (a fresh
  6. table counts from 1; an existing one keeps its stored counter), `@name`
  7. uuid pk, plain `name` string pk; a LEADING `!` on an index makes it
  8. unique, `*`/`@` on an index select numeric/uuid key parsing. On-disk
  9. format is compatible with the JS mpackdb 1.0.7 — a db written by either
  10. side is readable and mutable by the other. *\
  11. /* Wraps the Zig engine (plugins/mpackdb/{msgpack,engine}.zig, mission 066).
  12. `>` / `<>` hydration does NOT run the run body — construct with args. */
  13. \* The database is open (fired from the constructor's run body). *\
  14. emit opened(
  15. MPackDB db \\ this database
  16. )
  17. \* Opening failed. *\
  18. emit error(
  19. Hybrid e \\ the failure
  20. )
  21. \* close() finished. *\
  22. emit closed(
  23. MPackDB db \\ this database
  24. )
  25. \* One successful record mutation; delivered synchronously after the store unlocks. *\
  26. emit change(String kind, String op, Number | String key, Hybrid doc, Hybrid prev)
  27. String file = "" \\ the .db path, script-relative
  28. String primaryKey = "" \\ pk declaration: *name | @name | name | '' for none
  29. Hybrid indexes = [] \\ index declarations, '!' prefix = unique
  30. Boolean compact = true \\ compact the file on open
  31. Hybrid #handle
  32. Boolean #warned = false \\ find(null, null) over a big table was reported on stderr already
  33. String #pk \\ the primary key FIELD NAME, prefixes stripped (null when none)
  34. open() {
  35. #handle = __native("mpackdb.open", file, primaryKey, indexes, compact)
  36. if (#handle != null) {
  37. #pk = #handle.pk_name()
  38. emit opened(this)
  39. } else {
  40. emit error({ message = "mpackdb: cannot open " + file + ": " + lastError() })
  41. }
  42. }
  43. open()
  44. \* The primary key field name, prefixes stripped (null when none). *\
  45. pkField() {
  46. return #pk
  47. }
  48. \* Insert one record. Answers the primary key it was stored under (a
  49. generated one for `*`/`@` pks), true for a pk-less db, or null on failure
  50. — lastError() has the reason (e.g. a unique-index violation). *\
  51. put(
  52. Hybrid record \\ the record to store
  53. ) {
  54. return mutate('insert', null, record, null)
  55. }
  56. \* Read only the named top-level fields when fields is a list; null reads all.
  57. First record with this primary key, or null. (Named fetch(), not get():
  58. `get` is reserved for getter syntax.) *\
  59. fetch(key, Hybrid fields = null) {
  60. it = #handle.find_pk(key, fields)
  61. if (it == null) {
  62. return null
  63. }
  64. first = it.next()
  65. // run it to its end: the plugin frees what the lookup read there (hybriel#126)
  66. while (it.next() != null) {}
  67. return first
  68. }
  69. \* Raw iterator over matches. field null → every live record; the pk and any
  70. declared index are binary-searched — other fields need an index declared. *\
  71. iterate(field, value, Hybrid fields = null) {
  72. if (field == null) {
  73. return #handle.find_all(fields)
  74. }
  75. if (field == #pk) {
  76. return #handle.find_pk(value, fields)
  77. }
  78. return #handle.find_index(field, value, fields)
  79. }
  80. \* All matching records as a Hybrid; find(null) answers everything. find(null, null) over more than
  81. 100 000 records prints ONE line per table on stderr (the array holds the whole table decoded:
  82. use iterate() or cursor()); the result is the same. *\
  83. find(field, value, Hybrid fields = null) {
  84. out = drain(iterate(field, value, fields))
  85. if (field == null && value == null && out.length > 100000 && !#warned) {
  86. // one line per table: a whole big table decoded into one array holds ~27x its file in RAM
  87. #warned = true
  88. console.error("mpackdb: " + file + ": find(null, null) built an array of " + out.length + " records; use iterate()")
  89. }
  90. return out
  91. }
  92. \* Ascending index range scan, both bounds inclusive; null bound = open end. *\
  93. range(field, low, high, Hybrid fields = null) {
  94. return drain(#handle.find_range(field, low, high, fields))
  95. }
  96. \* Lazy Cursor over the same matches — records decode one at a time. *\
  97. cursor(field, value, Hybrid fields = null) {
  98. return {
  99. #iter = iterate(field, value, fields)
  100. } > new Cursor()
  101. }
  102. \* Delete every record with this primary key; answers how many went. *\
  103. delete(key) {
  104. return mutate('delete', key, null, null)
  105. }
  106. \* Replace the record(s) at this pk; answers how many were replaced. `record`
  107. need not carry the pk: it is taken from `key` (the JS update() contract). *\
  108. update(key, record) {
  109. return mutate('update', key, record, null)
  110. }
  111. \* Conditional replacement under the store lock. Every named expectation field
  112. uses == against the current record. True means replaced, false means absent
  113. or mismatched, null means failure (lastError()). Like update, key supplies
  114. a missing primary key. *\
  115. compareAndSet(key, Hybrid replacement, Hybrid expect) {
  116. return mutate('compareAndSet', key, replacement, expect)
  117. }
  118. \* Live record count. *\
  119. count() {
  120. return #handle.count()
  121. }
  122. \* Rewrite the data file without tombstones and rebuild the indexes. *\
  123. compactNow() {
  124. #handle.compact()
  125. }
  126. \* Cursors made by any db of this process that are neither exhausted nor closed
  127. (a `for` loop left by break/return closes its cursor at once; mission 404). *\
  128. openCursors() {
  129. return #handle.open_cursors()
  130. }
  131. \* How many cursors a `for` loop closed by leaving early (break/return). *\
  132. earlyCloses() {
  133. return #handle.early_closes()
  134. }
  135. \* Flush meta/index state to disk now. *\
  136. persist() {
  137. #handle.persist()
  138. }
  139. \* Reason for the last failed open/put/update ('' when none). *\
  140. lastError() {
  141. if (#handle == null) { return __native("mpackdb.last_error") }
  142. return #handle.last_error()
  143. }
  144. \* Close the database; the closed event fires. *\
  145. close() {
  146. #handle.close()
  147. emit closed(this)
  148. }
  149. // Internal: collect an iterator into an array.
  150. drain(it) {
  151. let out = []
  152. if (it == null) {
  153. return out
  154. }
  155. for (rec of it) {
  156. out.push(rec)
  157. }
  158. return out
  159. }
  160. \* Insert a missing primary key or replace its record, under one store lock.
  161. Answers the primary key (true without a pk), or null; lastError() gives the reason. *\
  162. upsert(Hybrid record) {
  163. return mutate('upsert', null, record, null)
  164. }
  165. // Consume the owned native result BEFORE emitting: handlers may reenter this db.
  166. mutate(String op, Number | String key, Hybrid record, Hybrid expect) {
  167. it = #handle.mutate(op, key, record, expect)
  168. if (it == null) { return null }
  169. result = it.next()
  170. while (it.next() != null) {}
  171. if (result.kind == 'insert') {
  172. storedKey = #pk == null ? null : result.doc[#pk]
  173. emit change('insert', op, storedKey, result.doc, null)
  174. } else {
  175. for (previous of result.prev) {
  176. storedKey = #pk == null ? null : previous[#pk]
  177. emit change(result.kind, op, storedKey, result.doc, previous)
  178. }
  179. }
  180. return result.answer
  181. }

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre