Skip to content

Commit 60351ba

Browse files
authored
feat(session): add tableExists and deregisterTable to SessionContext (#102)
## Which issue does this PR close? - Closes #101 . ## Rationale for this change SessionContext can let a caller register tables but there is no way to Check whether a table name is already registered Remove a registered table from the session This makes it tough to write safer code while registering ## What changes are included in this PR? - `SessionContext.tableExists(String name)` — returns true if a table with that name is registered in the session - `SessionContext.deregisterTable(String name)` — removes a registered table; no-op if the name is not found Both are thin JNI wrappers over DataFusion's existing `SessionContext::table_exist` and `SessionContext::deregister_table` on the Rust side. ## Are these changes tested? Yes. `SessionContextTableRegistrationTest` covers: - tableExists returns false for an unregistered table - tableExists returns true after registerCsv - deregisterTable removes a registered table - deregisterTable is a no-op for an unregistered table - Both methods throw IllegalStateException on a closed context --> ## Are there any user-facing changes? Yes — two new public methods on `SessionContext`. Additive only, no breaking changes.
1 parent bbd700a commit 60351ba

3 files changed

Lines changed: 153 additions & 0 deletions

File tree

‎core/src/main/java/org/apache/datafusion/SessionContext.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -601,6 +601,43 @@ private static byte[] serializeSchemaIpc(Schema schema) {
601601
return baos.toByteArray();
602602
}
603603

604+
/**
605+
* Returns {@code true} if a table with the given name is registered in this session.
606+
*
607+
* <p>This is the Java counterpart to DataFusion's Rust {@code SessionContext::table_exist}.
608+
*
609+
* @throws IllegalStateException if this context is closed.
610+
*/
611+
public boolean tableExists(String name) {
612+
checkOpenSessionContext();
613+
if (name == null) {
614+
throw new IllegalArgumentException("tableExists name must be non-null");
615+
}
616+
return tableExists(nativeHandle, name);
617+
}
618+
619+
/**
620+
* Removes the table with the given name from this session. Does nothing if no table with that
621+
* name is registered.
622+
*
623+
* <p>This is the Java counterpart to DataFusion's Rust {@code SessionContext::deregister_table}.
624+
*
625+
* @throws IllegalStateException if this context is closed.
626+
*/
627+
public void deregisterTable(String name) {
628+
checkOpenSessionContext();
629+
if (name == null) {
630+
throw new IllegalArgumentException("deregisterTable name must be non-null");
631+
}
632+
deregisterTable(nativeHandle, name);
633+
}
634+
635+
private void checkOpenSessionContext() {
636+
if (nativeHandle == 0) {
637+
throw new IllegalStateException("SessionContext is closed");
638+
}
639+
}
640+
604641
@Override
605642
public void close() {
606643
if (nativeHandle != 0) {
@@ -664,4 +701,8 @@ private static native void registerScalarUdf(
664701

665702
private static native void registerTableNative(
666703
long handle, String name, byte[] schemaIpcBytes, TableProvider provider);
704+
705+
private static native boolean tableExists(long handle, String name);
706+
707+
private static native void deregisterTable(long handle, String name);
667708
}

‎core/src/test/java/org/apache/datafusion/SessionContextTest.java‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
package org.apache.datafusion;
2121

2222
import static org.junit.jupiter.api.Assertions.assertEquals;
23+
import static org.junit.jupiter.api.Assertions.assertFalse;
2324
import static org.junit.jupiter.api.Assertions.assertThrows;
2425
import static org.junit.jupiter.api.Assertions.assertTrue;
2526

@@ -33,6 +34,7 @@
3334
import org.apache.arrow.vector.ipc.ArrowReader;
3435
import org.junit.jupiter.api.Assumptions;
3536
import org.junit.jupiter.api.Test;
37+
import org.junit.jupiter.api.io.TempDir;
3638

3739
class SessionContextTest {
3840
@Test
@@ -90,4 +92,71 @@ void dataFrameCollectTwiceFails() {
9092
assertThrows(IllegalStateException.class, () -> df.collect(allocator));
9193
}
9294
}
95+
96+
@Test
97+
void tableExistsReturnsFalseForUnregisteredTable() {
98+
try (SessionContext ctx = new SessionContext()) {
99+
assertFalse(ctx.tableExists("orders"));
100+
}
101+
}
102+
103+
@Test
104+
void tableExistsReturnsTrueAfterRegisterCsv(@TempDir Path tempDir) throws Exception {
105+
Path csv = tempDir.resolve("orders.csv");
106+
Files.writeString(csv, "id,amount\n1,100\n2,200\n");
107+
108+
try (SessionContext ctx = new SessionContext()) {
109+
assertFalse(ctx.tableExists("orders"));
110+
ctx.registerCsv("orders", csv.toAbsolutePath().toString());
111+
assertTrue(ctx.tableExists("orders"));
112+
}
113+
}
114+
115+
@Test
116+
void deregisterTableRemovesRegisteredTable(@TempDir Path tempDir) throws Exception {
117+
Path csv = tempDir.resolve("orders.csv");
118+
Files.writeString(csv, "id,amount\n1,100\n2,200\n");
119+
120+
try (SessionContext ctx = new SessionContext()) {
121+
ctx.registerCsv("orders", csv.toAbsolutePath().toString());
122+
assertTrue(ctx.tableExists("orders"));
123+
ctx.deregisterTable("orders");
124+
assertFalse(ctx.tableExists("orders"));
125+
}
126+
}
127+
128+
@Test
129+
void deregisterTableIsNoOpForUnregisteredTable() {
130+
try (SessionContext ctx = new SessionContext()) {
131+
ctx.deregisterTable("nonexistent");
132+
}
133+
}
134+
135+
@Test
136+
void tableExistsThrowsWhenContextIsClosed() {
137+
SessionContext ctx = new SessionContext();
138+
ctx.close();
139+
assertThrows(IllegalStateException.class, () -> ctx.tableExists("orders"));
140+
}
141+
142+
@Test
143+
void deregisterTableThrowsWhenContextIsClosed() {
144+
SessionContext ctx = new SessionContext();
145+
ctx.close();
146+
assertThrows(IllegalStateException.class, () -> ctx.deregisterTable("orders"));
147+
}
148+
149+
@Test
150+
void tableExistsThrowsForNullName() {
151+
try (SessionContext ctx = new SessionContext()) {
152+
assertThrows(IllegalArgumentException.class, () -> ctx.tableExists(null));
153+
}
154+
}
155+
156+
@Test
157+
void deregisterTableThrowsForNullName() {
158+
try (SessionContext ctx = new SessionContext()) {
159+
assertThrows(IllegalArgumentException.class, () -> ctx.deregisterTable(null));
160+
}
161+
}
93162
}

‎native/src/lib.rs‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1042,6 +1042,49 @@ pub extern "system" fn Java_org_apache_datafusion_SessionContext_getOptionNative
10421042
)
10431043
}
10441044

