| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // SPDX-FileCopyrightText: Copyright The LanceDB Authors |
| 3 | |
| 4 | use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration}; |
| 5 | |
| 6 | use arrow::{datatypes::Schema, ffi_stream::ArrowArrayStreamReader, pyarrow::FromPyArrow}; |
| 7 | use lancedb::connection::{Connection as LanceConnection, CreateTableMode, LanceFileVersion}; |
| 8 | use pyo3::{ |
| 9 | exceptions::{PyRuntimeError, PyValueError}, |
| 10 | pyclass, pyfunction, pymethods, Bound, FromPyObject, PyAny, PyRef, PyResult, Python, |
| 11 | }; |
| 12 | use pyo3_asyncio_0_21::tokio::future_into_py; |
| 13 | |
| 14 | use crate::{error::PythonErrorExt, table::Table}; |
| 15 | |
| 16 | #[pyclass] |
| 17 | pub struct Connection { |
| 18 | inner: Option<LanceConnection>, |
| 19 | } |
| 20 | |
| 21 | impl Connection { |
| 22 | pub(crate) fn new(inner: LanceConnection) -> Self { |
| 23 | Self { inner: Some(inner) } |
| 24 | } |
| 25 | |
| 26 | fn get_inner(&self) -> PyResult<&LanceConnection> { |
| 27 | self.inner |
| 28 | .as_ref() |
| 29 | .ok_or_else(|| PyRuntimeError::new_err("Connection is closed")) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl Connection { |
| 34 | fn parse_create_mode_str(mode: &str) -> PyResult<CreateTableMode> { |
| 35 | match mode { |
| 36 | "create" => Ok(CreateTableMode::Create), |
| 37 | "overwrite" => Ok(CreateTableMode::Overwrite), |
| 38 | "exist_ok" => Ok(CreateTableMode::exist_ok(|builder| builder)), |
| 39 | _ => Err(PyValueError::new_err(format!("Invalid mode {}", mode))), |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | #[pymethods] |
| 45 | impl Connection { |
| 46 | fn __repr__(&self) -> String { |
| 47 | match &self.inner { |
| 48 | Some(inner) => inner.to_string(), |
| 49 | None => "ClosedConnection".to_string(), |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | fn is_open(&self) -> bool { |
| 54 | self.inner.is_some() |
| 55 | } |
| 56 | |
| 57 | fn close(&mut self) { |
| 58 | self.inner.take(); |
| 59 | } |
| 60 | |
| 61 | pub fn table_names( |
| 62 | self_: PyRef<'_, Self>, |
| 63 | start_after: Option<String>, |
| 64 | limit: Option<u32>, |
| 65 | ) -> PyResult<Bound<'_, PyAny>> { |
| 66 | let inner = self_.get_inner()?.clone(); |
| 67 | let mut op = inner.table_names(); |
| 68 | if let Some(start_after) = start_after { |
| 69 | op = op.start_after(start_after); |
| 70 | } |
| 71 | if let Some(limit) = limit { |
| 72 | op = op.limit(limit); |
| 73 | } |
| 74 | future_into_py(self_.py(), async move { op.execute().await.infer_error() }) |
| 75 | } |
| 76 | |
| 77 | pub fn create_table<'a>( |
| 78 | self_: PyRef<'a, Self>, |
| 79 | name: String, |
| 80 | mode: &str, |
| 81 | data: Bound<'_, PyAny>, |
| 82 | storage_options: Option<HashMap<String, String>>, |
| 83 | data_storage_version: Option<String>, |
| 84 | enable_v2_manifest_paths: Option<bool>, |
| 85 | ) -> PyResult<Bound<'a, PyAny>> { |
| 86 | let inner = self_.get_inner()?.clone(); |
| 87 | |
| 88 | let mode = Self::parse_create_mode_str(mode)?; |
| 89 | |
| 90 | let batches = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; |
| 91 | let mut builder = inner.create_table(name, batches).mode(mode); |
| 92 | |
| 93 | if let Some(storage_options) = storage_options { |
| 94 | builder = builder.storage_options(storage_options); |
| 95 | } |
| 96 | |
| 97 | if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths { |
| 98 | builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths); |
| 99 | } |
| 100 | |
| 101 | if let Some(data_storage_version) = data_storage_version.as_ref() { |
| 102 | builder = builder.data_storage_version( |
| 103 | LanceFileVersion::from_str(data_storage_version) |
| 104 | .map_err(|e| PyValueError::new_err(e.to_string()))?, |
| 105 | ); |
| 106 | } |
| 107 | |
| 108 | future_into_py(self_.py(), async move { |
| 109 | let table = builder.execute().await.infer_error()?; |
| 110 | Ok(Table::new(table)) |
| 111 | }) |
| 112 | } |
| 113 | |
| 114 | pub fn create_empty_table<'a>( |
| 115 | self_: PyRef<'a, Self>, |
| 116 | name: String, |
| 117 | mode: &str, |
| 118 | schema: Bound<'_, PyAny>, |
| 119 | storage_options: Option<HashMap<String, String>>, |
| 120 | data_storage_version: Option<String>, |
| 121 | enable_v2_manifest_paths: Option<bool>, |
| 122 | ) -> PyResult<Bound<'a, PyAny>> { |
| 123 | let inner = self_.get_inner()?.clone(); |
| 124 | |
| 125 | let mode = Self::parse_create_mode_str(mode)?; |
| 126 | |
| 127 | let schema = Schema::from_pyarrow_bound(&schema)?; |
| 128 | |
| 129 | let mut builder = inner.create_empty_table(name, Arc::new(schema)).mode(mode); |
| 130 | |
| 131 | if let Some(storage_options) = storage_options { |
| 132 | builder = builder.storage_options(storage_options); |
| 133 | } |
| 134 | |
| 135 | if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths { |
| 136 | builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths); |
| 137 | } |
| 138 | |
| 139 | if let Some(data_storage_version) = data_storage_version.as_ref() { |
| 140 | builder = builder.data_storage_version( |
| 141 | LanceFileVersion::from_str(data_storage_version) |
| 142 | .map_err(|e| PyValueError::new_err(e.to_string()))?, |
| 143 | ); |
| 144 | } |
| 145 | |
| 146 | future_into_py(self_.py(), async move { |
| 147 | let table = builder.execute().await.infer_error()?; |
| 148 | Ok(Table::new(table)) |
| 149 | }) |
| 150 | } |
| 151 | |
| 152 | #[pyo3(signature = (name, storage_options = None, index_cache_size = None))] |
| 153 | pub fn open_table( |
| 154 | self_: PyRef<'_, Self>, |
| 155 | name: String, |
| 156 | storage_options: Option<HashMap<String, String>>, |
| 157 | index_cache_size: Option<u32>, |
| 158 | ) -> PyResult<Bound<'_, PyAny>> { |
| 159 | let inner = self_.get_inner()?.clone(); |
| 160 | let mut builder = inner.open_table(name); |
| 161 | if let Some(storage_options) = storage_options { |
| 162 | builder = builder.storage_options(storage_options); |
| 163 | } |
| 164 | if let Some(index_cache_size) = index_cache_size { |
| 165 | builder = builder.index_cache_size(index_cache_size); |
| 166 | } |
| 167 | future_into_py(self_.py(), async move { |
| 168 | let table = builder.execute().await.infer_error()?; |
| 169 | Ok(Table::new(table)) |
| 170 | }) |
| 171 | } |
| 172 | |
| 173 | pub fn drop_table(self_: PyRef<'_, Self>, name: String) -> PyResult<Bound<'_, PyAny>> { |
| 174 | let inner = self_.get_inner()?.clone(); |
| 175 | future_into_py(self_.py(), async move { |
| 176 | inner.drop_table(name).await.infer_error() |
| 177 | }) |
| 178 | } |
| 179 | |
| 180 | pub fn drop_db(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 181 | let inner = self_.get_inner()?.clone(); |
| 182 | future_into_py( |
| 183 | self_.py(), |
| 184 | async move { inner.drop_db().await.infer_error() }, |
| 185 | ) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | #[pyfunction] |
| 190 | #[allow(clippy::too_many_arguments)] |
| 191 | pub fn connect( |
| 192 | py: Python, |
| 193 | uri: String, |
| 194 | api_key: Option<String>, |
| 195 | region: Option<String>, |
| 196 | host_override: Option<String>, |
| 197 | read_consistency_interval: Option<f64>, |
| 198 | client_config: Option<PyClientConfig>, |
| 199 | storage_options: Option<HashMap<String, String>>, |
| 200 | ) -> PyResult<Bound<'_, PyAny>> { |
| 201 | future_into_py(py, async move { |
| 202 | let mut builder = lancedb::connect(&uri); |
| 203 | if let Some(api_key) = api_key { |
| 204 | builder = builder.api_key(&api_key); |
| 205 | } |
| 206 | if let Some(region) = region { |
| 207 | builder = builder.region(®ion); |
| 208 | } |
| 209 | if let Some(host_override) = host_override { |
| 210 | builder = builder.host_override(&host_override); |
| 211 | } |
| 212 | if let Some(read_consistency_interval) = read_consistency_interval { |
| 213 | let read_consistency_interval = Duration::from_secs_f64(read_consistency_interval); |
| 214 | builder = builder.read_consistency_interval(read_consistency_interval); |
| 215 | } |
| 216 | if let Some(storage_options) = storage_options { |
| 217 | builder = builder.storage_options(storage_options); |
| 218 | } |
| 219 | #[cfg(feature = "remote")] |
| 220 | if let Some(client_config) = client_config { |
| 221 | builder = builder.client_config(client_config.into()); |
| 222 | } |
| 223 | Ok(Connection::new(builder.execute().await.infer_error()?)) |
| 224 | }) |
| 225 | } |
| 226 | |
| 227 | #[derive(FromPyObject)] |
| 228 | pub struct PyClientConfig { |
| 229 | user_agent: String, |
| 230 | retry_config: Option<PyClientRetryConfig>, |
| 231 | timeout_config: Option<PyClientTimeoutConfig>, |
| 232 | } |
| 233 | |
| 234 | #[derive(FromPyObject)] |
| 235 | pub struct PyClientRetryConfig { |
| 236 | retries: Option<u8>, |
| 237 | connect_retries: Option<u8>, |
| 238 | read_retries: Option<u8>, |
| 239 | backoff_factor: Option<f32>, |
| 240 | backoff_jitter: Option<f32>, |
| 241 | statuses: Option<Vec<u16>>, |
| 242 | } |
| 243 | |
| 244 | #[derive(FromPyObject)] |
| 245 | pub struct PyClientTimeoutConfig { |
| 246 | connect_timeout: Option<Duration>, |
| 247 | read_timeout: Option<Duration>, |
| 248 | pool_idle_timeout: Option<Duration>, |
| 249 | } |
| 250 | |
| 251 | #[cfg(feature = "remote")] |
| 252 | impl From<PyClientRetryConfig> for lancedb::remote::RetryConfig { |
| 253 | fn from(value: PyClientRetryConfig) -> Self { |
| 254 | Self { |
| 255 | retries: value.retries, |
| 256 | connect_retries: value.connect_retries, |
| 257 | read_retries: value.read_retries, |
| 258 | backoff_factor: value.backoff_factor, |
| 259 | backoff_jitter: value.backoff_jitter, |
| 260 | statuses: value.statuses, |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | #[cfg(feature = "remote")] |
| 266 | impl From<PyClientTimeoutConfig> for lancedb::remote::TimeoutConfig { |
| 267 | fn from(value: PyClientTimeoutConfig) -> Self { |
| 268 | Self { |
| 269 | connect_timeout: value.connect_timeout, |
| 270 | read_timeout: value.read_timeout, |
| 271 | pool_idle_timeout: value.pool_idle_timeout, |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | #[cfg(feature = "remote")] |
| 277 | impl From<PyClientConfig> for lancedb::remote::ClientConfig { |
| 278 | fn from(value: PyClientConfig) -> Self { |
| 279 | Self { |
| 280 | user_agent: value.user_agent, |
| 281 | retry_config: value.retry_config.map(Into::into).unwrap_or_default(), |
| 282 | timeout_config: value.timeout_config.map(Into::into).unwrap_or_default(), |
| 283 | } |
| 284 | } |
| 285 | } |