瀏覽代碼

:art: 自动校验数据库索引 https://github.com/siyuan-note/siyuan/issues/7016

Liang Ding 2 年之前
父節點
當前提交
dc112fd56c
共有 2 個文件被更改,包括 36 次插入31 次删除
  1. 29 28
      kernel/model/transaction.go
  2. 7 3
      kernel/sql/block_query.go

+ 29 - 28
kernel/model/transaction.go

@@ -1238,42 +1238,43 @@ func autoFixIndex() {
 	defer autoFixLock.Unlock()
 
 	rootUpdatedMap := treenode.GetRootUpdated()
-	i := -1
-	size := len(rootUpdatedMap)
-	for rootID, updated := range rootUpdatedMap {
-		if isFullReindexing {
-			break
-		}
+	dbRootUpdatedMap, err := sql.GetRootUpdated()
+	if nil == err {
+		i := -1
+		size := len(rootUpdatedMap)
+		for rootID, updated := range rootUpdatedMap {
+			if isFullReindexing {
+				break
+			}
 
-		i++
+			i++
 
-		rootUpdated, err := sql.GetRootUpdated(rootID)
-		if nil != err {
-			continue
-		}
-		if "" == rootUpdated {
-			logging.LogWarnf("not found tree [%s] in database, reindex it", rootID)
-			reindexTree(rootID, i, size)
-			continue
-		}
+			rootUpdated := dbRootUpdatedMap[rootID]
+			if "" == rootUpdated {
+				logging.LogWarnf("not found tree [%s] in database, reindex it", rootID)
+				reindexTree(rootID, i, size)
+				continue
+			}
 
-		if "" == updated {
-			// BlockTree 迁移,v2.6.3 之前没有 updated 字段
-			reindexTree(rootID, i, size)
-			continue
-		}
+			if "" == updated {
+				// BlockTree 迁移,v2.6.3 之前没有 updated 字段
+				reindexTree(rootID, i, size)
+				continue
+			}
 
-		btUpdated, _ := time.Parse("20060102150405", updated)
-		dbUpdated, _ := time.Parse("20060102150405", rootUpdated)
-		if dbUpdated.Before(btUpdated.Add(-1 * time.Minute)) {
-			logging.LogWarnf("tree [%s] is not up to date, reindex it", rootID)
-			reindexTree(rootID, i, size)
-			continue
+			btUpdated, _ := time.Parse("20060102150405", updated)
+			dbUpdated, _ := time.Parse("20060102150405", rootUpdated)
+			if dbUpdated.Before(btUpdated.Add(-1 * time.Minute)) {
+				logging.LogWarnf("tree [%s] is not up to date, reindex it", rootID)
+				reindexTree(rootID, i, size)
+				continue
+			}
 		}
 	}
 
 	duplicatedRootIDs := sql.GetDuplicatedRootIDs()
-	for _, rootID := range duplicatedRootIDs {
+	size := len(duplicatedRootIDs)
+	for i, rootID := range duplicatedRootIDs {
 		root := sql.GetBlock(rootID)
 		if nil == root {
 			continue

+ 7 - 3
kernel/sql/block_query.go

@@ -581,15 +581,19 @@ func GetBlock(id string) (ret *Block) {
 	return
 }
 
-func GetRootUpdated(rootID string) (ret string, err error) {
-	rows, err := query("SELECT updated FROM blocks WHERE root_id = ? AND type = 'd'", rootID)
+func GetRootUpdated() (ret map[string]string, err error) {
+	rows, err := query("SELECT root_id, updated FROM blocks WHERE type = 'd'")
 	if nil != err {
 		logging.LogErrorf("sql query failed: %s", err)
 		return
 	}
 	defer rows.Close()
+
+	ret = map[string]string{}
 	for rows.Next() {
-		rows.Scan(&ret)
+		var rootID, updated string
+		rows.Scan(&rootID, &updated)
+		ret[rootID] = updated
 	}
 	return
 }