1use std::collections::BTreeMap;
16use std::time::Duration;
17
18use anyhow::{Context, anyhow};
19use risingwave_common::bail;
20use risingwave_common::hash::VnodeCount;
21use risingwave_common::util::epoch::Epoch;
22use risingwave_meta_model::{
23 PrivateLinkService, connection, database, function, index, object, schema, secret, sink,
24 source, subscription, table, view,
25};
26use risingwave_meta_model_migration::{MigrationStatus, Migrator, MigratorTrait};
27use risingwave_pb::catalog::connection::PbInfo as PbConnectionInfo;
28use risingwave_pb::catalog::source::PbOptionalAssociatedTableId;
29use risingwave_pb::catalog::table::{PbEngine, PbOptionalAssociatedSourceId, PbTableType};
30use risingwave_pb::catalog::{
31 PbConnection, PbCreateType, PbDatabase, PbFunction, PbHandleConflictBehavior, PbIndex,
32 PbSchema, PbSecret, PbSink, PbSinkType, PbSource, PbStreamJobStatus, PbSubscription, PbTable,
33 PbView,
34};
35use sea_orm::{ConnectOptions, DatabaseConnection, DbBackend, ModelTrait};
36
37use crate::{MetaError, MetaResult, MetaStoreBackend};
38
39pub mod catalog;
40pub mod cluster;
41pub mod fragment;
42pub mod id;
43pub mod rename;
44pub mod scale;
45pub mod session_params;
46pub mod streaming_job;
47pub mod system_param;
48pub mod user;
49pub mod utils;
50
51impl From<sea_orm::DbErr> for MetaError {
53 fn from(err: sea_orm::DbErr) -> Self {
54 if let Some(err) = err.sql_err() {
55 return anyhow!(err).into();
56 }
57 anyhow!(err).into()
58 }
59}
60
61#[derive(Clone)]
62pub struct SqlMetaStore {
63 pub conn: DatabaseConnection,
64 pub endpoint: String,
65}
66
67impl SqlMetaStore {
68 pub async fn connect(backend: MetaStoreBackend) -> MetaResult<Self> {
70 const MAX_DURATION: Duration = Duration::new(u64::MAX / 4, 0);
71
72 #[easy_ext::ext]
73 impl ConnectOptions {
74 fn sqlite_common(&mut self) -> &mut Self {
76 self
77 .min_connections(1)
80 .max_connections(1)
81 .acquire_timeout(MAX_DURATION)
85 .connect_timeout(MAX_DURATION)
86 }
87 }
88
89 Ok(match backend {
90 MetaStoreBackend::Mem => {
91 const IN_MEMORY_STORE: &str = "sqlite::memory:";
92
93 let mut options = ConnectOptions::new(IN_MEMORY_STORE);
94
95 options
96 .sqlite_common()
97 .idle_timeout(MAX_DURATION)
102 .max_lifetime(MAX_DURATION);
103
104 let conn = sea_orm::Database::connect(options).await?;
105 Self {
106 conn,
107 endpoint: IN_MEMORY_STORE.to_owned(),
108 }
109 }
110 MetaStoreBackend::Sql { endpoint, config } => {
111 let mut options = ConnectOptions::new(endpoint.clone());
112 options
113 .max_connections(config.max_connections)
114 .min_connections(config.min_connections)
115 .connect_timeout(Duration::from_secs(config.connection_timeout_sec))
116 .idle_timeout(Duration::from_secs(config.idle_timeout_sec))
117 .acquire_timeout(Duration::from_secs(config.acquire_timeout_sec));
118
119 if DbBackend::Sqlite.is_prefix_of(&endpoint) {
120 if endpoint.contains(":memory:") || endpoint.contains("mode=memory") {
121 bail!(
122 "use the `mem` backend instead of specifying a URL of in-memory SQLite"
123 );
124 }
125 options.sqlite_common();
126 }
127
128 let conn = sea_orm::Database::connect(options).await?;
129 Self { conn, endpoint }
130 }
131 })
132 }
133
134 #[cfg(any(test, feature = "test"))]
135 pub async fn for_test() -> Self {
136 let this = Self::connect(MetaStoreBackend::Mem).await.unwrap();
137 Migrator::up(&this.conn, None).await.unwrap();
138 this
139 }
140
141 async fn is_first_launch(&self) -> MetaResult<bool> {
147 let migrations = Migrator::get_applied_migrations(&self.conn)
148 .await
149 .context("failed to get applied migrations")?;
150 for migration in migrations {
151 if migration.name() == "m20230908_072257_init"
152 && migration.status() == MigrationStatus::Applied
153 {
154 return Ok(false);
155 }
156 }
157 Ok(true)
158 }
159
160 pub async fn up(&self) -> MetaResult<bool> {
164 let cluster_first_launch = self.is_first_launch().await?;
165 Migrator::up(&self.conn, None)
167 .await
168 .context("failed to upgrade models in meta store")?;
169
170 Ok(cluster_first_launch)
171 }
172}
173
174pub struct ObjectModel<M: ModelTrait>(M, object::Model);
175
176impl From<ObjectModel<database::Model>> for PbDatabase {
177 fn from(value: ObjectModel<database::Model>) -> Self {
178 Self {
179 id: value.0.database_id as _,
180 name: value.0.name,
181 owner: value.1.owner_id as _,
182 resource_group: value.0.resource_group.clone(),
183 barrier_interval_ms: value.0.barrier_interval_ms.map(|v| v as u32),
184 checkpoint_frequency: value.0.checkpoint_frequency.map(|v| v as u64),
185 }
186 }
187}
188
189impl From<ObjectModel<secret::Model>> for PbSecret {
190 fn from(value: ObjectModel<secret::Model>) -> Self {
191 Self {
192 id: value.0.secret_id as _,
193 name: value.0.name,
194 database_id: value.1.database_id.unwrap() as _,
195 value: value.0.value,
196 owner: value.1.owner_id as _,
197 schema_id: value.1.schema_id.unwrap() as _,
198 }
199 }
200}
201
202impl From<ObjectModel<schema::Model>> for PbSchema {
203 fn from(value: ObjectModel<schema::Model>) -> Self {
204 Self {
205 id: value.0.schema_id as _,
206 name: value.0.name,
207 database_id: value.1.database_id.unwrap() as _,
208 owner: value.1.owner_id as _,
209 }
210 }
211}
212
213impl From<ObjectModel<table::Model>> for PbTable {
214 fn from(value: ObjectModel<table::Model>) -> Self {
215 Self {
216 id: value.0.table_id as _,
217 schema_id: value.1.schema_id.unwrap() as _,
218 database_id: value.1.database_id.unwrap() as _,
219 name: value.0.name,
220 columns: value.0.columns.to_protobuf(),
221 pk: value.0.pk.to_protobuf(),
222 dependent_relations: vec![], table_type: PbTableType::from(value.0.table_type) as _,
224 distribution_key: value.0.distribution_key.0,
225 stream_key: value.0.stream_key.0,
226 append_only: value.0.append_only,
227 owner: value.1.owner_id as _,
228 fragment_id: value.0.fragment_id.unwrap_or_default() as u32,
229 vnode_col_index: value.0.vnode_col_index.map(|index| index as _),
230 row_id_index: value.0.row_id_index.map(|index| index as _),
231 value_indices: value.0.value_indices.0,
232 definition: value.0.definition,
233 handle_pk_conflict_behavior: PbHandleConflictBehavior::from(
234 value.0.handle_pk_conflict_behavior,
235 ) as _,
236 version_column_index: value.0.version_column_index.map(|x| x as u32),
237 read_prefix_len_hint: value.0.read_prefix_len_hint as _,
238 watermark_indices: value.0.watermark_indices.0,
239 dist_key_in_pk: value.0.dist_key_in_pk.0,
240 dml_fragment_id: value.0.dml_fragment_id.map(|id| id as u32),
241 cardinality: value
242 .0
243 .cardinality
244 .map(|cardinality| cardinality.to_protobuf()),
245 initialized_at_epoch: Some(
246 Epoch::from_unix_millis(value.1.initialized_at.and_utc().timestamp_millis() as _).0,
247 ),
248 created_at_epoch: Some(
249 Epoch::from_unix_millis(value.1.created_at.and_utc().timestamp_millis() as _).0,
250 ),
251 cleaned_by_watermark: value.0.cleaned_by_watermark,
252 stream_job_status: PbStreamJobStatus::Created as _,
253 create_type: PbCreateType::Foreground as _,
254 version: value.0.version.map(|v| v.to_protobuf()),
255 optional_associated_source_id: value
256 .0
257 .optional_associated_source_id
258 .map(|id| PbOptionalAssociatedSourceId::AssociatedSourceId(id as _)),
259 description: value.0.description,
260 incoming_sinks: value.0.incoming_sinks.into_u32_array(),
261 initialized_at_cluster_version: value.1.initialized_at_cluster_version,
262 created_at_cluster_version: value.1.created_at_cluster_version,
263 retention_seconds: value.0.retention_seconds.map(|id| id as u32),
264 cdc_table_id: value.0.cdc_table_id,
265 maybe_vnode_count: VnodeCount::set(value.0.vnode_count).to_protobuf(),
266 webhook_info: value.0.webhook_info.map(|info| info.to_protobuf()),
267 job_id: value.0.belongs_to_job_id.map(|id| id as _),
268 engine: value.0.engine.map(|engine| PbEngine::from(engine) as i32),
269 clean_watermark_index_in_pk: value.0.clean_watermark_index_in_pk,
270 }
271 }
272}
273
274impl From<ObjectModel<source::Model>> for PbSource {
275 fn from(value: ObjectModel<source::Model>) -> Self {
276 let mut secret_ref_map = BTreeMap::new();
277 if let Some(secret_ref) = value.0.secret_ref {
278 secret_ref_map = secret_ref.to_protobuf();
279 }
280 Self {
281 id: value.0.source_id as _,
282 schema_id: value.1.schema_id.unwrap() as _,
283 database_id: value.1.database_id.unwrap() as _,
284 name: value.0.name,
285 row_id_index: value.0.row_id_index.map(|id| id as _),
286 columns: value.0.columns.to_protobuf(),
287 pk_column_ids: value.0.pk_column_ids.0,
288 with_properties: value.0.with_properties.0,
289 owner: value.1.owner_id as _,
290 info: value.0.source_info.map(|info| info.to_protobuf()),
291 watermark_descs: value.0.watermark_descs.to_protobuf(),
292 definition: value.0.definition,
293 connection_id: value.0.connection_id.map(|id| id as _),
294 initialized_at_epoch: Some(
296 Epoch::from_unix_millis(value.1.initialized_at.and_utc().timestamp_millis() as _).0,
297 ),
298 created_at_epoch: Some(
299 Epoch::from_unix_millis(value.1.created_at.and_utc().timestamp_millis() as _).0,
300 ),
301 version: value.0.version as _,
302 optional_associated_table_id: value
303 .0
304 .optional_associated_table_id
305 .map(|id| PbOptionalAssociatedTableId::AssociatedTableId(id as _)),
306 initialized_at_cluster_version: value.1.initialized_at_cluster_version,
307 created_at_cluster_version: value.1.created_at_cluster_version,
308 secret_refs: secret_ref_map,
309 rate_limit: value.0.rate_limit.map(|v| v as _),
310 }
311 }
312}
313
314impl From<ObjectModel<sink::Model>> for PbSink {
315 fn from(value: ObjectModel<sink::Model>) -> Self {
316 let mut secret_ref_map = BTreeMap::new();
317 if let Some(secret_ref) = value.0.secret_ref {
318 secret_ref_map = secret_ref.to_protobuf();
319 }
320 #[allow(deprecated)] Self {
322 id: value.0.sink_id as _,
323 schema_id: value.1.schema_id.unwrap() as _,
324 database_id: value.1.database_id.unwrap() as _,
325 name: value.0.name,
326 columns: value.0.columns.to_protobuf(),
327 plan_pk: value.0.plan_pk.to_protobuf(),
328 dependent_relations: vec![],
329 distribution_key: value.0.distribution_key.0,
330 downstream_pk: value.0.downstream_pk.0,
331 sink_type: PbSinkType::from(value.0.sink_type) as _,
332 owner: value.1.owner_id as _,
333 properties: value.0.properties.0,
334 definition: value.0.definition,
335 connection_id: value.0.connection_id.map(|id| id as _),
336 initialized_at_epoch: Some(
337 Epoch::from_unix_millis(value.1.initialized_at.and_utc().timestamp_millis() as _).0,
338 ),
339 created_at_epoch: Some(
340 Epoch::from_unix_millis(value.1.created_at.and_utc().timestamp_millis() as _).0,
341 ),
342 db_name: value.0.db_name,
343 sink_from_name: value.0.sink_from_name,
344 stream_job_status: PbStreamJobStatus::Created as _,
345 format_desc: value.0.sink_format_desc.map(|desc| desc.to_protobuf()),
346 target_table: value.0.target_table.map(|id| id as _),
347 initialized_at_cluster_version: value.1.initialized_at_cluster_version,
348 created_at_cluster_version: value.1.created_at_cluster_version,
349 create_type: PbCreateType::Foreground as _,
350 secret_refs: secret_ref_map,
351 original_target_columns: value
352 .0
353 .original_target_columns
354 .map(|cols| cols.to_protobuf())
355 .unwrap_or_default(),
356 }
357 }
358}
359
360impl From<ObjectModel<subscription::Model>> for PbSubscription {
361 fn from(value: ObjectModel<subscription::Model>) -> Self {
362 Self {
363 id: value.0.subscription_id as _,
364 schema_id: value.1.schema_id.unwrap() as _,
365 database_id: value.1.database_id.unwrap() as _,
366 name: value.0.name,
367 owner: value.1.owner_id as _,
368 retention_seconds: value.0.retention_seconds as _,
369 definition: value.0.definition,
370 initialized_at_epoch: Some(
371 Epoch::from_unix_millis(value.1.initialized_at.and_utc().timestamp_millis() as _).0,
372 ),
373 created_at_epoch: Some(
374 Epoch::from_unix_millis(value.1.created_at.and_utc().timestamp_millis() as _).0,
375 ),
376 initialized_at_cluster_version: value.1.initialized_at_cluster_version,
377 created_at_cluster_version: value.1.created_at_cluster_version,
378 dependent_table_id: value.0.dependent_table_id as _,
379 subscription_state: value.0.subscription_state as _,
380 }
381 }
382}
383
384impl From<ObjectModel<index::Model>> for PbIndex {
385 fn from(value: ObjectModel<index::Model>) -> Self {
386 Self {
387 id: value.0.index_id as _,
388 schema_id: value.1.schema_id.unwrap() as _,
389 database_id: value.1.database_id.unwrap() as _,
390 name: value.0.name,
391 owner: value.1.owner_id as _,
392 index_table_id: value.0.index_table_id as _,
393 primary_table_id: value.0.primary_table_id as _,
394 index_item: value.0.index_items.to_protobuf(),
395 index_column_properties: value
396 .0
397 .index_column_properties
398 .map(|p| p.to_protobuf())
399 .unwrap_or_default(),
400 index_columns_len: value.0.index_columns_len as _,
401 initialized_at_epoch: Some(
402 Epoch::from_unix_millis(value.1.initialized_at.and_utc().timestamp_millis() as _).0,
403 ),
404 created_at_epoch: Some(
405 Epoch::from_unix_millis(value.1.created_at.and_utc().timestamp_millis() as _).0,
406 ),
407 stream_job_status: PbStreamJobStatus::Created as _,
408 initialized_at_cluster_version: value.1.initialized_at_cluster_version,
409 created_at_cluster_version: value.1.created_at_cluster_version,
410 }
411 }
412}
413
414impl From<ObjectModel<view::Model>> for PbView {
415 fn from(value: ObjectModel<view::Model>) -> Self {
416 Self {
417 id: value.0.view_id as _,
418 schema_id: value.1.schema_id.unwrap() as _,
419 database_id: value.1.database_id.unwrap() as _,
420 name: value.0.name,
421 owner: value.1.owner_id as _,
422 properties: value.0.properties.0,
423 sql: value.0.definition,
424 dependent_relations: vec![], columns: value.0.columns.to_protobuf(),
426 }
427 }
428}
429
430impl From<ObjectModel<connection::Model>> for PbConnection {
431 fn from(value: ObjectModel<connection::Model>) -> Self {
432 let info: PbConnectionInfo = if value.0.info == PrivateLinkService::default() {
433 PbConnectionInfo::ConnectionParams(value.0.params.to_protobuf())
434 } else {
435 PbConnectionInfo::PrivateLinkService(value.0.info.to_protobuf())
436 };
437 Self {
438 id: value.1.oid as _,
439 schema_id: value.1.schema_id.unwrap() as _,
440 database_id: value.1.database_id.unwrap() as _,
441 name: value.0.name,
442 owner: value.1.owner_id as _,
443 info: Some(info),
444 }
445 }
446}
447
448impl From<ObjectModel<function::Model>> for PbFunction {
449 fn from(value: ObjectModel<function::Model>) -> Self {
450 Self {
451 id: value.0.function_id as _,
452 schema_id: value.1.schema_id.unwrap() as _,
453 database_id: value.1.database_id.unwrap() as _,
454 name: value.0.name,
455 owner: value.1.owner_id as _,
456 arg_names: value.0.arg_names.split(',').map(|s| s.to_owned()).collect(),
457 arg_types: value.0.arg_types.to_protobuf(),
458 return_type: Some(value.0.return_type.to_protobuf()),
459 language: value.0.language,
460 runtime: value.0.runtime,
461 link: value.0.link,
462 name_in_runtime: value.0.name_in_runtime,
463 body: value.0.body,
464 compressed_binary: value.0.compressed_binary,
465 kind: Some(value.0.kind.into()),
466 always_retry_on_network_error: value.0.always_retry_on_network_error,
467 is_async: value
468 .0
469 .options
470 .as_ref()
471 .and_then(|o| o.0.get("async").map(|v| v == "true")),
472 is_batched: value
473 .0
474 .options
475 .as_ref()
476 .and_then(|o| o.0.get("batch").map(|v| v == "true")),
477 }
478 }
479}