1use std::collections::BTreeSet;
11use std::sync::atomic::Ordering;
12use std::sync::{Arc, Mutex};
13
14use bytes::BytesMut;
15use mz_catalog::memory::objects::CatalogItem;
16use mz_controller_types::ClusterId;
17use mz_ore::cast::{CastFrom, CastInto};
18use mz_ore::now::{EpochMillis, NowFn, epoch_to_uuid_v7, to_datetime};
19use mz_ore::soft_panic_or_log;
20use mz_repr::adt::array::ArrayDimension;
21use mz_repr::adt::timestamp::TimestampLike;
22use mz_repr::{Datum, GlobalId, Row, RowIterator, RowPacker, Timestamp};
23use mz_sql::ast::display::AstDisplay;
24use mz_sql::ast::{AstInfo, Statement};
25use mz_sql::plan::Params;
26use mz_sql::session::metadata::SessionMetadata;
27use mz_sql::session::vars::SystemVars;
28use mz_sql_parser::ast::{StatementKind, statement_kind_label_value};
29use qcell::QCell;
30use rand::distr::{Bernoulli, Distribution};
31use sha2::{Digest, Sha256};
32use uuid::Uuid;
33
34use crate::catalog::CatalogState;
35use crate::session::{LifecycleTimestamps, Session, TransactionId};
36use crate::{AdapterError, CollectionIdBundle, ExecuteResponse};
37
38#[derive(Clone, Debug)]
39pub enum StatementLifecycleEvent {
40 ExecutionBegan,
41 OptimizationFinished,
42 StorageDependenciesFinished,
43 ComputeDependenciesFinished,
44 ExecutionFinished,
45}
46
47impl StatementLifecycleEvent {
48 pub fn as_str(&self) -> &str {
49 match self {
50 Self::ExecutionBegan => "execution-began",
51 Self::OptimizationFinished => "optimization-finished",
52 Self::StorageDependenciesFinished => "storage-dependencies-finished",
53 Self::ComputeDependenciesFinished => "compute-dependencies-finished",
54 Self::ExecutionFinished => "execution-finished",
55 }
56 }
57}
58
59#[derive(Clone, Debug)]
63pub struct StatementBeganExecutionRecord {
64 pub id: Uuid,
65 pub prepared_statement_id: Uuid,
66 pub sample_rate: f64,
67 pub params: Vec<Option<String>>,
68 pub began_at: EpochMillis,
69 pub cluster_id: Option<ClusterId>,
70 pub cluster_name: Option<String>,
71 pub database_name: String,
72 pub search_path: Vec<String>,
73 pub application_name: String,
74 pub transaction_isolation: String,
75 pub execution_timestamp: Option<EpochMillis>,
76 pub transaction_id: TransactionId,
77 pub transient_index_id: Option<GlobalId>,
78 pub mz_version: String,
79}
80
81#[derive(Clone, Copy, Debug)]
82pub enum StatementExecutionStrategy {
83 Standard,
85 FastPath,
88 PersistFastPath,
91 Constant,
94}
95
96impl StatementExecutionStrategy {
97 pub fn name(&self) -> &'static str {
98 match self {
99 Self::Standard => "standard",
100 Self::FastPath => "fast-path",
101 Self::PersistFastPath => "persist-fast-path",
102 Self::Constant => "constant",
103 }
104 }
105}
106
107#[derive(Clone, Debug)]
108pub enum StatementEndedExecutionReason {
109 Success {
110 result_size: Option<u64>,
111 rows_returned: Option<u64>,
112 execution_strategy: Option<StatementExecutionStrategy>,
113 },
114 Canceled,
115 Errored {
116 error: String,
117 },
118 Aborted,
122}
123
124#[derive(Clone, Debug)]
125pub struct StatementEndedExecutionRecord {
126 pub id: Uuid,
127 pub reason: StatementEndedExecutionReason,
128 pub ended_at: EpochMillis,
129}
130
131#[derive(Clone, Debug)]
134pub(crate) struct StatementPreparedRecord {
135 pub id: Uuid,
136 pub sql_hash: [u8; 32],
137 pub name: String,
138 pub session_id: Uuid,
139 pub prepared_at: EpochMillis,
140 pub kind: Option<StatementKind>,
141}
142
143#[derive(Clone, Debug)]
144pub(crate) struct SessionHistoryEvent {
145 pub id: Uuid,
146 pub connected_at: EpochMillis,
147 pub application_name: String,
148 pub authenticated_user: String,
149}
150
151impl From<&Result<ExecuteResponse, AdapterError>> for StatementEndedExecutionReason {
152 fn from(value: &Result<ExecuteResponse, AdapterError>) -> StatementEndedExecutionReason {
153 match value {
154 Ok(resp) => resp.into(),
155 Err(e) => StatementEndedExecutionReason::Errored {
156 error: e.to_string(),
157 },
158 }
159 }
160}
161
162impl From<&ExecuteResponse> for StatementEndedExecutionReason {
163 fn from(value: &ExecuteResponse) -> StatementEndedExecutionReason {
164 match value {
165 ExecuteResponse::CopyTo { resp, .. } => match resp.as_ref() {
166 ExecuteResponse::SendingRowsImmediate { rows, .. } => {
169 let result_size: usize = rows.box_clone().map(|row| row.byte_len()).sum();
173 StatementEndedExecutionReason::Success {
174 result_size: Some(u64::cast_from(result_size)),
175 rows_returned: Some(u64::cast_from(rows.count())),
176 execution_strategy: Some(StatementExecutionStrategy::Constant),
177 }
178 }
179 ExecuteResponse::SendingRowsStreaming { .. } => {
180 panic!("SELECTs terminate on peek finalization, not here.")
181 }
182 ExecuteResponse::Subscribing { .. } => {
183 panic!("SUBSCRIBEs terminate in the protocol layer, not here.")
184 }
185 _ => panic!("Invalid COPY response type"),
186 },
187 ExecuteResponse::CopyFrom { .. } => {
188 panic!("COPY FROMs terminate in the protocol layer, not here.")
189 }
190 ExecuteResponse::Fetch { .. } => {
191 panic!("FETCHes terminate after a follow-up message is sent.")
192 }
193 ExecuteResponse::SendingRowsStreaming { .. } => {
194 panic!("SELECTs terminate on peek finalization, not here.")
195 }
196 ExecuteResponse::Subscribing { .. } => {
197 panic!("SUBSCRIBEs terminate in the protocol layer, not here.")
198 }
199
200 ExecuteResponse::SendingRowsImmediate { rows, .. } => {
201 let result_size: usize = rows.box_clone().map(|row| row.byte_len()).sum();
207 StatementEndedExecutionReason::Success {
208 result_size: Some(u64::cast_from(result_size)),
209 rows_returned: Some(u64::cast_from(rows.count())),
210 execution_strategy: Some(StatementExecutionStrategy::Constant),
211 }
212 }
213
214 ExecuteResponse::AlteredDefaultPrivileges
215 | ExecuteResponse::AlteredObject(_)
216 | ExecuteResponse::AlteredRole
217 | ExecuteResponse::AlteredSystemConfiguration
218 | ExecuteResponse::ClosedCursor
219 | ExecuteResponse::Comment
220 | ExecuteResponse::Copied(_)
221 | ExecuteResponse::CreatedConnection
222 | ExecuteResponse::CreatedDatabase
223 | ExecuteResponse::CreatedSchema
224 | ExecuteResponse::CreatedRole
225 | ExecuteResponse::CreatedCluster
226 | ExecuteResponse::CreatedClusterReplica
227 | ExecuteResponse::CreatedIndex
228 | ExecuteResponse::CreatedIntrospectionSubscribe
229 | ExecuteResponse::CreatedSecret
230 | ExecuteResponse::CreatedSink
231 | ExecuteResponse::CreatedSource
232 | ExecuteResponse::CreatedTable
233 | ExecuteResponse::CreatedView
234 | ExecuteResponse::CreatedViews
235 | ExecuteResponse::CreatedMaterializedView
236 | ExecuteResponse::CreatedType
237 | ExecuteResponse::CreatedNetworkPolicy
238 | ExecuteResponse::Deallocate { .. }
239 | ExecuteResponse::DeclaredCursor
240 | ExecuteResponse::Deleted(_)
241 | ExecuteResponse::DiscardedTemp
242 | ExecuteResponse::DiscardedAll
243 | ExecuteResponse::DroppedObject(_)
244 | ExecuteResponse::DroppedOwned
245 | ExecuteResponse::EmptyQuery
246 | ExecuteResponse::GrantedPrivilege
247 | ExecuteResponse::GrantedRole
248 | ExecuteResponse::Inserted(_)
249 | ExecuteResponse::Prepare
250 | ExecuteResponse::Raised
251 | ExecuteResponse::ReassignOwned
252 | ExecuteResponse::RevokedPrivilege
253 | ExecuteResponse::RevokedRole
254 | ExecuteResponse::SetVariable { .. }
255 | ExecuteResponse::StartedTransaction
256 | ExecuteResponse::TransactionCommitted { .. }
257 | ExecuteResponse::TransactionRolledBack { .. }
258 | ExecuteResponse::Updated(_)
259 | ExecuteResponse::ValidatedConnection { .. } => {
260 StatementEndedExecutionReason::Success {
261 result_size: None,
262 rows_returned: None,
263 execution_strategy: None,
264 }
265 }
266 }
267 }
268}
269
270mod sealed {
271 #[derive(Debug, Copy, Clone)]
274 pub struct Private;
275}
276
277#[derive(Debug)]
279pub enum PreparedStatementLoggingInfo {
280 AlreadyLogged { uuid: Uuid },
284 StillToLog {
287 sql: String,
289 redacted_sql: String,
292 prepared_at: EpochMillis,
294 name: String,
296 session_id: Uuid,
298 accounted: bool,
300 kind: Option<StatementKind>,
302
303 _sealed: sealed::Private,
306 },
307}
308
309impl PreparedStatementLoggingInfo {
310 pub fn still_to_log<A: AstInfo>(
313 raw_sql: String,
314 stmt: Option<&Statement<A>>,
315 prepared_at: EpochMillis,
316 name: String,
317 session_id: Uuid,
318 accounted: bool,
319 ) -> Self {
320 let kind = stmt.map(StatementKind::from);
321 let sql = match kind {
322 Some(
327 StatementKind::CreateSecret
328 | StatementKind::AlterSecret
329 | StatementKind::Insert
330 | StatementKind::Update
331 | StatementKind::Execute,
332 ) => stmt.map(|s| s.to_ast_string_redacted()).unwrap_or_default(),
333 _ => raw_sql,
334 };
335
336 PreparedStatementLoggingInfo::StillToLog {
337 sql,
338 redacted_sql: stmt.map(|s| s.to_ast_string_redacted()).unwrap_or_default(),
339 prepared_at,
340 name,
341 session_id,
342 accounted,
343 kind,
344 _sealed: sealed::Private,
345 }
346 }
347}
348
349#[derive(Copy, Clone, Debug, Ord, Eq, PartialOrd, PartialEq)]
350pub struct StatementLoggingId(pub Uuid);
351
352#[derive(Debug, Clone)]
354pub struct PreparedStatementEvent {
355 pub prepared_statement: Row,
356 pub sql_text: Row,
357 pub session_id: Uuid,
358}
359
360#[derive(Debug)]
363pub struct ThrottlingState {
364 inner: Mutex<ThrottlingStateInner>,
372 throttled_count: std::sync::atomic::AtomicUsize,
376}
377
378#[derive(Debug)]
379struct ThrottlingStateInner {
380 tokens: u64,
384 last_logged_ts_seconds: u64,
386}
387
388impl ThrottlingState {
389 pub fn new(now: &NowFn) -> Self {
391 Self {
392 inner: Mutex::new(ThrottlingStateInner {
393 tokens: 0,
394 last_logged_ts_seconds: now() / 1000,
395 }),
396 throttled_count: std::sync::atomic::AtomicUsize::new(0),
397 }
398 }
399
400 pub fn throttling_check(
407 &self,
408 cost: u64,
409 target_data_rate: u64,
410 max_data_credit: Option<u64>,
411 now: &NowFn,
412 ) -> bool {
413 let ts = now() / 1000;
414 let mut inner = self.inner.lock().expect("throttling state lock poisoned");
415 let elapsed = ts.saturating_sub(inner.last_logged_ts_seconds);
418 inner.last_logged_ts_seconds = ts;
419 inner.tokens = inner
420 .tokens
421 .saturating_add(target_data_rate.saturating_mul(elapsed));
422 if let Some(max_data_credit) = max_data_credit {
423 inner.tokens = inner.tokens.min(max_data_credit);
424 }
425 if let Some(remaining) = inner.tokens.checked_sub(cost) {
426 tracing::debug!("throttling check passed. tokens remaining: {remaining}; cost: {cost}");
427 inner.tokens = remaining;
428 true
429 } else {
430 tracing::debug!(
431 "throttling check failed. tokens available: {}; cost: {cost}",
432 inner.tokens
433 );
434 false
435 }
436 }
437
438 pub fn get_throttled_count(&self) -> usize {
439 self.throttled_count.load(Ordering::Relaxed)
440 }
441
442 pub fn increment_throttled_count(&self) {
443 self.throttled_count.fetch_add(1, Ordering::Relaxed);
444 }
445
446 pub fn reset_throttled_count(&self) {
447 self.throttled_count.store(0, Ordering::Relaxed);
448 }
449}
450
451#[derive(Debug, Clone)]
457pub struct StatementLoggingFrontend {
458 pub throttling_state: Arc<ThrottlingState>,
460 pub reproducible_rng: Arc<Mutex<rand_chacha::ChaCha8Rng>>,
462 pub build_info_human_version: String,
464 pub now: NowFn,
466}
467
468impl StatementLoggingFrontend {
469 fn get_prepared_statement_info(
485 &self,
486 session: &mut Session,
487 logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
488 ) -> (Option<PreparedStatementEvent>, Uuid) {
489 let logging_ref = session.qcell_rw(&*logging);
490 let mut prepared_statement_event = None;
491
492 let ps_uuid = match logging_ref {
493 PreparedStatementLoggingInfo::AlreadyLogged { uuid } => *uuid,
494 PreparedStatementLoggingInfo::StillToLog {
495 sql,
496 redacted_sql,
497 prepared_at,
498 name,
499 session_id,
500 accounted,
501 kind,
502 _sealed: _,
503 } => {
504 assert!(
505 *accounted,
506 "accounting for logging should be done in `begin_statement_execution`"
507 );
508 let uuid = epoch_to_uuid_v7(prepared_at);
509 let sql = std::mem::take(sql);
510 let redacted_sql = std::mem::take(redacted_sql);
511 let sql_hash: [u8; 32] = Sha256::digest(sql.as_bytes()).into();
512
513 let sid = *session_id;
515
516 let record = StatementPreparedRecord {
517 id: uuid,
518 sql_hash,
519 name: std::mem::take(name),
520 session_id: sid,
521 prepared_at: *prepared_at,
522 kind: *kind,
523 };
524
525 let mut mpsh_row = Row::default();
527 let mut mpsh_packer = mpsh_row.packer();
528 pack_statement_prepared_update(&record, &mut mpsh_packer);
529
530 let sql_row = Row::pack([
531 Datum::TimestampTz(
532 to_datetime(*prepared_at)
533 .truncate_day()
534 .try_into()
535 .expect("must fit"),
536 ),
537 Datum::Bytes(sql_hash.as_slice()),
538 Datum::String(sql.as_str()),
539 Datum::String(redacted_sql.as_str()),
540 ]);
541
542 let throttled_count = self.throttling_state.get_throttled_count();
544
545 mpsh_packer.push(Datum::UInt64(CastFrom::cast_from(throttled_count)));
546
547 prepared_statement_event = Some(PreparedStatementEvent {
548 prepared_statement: mpsh_row,
549 sql_text: sql_row,
550 session_id: sid,
551 });
552
553 *logging_ref = PreparedStatementLoggingInfo::AlreadyLogged { uuid };
554 uuid
555 }
556 };
557
558 (prepared_statement_event, ps_uuid)
559 }
560
561 pub fn begin_statement_execution(
576 &self,
577 session: &mut Session,
578 params: &Params,
579 logging: &Arc<QCell<PreparedStatementLoggingInfo>>,
580 system_config: &SystemVars,
581 lifecycle_timestamps: Option<LifecycleTimestamps>,
582 ) -> Option<(
583 StatementLoggingId,
584 StatementBeganExecutionRecord,
585 Row,
586 Option<PreparedStatementEvent>,
587 )> {
588 let enable_internal_statement_logging = system_config.enable_internal_statement_logging();
590 if session.user().is_internal() && !enable_internal_statement_logging {
591 return None;
592 }
593
594 let sample_rate = effective_sample_rate(session, system_config);
595
596 let use_reproducible_rng = system_config.statement_logging_use_reproducible_rng();
597 let target_data_rate: Option<u64> = system_config
598 .statement_logging_target_data_rate()
599 .map(|rate| rate.cast_into());
600 let max_data_credit: Option<u64> = system_config
601 .statement_logging_max_data_credit()
602 .map(|credit| credit.cast_into());
603
604 let sample = if use_reproducible_rng {
606 let mut rng = self.reproducible_rng.lock().expect("rng lock poisoned");
607 should_sample_statement(sample_rate, Some(&mut *rng))
608 } else {
609 should_sample_statement(sample_rate, None)
610 };
611
612 let sampled_label = sample.then_some("true").unwrap_or("false");
613 session
614 .metrics()
615 .statement_logging_records(&[sampled_label])
616 .inc_by(1);
617
618 let unsampled_bytes_metric = session
620 .metrics()
621 .statement_logging_unsampled_bytes()
622 .clone();
623 let actual_bytes_metric = session.metrics().statement_logging_actual_bytes().clone();
624
625 let is_new_prepared_statement = if let Some((sql, accounted)) =
627 match session.qcell_rw(logging) {
628 PreparedStatementLoggingInfo::AlreadyLogged { .. } => None,
629 PreparedStatementLoggingInfo::StillToLog { sql, accounted, .. } => {
630 Some((sql, accounted))
631 }
632 } {
633 if !*accounted {
634 unsampled_bytes_metric.inc_by(u64::cast_from(sql.len()));
635 if sample {
636 actual_bytes_metric.inc_by(u64::cast_from(sql.len()));
637 }
638 *accounted = true;
639 }
640 true
641 } else {
642 false
643 };
644
645 if !sample {
646 return None;
647 }
648
649 let (prepared_statement_event, ps_uuid) =
651 self.get_prepared_statement_info(session, logging);
652
653 let began_at = if let Some(lifecycle_timestamps) = lifecycle_timestamps {
654 lifecycle_timestamps.received
655 } else {
656 (self.now)()
657 };
658
659 let current_time = (self.now)();
660 let execution_uuid = epoch_to_uuid_v7(¤t_time);
661
662 let began_execution = create_began_execution_record(
664 execution_uuid,
665 ps_uuid,
666 sample_rate,
667 params,
668 session,
669 began_at,
670 self.build_info_human_version.clone(),
671 );
672
673 let mseh_update = pack_statement_began_execution_update(&began_execution);
675 let maybe_ps_prepared_statement = prepared_statement_event
676 .as_ref()
677 .map(|e| &e.prepared_statement);
678 let maybe_ps_sql_text = prepared_statement_event.as_ref().map(|e| &e.sql_text);
679
680 let cost: usize = [
682 Some(&mseh_update),
683 maybe_ps_prepared_statement,
684 maybe_ps_sql_text,
685 ]
686 .into_iter()
687 .filter_map(|row_opt| row_opt.map(|row| row.byte_len()))
688 .fold(0_usize, |acc, x| acc.saturating_add(x));
689
690 let passed = if let Some(target_data_rate) = target_data_rate {
692 self.throttling_state.throttling_check(
693 cost.cast_into(),
694 target_data_rate,
695 max_data_credit,
696 &self.now,
697 )
698 } else {
699 true };
701
702 if !passed {
703 self.throttling_state.increment_throttled_count();
705 return None;
706 }
707
708 if is_new_prepared_statement {
711 self.throttling_state.reset_throttled_count();
712 }
713
714 Some((
715 StatementLoggingId(execution_uuid),
716 began_execution,
717 mseh_update,
718 prepared_statement_event,
719 ))
720 }
721}
722
723pub(crate) fn effective_sample_rate(session: &Session, system_vars: &SystemVars) -> f64 {
727 let system_max: f64 = system_vars
728 .statement_logging_max_sample_rate()
729 .try_into()
730 .expect("value constrained to be convertible to f64");
731 let user_rate: f64 = session
732 .vars()
733 .get_statement_logging_sample_rate()
734 .try_into()
735 .expect("value constrained to be convertible to f64");
736 f64::min(system_max, user_rate)
737}
738
739pub(crate) fn should_sample_statement(
745 sample_rate: f64,
746 reproducible_rng: Option<&mut rand_chacha::ChaCha8Rng>,
747) -> bool {
748 let distribution = Bernoulli::new(sample_rate).unwrap_or_else(|_| {
749 soft_panic_or_log!("statement_logging_sample_rate is out of range [0, 1]");
750 Bernoulli::new(0.0).expect("0.0 is valid for Bernoulli")
751 });
752 if let Some(rng) = reproducible_rng {
753 distribution.sample(rng)
754 } else {
755 distribution.sample(&mut rand::rng())
756 }
757}
758
759fn serialize_params(params: &Params) -> Vec<Option<String>> {
761 std::iter::zip(params.execute_types.iter(), params.datums.iter())
762 .map(|(r#type, datum)| {
763 mz_pgrepr::Value::from_datum(datum, r#type).map(|val| {
764 let mut buf = BytesMut::new();
765 val.encode_text(&mut buf);
766 String::from_utf8(Into::<Vec<u8>>::into(buf))
767 .expect("Serialization shouldn't produce non-UTF-8 strings.")
768 })
769 })
770 .collect()
771}
772
773pub(crate) fn create_began_execution_record(
775 execution_uuid: Uuid,
776 prepared_statement_uuid: Uuid,
777 sample_rate: f64,
778 params: &Params,
779 session: &Session,
780 began_at: EpochMillis,
781 build_info_version: String,
782) -> StatementBeganExecutionRecord {
783 let params = serialize_params(params);
784 StatementBeganExecutionRecord {
785 id: execution_uuid,
786 prepared_statement_id: prepared_statement_uuid,
787 sample_rate,
788 params,
789 began_at,
790 application_name: session.application_name().to_string(),
791 transaction_isolation: session.vars().transaction_isolation().to_string(),
792 transaction_id: session
793 .transaction()
794 .inner()
795 .map(|t| t.id)
796 .unwrap_or_else(|| {
797 soft_panic_or_log!(
800 "Statement logging got a statement with no associated transaction"
801 );
802 9999999
803 }),
804 mz_version: build_info_version,
805 cluster_id: None,
807 cluster_name: None,
808 execution_timestamp: None,
809 transient_index_id: None,
810 database_name: session.vars().database().into(),
811 search_path: session
812 .vars()
813 .search_path()
814 .iter()
815 .map(|s| s.as_str().to_string())
816 .collect(),
817 }
818}
819
820#[derive(Debug, Clone)]
823pub enum FrontendStatementLoggingEvent {
824 BeganExecution {
827 record: StatementBeganExecutionRecord,
828 mseh_update: Row,
830 prepared_statement: Option<PreparedStatementEvent>,
831 },
832 EndedExecution(StatementEndedExecutionRecord),
834 SetCluster {
836 id: StatementLoggingId,
837 cluster_id: ClusterId,
838 },
839 SetTimestamp {
841 id: StatementLoggingId,
842 timestamp: Timestamp,
843 },
844 SetTransientIndex {
846 id: StatementLoggingId,
847 transient_index_id: GlobalId,
848 },
849 Lifecycle {
851 id: StatementLoggingId,
852 event: StatementLifecycleEvent,
853 when: EpochMillis,
854 },
855}
856
857pub(crate) fn pack_statement_execution_inner(
858 record: &StatementBeganExecutionRecord,
859 packer: &mut RowPacker,
860) {
861 let StatementBeganExecutionRecord {
862 id,
863 prepared_statement_id,
864 sample_rate,
865 params,
866 began_at,
867 cluster_id,
868 cluster_name,
869 database_name,
870 search_path,
871 application_name,
872 transaction_isolation,
873 execution_timestamp,
874 transaction_id,
875 transient_index_id,
876 mz_version,
877 } = record;
878
879 let cluster = cluster_id.map(|id| id.to_string());
880 let transient_index_id = transient_index_id.map(|id| id.to_string());
881 packer.extend([
882 Datum::Uuid(*id),
883 Datum::Uuid(*prepared_statement_id),
884 Datum::Float64((*sample_rate).into()),
885 match &cluster {
886 None => Datum::Null,
887 Some(cluster_id) => Datum::String(cluster_id),
888 },
889 Datum::String(&*application_name),
890 cluster_name.as_ref().map(String::as_str).into(),
891 Datum::String(database_name),
892 ]);
893 packer.push_list(search_path.iter().map(|s| Datum::String(s)));
894 packer.extend([
895 Datum::String(&*transaction_isolation),
896 (*execution_timestamp).into(),
897 Datum::UInt64(*transaction_id),
898 match &transient_index_id {
899 None => Datum::Null,
900 Some(transient_index_id) => Datum::String(transient_index_id),
901 },
902 ]);
903 packer
904 .try_push_array(
905 &[ArrayDimension {
906 lower_bound: 1,
907 length: params.len(),
908 }],
909 params
910 .iter()
911 .map(|p| Datum::from(p.as_ref().map(String::as_str))),
912 )
913 .expect("correct array dimensions");
914 packer.push(Datum::from(mz_version.as_str()));
915 packer.push(Datum::TimestampTz(
916 to_datetime(*began_at).try_into().expect("Sane system time"),
917 ));
918}
919
920pub(crate) fn pack_statement_began_execution_update(record: &StatementBeganExecutionRecord) -> Row {
921 let mut row = Row::default();
922 let mut packer = row.packer();
923 pack_statement_execution_inner(record, &mut packer);
924 packer.extend([
925 Datum::Null,
927 Datum::Null,
929 Datum::Null,
931 Datum::Null,
933 Datum::Null,
935 Datum::Null,
937 ]);
938 row
939}
940
941pub(crate) fn pack_statement_prepared_update(
942 record: &StatementPreparedRecord,
943 packer: &mut RowPacker,
944) {
945 let StatementPreparedRecord {
946 id,
947 session_id,
948 name,
949 sql_hash,
950 prepared_at,
951 kind,
952 } = record;
953 packer.extend([
954 Datum::Uuid(*id),
955 Datum::Uuid(*session_id),
956 Datum::String(name.as_str()),
957 Datum::Bytes(sql_hash.as_slice()),
958 Datum::TimestampTz(to_datetime(*prepared_at).try_into().expect("must fit")),
959 kind.map(statement_kind_label_value).into(),
960 ]);
961}
962
963#[derive(Debug)]
966pub struct WatchSetCreation {
967 pub logging_id: StatementLoggingId,
969 pub timestamp: Timestamp,
971 pub storage_ids: BTreeSet<GlobalId>,
973 pub compute_ids: BTreeSet<GlobalId>,
975}
976
977impl WatchSetCreation {
978 pub fn new(
981 logging_id: StatementLoggingId,
982 catalog_state: &CatalogState,
983 input_id_bundle: &CollectionIdBundle,
984 timestamp: Timestamp,
985 ) -> Self {
986 let mut storage_ids = BTreeSet::new();
987 let mut compute_ids = BTreeSet::new();
988
989 for item_id in input_id_bundle
990 .iter()
991 .map(|gid| catalog_state.get_entry_by_global_id(&gid).id())
992 .flat_map(|id| catalog_state.transitive_uses(id))
993 {
994 let entry = catalog_state.get_entry(&item_id);
995 match entry.item() {
996 CatalogItem::Table(_) | CatalogItem::Source(_) => {
1001 storage_ids.extend(entry.global_ids());
1002 }
1003 CatalogItem::MaterializedView(_) | CatalogItem::Index(_) => {
1006 compute_ids.insert(entry.latest_global_id());
1007 }
1008 _ => {}
1009 }
1010 }
1011
1012 Self {
1013 logging_id,
1014 timestamp,
1015 storage_ids,
1016 compute_ids,
1017 }
1018 }
1019}