Skip to main content

risingwave_common/catalog/
mod.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod cdc_type_compatibility;
16mod column;
17mod external_table;
18mod internal_table;
19mod physical_table;
20mod schema;
21pub mod test_utils;
22
23use std::fmt::Binary;
24use std::sync::Arc;
25
26pub use column::*;
27pub use external_table::*;
28use futures::stream::BoxStream;
29pub use internal_table::*;
30use parse_display::Display;
31pub use physical_table::*;
32use risingwave_pb::catalog::table::PbEngine;
33use risingwave_pb::catalog::{
34    CreateType as PbCreateType, HandleConflictBehavior as PbHandleConflictBehavior,
35    StreamJobStatus as PbStreamJobStatus,
36};
37use risingwave_pb::plan_common::ColumnDescVersion;
38pub use schema::{Field, FieldDisplay, FieldLike, Schema, test_utils as schema_test_utils};
39
40use crate::array::DataChunk;
41pub use crate::constants::hummock;
42use crate::error::BoxedError;
43pub use crate::id::*;
44
45/// The global version of the catalog.
46pub type CatalogVersion = u64;
47
48/// The version number of the per-table catalog.
49pub type TableVersionId = u64;
50/// The default version ID for a new table.
51pub const INITIAL_TABLE_VERSION_ID: u64 = 0;
52/// The version number of the per-source catalog.
53pub type SourceVersionId = u64;
54/// The default version ID for a new source.
55pub const INITIAL_SOURCE_VERSION_ID: u64 = 0;
56
57pub const DEFAULT_DATABASE_NAME: &str = "dev";
58pub const DEFAULT_SCHEMA_NAME: &str = "public";
59pub const PG_CATALOG_SCHEMA_NAME: &str = "pg_catalog";
60pub const INFORMATION_SCHEMA_SCHEMA_NAME: &str = "information_schema";
61pub const RW_CATALOG_SCHEMA_NAME: &str = "rw_catalog";
62pub const RESERVED_PG_SCHEMA_PREFIX: &str = "pg_";
63pub const DEFAULT_SUPER_USER: &str = "root";
64pub const DEFAULT_SUPER_USER_ID: UserId = UserId::new(1);
65// This is for compatibility with customized utils for PostgreSQL.
66pub const DEFAULT_SUPER_USER_FOR_PG: &str = "postgres";
67pub const DEFAULT_SUPER_USER_FOR_PG_ID: u32 = 2;
68
69// This is the default superuser for admin, which is used only for cloud control plane.
70pub const DEFAULT_SUPER_USER_FOR_ADMIN: &str = "rwadmin";
71pub const DEFAULT_SUPER_USER_FOR_ADMIN_ID: UserId = UserId::new(3);
72
73pub const NON_RESERVED_USER_ID: UserId = UserId::new(11);
74
75pub const MAX_SYS_CATALOG_NUM: i32 = 5000;
76pub const SYS_CATALOG_START_ID: i32 = i32::MAX - MAX_SYS_CATALOG_NUM;
77
78pub use risingwave_pb::id::OBJECT_ID_PLACEHOLDER;
79
80pub const SYSTEM_SCHEMAS: [&str; 3] = [
81    PG_CATALOG_SCHEMA_NAME,
82    INFORMATION_SCHEMA_SCHEMA_NAME,
83    RW_CATALOG_SCHEMA_NAME,
84];
85pub fn is_system_schema(schema_name: &str) -> bool {
86    SYSTEM_SCHEMAS.contains(&schema_name)
87}
88
89pub fn is_reserved_admin_user(user_name: &str) -> bool {
90    user_name == DEFAULT_SUPER_USER_FOR_ADMIN
91}
92
93pub const RW_RESERVED_COLUMN_NAME_PREFIX: &str = "_rw_";
94
95/// When there is no primary key specified while creating source, will use
96/// the message key as primary key in `BYTEA` type with this name.
97/// Note: the field has version to track, please refer to [`default_key_column_name_version_mapping`]
98pub const DEFAULT_KEY_COLUMN_NAME: &str = "_rw_key";
99
100pub fn default_key_column_name_version_mapping(version: &ColumnDescVersion) -> &str {
101    match version {
102        ColumnDescVersion::Unspecified => DEFAULT_KEY_COLUMN_NAME,
103        _ => DEFAULT_KEY_COLUMN_NAME,
104    }
105}
106
107/// For kafka source, we attach a hidden column [`KAFKA_TIMESTAMP_COLUMN_NAME`] to it, so that we
108/// can limit the timestamp range when querying it directly with batch query. The column type is
109/// [`crate::types::DataType::Timestamptz`]. For more details, please refer to
110/// [this rfc](https://github.com/risingwavelabs/rfcs/pull/20).
111pub const KAFKA_TIMESTAMP_COLUMN_NAME: &str = "_rw_kafka_timestamp";
112
113/// RisingWave iceberg table engine will create the column `_risingwave_iceberg_row_id` in the iceberg table.
114///
115/// Iceberg V3 spec use `_row_id` as a reserved column name for row lineage, so if the table without primary key,
116/// we can't use `_row_id` directly for iceberg, so use `_risingwave_iceberg_row_id` instead.
117pub const RISINGWAVE_ICEBERG_ROW_ID: &str = "_risingwave_iceberg_row_id";
118
119pub const ROW_ID_COLUMN_NAME: &str = "_row_id";
120/// The column ID preserved for the row ID column.
121pub const ROW_ID_COLUMN_ID: ColumnId = ColumnId::new(0);
122
123/// The column ID offset for user-defined columns.
124///
125/// All IDs of user-defined columns must be greater or equal to this value.
126pub const USER_COLUMN_ID_OFFSET: i32 = ROW_ID_COLUMN_ID.next().get_id();
127
128pub const RW_TIMESTAMP_COLUMN_NAME: &str = "_rw_timestamp";
129pub const RW_TIMESTAMP_COLUMN_ID: ColumnId = ColumnId::new(-1);
130pub const RW_VNODE_COLUMN_NAME: &str = "_rw_vnode";
131pub const RW_VNODE_COLUMN_ID: ColumnId = ColumnId::new(-2);
132
133/// The column name for the projected row ID in `ProjectSet`.
134/// This is a hidden column used to track row indices when expanding set-returning functions.
135pub const PROJECTED_ROW_ID_COLUMN_NAME: &str = "_rw_projected_row_id";
136
137pub const ICEBERG_SEQUENCE_NUM_COLUMN_NAME: &str = "_iceberg_sequence_number";
138pub const ICEBERG_FILE_PATH_COLUMN_NAME: &str = "_iceberg_file_path";
139pub const ICEBERG_FILE_POS_COLUMN_NAME: &str = "_iceberg_file_pos";
140
141pub const CDC_OFFSET_COLUMN_NAME: &str = "_rw_offset";
142/// The number of columns output by the cdc source job
143/// see [`ColumnCatalog::debezium_cdc_source_cols()`] for details
144pub const CDC_SOURCE_COLUMN_NUM: u32 = 3;
145pub const CDC_TABLE_NAME_COLUMN_NAME: &str = "_rw_table_name";
146
147pub const ICEBERG_SOURCE_PREFIX: &str = "__iceberg_source_";
148pub const ICEBERG_SINK_PREFIX: &str = "__iceberg_sink_";
149
150/// Iceberg snapshot summary property containing the highest RisingWave epoch committed by the
151/// sink. Append-only Iceberg engine batch reads use it to exclude committed rows from the sink
152/// log store.
153pub const RISINGWAVE_ICEBERG_COMMIT_EPOCH: &str = "risingwave.commit.epoch";
154
155/// The local system catalog reader in the frontend node.
156pub trait SysCatalogReader: Sync + Send + 'static {
157    /// Reads the data of the system catalog table.
158    fn read_table(&self, table_id: TableId) -> BoxStream<'_, Result<DataChunk, BoxedError>>;
159}
160
161pub type SysCatalogReaderRef = Arc<dyn SysCatalogReader>;
162
163#[derive(Clone, Debug, PartialEq, Default, Copy)]
164pub struct TableOption {
165    pub retention_seconds: Option<u32>, // second
166}
167
168impl From<&risingwave_pb::hummock::TableOption> for TableOption {
169    fn from(table_option: &risingwave_pb::hummock::TableOption) -> Self {
170        Self {
171            retention_seconds: table_option.retention_seconds,
172        }
173    }
174}
175
176impl From<&TableOption> for risingwave_pb::hummock::TableOption {
177    fn from(table_option: &TableOption) -> Self {
178        Self {
179            retention_seconds: table_option.retention_seconds,
180        }
181    }
182}
183
184impl TableOption {
185    pub fn new(retention_seconds: Option<u32>) -> Self {
186        // now we only support ttl for TableOption
187        TableOption { retention_seconds }
188    }
189}
190
191#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
192pub enum ConflictBehavior {
193    #[default]
194    NoCheck,
195    Overwrite,
196    IgnoreConflict,
197    DoUpdateIfNotNull,
198}
199
200#[macro_export]
201macro_rules! _checked_conflict_behaviors {
202    () => {
203        ConflictBehavior::Overwrite
204            | ConflictBehavior::IgnoreConflict
205            | ConflictBehavior::DoUpdateIfNotNull
206    };
207}
208pub use _checked_conflict_behaviors as checked_conflict_behaviors;
209
210impl ConflictBehavior {
211    pub fn from_protobuf(tb_conflict_behavior: &PbHandleConflictBehavior) -> Self {
212        match tb_conflict_behavior {
213            PbHandleConflictBehavior::Overwrite => ConflictBehavior::Overwrite,
214            PbHandleConflictBehavior::Ignore => ConflictBehavior::IgnoreConflict,
215            PbHandleConflictBehavior::DoUpdateIfNotNull => ConflictBehavior::DoUpdateIfNotNull,
216            // This is for backward compatibility, in the previous version
217            // `HandleConflictBehavior::Unspecified` represented `NoCheck`, so just treat it as `NoCheck`.
218            PbHandleConflictBehavior::NoCheck | PbHandleConflictBehavior::Unspecified => {
219                ConflictBehavior::NoCheck
220            }
221        }
222    }
223
224    pub fn to_protobuf(self) -> PbHandleConflictBehavior {
225        match self {
226            ConflictBehavior::NoCheck => PbHandleConflictBehavior::NoCheck,
227            ConflictBehavior::Overwrite => PbHandleConflictBehavior::Overwrite,
228            ConflictBehavior::IgnoreConflict => PbHandleConflictBehavior::Ignore,
229            ConflictBehavior::DoUpdateIfNotNull => PbHandleConflictBehavior::DoUpdateIfNotNull,
230        }
231    }
232
233    pub fn debug_to_string(self) -> String {
234        match self {
235            ConflictBehavior::NoCheck => "NoCheck".to_owned(),
236            ConflictBehavior::Overwrite => "Overwrite".to_owned(),
237            ConflictBehavior::IgnoreConflict => "IgnoreConflict".to_owned(),
238            ConflictBehavior::DoUpdateIfNotNull => "DoUpdateIfNotNull".to_owned(),
239        }
240    }
241}
242
243#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
244pub enum Engine {
245    #[default]
246    Hummock,
247    Iceberg,
248}
249
250impl Engine {
251    pub fn from_protobuf(engine: &PbEngine) -> Self {
252        match engine {
253            PbEngine::Hummock | PbEngine::Unspecified => Engine::Hummock,
254            PbEngine::Iceberg => Engine::Iceberg,
255        }
256    }
257
258    pub fn to_protobuf(self) -> PbEngine {
259        match self {
260            Engine::Hummock => PbEngine::Hummock,
261            Engine::Iceberg => PbEngine::Iceberg,
262        }
263    }
264
265    pub fn debug_to_string(self) -> String {
266        match self {
267            Engine::Hummock => "Hummock".to_owned(),
268            Engine::Iceberg => "Iceberg".to_owned(),
269        }
270    }
271}
272
273#[derive(Clone, Copy, Debug, Default, Display, Hash, PartialOrd, PartialEq, Eq, Ord)]
274pub enum StreamJobStatus {
275    #[default]
276    Creating,
277    Created,
278}
279
280impl StreamJobStatus {
281    pub fn from_proto(stream_job_status: PbStreamJobStatus) -> Self {
282        match stream_job_status {
283            PbStreamJobStatus::Creating => StreamJobStatus::Creating,
284            PbStreamJobStatus::Created | PbStreamJobStatus::Unspecified => StreamJobStatus::Created,
285        }
286    }
287
288    pub fn to_proto(self) -> PbStreamJobStatus {
289        match self {
290            StreamJobStatus::Creating => PbStreamJobStatus::Creating,
291            StreamJobStatus::Created => PbStreamJobStatus::Created,
292        }
293    }
294}
295
296#[derive(Clone, Copy, Debug, Display, Hash, PartialOrd, PartialEq, Eq, Ord, Default)]
297pub enum CreateType {
298    #[default]
299    Foreground,
300    Background,
301}
302
303impl CreateType {
304    pub fn from_proto(pb_create_type: PbCreateType) -> Self {
305        match pb_create_type {
306            PbCreateType::Foreground | PbCreateType::Unspecified => CreateType::Foreground,
307            PbCreateType::Background => CreateType::Background,
308        }
309    }
310
311    pub fn to_proto(self) -> PbCreateType {
312        match self {
313            CreateType::Foreground => PbCreateType::Foreground,
314            CreateType::Background => PbCreateType::Background,
315        }
316    }
317}
318
319#[derive(Clone, Debug)]
320pub enum AlterDatabaseParam {
321    // Barrier related parameters, per database.
322    // None represents the default value, which means it follows `SystemParams`.
323    BarrierIntervalMs(Option<u32>),
324    CheckpointFrequency(Option<u64>),
325}
326
327macro_rules! for_all_fragment_type_flags {
328    () => {
329        for_all_fragment_type_flags! {
330            {
331                Source,
332                Mview,
333                Sink,
334                Now,
335                StreamScan,
336                BarrierRecv,
337                Values,
338                Dml,
339                CdcFilter,
340                Skipped1,
341                SourceScan,
342                SnapshotBackfillStreamScan,
343                FsFetch,
344                CrossDbSnapshotBackfillStreamScan,
345                StreamCdcScan,
346                VectorIndexWrite,
347                UpstreamSinkUnion,
348                LocalityProvider,
349                IcebergWithPkIndexWriter
350            },
351            {},
352            0
353        }
354    };
355    (
356        {},
357        {
358            $(
359                {$flag:ident, $index:expr}
360            ),*
361        },
362        $next_index:expr
363    ) => {
364        #[derive(Clone, Copy, Debug, Display, Hash, PartialOrd, PartialEq, Eq)]
365        #[repr(u32)]
366        pub enum FragmentTypeFlag {
367            $(
368                $flag = (1 << $index),
369            )*
370        }
371
372        pub const FRAGMENT_TYPE_FLAG_LIST: [FragmentTypeFlag; $next_index] = [
373            $(
374                FragmentTypeFlag::$flag,
375            )*
376        ];
377
378        impl TryFrom<u32> for FragmentTypeFlag {
379            type Error = String;
380
381            fn try_from(value: u32) -> Result<Self, Self::Error> {
382                match value {
383                    $(
384                        value if value == (FragmentTypeFlag::$flag as u32) => Ok(FragmentTypeFlag::$flag),
385                    )*
386                    _ => Err(format!("Invalid FragmentTypeFlag value: {}", value)),
387                }
388            }
389        }
390
391        impl FragmentTypeFlag {
392            pub fn as_str_name(&self) -> &'static str {
393                match self {
394                    $(
395                        FragmentTypeFlag::$flag => paste::paste!{stringify!( [< $flag:snake:upper >] )},
396                    )*
397                }
398            }
399        }
400    };
401    (
402        {$first:ident $(, $rest:ident)*},
403        {
404            $(
405                {$flag:ident, $index:expr}
406            ),*
407        },
408        $next_index:expr
409    ) => {
410        for_all_fragment_type_flags! {
411            {$($rest),*},
412            {
413                $({$flag, $index},)*
414                {$first, $next_index}
415            },
416            $next_index + 1
417        }
418    };
419}
420
421for_all_fragment_type_flags!();
422
423impl FragmentTypeFlag {
424    pub fn raw_flag(flags: impl IntoIterator<Item = FragmentTypeFlag>) -> u32 {
425        flags.into_iter().fold(0, |acc, flag| acc | (flag as u32))
426    }
427
428    /// Fragments that may be affected by `BACKFILL_RATE_LIMIT`.
429    pub fn backfill_rate_limit_fragments() -> impl Iterator<Item = FragmentTypeFlag> {
430        [
431            FragmentTypeFlag::SourceScan,
432            FragmentTypeFlag::StreamScan,
433            FragmentTypeFlag::StreamCdcScan,
434            FragmentTypeFlag::LocalityProvider,
435        ]
436        .into_iter()
437    }
438
439    /// Fragments that may be affected by `SOURCE_RATE_LIMIT`.
440    /// Note: for `FsFetch`, old fragments don't have this flag set, so don't use this to check.
441    pub fn source_rate_limit_fragments() -> impl Iterator<Item = FragmentTypeFlag> {
442        [FragmentTypeFlag::Source, FragmentTypeFlag::FsFetch].into_iter()
443    }
444
445    /// Fragments that may be affected by `BACKFILL_RATE_LIMIT`.
446    pub fn sink_rate_limit_fragments() -> impl Iterator<Item = FragmentTypeFlag> {
447        [FragmentTypeFlag::Sink].into_iter()
448    }
449
450    /// Note: this doesn't include `FsFetch` created in old versions.
451    pub fn rate_limit_fragments() -> impl Iterator<Item = FragmentTypeFlag> {
452        Self::backfill_rate_limit_fragments()
453            .chain(Self::source_rate_limit_fragments())
454            .chain(Self::sink_rate_limit_fragments())
455            .chain(Self::dml_rate_limit_fragments())
456    }
457
458    pub fn dml_rate_limit_fragments() -> impl Iterator<Item = FragmentTypeFlag> {
459        [FragmentTypeFlag::Dml].into_iter()
460    }
461}
462
463#[derive(Clone, Copy, Debug, Hash, PartialOrd, PartialEq, Eq, Default)]
464pub struct FragmentTypeMask(u32);
465
466impl Binary for FragmentTypeMask {
467    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
468        write!(f, "{:b}", self.0)
469    }
470}
471
472impl From<i32> for FragmentTypeMask {
473    fn from(value: i32) -> Self {
474        Self(value as u32)
475    }
476}
477
478impl From<u32> for FragmentTypeMask {
479    fn from(value: u32) -> Self {
480        Self(value)
481    }
482}
483
484impl From<FragmentTypeMask> for u32 {
485    fn from(value: FragmentTypeMask) -> Self {
486        value.0
487    }
488}
489
490impl From<FragmentTypeMask> for i32 {
491    fn from(value: FragmentTypeMask) -> Self {
492        value.0 as _
493    }
494}
495
496impl FragmentTypeMask {
497    pub fn empty() -> Self {
498        FragmentTypeMask(0)
499    }
500
501    pub fn add(&mut self, flag: FragmentTypeFlag) {
502        self.0 |= flag as u32;
503    }
504
505    pub fn contains_any(&self, flags: impl IntoIterator<Item = FragmentTypeFlag>) -> bool {
506        let flag = FragmentTypeFlag::raw_flag(flags);
507        (self.0 & flag) != 0
508    }
509
510    pub fn contains(&self, flag: FragmentTypeFlag) -> bool {
511        self.contains_any([flag])
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use itertools::Itertools;
518    use risingwave_common::catalog::FRAGMENT_TYPE_FLAG_LIST;
519
520    use crate::catalog::FragmentTypeFlag;
521
522    #[test]
523    fn test_all_fragment_type_flag() {
524        expect_test::expect![[r#"
525            [
526                (
527                    Source,
528                    1,
529                    "SOURCE",
530                ),
531                (
532                    Mview,
533                    2,
534                    "MVIEW",
535                ),
536                (
537                    Sink,
538                    4,
539                    "SINK",
540                ),
541                (
542                    Now,
543                    8,
544                    "NOW",
545                ),
546                (
547                    StreamScan,
548                    16,
549                    "STREAM_SCAN",
550                ),
551                (
552                    BarrierRecv,
553                    32,
554                    "BARRIER_RECV",
555                ),
556                (
557                    Values,
558                    64,
559                    "VALUES",
560                ),
561                (
562                    Dml,
563                    128,
564                    "DML",
565                ),
566                (
567                    CdcFilter,
568                    256,
569                    "CDC_FILTER",
570                ),
571                (
572                    Skipped1,
573                    512,
574                    "SKIPPED1",
575                ),
576                (
577                    SourceScan,
578                    1024,
579                    "SOURCE_SCAN",
580                ),
581                (
582                    SnapshotBackfillStreamScan,
583                    2048,
584                    "SNAPSHOT_BACKFILL_STREAM_SCAN",
585                ),
586                (
587                    FsFetch,
588                    4096,
589                    "FS_FETCH",
590                ),
591                (
592                    CrossDbSnapshotBackfillStreamScan,
593                    8192,
594                    "CROSS_DB_SNAPSHOT_BACKFILL_STREAM_SCAN",
595                ),
596                (
597                    StreamCdcScan,
598                    16384,
599                    "STREAM_CDC_SCAN",
600                ),
601                (
602                    VectorIndexWrite,
603                    32768,
604                    "VECTOR_INDEX_WRITE",
605                ),
606                (
607                    UpstreamSinkUnion,
608                    65536,
609                    "UPSTREAM_SINK_UNION",
610                ),
611                (
612                    LocalityProvider,
613                    131072,
614                    "LOCALITY_PROVIDER",
615                ),
616                (
617                    IcebergWithPkIndexWriter,
618                    262144,
619                    "ICEBERG_WITH_PK_INDEX_WRITER",
620                ),
621            ]
622        "#]]
623        .assert_debug_eq(
624            &FRAGMENT_TYPE_FLAG_LIST
625                .into_iter()
626                .map(|flag| (flag, flag as u32, flag.as_str_name()))
627                .collect_vec(),
628        );
629        for flag in FRAGMENT_TYPE_FLAG_LIST {
630            assert_eq!(FragmentTypeFlag::try_from(flag as u32).unwrap(), flag);
631        }
632    }
633
634    #[test]
635    fn test_backfill_rate_limit_fragments_include_cdc_scan() {
636        // `ALTER TABLE ... SET BACKFILL_RATE_LIMIT` on a CDC table must reach the
637        // `StreamCdcScan` fragment, otherwise meta reports "stream scan node not found".
638        assert!(
639            FragmentTypeFlag::backfill_rate_limit_fragments()
640                .any(|f| f == FragmentTypeFlag::StreamCdcScan)
641        );
642    }
643}