primary_handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. package index
  2. import (
  3. "TsDB2/DB/core/index/btree"
  4. "TsDB2/DB/core/index/datapage"
  5. "TsDB2/DB/core/page"
  6. "encoding/binary"
  7. )
  8. // PrimaryHandler — 主键 B+ 树索引 (IndexTypePrimary)
  9. // 存储: storeRow = [pkID(8B LE) + rowData]
  10. type PrimaryHandler struct{}
  11. func init() {
  12. Compose.RegisterHandler(page.IndexTypePrimary, &PrimaryHandler{})
  13. // 主键 B+ 树分裂参数 —— 写死在本文件, 不随索引元数据传递。
  14. // 主键多为自增/递增: 顺序追加时右叶只保留 1 条 (SequentialRight), 避免每次
  15. // 分裂都把整页对半搬运; 非顺序插入仍按 SplitPercent 的比例分裂。
  16. btree.PKSplitCfg = btree.SplitConfig{SplitPercent: 50, SequentialRight: true}
  17. }
  18. func (h *PrimaryHandler) Insert(handle page.HandleDb, entryPage *uint32, indexKey []byte, pkID uint64, rowData []byte, keyLen int) (uint32, error) {
  19. // 一次分配即得 [pkID(8B BE) + rowData]: 前 8 字节同时作为 B+ 树 key (只读)
  20. storeRowData := make([]byte, 8+len(rowData))
  21. binary.BigEndian.PutUint64(storeRowData[:8], pkID)
  22. copy(storeRowData[8:], rowData)
  23. // 主键 B+ 树始终以 pkID(8B BE) 为 key, 与 Search/Delete/Update 保持一致
  24. return h.insertPrebuilt(handle, entryPage, storeRowData[:8], storeRowData)
  25. }
  26. // insertPrebuilt 写入已构建好的 storeRowData (storeRowData = [pkID(8B BE) + rowData])
  27. func (h *PrimaryHandler) insertPrebuilt(handle page.HandleDb, entryPage *uint32, indexKey []byte, storeRowData []byte) (uint32, error) {
  28. rootPID := *entryPage
  29. rowSize := uint32(len(storeRowData)) + 4 // 4B len prefix + row data
  30. // appendInto 把行写进 dpID 这一页, 并把 (key -> dpID, slot) 挂进 B+ 树叶。
  31. // 返回 (B+ 树新根, 是否写入成功, 错误) —— "未写入"只表示这一页装不下, 由调用方决定换页。
  32. //
  33. // 用 InsertRowSorted 而不是 AppendRow: 主键由调用方显式给出时
  34. // (自定义主键 / BaseModel.ID) 插入顺序与 pkID 顺序无关, 而
  35. // FindRowByPK 依赖"页内行按 pkID 升序"提前终止 —— 追加小号会让
  36. // 行在页里却查不到 (详见 datapage.InsertRowSorted 的说明)。
  37. //
  38. // 返回的 slot 会一并写进叶条目, 之后查找/范围扫描就能 O(1) 取行。
  39. appendInto := func(dpID uint32) (uint32, bool, error) {
  40. dp, err := datapage.Load(handle, dpID)
  41. if err != nil {
  42. return 0, false, nil
  43. }
  44. slot, ok := dp.InsertRowSortedSlot(storeRowData)
  45. if !ok {
  46. dp.Release()
  47. return 0, false, nil
  48. }
  49. dp.Save()
  50. dp.Release() // Save 已把整页交给缓冲池, 此后不再访问 dp
  51. newRoot, _, _, err := btree.BTreePKInsert(rootPID, indexKey, dpID, uint16(slot), handle)
  52. if err != nil {
  53. return 0, false, err
  54. }
  55. return newRoot, true, nil
  56. }
  57. // commit 记录新的树根 (B+ 树未改根时 newRoot == rootPID, 无需回写)
  58. commit := func(newRoot uint32) uint32 {
  59. if newRoot != rootPID {
  60. *entryPage = newRoot
  61. }
  62. return newRoot
  63. }
  64. // 1) 尝试复用 DataPage: 只在路由目标叶子内查找
  65. if rootPID != 0 {
  66. if dpID, found := btree.FindLastLeafDP(handle, rootPID, rowSize, indexKey); found {
  67. if newRoot, ok, err := appendInto(dpID); err != nil {
  68. return 0, err
  69. } else if ok {
  70. return commit(newRoot), nil
  71. }
  72. }
  73. // 2) 末页判满: 开新页之前先按配置就地整理一次 (墓碑占比达到 CompactDeadRatio 才动手,
  74. // 配置 <=0 即关闭)。整理会把墓碑占的空间还给活行, 常常就够放下这一行;
  75. // CompactForInsert 会先判断"整理后确实装得下", 判断不成立就放弃, 不白搬一趟。
  76. //
  77. // 为什么值得做: 被删掉大半的页若一直占着位置, 写入就只能不断开新页 (每页只放
  78. // 少量行), 全表扫描要读的页数随之膨胀 —— 这正是"删多了以后表越写越散"的来路。
  79. if dpID, ok := btree.LastLeafDPID(handle, rootPID, indexKey); ok {
  80. if dp, lerr := datapage.Load(handle, dpID); lerr == nil && dp.CompactForInsert(rowSize) {
  81. if newRoot, ok, err := appendInto(dpID); err != nil {
  82. return 0, err
  83. } else if ok {
  84. return commit(newRoot), nil
  85. }
  86. }
  87. }
  88. }
  89. // 3) 整理后仍装不下 (或本页没有值得回收的墓碑, 或树为空): 创建新 DataPage
  90. dp := datapage.New(handle)
  91. slot := dp.AppendRowSlot(storeRowData)
  92. if slot == 0 {
  93. // 空页都装不下 → 行本身超长 (调用方应先经 CheckRowSize / 溢出页处理)
  94. return 0, page.ErrRowTooLarge
  95. }
  96. dp.Save()
  97. newRoot, _, _, err := btree.BTreePKInsert(rootPID, indexKey, dp.PageID(), uint16(slot), handle)
  98. if err != nil {
  99. return 0, err
  100. }
  101. *entryPage = newRoot
  102. return newRoot, nil
  103. }
  104. func (h *PrimaryHandler) Search(handle page.HandleDb, entryPage uint32, indexKey []byte, keyLen int, resolve RowResolver) ([]byte, bool) {
  105. // 主键索引自己就是行数据所在, 不需要回表 (resolve 仅对二级索引有意义)
  106. if entryPage == 0 || len(indexKey) < 8 {
  107. return nil, false
  108. }
  109. // 主键索引的键就是 pkID (见 Insert: 叶键 = storeRow[:8]), 所以这里必须按 pkID 定位。
  110. // 旧实现是 dp.FindRowByIndexKey(indexKey, 9) —— 即"拿 key 去和第 1 个字段的值比",
  111. // 只有当第 1 列的值恒等于 pkID (ORM 的 _id/_ts) 时才凑巧成立; 主键索引声明在别的
  112. // 列上时, SearchByIndex(pk_.., pkKey(id)) 会查不到行 (数据在, 但 pkID 不可达),
  113. // 而且它按偏移 9 匹配的是"页内第一行满足者", 大表上还会路由到别的页而漏行。
  114. // 统一按 pkID 走, 与 SearchByPK/DeleteByPK/Update/ResolveRow 同一套语义。
  115. return h.SearchByPK(handle, entryPage, binary.BigEndian.Uint64(indexKey[:8]))
  116. }
  117. // IsRowStore 主键索引直接承载行数据
  118. func (h *PrimaryHandler) IsRowStore() bool { return true }
  119. // ResolveRow 按 pkID 读取整行。
  120. //
  121. // 叶条目现在直接给出 (dpID, slot), 一次树下降 + ReadRowBySlotPK 就是 O(1); 而旧的
  122. // 「页区间二分 cache + 页内全扫」在 slot 之后反而更慢 (它仍要逐行扫页), 所以这里统一
  123. // 交给 SearchByPK。cache 参数仅为兼容接口保留 —— 不再需要它来避免重复扫页。
  124. func (h *PrimaryHandler) ResolveRow(handle page.HandleDb, entryPage uint32, pkID uint64, cache *[]DPRange) ([]byte, bool) {
  125. _ = cache
  126. return h.SearchByPK(handle, entryPage, pkID)
  127. }
  128. func (h *PrimaryHandler) SearchByPK(handle page.HandleDb, entryPage uint32, pkID uint64) ([]byte, bool) {
  129. rootPID := entryPage
  130. if rootPID == 0 {
  131. return nil, false
  132. }
  133. pkKeyBE := make([]byte, 8)
  134. binary.BigEndian.PutUint64(pkKeyBE, pkID)
  135. // 叶条目带 slot: 命中叶即 O(1) 取行, 无需在页内按 pkID 扫一遍
  136. dpID, slot, st := btree.BTreePKSearchEx(rootPID, pkKeyBE, handle)
  137. if st == btree.PKMiss {
  138. // 正常下降到达叶子且键不在: 该主键不存在, 直接返回。
  139. // 旧实现在这里无条件全叶扫描 —— 查不存在的键是 O(叶数), 插入查重
  140. // (rowStoreHasPK) 逐行触发它, 显式主键的批量导入退化成 O(N²)。
  141. return nil, false
  142. }
  143. if st == btree.PKHit {
  144. dp, err := datapage.Load(handle, dpID)
  145. if err == nil {
  146. if rowData, ok := dp.ReadRowBySlotPK(uint32(slot), pkKeyBE); ok {
  147. return rowData, true
  148. }
  149. }
  150. // 叶条目命中但槽位取不到行 (slot 失配): 数据页可能被换页/重建过, 仍走兜底确认
  151. }
  152. // 路由失败 (树结构异常): 扫描所有叶子
  153. return btree.ScanAllLeavesForPK(rootPID, handle, pkKeyBE)
  154. }
  155. func (h *PrimaryHandler) Delete(handle page.HandleDb, entryPage *uint32, indexKey []byte, pkID uint64, keyLen int) error {
  156. rootPID := *entryPage
  157. if rootPID == 0 {
  158. return page.ErrNotFound
  159. }
  160. dpID, slot, st := btree.BTreePKSearchEx(rootPID, indexKey, handle)
  161. if st == btree.PKMiss {
  162. return page.ErrNotFound // 键不存在: 树里没有条目可删, 也无行可删
  163. }
  164. if st == btree.PKHit {
  165. dp, err := datapage.Load(handle, dpID)
  166. if err == nil {
  167. deleted := false
  168. if _, ok := dp.ReadRowBySlotPK(uint32(slot), indexKey); ok {
  169. // 槽位命中 → O(1) 删行
  170. deleted = dp.DeleteBySlot(uint32(slot))
  171. } else if dp.DeleteByIndexKey(indexKey, 8) {
  172. deleted = true
  173. } else if dp.DeleteByPK(indexKey) {
  174. deleted = true
  175. }
  176. if deleted {
  177. // 摘除本行在 B+ 树叶里的条目 (pk -> dpID)。必须「每次删除都做」,
  178. // 不能只在 DataPage 变空时做: 旧实现只在 AllDeleted() 时删除
  179. // 「触发变空的那一个键」, 同一页里先被删掉的行会留下陈旧叶条目。
  180. // 该 DataPage 随后被回收复用 (例如改作 WAL 页) 时, 这些条目就指向了
  181. // 非数据页, 空闲链上也挂着仍被索引引用的页
  182. // (analyzer 报 not-data-page / freeLive, 属数据损坏前兆)。
  183. newRoot, _, derr := btree.BTreePKDelete(rootPID, indexKey, handle)
  184. if derr != nil && derr != page.ErrNotFound {
  185. return derr
  186. }
  187. if newRoot != rootPID {
  188. *entryPage = newRoot
  189. }
  190. if dp.AllDeleted() {
  191. if handle.FreePage != nil {
  192. handle.FreePage(dpID)
  193. }
  194. } else {
  195. dp.Save()
  196. }
  197. return nil
  198. }
  199. }
  200. }
  201. // 路由失败 (树结构异常), 扫描所有叶子
  202. return btree.ScanAndDelete(rootPID, handle, indexKey, indexKey)
  203. }
  204. func (h *PrimaryHandler) DeleteByPK(handle page.HandleDb, entryPage *uint32, pkID uint64) error {
  205. rootPID := *entryPage
  206. if rootPID == 0 {
  207. return page.ErrNotFound
  208. }
  209. pkKeyBE := make([]byte, 8)
  210. binary.BigEndian.PutUint64(pkKeyBE, pkID)
  211. dpID, slot, st := btree.BTreePKSearchEx(rootPID, pkKeyBE, handle)
  212. if st == btree.PKMiss {
  213. return page.ErrNotFound // 键不存在
  214. }
  215. if st == btree.PKHit {
  216. dp, err := datapage.Load(handle, dpID)
  217. if err == nil {
  218. deleted := false
  219. if _, ok := dp.ReadRowBySlotPK(uint32(slot), pkKeyBE); ok {
  220. deleted = dp.DeleteBySlot(uint32(slot))
  221. } else {
  222. deleted = dp.DeleteByPK(pkKeyBE)
  223. }
  224. if deleted {
  225. // 同 Delete: 每次成功删除都要摘掉本行的叶条目, 否则 DataPage 回收复用后
  226. // 会留下指向非数据页的陈旧条目 (详见 Delete 处的说明)。
  227. newRoot, _, derr := btree.BTreePKDelete(rootPID, pkKeyBE, handle)
  228. if derr != nil && derr != page.ErrNotFound {
  229. return derr
  230. }
  231. if newRoot != rootPID {
  232. *entryPage = newRoot
  233. }
  234. if dp.AllDeleted() {
  235. if handle.FreePage != nil {
  236. handle.FreePage(dpID)
  237. }
  238. } else {
  239. dp.Save()
  240. }
  241. return nil
  242. }
  243. }
  244. }
  245. // 路由失败 (树结构异常), 扫描所有叶子
  246. return btree.ScanAndDeleteByPK(rootPID, handle, pkKeyBE)
  247. }
  248. // Update 更新主键索引中 pkID 对应的行。
  249. //
  250. // schema 演进 (AddField) 后, 旧行的 schemaVer 与行长都会变长, "原地覆盖"不再可行,
  251. // 因此采用三级策略, 保证更新要么真正生效, 要么返回明确错误:
  252. //
  253. // 1. 原地更新 — 新行长 <= 旧行长 (最常见, 零成本)
  254. // 2. 页内重建 — 页内腾挪并顺带回收墓碑, 支持行变长而无需换页
  255. // 3. 换页 — 页内确实装不下时, 把行搬到新 DataPage 并改写 B+ 树叶条目
  256. func (h *PrimaryHandler) Update(handle page.HandleDb, entryPage *uint32, oldKey, newKey, rowData []byte, pkID uint64, keyLen int) error {
  257. rootPID := *entryPage
  258. if rootPID == 0 {
  259. return page.ErrNotFound
  260. }
  261. pkKeyBE := make([]byte, 8)
  262. binary.BigEndian.PutUint64(pkKeyBE, pkID)
  263. // 一次分配构造 [pkID(8B BE) + rowData], 取代 pkBuf+append 的二次分配
  264. storeRowData := make([]byte, 8+len(rowData))
  265. copy(storeRowData, pkKeyBE)
  266. copy(storeRowData[8:], rowData)
  267. // 1/2 级: B+ 树路由定位 DataPage (slot 直接给出该行的槽位号)
  268. dpID, slot, st := btree.BTreePKSearchEx(rootPID, pkKeyBE, handle)
  269. if st == btree.PKMiss {
  270. return page.ErrNotFound // 键不存在, 无行可更新
  271. }
  272. if st == btree.PKHit {
  273. if dp, err := datapage.Load(handle, dpID); err == nil {
  274. if err := dp.UpdateBySlot(uint32(slot), storeRowData); err == nil {
  275. return nil
  276. }
  277. if err := dp.RebuildWithSlot(uint32(slot), storeRowData); err == nil {
  278. return nil
  279. }
  280. // 页内装不下 → 直接换页, 不再做无意义的全树扫描
  281. return h.relocateRow(handle, entryPage, pkKeyBE, storeRowData, dpID)
  282. }
  283. }
  284. // 路由失败: 回退扫描所有叶子 (内部同样含 1/2 级兜底)
  285. if err := btree.ScanAndUpdate(rootPID, handle, pkKeyBE, storeRowData); err == nil {
  286. return nil
  287. }
  288. // 3 级: 目标行位于"已满且需变长"的页上, 定位后换页
  289. if oldDPID, ok := btree.FindDataPageIDByPK(rootPID, handle, pkKeyBE); ok {
  290. return h.relocateRow(handle, entryPage, pkKeyBE, storeRowData, oldDPID)
  291. }
  292. return page.ErrNotFound
  293. }
  294. // relocateRow 把 pkID 对应的行搬到新的 DataPage 承载。
  295. //
  296. // 步骤 (无事务, 顺序上优先保证"索引始终可达该行"):
  297. // 1. 新建 DataPage 并写入新行 (此时尚未被索引引用)
  298. // 2. 摘除该键的旧叶条目, 再插入指向新页的条目
  299. // 3. 旧页软删该行; 若旧页已无活行则直接回收
  300. func (h *PrimaryHandler) relocateRow(handle page.HandleDb, entryPage *uint32, pkKeyBE, storeRowData []byte, oldDPID uint32) error {
  301. newDP := datapage.New(handle)
  302. newSlot := newDP.AppendRowSlot(storeRowData)
  303. if newSlot == 0 {
  304. return page.ErrRowTooLarge
  305. }
  306. newDP.Save()
  307. newDPID := newDP.PageID()
  308. // BTreePKInsert 遇到已存在的键会判为重复而不更新指向, 故必须先摘除旧条目
  309. newRoot, _, err := btree.BTreePKDelete(*entryPage, pkKeyBE, handle)
  310. if err != nil {
  311. if handle.FreePage != nil {
  312. handle.FreePage(newDPID)
  313. }
  314. return err
  315. }
  316. newRoot2, _, _, err := btree.BTreePKInsert(newRoot, pkKeyBE, newDPID, uint16(newSlot), handle)
  317. if err != nil {
  318. *entryPage = newRoot
  319. if handle.FreePage != nil {
  320. handle.FreePage(newDPID)
  321. }
  322. return err
  323. }
  324. *entryPage = newRoot2
  325. // 旧页收尾: 只软删这一行, 其它行仍由各自的叶条目引用
  326. if oldDP, lerr := datapage.Load(handle, oldDPID); lerr == nil {
  327. if oldDP.DeleteByPK(pkKeyBE) {
  328. if oldDP.AllDeleted() {
  329. if handle.FreePage != nil {
  330. handle.FreePage(oldDPID)
  331. }
  332. } else {
  333. oldDP.Save()
  334. }
  335. }
  336. }
  337. return nil
  338. }
  339. func (h *PrimaryHandler) GetDataPageIDs(handle page.HandleDb, entryPage uint32) []uint32 {
  340. return btree.GetDataPageIDs(handle, entryPage)
  341. }
  342. func (h *PrimaryHandler) ReadDataPageRows(handle page.HandleDb, dpID uint32) [][]byte {
  343. dp, err := datapage.Load(handle, dpID)
  344. if err != nil {
  345. return nil
  346. }
  347. return dp.GetAllRows()
  348. }
  349. // ReadDataPageLiveCount 返回数据页中未删除的行数 (不物化行)。
  350. // 无条件 COUNT(*) 的快速路径; 通过接口断言暴露, 不强加给所有 IndexHandler。
  351. func (h *PrimaryHandler) ReadDataPageLiveCount(handle page.HandleDb, dpID uint32) int {
  352. dp, err := datapage.Load(handle, dpID)
  353. if err != nil {
  354. return 0
  355. }
  356. return dp.CountLiveRows()
  357. }
  358. func (h *PrimaryHandler) RangeScan(handle page.HandleDb, entryPage uint32,
  359. startKey, endKey []byte, startInclusive, endInclusive bool, reverse bool,
  360. callback func(row []byte) bool) error {
  361. return btree.BTreePKRangeScan(entryPage, handle, startKey, endKey, startInclusive, endInclusive, reverse, callback)
  362. }
  363. // InsertBatch 批量写入行存储 (主键 B+ 树 + 数据页)。
  364. //
  365. // 两段式:
  366. // 1) 数据页驻留灌行 —— 路由到首行归属的叶末数据页, 加载一次后连续写入,
  367. // 装满才落盘换新页 (逐条路径每行 Load+Save 整页, 16KB×2 memcpy/行;
  368. // 批量路径摊到 ~每页一次)。行内仍走 InsertRowSortedSlot 保持"页内按
  369. // pkID 升序"不变式。
  370. // 2) 主键树批量挂条目 —— 收集 (pkID → 数据页, 槽位) 后交给 BTreePKBulkInsert。
  371. //
  372. // rows 必须按 PKID 升序 (Table.InsertRowsWithIDs 保证; 自增批量天然满足)。
  373. // 页内整理 (CompactForInsert) 不做: 批量灌行不依赖旧页腾挪, 装不下直接开新页。
  374. func (h *PrimaryHandler) InsertBatch(handle page.HandleDb, entryPage *uint32, rows []BatchRow) error {
  375. if len(rows) == 0 {
  376. return nil
  377. }
  378. // 数据页: 路由到首行归属叶的末数据页, 驻留复用
  379. rootPID := *entryPage
  380. var dp *datapage.DataPage
  381. if rootPID != 0 {
  382. firstKey := make([]byte, 8)
  383. binary.BigEndian.PutUint64(firstKey, rows[0].PKID)
  384. if dpID, ok := btree.LastLeafDPID(handle, rootPID, firstKey); ok {
  385. if d, err := datapage.Load(handle, dpID); err == nil {
  386. dp = d
  387. }
  388. }
  389. }
  390. items := make([]btree.PKBulkItem, len(rows))
  391. for i := range rows {
  392. r := &rows[i]
  393. // [pkID(8B BE) + rowData]: 前 8 字节同时作为 B+ 树 key (与 Insert 一致)
  394. storeRow := make([]byte, 8+len(r.RowData))
  395. binary.BigEndian.PutUint64(storeRow[:8], r.PKID)
  396. copy(storeRow[8:], r.RowData)
  397. if dp != nil {
  398. if slot, ok := dp.InsertRowSortedSlot(storeRow); ok {
  399. items[i] = btree.PKBulkItem{DPID: dp.PageID(), Slot: uint16(slot)}
  400. binary.BigEndian.PutUint64(items[i].Key[:], r.PKID)
  401. continue
  402. }
  403. dp.Save()
  404. dp.Release()
  405. dp = nil
  406. }
  407. dp = datapage.New(handle)
  408. slot := dp.AppendRowSlot(storeRow)
  409. if slot == 0 {
  410. dp.Save()
  411. dp.Release()
  412. return page.ErrRowTooLarge
  413. }
  414. items[i] = btree.PKBulkItem{DPID: dp.PageID(), Slot: uint16(slot)}
  415. binary.BigEndian.PutUint64(items[i].Key[:], r.PKID)
  416. }
  417. if dp != nil {
  418. dp.Save()
  419. dp.Release()
  420. }
  421. newRoot, err := btree.BTreePKBulkInsert(rootPID, items, handle)
  422. if err != nil {
  423. return err
  424. }
  425. if newRoot != *entryPage {
  426. *entryPage = newRoot
  427. }
  428. return nil
  429. }