db.go 8.9 KB

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