Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions python/sedona/spark/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,27 @@
from sedona.spark.utils.adapter import Adapter
from sedona.spark.utils.spatial_rdd_parser import GeoData
from sedona.spark.utils.structured_adapter import StructuredAdapter

from pyspark.sql import DataFrame


def to_sedonadb(self, connection=None):
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function imports sedona.db unconditionally, even when a connection is explicitly provided. That makes the method fail with ImportError in cases where a caller passes a compatible connection object (or in environments doing partial installs) even though sedona.db isn’t required on that code path. Move the import sedona.db + connect() logic inside the if connection is None: branch so only the auto-connect path requires the SedonaDB package.

Copilot uses AI. Check for mistakes.
"""
Converts a SedonaSpark DataFrame to a SedonaDB DataFrame.
:param connection: Optional SedonaDB connection object. If None, a new connection will be created.
:return: SedonaDB DataFrame
"""
try:
import sedona.db
except ImportError:
raise ImportError(
"SedonaDB is not installed. Please install it using `pip install sedona-db`."
)
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new ImportError branch isn’t covered by the added tests. Consider adding a test that ensures to_sedonadb() raises the expected ImportError (and message) when sedona.db is unavailable, so regressions in dependency handling are caught.

Copilot uses AI. Check for mistakes.

if connection is None:
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function imports sedona.db unconditionally, even when a connection is explicitly provided. That makes the method fail with ImportError in cases where a caller passes a compatible connection object (or in environments doing partial installs) even though sedona.db isn’t required on that code path. Move the import sedona.db + connect() logic inside the if connection is None: branch so only the auto-connect path requires the SedonaDB package.

Suggested change
try:
import sedona.db
except ImportError:
raise ImportError(
"SedonaDB is not installed. Please install it using `pip install sedona-db`."
)
if connection is None:
if connection is None:
try:
import sedona.db
except ImportError:
raise ImportError(
"SedonaDB is not installed. Please install it using `pip install sedona-db`."
)

Copilot uses AI. Check for mistakes.
connection = sedona.db.connect()

return connection.create_data_frame(dataframe_to_arrow(self))


DataFrame.to_sedonadb = to_sedonadb
91 changes: 91 additions & 0 deletions python/tests/test_to_sedonadb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import unittest
import sys
from unittest.mock import MagicMock, patch
from pyspark.sql import SparkSession, DataFrame
from sedona.spark import *


class TestToSedonaDB(unittest.TestCase):

def setUp(self):
# Mock sedona.db to avoid ImportError
self.mock_sedona_db = MagicMock()
sys.modules["sedona.db"] = self.mock_sedona_db
import sedona

sedona.db = self.mock_sedona_db
self.spark = SparkSession.builder.getOrCreate()

def tearDown(self):
if "sedona.db" in sys.modules:
del sys.modules["sedona.db"]
import sedona

if hasattr(sedona, "db"):
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test mutates global import state (sys.modules and sedona.db) without restoring the prior values. If another test in the same process relies on the real sedona.db module (or if it was already imported), deleting it can cause order-dependent failures. Store any prior sys.modules['sedona.db'] / sedona.db values in setUp and restore them in tearDown, or use unittest.mock.patch.dict(sys.modules, ...) and patch.object(sedona, 'db', ...) to ensure clean, reversible patching.

Suggested change
# Mock sedona.db to avoid ImportError
self.mock_sedona_db = MagicMock()
sys.modules["sedona.db"] = self.mock_sedona_db
import sedona
sedona.db = self.mock_sedona_db
self.spark = SparkSession.builder.getOrCreate()
def tearDown(self):
if "sedona.db" in sys.modules:
del sys.modules["sedona.db"]
import sedona
if hasattr(sedona, "db"):
# Preserve any existing sedona.db module and sedona.db attribute
self._original_sedona_db_module = sys.modules.get("sedona.db")
import sedona
self._had_sedona_db_attr = hasattr(sedona, "db")
self._original_sedona_db_attr = getattr(sedona, "db", None)
# Mock sedona.db to avoid ImportError
self.mock_sedona_db = MagicMock()
sys.modules["sedona.db"] = self.mock_sedona_db
sedona.db = self.mock_sedona_db
self.spark = SparkSession.builder.getOrCreate()
def tearDown(self):
# Restore prior sys.modules['sedona.db'] state
if self._original_sedona_db_module is not None:
sys.modules["sedona.db"] = self._original_sedona_db_module
elif "sedona.db" in sys.modules:
del sys.modules["sedona.db"]
import sedona
# Restore prior sedona.db attribute state
if self._had_sedona_db_attr:
sedona.db = self._original_sedona_db_attr
elif hasattr(sedona, "db"):

Copilot uses AI. Check for mistakes.
del sedona.db
Comment on lines +36 to +51
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test creates/gets a SparkSession in setUp but never stops it in tearDown. This can leak resources across the test process and cause flakiness/hangs in CI. Add self.spark.stop() (or use the repo’s existing Spark test fixture/session management if one exists) so the session lifecycle is properly bounded per test/module.

Copilot uses AI. Check for mistakes.

@patch("sedona.spark.dataframe_to_arrow")
def test_to_sedonadb_no_connection(self, mock_dataframe_to_arrow):
# Mock dependencies
mock_arrow_table = MagicMock()
mock_dataframe_to_arrow.return_value = mock_arrow_table

mock_connection = MagicMock()
self.mock_sedona_db.connect.return_value = mock_connection

mock_sedonadb_df = MagicMock()
mock_connection.create_data_frame.return_value = mock_sedonadb_df

# Create a dummy Spark DataFrame
df = self.spark.range(1)

# Call the method
result = df.to_sedonadb()

# Verify calls
self.mock_sedona_db.connect.assert_called_once()
mock_dataframe_to_arrow.assert_called_once_with(df)
mock_connection.create_data_frame.assert_called_once_with(mock_arrow_table)
self.assertEqual(result, mock_sedonadb_df)

@patch("sedona.spark.dataframe_to_arrow")
def test_to_sedonadb_with_connection(self, mock_dataframe_to_arrow):
# Mock dependencies
mock_arrow_table = MagicMock()
mock_dataframe_to_arrow.return_value = mock_arrow_table

mock_connection = MagicMock()
mock_sedonadb_df = MagicMock()
mock_connection.create_data_frame.return_value = mock_sedonadb_df

# Create a dummy Spark DataFrame
df = self.spark.range(1)

# Call the method
result = df.to_sedonadb(connection=mock_connection)

# Verify calls
mock_dataframe_to_arrow.assert_called_once_with(df)
mock_connection.create_data_frame.assert_called_once_with(mock_arrow_table)
self.assertEqual(result, mock_sedonadb_df)


if __name__ == "__main__":
unittest.main()
Loading