1045+
/// Converts a raw JNI handle into a shared reference to a [`SessionContext`].
1046+
///
1047+
/// # Safety for the unsafe usage
1048+
/// The caller must ensure `handle` was produced by `Box::into_raw(Box::new(ctx))`
1049+
/// in `createSessionContext` and has not yet been freed. The Java side zeroes
1050+
/// `nativeHandle` on `close()`, so the `handle == 0` guard in every JNI handler
1051+
/// ensures this invariant holds before `unwrap_context` is called.
1052+
fn unwrap_context(handle: jlong) -> JniResult<&'static SessionContext> {
1053+
if handle == 0 {
1054+
return Err("SessionContext handle is null".into());
1055+
}
1056+
Ok(unsafe { &*(handle as *const SessionContext) })
1057+
}
1058+
1059+
#[no_mangle]
1060+
pub extern "system" fn Java_org_apache_datafusion_SessionContext_tableExists<'local>(
1061+
mut env: JNIEnv<'local>,
1062+
_class: JClass<'local>,
1063+
handle: jlong,
1064+
name: JString<'local>,
1065+
) -> jboolean {
1066+
try_unwrap_or_throw(&mut env, 0, |env| -> JniResult<jboolean> {
1067+
let ctx = unwrap_context(handle)?;
1068+
let name: String = env.get_string(&name)?.into();
1069+
Ok(ctx.table_exist(&name)? as jboolean)
1070+
})
1071+
}
1072+
1073+
#[no_mangle]
1074+
pub extern "system" fn Java_org_apache_datafusion_SessionContext_deregisterTable<'local>(
1075+
mut env: JNIEnv<'local>,
1076+
_class: JClass<'local>,
1077+
handle: jlong,
1078+
name: JString<'local>,
1079+
) {
1080+
try_unwrap_or_throw(&mut env, (), |env| -> JniResult<()> {
1081+
let ctx = unwrap_context(handle)?;
1082+
let name: String = env.get_string(&name)?.into();
1083+
ctx.deregister_table(&name)?;
1084+
Ok(())
1085+
})
1086+
}
1087+
10451088
#[no_mangle]
10461089
pub extern "system" fn Java_org_apache_datafusion_SessionContext_closeSessionContext<'local>(
10471090
mut env: JNIEnv<'local>,

0 commit comments

Comments
 (0)