1use risingwave_common::catalog::OBJECT_ID_PLACEHOLDER;
16use risingwave_common::hash::VnodeCountCompat;
17use risingwave_common::id::JobId;
18use risingwave_pb::catalog::table::{CdcTableType as PbCdcTableType, PbEngine, PbTableType};
19use risingwave_pb::catalog::{PbHandleConflictBehavior, PbTable, PbVectorIndexInfo};
20use sea_orm::ActiveValue::Set;
21use sea_orm::NotSet;
22use sea_orm::entity::prelude::*;
23use serde::{Deserialize, Serialize};
24
25use crate::{
26 Cardinality, ColumnCatalogArray, ColumnOrderArray, FragmentId, I32Array, SourceId, TableId,
27 TableVersion, WebhookSourceInfo,
28};
29
30#[derive(
31 Clone, Debug, PartialEq, Hash, Copy, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize,
32)]
33#[sea_orm(rs_type = "String", db_type = "string(None)")]
34pub enum TableType {
35 #[sea_orm(string_value = "TABLE")]
36 Table,
37 #[sea_orm(string_value = "MATERIALIZED_VIEW")]
38 MaterializedView,
39 #[sea_orm(string_value = "INDEX")]
40 Index,
41 #[sea_orm(string_value = "INTERNAL")]
42 Internal,
43 #[sea_orm(string_value = "VECTOR_INDEX")]
44 VectorIndex,
45}
46
47impl From<TableType> for PbTableType {
48 fn from(table_type: TableType) -> Self {
49 match table_type {
50 TableType::Table => Self::Table,
51 TableType::MaterializedView => Self::MaterializedView,
52 TableType::Index => Self::Index,
53 TableType::Internal => Self::Internal,
54 TableType::VectorIndex => Self::VectorIndex,
55 }
56 }
57}
58
59impl From<PbTableType> for TableType {
60 fn from(table_type: PbTableType) -> Self {
61 match table_type {
62 PbTableType::Table => Self::Table,
63 PbTableType::MaterializedView => Self::MaterializedView,
64 PbTableType::Index => Self::Index,
65 PbTableType::Internal => Self::Internal,
66 PbTableType::VectorIndex => Self::VectorIndex,
67 PbTableType::Unspecified => unreachable!("Unspecified table type"),
68 }
69 }
70}
71
72#[derive(Clone, Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize)]
73#[sea_orm(rs_type = "String", db_type = "string(None)")]
74pub enum HandleConflictBehavior {
75 #[sea_orm(string_value = "OVERWRITE")]
76 Overwrite,
77 #[sea_orm(string_value = "IGNORE")]
78 Ignore,
79 #[sea_orm(string_value = "NO_CHECK")]
80 NoCheck,
81 #[sea_orm(string_value = "DO_UPDATE_IF_NOT_NULL")]
82 DoUpdateIfNotNull,
83}
84
85impl From<HandleConflictBehavior> for PbHandleConflictBehavior {
86 fn from(handle_conflict_behavior: HandleConflictBehavior) -> Self {
87 match handle_conflict_behavior {
88 HandleConflictBehavior::Overwrite => Self::Overwrite,
89 HandleConflictBehavior::Ignore => Self::Ignore,
90 HandleConflictBehavior::NoCheck => Self::NoCheck,
91 HandleConflictBehavior::DoUpdateIfNotNull => Self::DoUpdateIfNotNull,
92 }
93 }
94}
95
96impl From<PbHandleConflictBehavior> for HandleConflictBehavior {
97 fn from(handle_conflict_behavior: PbHandleConflictBehavior) -> Self {
98 match handle_conflict_behavior {
99 PbHandleConflictBehavior::Overwrite => Self::Overwrite,
100 PbHandleConflictBehavior::Ignore => Self::Ignore,
101 PbHandleConflictBehavior::NoCheck => Self::NoCheck,
102 PbHandleConflictBehavior::DoUpdateIfNotNull => Self::DoUpdateIfNotNull,
103 PbHandleConflictBehavior::Unspecified => {
104 unreachable!("Unspecified handle conflict behavior")
105 }
106 }
107 }
108}
109
110#[derive(Clone, Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize)]
111#[sea_orm(rs_type = "String", db_type = "string(None)")]
112pub enum Engine {
113 #[sea_orm(string_value = "HUMMOCK")]
114 Hummock,
115 #[sea_orm(string_value = "ICEBERG")]
116 Iceberg,
117}
118
119impl From<Engine> for PbEngine {
120 fn from(engine: Engine) -> Self {
121 match engine {
122 Engine::Hummock => Self::Hummock,
123 Engine::Iceberg => Self::Iceberg,
124 }
125 }
126}
127
128impl From<PbEngine> for Engine {
129 fn from(engine: PbEngine) -> Self {
130 match engine {
131 PbEngine::Hummock => Self::Hummock,
132 PbEngine::Iceberg => Self::Iceberg,
133 PbEngine::Unspecified => Self::Hummock,
134 }
135 }
136}
137
138#[derive(Clone, Debug, PartialEq, Eq, Hash, EnumIter, DeriveActiveEnum, Serialize, Deserialize)]
139#[sea_orm(rs_type = "String", db_type = "string(None)")]
140pub enum CdcTableType {
141 #[sea_orm(string_value = "UNSPECIFIED")]
142 Unspecified,
143 #[sea_orm(string_value = "POSTGRES")]
144 Postgres,
145 #[sea_orm(string_value = "MYSQL")]
146 Mysql,
147 #[sea_orm(string_value = "MARIADB")]
148 Mariadb,
149 #[sea_orm(string_value = "SQLSERVER")]
150 #[serde(rename = "Sqlserver")] SqlServer,
152 #[sea_orm(string_value = "MONGO")]
153 #[serde(rename = "Mongo")] Mongodb,
155 #[sea_orm(string_value = "ORACLE")]
156 Oracle,
157}
158
159impl From<CdcTableType> for PbCdcTableType {
160 fn from(cdc_table_type: CdcTableType) -> Self {
161 match cdc_table_type {
162 CdcTableType::Postgres => Self::Postgres,
163 CdcTableType::Mysql => Self::Mysql,
164 CdcTableType::Mariadb => Self::Mariadb,
165 CdcTableType::SqlServer => Self::SqlServer,
166 CdcTableType::Mongodb => Self::Mongodb,
167 CdcTableType::Oracle => Self::Oracle,
168 CdcTableType::Unspecified => Self::Unspecified,
169 }
170 }
171}
172
173impl From<PbCdcTableType> for CdcTableType {
174 fn from(cdc_table_type: PbCdcTableType) -> Self {
175 match cdc_table_type {
176 PbCdcTableType::Postgres => Self::Postgres,
177 PbCdcTableType::Mysql => Self::Mysql,
178 PbCdcTableType::Mariadb => Self::Mariadb,
179 PbCdcTableType::SqlServer => Self::SqlServer,
180 PbCdcTableType::Mongodb => Self::Mongodb,
181 PbCdcTableType::Oracle => Self::Oracle,
182 PbCdcTableType::Unspecified => Self::Unspecified,
183 }
184 }
185}
186
187crate::derive_from_blob!(VectorIndexInfo, PbVectorIndexInfo);
188
189#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
190#[sea_orm(table_name = "table")]
191pub struct Model {
192 #[sea_orm(primary_key, auto_increment = false)]
193 pub table_id: TableId,
194 pub name: String,
195 pub optional_associated_source_id: Option<SourceId>,
196 pub table_type: TableType,
197 pub belongs_to_job_id: Option<JobId>,
198 pub columns: ColumnCatalogArray,
199 pub pk: ColumnOrderArray,
200 pub distribution_key: I32Array,
201 pub stream_key: I32Array,
202 pub append_only: bool,
203 pub fragment_id: Option<FragmentId>,
204 pub vnode_col_index: Option<i32>,
205 pub row_id_index: Option<i32>,
206 pub value_indices: I32Array,
207 pub definition: String,
208 pub handle_pk_conflict_behavior: HandleConflictBehavior,
209 pub version_column_indices: Option<I32Array>,
210 pub read_prefix_len_hint: i32,
211 pub watermark_indices: I32Array,
212 pub dist_key_in_pk: I32Array,
213 pub dml_fragment_id: Option<FragmentId>,
214 pub cardinality: Option<Cardinality>,
215 pub cleaned_by_watermark: bool,
216 pub description: Option<String>,
217 pub version: Option<TableVersion>,
218 pub retention_seconds: Option<i32>,
219 pub cdc_table_id: Option<String>,
220 pub vnode_count: i32,
221 pub webhook_info: Option<WebhookSourceInfo>,
222 pub engine: Option<Engine>,
223 pub clean_watermark_index_in_pk: Option<i32>,
224 pub clean_watermark_indices: Option<I32Array>,
225 pub refreshable: bool,
226 pub vector_index_info: Option<VectorIndexInfo>,
227 pub cdc_table_type: Option<CdcTableType>,
228}
229
230#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
231pub enum Relation {
232 #[sea_orm(
233 belongs_to = "super::fragment::Entity",
234 from = "Column::DmlFragmentId",
235 to = "super::fragment::Column::FragmentId",
236 on_update = "NoAction",
237 on_delete = "NoAction"
238 )]
239 Fragment2,
240 #[sea_orm(
241 belongs_to = "super::fragment::Entity",
242 from = "Column::FragmentId",
243 to = "super::fragment::Column::FragmentId",
244 on_update = "NoAction",
245 on_delete = "NoAction"
246 )]
247 Fragment1,
248 #[sea_orm(
249 belongs_to = "super::object::Entity",
250 from = "Column::BelongsToJobId",
251 to = "super::object::Column::Oid",
252 on_update = "NoAction",
253 on_delete = "Cascade"
254 )]
255 Object2,
256 #[sea_orm(
257 belongs_to = "super::object::Entity",
258 from = "Column::TableId",
259 to = "super::object::Column::Oid",
260 on_update = "NoAction",
261 on_delete = "Cascade"
262 )]
263 Object1,
264 #[sea_orm(
265 belongs_to = "super::source::Entity",
266 from = "Column::OptionalAssociatedSourceId",
267 to = "super::source::Column::SourceId",
268 on_update = "NoAction",
269 on_delete = "NoAction"
270 )]
271 Source,
272
273 #[sea_orm(
275 belongs_to = "super::object_dependency::Entity",
276 from = "Column::TableId",
277 to = "super::object_dependency::Column::UsedBy",
278 on_update = "NoAction",
279 on_delete = "Cascade"
280 )]
281 ObjectDependency,
282}
283
284impl Related<super::object::Entity> for Entity {
285 fn to() -> RelationDef {
286 Relation::Object1.def()
287 }
288}
289
290impl Related<super::source::Entity> for Entity {
291 fn to() -> RelationDef {
292 Relation::Source.def()
293 }
294}
295
296impl ActiveModelBehavior for ActiveModel {}
297
298impl Model {
299 pub fn job_id(&self) -> JobId {
300 self.belongs_to_job_id
301 .unwrap_or_else(|| self.table_id.as_job_id())
302 }
303}
304
305impl From<PbTable> for ActiveModel {
306 fn from(pb_table: PbTable) -> Self {
307 let table_type = pb_table.table_type();
308 let handle_pk_conflict_behavior = pb_table.handle_pk_conflict_behavior();
309
310 let vnode_count = pb_table
314 .vnode_count_inner()
315 .value_opt()
316 .map(|v| v as _)
317 .map_or(NotSet, Set);
318 let fragment_id = if pb_table.fragment_id == OBJECT_ID_PLACEHOLDER {
319 NotSet
320 } else {
321 Set(Some(pb_table.fragment_id))
322 };
323 let dml_fragment_id = pb_table
324 .dml_fragment_id
325 .map(|x| Set(Some(x)))
326 .unwrap_or_default();
327 let optional_associated_source_id =
328 if let Some(src_id) = pb_table.optional_associated_source_id {
329 Set(Some(src_id.into()))
330 } else {
331 NotSet
332 };
333
334 Self {
335 table_id: Set(pb_table.id),
336 name: Set(pb_table.name),
337 optional_associated_source_id,
338 table_type: Set(table_type.into()),
339 belongs_to_job_id: Set(pb_table.job_id),
340 columns: Set(pb_table.columns.into()),
341 pk: Set(pb_table.pk.into()),
342 distribution_key: Set(pb_table.distribution_key.into()),
343 stream_key: Set(pb_table.stream_key.into()),
344 append_only: Set(pb_table.append_only),
345 fragment_id,
346 vnode_col_index: Set(pb_table.vnode_col_index.map(|x| x as i32)),
347 row_id_index: Set(pb_table.row_id_index.map(|x| x as i32)),
348 value_indices: Set(pb_table.value_indices.into()),
349 definition: Set(pb_table.definition),
350 handle_pk_conflict_behavior: Set(handle_pk_conflict_behavior.into()),
351 version_column_indices: Set(Some(
352 pb_table
353 .version_column_indices
354 .iter()
355 .map(|x| *x as i32)
356 .collect::<Vec<_>>()
357 .into(),
358 )),
359 read_prefix_len_hint: Set(pb_table.read_prefix_len_hint as _),
360 watermark_indices: Set(pb_table.watermark_indices.into()),
361 dist_key_in_pk: Set(pb_table.dist_key_in_pk.into()),
362 dml_fragment_id,
363 cardinality: Set(pb_table.cardinality.as_ref().map(|x| x.into())),
364 #[expect(deprecated)]
365 cleaned_by_watermark: Set(pb_table.cleaned_by_watermark),
366 description: Set(pb_table.description),
367 version: Set(pb_table.version.as_ref().map(|v| v.into())),
368 retention_seconds: Set(pb_table.retention_seconds.map(|i| i as _)),
369 cdc_table_id: Set(pb_table.cdc_table_id),
370 vnode_count,
371 webhook_info: Set(pb_table.webhook_info.as_ref().map(WebhookSourceInfo::from)),
372 engine: Set(pb_table
373 .engine
374 .map(|engine| Engine::from(PbEngine::try_from(engine).expect("Invalid engine")))),
375 #[expect(deprecated)]
376 clean_watermark_index_in_pk: Set(pb_table.clean_watermark_index_in_pk),
377 clean_watermark_indices: Set(if pb_table.clean_watermark_indices.is_empty() {
378 None
379 } else {
380 Some(
381 pb_table
382 .clean_watermark_indices
383 .iter()
384 .map(|x| *x as i32)
385 .collect::<Vec<_>>()
386 .into(),
387 )
388 }),
389 refreshable: Set(pb_table.refreshable),
390 vector_index_info: Set(pb_table
391 .vector_index_info
392 .as_ref()
393 .map(VectorIndexInfo::from)),
394 cdc_table_type: Set(pb_table.cdc_table_type.map(|cdc_table_type| {
395 match cdc_table_type {
396 0 => CdcTableType::Postgres, 1 => CdcTableType::Postgres,
398 2 => CdcTableType::Mysql,
399 3 => CdcTableType::SqlServer,
400 4 => CdcTableType::Mongodb,
401 6 => CdcTableType::Mariadb,
402 7 => CdcTableType::Oracle,
403 _ => panic!("Invalid CDC table type: {cdc_table_type}"),
404 }
405 })),
406 }
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 #[test]
415 fn test_cdc_table_type_persisted_names() {
416 for (cdc_table_type, sea_orm_value, serde_name) in [
417 (CdcTableType::Unspecified, "UNSPECIFIED", "Unspecified"),
418 (CdcTableType::Postgres, "POSTGRES", "Postgres"),
419 (CdcTableType::Mysql, "MYSQL", "Mysql"),
420 (CdcTableType::Mariadb, "MARIADB", "Mariadb"),
421 (CdcTableType::SqlServer, "SQLSERVER", "Sqlserver"),
422 (CdcTableType::Mongodb, "MONGO", "Mongo"),
423 (CdcTableType::Oracle, "ORACLE", "Oracle"),
424 ] {
425 assert_eq!(cdc_table_type.to_value(), sea_orm_value);
426 assert_eq!(
427 serde_json::to_string(&cdc_table_type).unwrap(),
428 format!("\"{serde_name}\"")
429 );
430 }
431 }
432}