upsert.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package sql
  17. import (
  18. "bytes"
  19. "crypto/sha256"
  20. "database/sql"
  21. "fmt"
  22. "os"
  23. "path"
  24. "path/filepath"
  25. "strings"
  26. "sync"
  27. "github.com/88250/gulu"
  28. "github.com/88250/lute/parse"
  29. "github.com/emirpasic/gods/sets/hashset"
  30. ignore "github.com/sabhiram/go-gitignore"
  31. "github.com/siyuan-note/eventbus"
  32. "github.com/siyuan-note/logging"
  33. "github.com/siyuan-note/siyuan/kernel/util"
  34. )
  35. var luteEngine = util.NewLute()
  36. func init() {
  37. luteEngine.RenderOptions.KramdownBlockIAL = false // 数据库 markdown 字段为标准 md,但是要保留 span block ial
  38. }
  39. const (
  40. BlocksInsert = "INSERT INTO blocks (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES %s"
  41. BlocksFTSInsert = "INSERT INTO blocks_fts (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES %s"
  42. BlocksFTSCaseInsensitiveInsert = "INSERT INTO blocks_fts_case_insensitive (id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated) VALUES %s"
  43. BlocksPlaceholder = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  44. SpansInsert = "INSERT INTO spans (id, block_id, root_id, box, path, content, markdown, type, ial) VALUES %s"
  45. SpansPlaceholder = "(?, ?, ?, ?, ?, ?, ?, ?, ?)"
  46. AssetsPlaceholder = "(?, ?, ?, ?, ?, ?, ?, ?, ?)"
  47. AttributesPlaceholder = "(?, ?, ?, ?, ?, ?, ?, ?)"
  48. RefsPlaceholder = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  49. FileAnnotationRefsPlaceholder = "(?, ?, ?, ?, ?, ?, ?, ?, ?)"
  50. )
  51. func insertBlocks(tx *sql.Tx, blocks []*Block, context map[string]interface{}) (err error) {
  52. if 1 > len(blocks) {
  53. return
  54. }
  55. var bulk []*Block
  56. for _, block := range blocks {
  57. bulk = append(bulk, block)
  58. if 512 > len(bulk) {
  59. continue
  60. }
  61. if err = insertBlocks0(tx, bulk, context); nil != err {
  62. return
  63. }
  64. bulk = []*Block{}
  65. }
  66. if 0 < len(bulk) {
  67. if err = insertBlocks0(tx, bulk, context); nil != err {
  68. return
  69. }
  70. }
  71. return
  72. }
  73. func insertBlocks0(tx *sql.Tx, bulk []*Block, context map[string]interface{}) (err error) {
  74. valueStrings := make([]string, 0, len(bulk))
  75. valueArgs := make([]interface{}, 0, len(bulk)*strings.Count(BlocksPlaceholder, "?"))
  76. hashBuf := bytes.Buffer{}
  77. for _, b := range bulk {
  78. valueStrings = append(valueStrings, BlocksPlaceholder)
  79. valueArgs = append(valueArgs, b.ID)
  80. valueArgs = append(valueArgs, b.ParentID)
  81. valueArgs = append(valueArgs, b.RootID)
  82. valueArgs = append(valueArgs, b.Hash)
  83. valueArgs = append(valueArgs, b.Box)
  84. valueArgs = append(valueArgs, b.Path)
  85. valueArgs = append(valueArgs, b.HPath)
  86. valueArgs = append(valueArgs, b.Name)
  87. valueArgs = append(valueArgs, b.Alias)
  88. valueArgs = append(valueArgs, b.Memo)
  89. valueArgs = append(valueArgs, b.Tag)
  90. valueArgs = append(valueArgs, b.Content)
  91. valueArgs = append(valueArgs, b.FContent)
  92. valueArgs = append(valueArgs, b.Markdown)
  93. valueArgs = append(valueArgs, b.Length)
  94. valueArgs = append(valueArgs, b.Type)
  95. valueArgs = append(valueArgs, b.SubType)
  96. valueArgs = append(valueArgs, b.IAL)
  97. valueArgs = append(valueArgs, b.Sort)
  98. valueArgs = append(valueArgs, b.Created)
  99. valueArgs = append(valueArgs, b.Updated)
  100. putBlockCache(b)
  101. hashBuf.WriteString(b.Hash)
  102. }
  103. stmt := fmt.Sprintf(BlocksInsert, strings.Join(valueStrings, ","))
  104. if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err {
  105. return
  106. }
  107. hashBuf.WriteString("blocks")
  108. evtHash := fmt.Sprintf("%x", sha256.Sum256(hashBuf.Bytes()))[:7]
  109. // 使用下面的 EvtSQLInsertBlocksFTS 就可以了
  110. //eventbus.Publish(eventbus.EvtSQLInsertBlocks, context, current, total, len(bulk), evtHash)
  111. stmt = fmt.Sprintf(BlocksFTSInsert, strings.Join(valueStrings, ","))
  112. if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err {
  113. return
  114. }
  115. if !caseSensitive {
  116. stmt = fmt.Sprintf(BlocksFTSCaseInsensitiveInsert, strings.Join(valueStrings, ","))
  117. if err = prepareExecInsertTx(tx, stmt, valueArgs); nil != err {
  118. return
  119. }
  120. }
  121. hashBuf.WriteString("fts")
  122. evtHash = fmt.Sprintf("%x", sha256.Sum256(hashBuf.Bytes()))[:7]
  123. eventbus.Publish(eventbus.EvtSQLInsertBlocksFTS, context, len(bulk), evtHash)
  124. return
  125. }
  126. func insertAttributes(tx *sql.Tx, attributes []*Attribute) (err error) {
  127. if 1 > len(attributes) {
  128. return
  129. }
  130. var bulk []*Attribute
  131. for _, attr := range attributes {
  132. bulk = append(bulk, attr)
  133. if 512 > len(bulk) {
  134. continue
  135. }
  136. if err = insertAttribute0(tx, bulk); nil != err {
  137. return
  138. }
  139. bulk = []*Attribute{}
  140. }
  141. if 0 < len(bulk) {
  142. if err = insertAttribute0(tx, bulk); nil != err {
  143. return
  144. }
  145. }
  146. return
  147. }
  148. func insertAttribute0(tx *sql.Tx, bulk []*Attribute) (err error) {
  149. if 1 > len(bulk) {
  150. return
  151. }
  152. valueStrings := make([]string, 0, len(bulk))
  153. valueArgs := make([]interface{}, 0, len(bulk)*strings.Count(AttributesPlaceholder, "?"))
  154. for _, attr := range bulk {
  155. valueStrings = append(valueStrings, AttributesPlaceholder)
  156. valueArgs = append(valueArgs, attr.ID)
  157. valueArgs = append(valueArgs, attr.Name)
  158. valueArgs = append(valueArgs, attr.Value)
  159. valueArgs = append(valueArgs, attr.Type)
  160. valueArgs = append(valueArgs, attr.BlockID)
  161. valueArgs = append(valueArgs, attr.RootID)
  162. valueArgs = append(valueArgs, attr.Box)
  163. valueArgs = append(valueArgs, attr.Path)
  164. }
  165. stmt := fmt.Sprintf("INSERT INTO attributes (id, name, value, type, block_id, root_id, box, path) VALUES %s", strings.Join(valueStrings, ","))
  166. err = prepareExecInsertTx(tx, stmt, valueArgs)
  167. return
  168. }
  169. func insertAssets(tx *sql.Tx, assets []*Asset) (err error) {
  170. if 1 > len(assets) {
  171. return
  172. }
  173. var bulk []*Asset
  174. for _, asset := range assets {
  175. bulk = append(bulk, asset)
  176. if 512 > len(bulk) {
  177. continue
  178. }
  179. if err = insertAsset0(tx, bulk); nil != err {
  180. return
  181. }
  182. bulk = []*Asset{}
  183. }
  184. if 0 < len(bulk) {
  185. if err = insertAsset0(tx, bulk); nil != err {
  186. return
  187. }
  188. }
  189. return
  190. }
  191. func insertAsset0(tx *sql.Tx, bulk []*Asset) (err error) {
  192. if 1 > len(bulk) {
  193. return
  194. }
  195. valueStrings := make([]string, 0, len(bulk))
  196. valueArgs := make([]interface{}, 0, len(bulk)*strings.Count(AssetsPlaceholder, "?"))
  197. for _, asset := range bulk {
  198. valueStrings = append(valueStrings, AssetsPlaceholder)
  199. valueArgs = append(valueArgs, asset.ID)
  200. valueArgs = append(valueArgs, asset.BlockID)
  201. valueArgs = append(valueArgs, asset.RootID)
  202. valueArgs = append(valueArgs, asset.Box)
  203. valueArgs = append(valueArgs, asset.DocPath)
  204. valueArgs = append(valueArgs, asset.Path)
  205. valueArgs = append(valueArgs, asset.Name)
  206. valueArgs = append(valueArgs, asset.Title)
  207. valueArgs = append(valueArgs, asset.Hash)
  208. }
  209. stmt := fmt.Sprintf("INSERT INTO assets (id, block_id, root_id, box, docpath, path, name, title, hash) VALUES %s", strings.Join(valueStrings, ","))
  210. err = prepareExecInsertTx(tx, stmt, valueArgs)
  211. return
  212. }
  213. func insertSpans(tx *sql.Tx, spans []*Span) (err error) {
  214. if 1 > len(spans) {
  215. return
  216. }
  217. var bulk []*Span
  218. for _, span := range spans {
  219. bulk = append(bulk, span)
  220. if 512 > len(bulk) {
  221. continue
  222. }
  223. if err = insertSpans0(tx, bulk); nil != err {
  224. return
  225. }
  226. bulk = []*Span{}
  227. }
  228. if 0 < len(bulk) {
  229. if err = insertSpans0(tx, bulk); nil != err {
  230. return
  231. }
  232. }
  233. return
  234. }
  235. func insertSpans0(tx *sql.Tx, bulk []*Span) (err error) {
  236. if 1 > len(bulk) {
  237. return
  238. }
  239. valueStrings := make([]string, 0, len(bulk))
  240. valueArgs := make([]interface{}, 0, len(bulk)*strings.Count(SpansPlaceholder, "?"))
  241. for _, span := range bulk {
  242. valueStrings = append(valueStrings, SpansPlaceholder)
  243. valueArgs = append(valueArgs, span.ID)
  244. valueArgs = append(valueArgs, span.BlockID)
  245. valueArgs = append(valueArgs, span.RootID)
  246. valueArgs = append(valueArgs, span.Box)
  247. valueArgs = append(valueArgs, span.Path)
  248. valueArgs = append(valueArgs, span.Content)
  249. valueArgs = append(valueArgs, span.Markdown)
  250. valueArgs = append(valueArgs, span.Type)
  251. valueArgs = append(valueArgs, span.IAL)
  252. }
  253. stmt := fmt.Sprintf(SpansInsert, strings.Join(valueStrings, ","))
  254. err = prepareExecInsertTx(tx, stmt, valueArgs)
  255. return
  256. }
  257. func insertBlockRefs(tx *sql.Tx, refs []*Ref) (err error) {
  258. if 1 > len(refs) {
  259. return
  260. }
  261. var bulk []*Ref
  262. for _, ref := range refs {
  263. bulk = append(bulk, ref)
  264. if 512 > len(bulk) {
  265. continue
  266. }
  267. if err = insertRefs0(tx, bulk); nil != err {
  268. return
  269. }
  270. bulk = []*Ref{}
  271. }
  272. if 0 < len(bulk) {
  273. if err = insertRefs0(tx, bulk); nil != err {
  274. return
  275. }
  276. }
  277. return
  278. }
  279. func insertRefs0(tx *sql.Tx, bulk []*Ref) (err error) {
  280. if 1 > len(bulk) {
  281. return
  282. }
  283. valueStrings := make([]string, 0, len(bulk))
  284. valueArgs := make([]interface{}, 0, len(bulk)*strings.Count(RefsPlaceholder, "?"))
  285. for _, ref := range bulk {
  286. valueStrings = append(valueStrings, RefsPlaceholder)
  287. valueArgs = append(valueArgs, ref.ID)
  288. valueArgs = append(valueArgs, ref.DefBlockID)
  289. valueArgs = append(valueArgs, ref.DefBlockParentID)
  290. valueArgs = append(valueArgs, ref.DefBlockRootID)
  291. valueArgs = append(valueArgs, ref.DefBlockPath)
  292. valueArgs = append(valueArgs, ref.BlockID)
  293. valueArgs = append(valueArgs, ref.RootID)
  294. valueArgs = append(valueArgs, ref.Box)
  295. valueArgs = append(valueArgs, ref.Path)
  296. valueArgs = append(valueArgs, ref.Content)
  297. valueArgs = append(valueArgs, ref.Markdown)
  298. valueArgs = append(valueArgs, ref.Type)
  299. putRefCache(ref)
  300. }
  301. stmt := fmt.Sprintf("INSERT INTO refs (id, def_block_id, def_block_parent_id, def_block_root_id, def_block_path, block_id, root_id, box, path, content, markdown, type) VALUES %s", strings.Join(valueStrings, ","))
  302. err = prepareExecInsertTx(tx, stmt, valueArgs)
  303. return
  304. }
  305. func insertFileAnnotationRefs(tx *sql.Tx, refs []*FileAnnotationRef) (err error) {
  306. if 1 > len(refs) {
  307. return
  308. }
  309. var bulk []*FileAnnotationRef
  310. for _, ref := range refs {
  311. bulk = append(bulk, ref)
  312. if 512 > len(bulk) {
  313. continue
  314. }
  315. if err = insertFileAnnotationRefs0(tx, bulk); nil != err {
  316. return
  317. }
  318. bulk = []*FileAnnotationRef{}
  319. }
  320. if 0 < len(bulk) {
  321. if err = insertFileAnnotationRefs0(tx, bulk); nil != err {
  322. return
  323. }
  324. }
  325. return
  326. }
  327. func insertFileAnnotationRefs0(tx *sql.Tx, bulk []*FileAnnotationRef) (err error) {
  328. if 1 > len(bulk) {
  329. return
  330. }
  331. valueStrings := make([]string, 0, len(bulk))
  332. valueArgs := make([]interface{}, 0, len(bulk)*strings.Count(FileAnnotationRefsPlaceholder, "?"))
  333. for _, ref := range bulk {
  334. valueStrings = append(valueStrings, FileAnnotationRefsPlaceholder)
  335. valueArgs = append(valueArgs, ref.ID)
  336. valueArgs = append(valueArgs, ref.FilePath)
  337. valueArgs = append(valueArgs, ref.AnnotationID)
  338. valueArgs = append(valueArgs, ref.BlockID)
  339. valueArgs = append(valueArgs, ref.RootID)
  340. valueArgs = append(valueArgs, ref.Box)
  341. valueArgs = append(valueArgs, ref.Path)
  342. valueArgs = append(valueArgs, ref.Content)
  343. valueArgs = append(valueArgs, ref.Type)
  344. }
  345. stmt := fmt.Sprintf("INSERT INTO file_annotation_refs (id, file_path, annotation_id, block_id, root_id, box, path, content, type) VALUES %s", strings.Join(valueStrings, ","))
  346. err = prepareExecInsertTx(tx, stmt, valueArgs)
  347. return
  348. }
  349. func indexTree(tx *sql.Tx, tree *parse.Tree, context map[string]interface{}) (err error) {
  350. blocks, spans, assets, attributes := fromTree(tree.Root, tree)
  351. refs, fileAnnotationRefs := refsFromTree(tree)
  352. err = insertTree0(tx, tree, context, blocks, spans, assets, attributes, refs, fileAnnotationRefs)
  353. return
  354. }
  355. func upsertTree(tx *sql.Tx, tree *parse.Tree, context map[string]interface{}) (err error) {
  356. oldBlockHashes := queryBlockHashes(tree.ID)
  357. blocks, spans, assets, attributes := fromTree(tree.Root, tree)
  358. newBlockHashes := map[string]string{}
  359. for _, block := range blocks {
  360. newBlockHashes[block.ID] = block.Hash
  361. }
  362. unChanges := hashset.New()
  363. var toRemoves []string
  364. for id, hash := range oldBlockHashes {
  365. if newHash, ok := newBlockHashes[id]; ok {
  366. if newHash == hash {
  367. unChanges.Add(id)
  368. }
  369. } else {
  370. toRemoves = append(toRemoves, id)
  371. }
  372. }
  373. tmp := blocks[:0]
  374. for _, b := range blocks {
  375. if !unChanges.Contains(b.ID) {
  376. tmp = append(tmp, b)
  377. }
  378. }
  379. blocks = tmp
  380. for _, b := range blocks {
  381. toRemoves = append(toRemoves, b.ID)
  382. }
  383. if err = deleteBlocksByIDs(tx, toRemoves); nil != err {
  384. return
  385. }
  386. if err = deleteSpansByRootID(tx, tree.ID); nil != err {
  387. return
  388. }
  389. if err = deleteAssetsByRootID(tx, tree.ID); nil != err {
  390. return
  391. }
  392. if err = deleteAttributesByRootID(tx, tree.ID); nil != err {
  393. return
  394. }
  395. if err = deleteRefsByPathTx(tx, tree.Box, tree.Path); nil != err {
  396. return
  397. }
  398. if err = deleteFileAnnotationRefsByPathTx(tx, tree.Box, tree.Path); nil != err {
  399. return
  400. }
  401. refs, fileAnnotationRefs := refsFromTree(tree)
  402. if err = insertTree0(tx, tree, context, blocks, spans, assets, attributes, refs, fileAnnotationRefs); nil != err {
  403. return
  404. }
  405. return err
  406. }
  407. func insertTree0(tx *sql.Tx, tree *parse.Tree, context map[string]interface{},
  408. blocks []*Block, spans []*Span, assets []*Asset, attributes []*Attribute,
  409. refs []*Ref, fileAnnotationRefs []*FileAnnotationRef) (err error) {
  410. if ignoreLines := getIndexIgnoreLines(); 0 < len(ignoreLines) {
  411. // Support ignore index https://github.com/siyuan-note/siyuan/issues/9198
  412. matcher := ignore.CompileIgnoreLines(ignoreLines...)
  413. if matcher.MatchesPath("/" + path.Join(tree.Box, tree.Path)) {
  414. return
  415. }
  416. }
  417. if err = insertBlocks(tx, blocks, context); nil != err {
  418. return
  419. }
  420. if err = insertBlockRefs(tx, refs); nil != err {
  421. return
  422. }
  423. if err = insertFileAnnotationRefs(tx, fileAnnotationRefs); nil != err {
  424. return
  425. }
  426. if 0 < len(spans) {
  427. // 移除文档标签,否则会重复添加 https://github.com/siyuan-note/siyuan/issues/3723
  428. if err = deleteSpansByRootID(tx, tree.Root.ID); nil != err {
  429. return
  430. }
  431. if err = insertSpans(tx, spans); nil != err {
  432. return
  433. }
  434. }
  435. if err = insertAssets(tx, assets); nil != err {
  436. return
  437. }
  438. if err = insertAttributes(tx, attributes); nil != err {
  439. return
  440. }
  441. return
  442. }
  443. var (
  444. IndexIgnoreCached bool
  445. indexIgnore []string
  446. indexIgnoreLock = sync.Mutex{}
  447. )
  448. func getIndexIgnoreLines() (ret []string) {
  449. // Support ignore index https://github.com/siyuan-note/siyuan/issues/9198
  450. if IndexIgnoreCached {
  451. return indexIgnore
  452. }
  453. indexIgnoreLock.Lock()
  454. defer indexIgnoreLock.Unlock()
  455. IndexIgnoreCached = true
  456. indexIgnorePath := filepath.Join(util.DataDir, ".siyuan", "indexignore")
  457. err := os.MkdirAll(filepath.Dir(indexIgnorePath), 0755)
  458. if nil != err {
  459. return
  460. }
  461. if !gulu.File.IsExist(indexIgnorePath) {
  462. if err = gulu.File.WriteFileSafer(indexIgnorePath, nil, 0644); nil != err {
  463. logging.LogErrorf("create indexignore [%s] failed: %s", indexIgnorePath, err)
  464. return
  465. }
  466. }
  467. data, err := os.ReadFile(indexIgnorePath)
  468. if nil != err {
  469. logging.LogErrorf("read indexignore [%s] failed: %s", indexIgnorePath, err)
  470. return
  471. }
  472. dataStr := string(data)
  473. dataStr = strings.ReplaceAll(dataStr, "\r\n", "\n")
  474. ret = strings.Split(dataStr, "\n")
  475. ret = gulu.Str.RemoveDuplicatedElem(ret)
  476. if 0 < len(ret) && "" == ret[0] {
  477. ret = ret[1:]
  478. }
  479. indexIgnore = nil
  480. for _, line := range ret {
  481. indexIgnore = append(indexIgnore, line)
  482. }
  483. return
  484. }