db.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package core
  2. import (
  3. "TsDB2/DB/core/index"
  4. "TsDB2/DB/core/page"
  5. "TsDB2/DB/core/types"
  6. "TsDB2/DB/core/util"
  7. "encoding/binary"
  8. "fmt"
  9. "sync"
  10. "time"
  11. "unsafe"
  12. )
  13. type TableMeta struct {
  14. Name string
  15. FieldCount uint32
  16. TotalRows uint64
  17. FirstHeap uint32
  18. LastHeap uint32
  19. FirstIndex uint32
  20. LastIndex uint32
  21. FirstData uint32
  22. LastData uint32
  23. RowSize uint16
  24. }
  25. type DB struct {
  26. header *HeaderPage
  27. tables *TablePage
  28. file *File
  29. // 防抖自动提交
  30. autoCommitDelay time.Duration
  31. autoCommitTimer *time.Timer
  32. autoCommitMu sync.Mutex
  33. // 当前活跃事务(nil 表示无事务)
  34. currentTxn *Transaction
  35. }
  36. func Open(path string) (*DB, error) {
  37. ff, err := OpenFile(path)
  38. if err != nil {
  39. return nil, err
  40. }
  41. // 启用页面缓冲池
  42. ff.InitBufferPool(DefaultBufferPoolCapacity)
  43. stat, err := ff.f.Stat()
  44. if err != nil {
  45. return nil, err
  46. }
  47. var header *HeaderPage
  48. if stat.Size() == 0 {
  49. header, err = newHeader("tsdb")
  50. if err != nil {
  51. return nil, err
  52. }
  53. if err := ff.WriteHeader(header); err != nil {
  54. return nil, err
  55. }
  56. } else {
  57. header, err = ff.ReadHeader()
  58. if err != nil {
  59. return nil, err
  60. }
  61. }
  62. // ==========================
  63. // 初始化表页
  64. // ==========================
  65. tablePage := &TablePage{
  66. handle: page.HandleDb{
  67. NewPage: func() uint32 {
  68. pid := header.newPageWithReader(ff.readPageDisk) // 必须直接读盘, 绕过 BufferPool
  69. _ = ff.WriteHeader(header)
  70. return pid
  71. },
  72. FreePage: func(pageID uint32) {
  73. header.recyclePage(pageID, ff.WritePageDirect) // 必须直接写盘! 走 BufferPool 会被 ClearCache 清掉
  74. _ = ff.WriteHeader(header)
  75. },
  76. ReadPage: ff.ReadPage,
  77. SavePage: ff.WritePage,
  78. },
  79. }
  80. // ==========================
  81. // 初始化索引元数据页
  82. // ==========================
  83. saveHeader := false
  84. //如果索引页和表页都是空的话则直接创建
  85. if header.TablePage == 0 {
  86. header.TablePage = header.newPage()
  87. tablePage.InitHeader(header.TablePage)
  88. saveHeader = true
  89. }
  90. tablePage.Init(header.TablePage)
  91. if saveHeader {
  92. err = ff.WriteHeader(header)
  93. if err != nil {
  94. return nil, err
  95. }
  96. }
  97. // ==========================
  98. // WAL 恢复: 检查是否有未完成的 WAL 事务
  99. // ==========================
  100. if err := RecoverWAL(ff, header); err != nil {
  101. return nil, err
  102. }
  103. db := &DB{
  104. file: ff,
  105. header: header,
  106. tables: tablePage,
  107. autoCommitDelay: DefaultAutoCommitDelay,
  108. }
  109. db.startAutoCommit()
  110. // 设置事务回调(在 BufferPool.WritePage 时缓存原始数据)
  111. ff.SetOnPageWriteCallback(func(pageID uint32) {
  112. // 如果有活跃事务,缓存原始页数据
  113. if db.currentTxn != nil {
  114. _ = db.currentTxn.cacheOriginalPage(pageID)
  115. }
  116. })
  117. // 脏页阈值: 超过时自动触发 Commit 刷盘, 防止内存暴涨
  118. ff.SetDirtyThreshold(DefaultDirtyThreshold, func() {
  119. _ = db.Commit()
  120. })
  121. return db, nil
  122. }
  123. func (db *DB) updateTime() {
  124. db.header.ModifyTime = time.Now().UnixNano()
  125. _ = db.file.WriteHeader(db.header)
  126. }
  127. func (db *DB) FindTable(name string) (*Table, bool) {
  128. tbl, ok := db.tables.Find(name)
  129. if ok && tbl.onWrite == nil {
  130. tbl.SetOnWrite(db.NotifyWrite)
  131. }
  132. return tbl, ok
  133. }
  134. func (db *DB) CreateTable(name string, fields []types.FieldInfo) (*Table, error) {
  135. tbl, err := db.tables.Create(name, fields)
  136. if err != nil {
  137. return nil, err
  138. }
  139. tbl.SetOnWrite(db.NotifyWrite)
  140. db.header.TableCount++
  141. _ = db.file.WriteHeader(db.header)
  142. db.updateTime()
  143. return tbl, nil
  144. }
  145. func (db *DB) DropTable(name string) error {
  146. // 先清除 BufferPool 缓存, 确保回收时读取磁盘最新数据
  147. db.file.ClearCache()
  148. if err := db.tables.Drop(name); err != nil {
  149. return err
  150. }
  151. db.header.TableCount--
  152. _ = db.file.WriteHeader(db.header)
  153. db.updateTime()
  154. // 先刷盘再清缓存, 防止 Drop 中标记的 Flag(0x80) 丢失
  155. db.file.FlushBufferPool()
  156. db.file.ClearCache()
  157. return nil
  158. }
  159. func (db *DB) GetAllTables() []TableMeta {
  160. res := make([]TableMeta, 0, len(db.tables.tables))
  161. for _, t := range db.tables.tables {
  162. if util.IsHighBitSet(t.info.Flag) {
  163. continue
  164. }
  165. res = append(res, TableMeta{
  166. Name: util.BytesToString(t.info.Name[:]),
  167. FieldCount: uint32(t.info.FieldCount),
  168. TotalRows: t.info.TotalRows,
  169. FirstHeap: t.info.FirstHeap,
  170. LastHeap: t.info.LastHeap,
  171. FirstData: t.info.FirstData,
  172. LastData: t.info.LastData,
  173. RowSize: t.info.RowSize,
  174. })
  175. }
  176. return res
  177. }
  178. func (db *DB) Close() error {
  179. // 停止防抖定时器
  180. db.stopAutoCommit()
  181. // 先提交剩余脏页 (走 WAL)
  182. _ = db.Commit()
  183. // BufferPool 安全网 (理论上已无脏页)
  184. db.file.FlushBufferPool()
  185. return db.file.Close()
  186. }
  187. // Commit 显式提交 — 通过 WAL 保证原子性
  188. // 同时重置防抖定时器
  189. func (db *DB) Commit() error {
  190. // 取消待执行的自动提交
  191. db.autoCommitMu.Lock()
  192. if db.autoCommitTimer != nil {
  193. db.autoCommitTimer.Stop()
  194. }
  195. db.autoCommitMu.Unlock()
  196. // 1. 收集所有 BufferPool 脏页 (TablePage + IndexPage + DataPage 等)
  197. dirty := db.file.CollectDirty()
  198. if len(dirty) == 0 {
  199. return nil // 无脏页, 跳过
  200. }
  201. // 2. 创建事务
  202. wal := db.BeginTxn()
  203. // 3. 记录所有脏页
  204. for _, d := range dirty {
  205. wal.RecordPage(d.PageID, d.Data)
  206. }
  207. // 4. HeaderPage 也纳入 (pageID=0)
  208. wal.RecordPage(0, marshalHeader(db.header))
  209. // 5. 原子提交
  210. return wal.Commit()
  211. }
  212. // ======================== 防抖自动提交 ========================
  213. // SetAutoCommitDelay 设置防抖自动提交延迟
  214. // delay=0 表示禁用自动提交 (仅手动 Commit)
  215. func (db *DB) SetAutoCommitDelay(d time.Duration) {
  216. db.autoCommitMu.Lock()
  217. defer db.autoCommitMu.Unlock()
  218. db.autoCommitDelay = d
  219. if db.autoCommitTimer != nil {
  220. db.autoCommitTimer.Stop()
  221. db.autoCommitTimer = nil
  222. }
  223. }
  224. // NotifyWrite 写操作通知 (InsertRow/DeleteRow/UpdateRow 完成后调用)
  225. // 重置防抖定时器: 如果延迟期间没有新操作, 则自动 Commit
  226. func (db *DB) NotifyWrite() {
  227. if db.autoCommitDelay <= 0 {
  228. return
  229. }
  230. db.autoCommitMu.Lock()
  231. defer db.autoCommitMu.Unlock()
  232. // 复用同一个 timer 对象,避免频繁创建/销毁
  233. if db.autoCommitTimer == nil {
  234. // 首次创建
  235. db.autoCommitTimer = time.AfterFunc(db.autoCommitDelay, func() {
  236. _ = db.Commit()
  237. })
  238. } else {
  239. // 后续重置(无需重新分配对象,减少 GC 压力)
  240. db.autoCommitTimer.Reset(db.autoCommitDelay)
  241. }
  242. }
  243. // startAutoCommit 启动防抖自动提交
  244. func (db *DB) startAutoCommit() {
  245. // 不立即启动定时器, 等待第一次 NotifyWrite
  246. }
  247. // stopAutoCommit 停止防抖自动提交
  248. func (db *DB) stopAutoCommit() {
  249. db.autoCommitMu.Lock()
  250. defer db.autoCommitMu.Unlock()
  251. if db.autoCommitTimer != nil {
  252. db.autoCommitTimer.Stop()
  253. db.autoCommitTimer = nil
  254. }
  255. }
  256. // SetDirtyThreshold 设置脏页阈值(页数),超过此值自动触发 Commit
  257. func (db *DB) SetDirtyThreshold(threshold int) {
  258. db.file.SetDirtyThreshold(threshold, func() {
  259. _ = db.Commit() // Commit 内部会自动停止防抖定时器
  260. })
  261. }
  262. // LockWrites 锁定写入(禁止 Insert/Update/Delete)
  263. func (db *DB) LockWrites() {
  264. db.file.LockWrites()
  265. }
  266. // UnlockWrites 解锁写入(允许 Insert/Update/Delete)
  267. func (db *DB) UnlockWrites() {
  268. db.file.UnlockWrites()
  269. }
  270. // SetBufferPoolCapacity 设置 BufferPool 容量(页数)
  271. func (db *DB) SetBufferPoolCapacity(capacity int) {
  272. db.file.SetBufferPoolCapacity(capacity)
  273. }
  274. // marshalHeader 将 HeaderPage 序列化为字节切片 (填充到 PageSize)
  275. func marshalHeader(h *HeaderPage) []byte {
  276. buf := make([]byte, PageSize)
  277. src := (*[PageSize4K]byte)(unsafe.Pointer(h))[:]
  278. copy(buf, src)
  279. return buf
  280. }
  281. // ======================== 调试诊断 ========================
  282. // DebugDBState 打印数据库调试信息
  283. func (db *DB) DebugDBState() {
  284. fmt.Printf("[DEBUG] Header: TablePage=%d NextFreePage=%d FreePageStart=%d FirstWAL=%d LastWAL=%d NextTxn=%d\n",
  285. db.header.TablePage, db.header.NextFreePage, db.header.FreePageStart,
  286. db.header.FirstWALPage, db.header.LastWALPage, db.header.NextTxnID)
  287. fmt.Printf("[DEBUG] BufferPool: total=%d dirty=%d\n", db.file.bp.Len(), db.file.bp.DirtyCount())
  288. }
  289. // DebugTableState 打印表调试信息 (从磁盘读取, 绕过 BufferPool)
  290. func (db *DB) DebugTableState(tableName string) {
  291. tbl, ok := db.tables.Find(tableName)
  292. if !ok {
  293. fmt.Printf("[DEBUG] Table '%s' not found\n", tableName)
  294. return
  295. }
  296. fmt.Printf("[DEBUG] Table '%s': TotalRows=%d (memory)\n", tableName, tbl.info.TotalRows)
  297. // 从磁盘读取 TablePage 检查 TotalRows
  298. buf := make([]byte, PageSize)
  299. if err := db.file.ReadPage(tbl.TablePageID(), buf); err == nil {
  300. info := (*TableInfo)(unsafe.Pointer(&buf[tbl.TableStartOffset()]))
  301. fmt.Printf("[DEBUG] TablePage on disk: TotalRows=%d FieldCount=%d\n", info.TotalRows, info.FieldCount)
  302. }
  303. // 检查索引元数据
  304. im := tbl.IndexMeta()
  305. if im != nil {
  306. for i := range im.metas {
  307. m := &im.metas[i]
  308. if m.Flag&0x80 != 0 {
  309. continue
  310. }
  311. fmt.Printf("[DEBUG] Index '%s': EntryPage=%d IndexType=%d\n",
  312. string(m.IndexName[:]), m.EntryPage, m.IndexType)
  313. // 从磁盘读取 IndexMetaPage 检查 EntryPage
  314. imBuf := make([]byte, PageSize)
  315. if err := db.file.ReadPage(im.PageID(), imBuf); err == nil {
  316. // 读取磁盘上的 EntryPage
  317. diskMeta := (*IndexMeta)(unsafe.Pointer(&imBuf[im.HdrSize()]))
  318. fmt.Printf("[DEBUG] IndexMetaPage on disk: EntryPage=%d\n", diskMeta.EntryPage)
  319. }
  320. // 统计 B+ 树 DataPage 数量
  321. if m.IndexType == page.IndexTypePrimary {
  322. handler, _ := index.Compose.GetHandler(m.IndexType)
  323. if handler != nil {
  324. dpIDs := handler.GetDataPageIDs(tbl.handle, m.EntryPage)
  325. totalRows := 0
  326. for _, dpID := range dpIDs {
  327. dpBuf := make([]byte, PageSize)
  328. if err := db.file.ReadPage(dpID, dpBuf); err == nil {
  329. // 读取 DataPage 的行数 (在 offset 18 处的 4 字节 Count)
  330. count := binary.LittleEndian.Uint32(dpBuf[18:])
  331. totalRows += int(count)
  332. }
  333. }
  334. fmt.Printf("[DEBUG] B+ tree: %d DataPages, %d total rows\n", len(dpIDs), totalRows)
  335. }
  336. }
  337. }
  338. }
  339. }
  340. // DebugFreePageCount 返回空闲页数量 (调试用)
  341. func (db *DB) DebugFreePageCount() int {
  342. return int(db.header.FreePageCount)
  343. }