@@ -190,31 +190,11 @@ async fn materialize_in_tx(
190190 . rows_affected ( ) ;
191191
192192 // 1. 删不再成立的来源:陈述死了、行死了、签名没绑着、属性或方向变了、陈述带了 mood
193- sqlx:: query ( & format ! (
194- "DELETE FROM typed_fact_sources src
195- USING facts t
196- WHERE src.fact_id = t.id AND t.kb_id = $1
197- AND NOT EXISTS (
198- SELECT 1
199- FROM facts s
200- JOIN entities se ON se.id = s.subject_id
201- LEFT JOIN entities oe ON oe.id = s.object_id
202- JOIN phrase_bindings b ON {MATCH}
203- WHERE s.id = src.statement_id
204- AND s.kb_id = $1
205- AND s.invalidated_at IS NULL
206- AND t.invalidated_at IS NULL
207- AND b.status = 'bound'
208- AND b.relation_type_id = t.predicate_id
209- AND ((b.direction = 'forward' AND t.subject_id = s.subject_id)
210- OR (b.direction = 'reverse' AND t.subject_id = s.object_id))
211- AND {NO_MOOD})" ,
212- NO_MOOD = no_mood_spoken( ) ,
213- ) )
214- . persistent ( false )
215- . bind ( kb_id)
216- . execute ( & mut * * tx)
217- . await ?;
193+ sqlx:: query ( & source_cleanup_sql ( ) )
194+ . persistent ( false )
195+ . bind ( kb_id)
196+ . execute ( & mut * * tx)
197+ . await ?;
218198
219199 // 1b. 隐含行的来源:规则不再批准、触发它的陈述死了或换了签名、实体没了或换了类别词,
220200 // 来源就删;与 1 同一条规矩,只是来源表是另一张(implied_fact_sources)
@@ -861,6 +841,35 @@ pub async fn count(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {
861841 . await ?)
862842}
863843
844+ /// 步骤 1 的语句:仍然成立的来源只算一遍(CTE),再用反连接删掉其余的。
845+ /// 写成相关的 NOT EXISTS 时,规划器把绑定匹配估成一行,对每个来源重扫一遍:
846+ /// 69 万个来源的库上跑了十二小时,这样写两分钟。条件和删掉的行都没变。
847+ fn source_cleanup_sql ( ) -> String {
848+ format ! (
849+ "WITH holding AS MATERIALIZED (
850+ SELECT src.fact_id, src.statement_id
851+ FROM typed_fact_sources src
852+ JOIN facts t ON t.id = src.fact_id AND t.kb_id = $1 AND t.invalidated_at IS NULL
853+ JOIN facts s ON s.id = src.statement_id AND s.kb_id = $1
854+ AND s.invalidated_at IS NULL
855+ JOIN entities se ON se.id = s.subject_id
856+ LEFT JOIN entities oe ON oe.id = s.object_id
857+ JOIN phrase_bindings b ON {MATCH}
858+ WHERE b.status = 'bound'
859+ AND b.relation_type_id = t.predicate_id
860+ AND ((b.direction = 'forward' AND t.subject_id = s.subject_id)
861+ OR (b.direction = 'reverse' AND t.subject_id = s.object_id))
862+ AND {NO_MOOD})
863+ DELETE FROM typed_fact_sources src
864+ USING facts t
865+ WHERE src.fact_id = t.id AND t.kb_id = $1
866+ AND NOT EXISTS (SELECT 1 FROM holding h
867+ WHERE h.fact_id = src.fact_id
868+ AND h.statement_id = src.statement_id)" ,
869+ NO_MOOD = no_mood_spoken( ) ,
870+ )
871+ }
872+
864873#[ cfg( test) ]
865874#[ path = "materialize_delivery_tests.rs" ]
866875mod delivery_tests;
0 commit comments