1use std::collections::HashMap;
16use std::fmt;
17use std::io::Cursor;
18use std::ops::Deref;
19
20use anyhow::{Context, anyhow};
21use arrow_58_ipc::reader::StreamReader;
22use futures::StreamExt;
23use futures::stream::{self, BoxStream};
24use futures_async_stream::try_stream;
25use jni::objects::GlobalRef;
26use jni::sys::jlong;
27use prost::Message;
28use risingwave_common::array::DataChunk;
29use risingwave_common::array::arrow::from_arrow58_record_batch;
30use risingwave_common::bail;
31use risingwave_common::catalog::{ColumnDesc, ColumnId, Field, Schema};
32use risingwave_common::global_jvm::Jvm;
33use risingwave_common::row::{OwnedRow, Row};
34use risingwave_jni_core::jvm_runtime::execute_with_jni_env;
35use risingwave_jni_core::{JavaBindingIterator, JniSenderType, call_static_method};
36use risingwave_pb::connector_service::{
37 OracleConnectionProperties, OracleSnapshotReadRequest, OracleSnapshotReadResponse, TableSchema,
38};
39use serde::{Deserialize, Serialize};
40use thiserror_ext::AsReport;
41use tokio::sync::{OnceCell, mpsc};
42
43use crate::error::{ConnectorError, ConnectorResult};
44use crate::source::CdcTableSnapshotSplit;
45use crate::source::cdc::external::{
46 CdcOffset, CdcOffsetParseFunc, CdcTableSnapshotSplitOption, ExternalTableConfig,
47 ExternalTableReader, SchemaTableName,
48};
49
50const ORACLE_SNAPSHOT_CHANNEL_SIZE: usize = 4;
51
52#[derive(Debug, Clone, Default, PartialEq, PartialOrd, Serialize, Deserialize)]
53pub struct OracleOffset {
54 pub decoded_commit_scn: u64,
55}
56
57impl OracleOffset {
58 pub fn parse_debezium_offset(offset: &str) -> ConnectorResult<Self> {
61 let dbz_offset: serde_json::Value = serde_json::from_str(offset)
63 .with_context(|| format!("invalid upstream Oracle CDC offset: {offset}"))?;
64 let decoded_commit_scn = dbz_offset
65 .pointer("/sourceOffset/decoded_commit_scn")
66 .and_then(serde_json::Value::as_str)
67 .context("Oracle CDC data offset is missing decoded_commit_scn")?
68 .parse::<u64>()
69 .context("invalid Oracle CDC commit SCN")?;
70 if decoded_commit_scn == 0 {
71 bail!("Oracle CDC commit SCN must be positive");
72 }
73 Ok(Self { decoded_commit_scn })
74 }
75}
76
77pub struct OracleExternalTable {
78 column_descs: Vec<ColumnDesc>,
79 pk_names: Vec<String>,
80}
81
82impl OracleExternalTable {
83 pub async fn connect(config: ExternalTableConfig) -> ConnectorResult<Self> {
92 let properties = config.oracle_connection_properties()?;
93 let table_schema = tokio::task::spawn_blocking(move || invoke_jni_discover(&properties))
94 .await
95 .context("failed to join Oracle schema discovery task")??;
96
97 let column_descs = table_schema
98 .columns
99 .iter()
100 .map(ColumnDesc::from)
101 .collect::<Vec<_>>();
102 let pk_names = table_schema
103 .pk_indices
104 .iter()
105 .map(|index| {
106 table_schema
107 .columns
108 .get(*index as usize)
109 .map(|column| column.name.clone())
110 .with_context(|| {
111 format!("Oracle primary-key index {index} is unable to extract column name")
112 })
113 })
114 .collect::<anyhow::Result<Vec<_>>>()?;
115
116 if column_descs.is_empty() {
117 bail!("Oracle schema discovery returned no columns");
118 }
119 if pk_names.is_empty() {
120 bail!("Oracle schema discovery returned no valid primary keys");
121 }
122
123 Ok(Self {
124 column_descs,
125 pk_names,
126 })
127 }
128
129 pub fn column_descs(&self) -> &Vec<ColumnDesc> {
130 &self.column_descs
131 }
132
133 pub fn pk_names(&self) -> &Vec<String> {
134 &self.pk_names
135 }
136}
137
138#[derive(Debug)]
139pub struct OracleExternalTableReader {
140 connection_properties: OracleConnectionProperties,
141 rw_schema: Schema,
142 pk_indices: Vec<usize>,
143 table_schema: TableSchema,
144 table: String,
145 pool: OnceCell<OraclePool>,
146}
147
148impl ExternalTableReader for OracleExternalTableReader {
149 async fn current_cdc_offset(&self) -> ConnectorResult<CdcOffset> {
155 let pool = self.pool().await?;
156 let cancel = invoke_jni_new_statement_cancel(&self.table, "current SCN query")?;
157 let cancel_on_drop =
158 cancel_statement_on_drop(cancel.clone(), self.table.clone(), "current SCN query");
159 let result =
160 tokio::task::spawn_blocking(move || invoke_jni_current_scn(&pool, &cancel)).await;
161 cancel_on_drop.disarm();
162 let scn = result.context("failed to join Oracle SCN query task")??;
163 if scn <= 0 {
164 bail!("Oracle returned an invalid current SCN: {scn}");
165 }
166 Ok(CdcOffset::Oracle(OracleOffset {
167 decoded_commit_scn: scn as u64,
168 }))
169 }
170
171 fn snapshot_read(
178 &self,
179 table_name: SchemaTableName,
180 start_pk: Option<OwnedRow>,
181 primary_keys: Vec<String>,
182 _limit: u32,
183 ) -> BoxStream<'_, ConnectorResult<OwnedRow>> {
184 self.snapshot_read_inner(table_name, start_pk, primary_keys)
185 }
186
187 fn get_parallel_cdc_splits(
188 &self,
189 _options: CdcTableSnapshotSplitOption,
190 ) -> BoxStream<'_, ConnectorResult<CdcTableSnapshotSplit>> {
191 stream::empty().boxed()
193 }
194
195 fn split_snapshot_read(
196 &self,
197 _table_name: SchemaTableName,
198 _left: OwnedRow,
199 _right: OwnedRow,
200 _split_columns: Vec<Field>,
201 ) -> BoxStream<'_, ConnectorResult<OwnedRow>> {
202 stream::once(async {
204 Err(anyhow!("Oracle CDC parallelized backfill is not implemented").into())
205 })
206 .boxed()
207 }
208}
209
210impl OracleExternalTableReader {
211 pub fn get_cdc_offset_parser() -> CdcOffsetParseFunc {
212 Box::new(|offset| {
213 Ok(CdcOffset::Oracle(OracleOffset::parse_debezium_offset(
214 offset,
215 )?))
216 })
217 }
218
219 pub fn new(
220 config: ExternalTableConfig,
221 rw_schema: Schema,
222 pk_indices: Vec<usize>,
223 ) -> ConnectorResult<Self> {
224 if pk_indices.is_empty() {
225 bail!("Oracle snapshot reader requires at least one primary-key column");
226 }
227 for &index in &pk_indices {
228 if index >= rw_schema.len() {
229 bail!(
230 "Oracle snapshot primary-key index {index} is outside a {}-column schema",
231 rw_schema.len()
232 );
233 }
234 }
235
236 let table_schema = TableSchema {
237 columns: rw_schema
238 .fields
239 .iter()
240 .map(|field| {
241 ColumnDesc::named(
242 field.name.clone(),
243 ColumnId::placeholder(),
244 field.data_type.clone(),
245 )
246 .to_protobuf()
247 })
248 .collect(),
249 pk_indices: pk_indices.iter().map(|index| *index as u32).collect(),
250 };
251
252 Ok(Self {
253 connection_properties: config.oracle_connection_properties()?,
254 rw_schema,
255 pk_indices,
256 table_schema,
257 table: format!("{}.{}", config.schema, config.table),
258 pool: OnceCell::new(),
259 })
260 }
261
262 async fn pool(&self) -> ConnectorResult<JavaRef> {
268 let pool = self
269 .pool
270 .get_or_try_init(|| async {
271 let properties = self.connection_properties.clone();
272 let table = self.table.clone();
273 tokio::task::spawn_blocking(move || OraclePool::open(&properties, table))
274 .await
275 .context("failed to join Oracle connection pool open task")?
276 .map_err(ConnectorError::from)
277 })
278 .await?;
279 Ok(pool.pool.clone())
280 }
281
282 #[try_stream(boxed, ok = OwnedRow, error = ConnectorError)]
283 async fn snapshot_read_inner(
284 &self,
285 table_name: SchemaTableName,
286 start_pk: Option<OwnedRow>,
287 primary_keys: Vec<String>,
288 ) {
289 if primary_keys.len() != self.pk_indices.len() {
290 Err(anyhow!(
291 "Oracle snapshot read received {} primary-key columns but there are actually {} primary-key columns",
292 primary_keys.len(),
293 self.pk_indices.len()
294 ))?;
295 }
296
297 if let Some(start_pk) = &start_pk {
298 validate_start_pk(start_pk, self.pk_indices.len())?;
299 }
300
301 let pool = self.pool().await?;
302 let cancel = invoke_jni_new_statement_cancel(&self.table, "snapshot read")?;
303 let cancel_on_drop =
304 cancel_statement_on_drop(cancel.clone(), self.table.clone(), "snapshot read");
305 let request = OracleSnapshotReadRequest {
306 schema_name: table_name.schema_name,
307 table_name: table_name.table_name,
308 table_schema: Some(self.table_schema.clone()),
309 primary_keys,
310 };
311 let (sender, mut receiver) = mpsc::channel(ORACLE_SNAPSHOT_CHANNEL_SIZE);
312 let read_task = tokio::task::spawn_blocking(move || {
313 invoke_jni_snapshot_read(&pool, &request, start_pk, &sender, &cancel)
314 });
315
316 while let Some(response) = receiver.recv().await {
317 let chunk = decode_arrow_batch(&response?.arrow_ipc, &self.rw_schema)?;
318 for row in chunk.rows() {
319 if let Some(&index) = self
325 .pk_indices
326 .iter()
327 .find(|&&index| row.datum_at(index).is_none())
328 {
329 Err(anyhow!(
330 "Oracle snapshot primary key `{}` cannot be NULL",
331 self.rw_schema.fields[index].name
332 ))?;
333 }
334 yield row.into_owned_row();
335 }
336 }
337 let result = read_task.await;
338 cancel_on_drop.disarm();
339 result.context("failed to join Oracle snapshot query task")??;
340 }
341}
342
343#[derive(Debug, Clone)]
346struct JavaRef(Option<GlobalRef>);
347
348impl JavaRef {
349 fn as_obj(&self) -> &jni::objects::JObject<'static> {
350 self.0
351 .as_ref()
352 .expect("Java reference is present until dropped")
353 }
354}
355
356impl Drop for JavaRef {
357 fn drop(&mut self) {
358 let Some(object) = self.0.take() else {
359 return;
360 };
361 let attached = Jvm::get_or_init()
362 .ok()
363 .and_then(|jvm| jvm.0.attach_current_thread().ok());
364 drop(object);
365 drop(attached);
366 }
367}
368
369struct ReleaseOnDrop(Option<Box<dyn FnOnce() + Send + Sync>>);
371
372impl ReleaseOnDrop {
373 fn new(release: impl FnOnce() + Send + Sync + 'static) -> Self {
374 Self(Some(Box::new(release)))
375 }
376
377 fn disarm(mut self) {
378 self.0 = None;
379 }
380}
381
382impl fmt::Debug for ReleaseOnDrop {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 f.debug_tuple("ReleaseOnDrop")
385 .field(&self.0.is_some())
386 .finish()
387 }
388}
389
390impl Drop for ReleaseOnDrop {
391 fn drop(&mut self) {
392 let Some(release) = self.0.take() else {
393 return;
394 };
395 let span = tracing::Span::current();
396 let release = move || span.in_scope(release);
397 match tokio::runtime::Handle::try_current() {
398 Ok(handle) => drop(handle.spawn_blocking(release)),
399 Err(_) => release(),
400 }
401 }
402}
403
404#[derive(Debug)]
406struct OraclePool {
407 pool: JavaRef,
408 _close_on_drop: ReleaseOnDrop,
409}
410
411impl OraclePool {
412 fn open(properties: &OracleConnectionProperties, table: String) -> anyhow::Result<Self> {
413 let pool = invoke_jni_open_pool(properties)?;
414 let closing = pool.clone();
415 Ok(Self {
416 pool,
417 _close_on_drop: ReleaseOnDrop::new(move || {
418 tracing::info!(table, "closing Oracle connection pool");
419 match invoke_jni_close_pool(&closing) {
420 Ok(()) => tracing::info!(table, "closed Oracle connection pool"),
421 Err(error) => tracing::warn!(
422 table,
423 error = %error.as_report(),
424 "failed to close Oracle connection pool"
425 ),
426 }
427 }),
428 })
429 }
430}
431
432fn cancel_statement_on_drop(cancel: JavaRef, table: String, query: &'static str) -> ReleaseOnDrop {
434 ReleaseOnDrop::new(move || {
435 if let Err(error) = invoke_jni_cancel_statement(&cancel) {
436 tracing::warn!(
437 table,
438 query,
439 error = %error.as_report(),
440 "failed to cancel Oracle query"
441 );
442 }
443 })
444}
445
446impl ExternalTableConfig {
447 pub fn oracle_connection_properties(&self) -> ConnectorResult<OracleConnectionProperties> {
448 let pdb_name = self
449 .pdb_name
450 .clone()
451 .context("Oracle CDC requires 'database.pdb.name'")?;
452 Ok(OracleConnectionProperties {
453 properties: HashMap::from([
454 ("hostname".to_owned(), self.host.clone()),
455 ("port".to_owned(), self.port.clone()),
456 ("username".to_owned(), self.username.clone()),
457 ("password".to_owned(), self.password.clone()),
458 ("database.name".to_owned(), self.database.clone()),
459 ("database.pdb.name".to_owned(), pdb_name),
460 ("schema.name".to_owned(), self.schema.clone()),
461 ("table.name".to_owned(), self.table.clone()),
462 ]),
463 })
464 }
465}
466
467fn validate_start_pk(row: &OwnedRow, pk_len: usize) -> ConnectorResult<()> {
468 if row.len() != pk_len {
469 bail!(
470 "Oracle snapshot start key has {} values for {} primary-key columns",
471 row.len(),
472 pk_len
473 );
474 }
475 if let Some(position) = row.iter().position(|datum| datum.is_none()) {
476 bail!("Oracle snapshot primary-key position {position} cannot be NULL");
477 }
478 Ok(())
479}
480
481fn decode_arrow_batch(arrow_ipc: &[u8], schema: &Schema) -> ConnectorResult<DataChunk> {
482 let mut reader = StreamReader::try_new(Cursor::new(arrow_ipc), None)
483 .context("failed to read Oracle snapshot Arrow stream")?;
484 let batch = reader
485 .next()
486 .context("Oracle snapshot Arrow stream has no record batch")?
487 .context("failed to read Oracle snapshot Arrow record batch")?;
488 let chunk = from_arrow58_record_batch(&batch)
489 .context("failed to convert Oracle snapshot Arrow record batch")?;
490 if chunk.data_types() != schema.data_types() {
491 bail!(
492 "Oracle snapshot batch has types {:?} but the table schema has types {:?}",
493 chunk.data_types(),
494 schema.data_types()
495 );
496 }
497 Ok(chunk)
498}
499
500fn invoke_jni_discover(properties: &OracleConnectionProperties) -> anyhow::Result<TableSchema> {
501 let jvm = Jvm::get_or_init()?;
502 execute_with_jni_env(jvm, |env| {
503 let properties_bytes = env.byte_array_from_slice(&properties.encode_to_vec())?;
504 let response_bytes = call_static_method!(
505 env,
506 {com.risingwave.connector.source.common.JniOracleExternalTable},
507 {byte[] discover(byte[] propertiesBytes)},
508 &properties_bytes
509 )?;
510 TableSchema::decode(risingwave_jni_core::to_guarded_slice(&response_bytes, env)?.deref())
511 .map_err(Into::into)
512 })
513}
514
515fn invoke_jni_open_pool(properties: &OracleConnectionProperties) -> anyhow::Result<JavaRef> {
516 let jvm = Jvm::get_or_init()?;
517 execute_with_jni_env(jvm, |env| {
518 let properties_bytes = env.byte_array_from_slice(&properties.encode_to_vec())?;
519 let pool = call_static_method!(
520 env,
521 {com.risingwave.connector.source.common.JniOracleExternalTable},
522 {Object openPool(byte[] propertiesBytes)},
523 &properties_bytes
524 )?;
525 Ok(JavaRef(Some(env.new_global_ref(pool)?)))
526 })
527}
528
529fn invoke_jni_close_pool(pool: &JavaRef) -> anyhow::Result<()> {
530 let jvm = Jvm::get_or_init()?;
531 execute_with_jni_env(jvm, |env| {
532 call_static_method!(
533 env,
534 {com.risingwave.connector.source.common.JniOracleExternalTable},
535 {void closePool(Object)},
536 pool.as_obj()
537 )?;
538 Ok(())
539 })
540}
541
542fn invoke_jni_current_scn(pool: &JavaRef, cancel: &JavaRef) -> anyhow::Result<i64> {
543 let jvm = Jvm::get_or_init()?;
544 execute_with_jni_env(jvm, |env| {
545 let scn = call_static_method!(
546 env,
547 {com.risingwave.connector.source.common.JniOracleExternalTable},
548 {long currentScn(Object, Object)},
549 pool.as_obj(),
550 cancel.as_obj()
551 )?;
552 Ok(scn)
553 })
554}
555
556fn invoke_jni_new_statement_cancel(table: &str, query: &str) -> anyhow::Result<JavaRef> {
557 let jvm = Jvm::get_or_init()?;
558 execute_with_jni_env(jvm, |env| {
559 let table = env.new_string(table)?;
560 let query = env.new_string(query)?;
561 let cancel = call_static_method!(
562 env,
563 {com.risingwave.connector.source.common.JniOracleExternalTable},
564 {Object newStatementCancel(String, String)},
565 &table,
566 &query
567 )?;
568 Ok(JavaRef(Some(env.new_global_ref(cancel)?)))
569 })
570}
571
572fn invoke_jni_cancel_statement(cancel: &JavaRef) -> anyhow::Result<()> {
573 let jvm = Jvm::get_or_init()?;
574 execute_with_jni_env(jvm, |env| {
575 call_static_method!(
576 env,
577 {com.risingwave.connector.source.common.JniOracleExternalTable},
578 {void cancelStatement(Object)},
579 cancel.as_obj()
580 )?;
581 Ok(())
582 })
583}
584
585fn invoke_jni_snapshot_read(
586 pool: &JavaRef,
587 request: &OracleSnapshotReadRequest,
588 start_pk: Option<OwnedRow>,
589 sender: &JniSenderType<OracleSnapshotReadResponse>,
590 cancel: &JavaRef,
591) -> anyhow::Result<()> {
592 let start_pk = start_pk.map(JavaBindingIterator::new_singleton_row);
593 let start_pk_pointer = start_pk
594 .as_ref()
595 .map_or(0, |row| row as *const JavaBindingIterator<'_> as jlong);
596 let channel_pointer = sender as *const JniSenderType<OracleSnapshotReadResponse> as jlong;
597 let jvm = Jvm::get_or_init()?;
598 execute_with_jni_env(jvm, |env| {
599 let request_bytes = env.byte_array_from_slice(&request.encode_to_vec())?;
600 call_static_method!(
601 env,
602 {com.risingwave.connector.source.common.JniOracleExternalTable},
603 {void snapshotRead(Object, byte[] requestBytes, long startPkPointer, long channelPtr, Object)},
604 pool.as_obj(),
605 &request_bytes,
606 start_pk_pointer,
607 channel_pointer,
608 cancel.as_obj()
609 )?;
610 Ok(())
611 })
612}