| 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, 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 | ) -> PyResult<Bound<'a, PyAny>> { |
| 85 | let inner = self_.get_inner()?.clone(); |
| 86 | |
| 87 | let mode = Self::parse_create_mode_str(mode)?; |
| 88 | |
| 89 | let batches = ArrowArrayStreamReader::from_pyarrow_bound(&data)?; |
| 90 | let mut builder = inner.create_table(name, batches).mode(mode); |
| 91 | |
| 92 | if let Some(storage_options) = storage_options { |
| 93 | builder = builder.storage_options(storage_options); |
| 94 | } |
| 95 | |
| 96 | if let Some(data_storage_version) = data_storage_version.as_ref() { |
| 97 | builder = builder.data_storage_version( |
| 98 | LanceFileVersion::from_str(data_storage_version) |
| 99 | .map_err(|e| PyValueError::new_err(e.to_string()))?, |
| 100 | ); |
| 101 | } |
| 102 | |
| 103 | future_into_py(self_.py(), async move { |
| 104 | let table = builder.execute().await.infer_error()?; |
| 105 | Ok(Table::new(table)) |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | pub fn create_empty_table<'a>( |
| 110 | self_: PyRef<'a, Self>, |
| 111 | name: String, |
| 112 | mode: &str, |
| 113 | schema: Bound<'_, PyAny>, |
| 114 | storage_options: Option<HashMap<String, String>>, |
| 115 | data_storage_version: Option<String>, |
| 116 | ) -> PyResult<Bound<'a, PyAny>> { |
| 117 | let inner = self_.get_inner()?.clone(); |
| 118 | |
| 119 | let mode = Self::parse_create_mode_str(mode)?; |
| 120 | |
| 121 | let schema = Schema::from_pyarrow_bound(&schema)?; |
| 122 | |
| 123 | let mut builder = inner.create_empty_table(name, Arc::new(schema)).mode(mode); |
| 124 | |
| 125 | if let Some(storage_options) = storage_options { |
| 126 | builder = builder.storage_options(storage_options); |
| 127 | } |
| 128 | |
| 129 | if let Some(data_storage_version) = data_storage_version.as_ref() { |
| 130 | builder = builder.data_storage_version( |
| 131 | LanceFileVersion::from_str(data_storage_version) |
| 132 | .map_err(|e| PyValueError::new_err(e.to_string()))?, |
| 133 | ); |
| 134 | } |
| 135 | |
| 136 | future_into_py(self_.py(), async move { |
| 137 | let table = builder.execute().await.infer_error()?; |
| 138 | Ok(Table::new(table)) |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | #[pyo3(signature = (name, storage_options = None, index_cache_size = None))] |
| 143 | pub fn open_table( |
| 144 | self_: PyRef<'_, Self>, |
| 145 | name: String, |
| 146 | storage_options: Option<HashMap<String, String>>, |
| 147 | index_cache_size: Option<u32>, |
| 148 | ) -> PyResult<Bound<'_, PyAny>> { |
| 149 | let inner = self_.get_inner()?.clone(); |
| 150 | let mut builder = inner.open_table(name); |
| 151 | if let Some(storage_options) = storage_options { |
| 152 | builder = builder.storage_options(storage_options); |
| 153 | } |
| 154 | if let Some(index_cache_size) = index_cache_size { |
| 155 | builder = builder.index_cache_size(index_cache_size); |
| 156 | } |
| 157 | future_into_py(self_.py(), async move { |
| 158 | let table = builder.execute().await.infer_error()?; |
| 159 | Ok(Table::new(table)) |
| 160 | }) |
| 161 | } |
| 162 | |
| 163 | pub fn drop_table(self_: PyRef<'_, Self>, name: String) -> PyResult<Bound<'_, PyAny>> { |
| 164 | let inner = self_.get_inner()?.clone(); |
| 165 | future_into_py(self_.py(), async move { |
| 166 | inner.drop_table(name).await.infer_error() |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | pub fn drop_db(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> { |
| 171 | let inner = self_.get_inner()?.clone(); |
| 172 | future_into_py( |
| 173 | self_.py(), |
| 174 | async move { inner.drop_db().await.infer_error() }, |
| 175 | ) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | #[pyfunction] |
| 180 | pub fn connect( |
| 181 | py: Python, |
| 182 | uri: String, |
| 183 | api_key: Option<String>, |
| 184 | region: Option<String>, |
| 185 | host_override: Option<String>, |
| 186 | read_consistency_interval: Option<f64>, |
| 187 | storage_options: Option<HashMap<String, String>>, |
| 188 | ) -> PyResult<Bound<'_, PyAny>> { |
| 189 | future_into_py(py, async move { |
| 190 | let mut builder = lancedb::connect(&uri); |
| 191 | if let Some(api_key) = api_key { |
| 192 | builder = builder.api_key(&api_key); |
| 193 | } |
| 194 | if let Some(region) = region { |
| 195 | builder = builder.region(®ion); |
| 196 | } |
| 197 | if let Some(host_override) = host_override { |
| 198 | builder = builder.host_override(&host_override); |
| 199 | } |
| 200 | if let Some(read_consistency_interval) = read_consistency_interval { |
| 201 | let read_consistency_interval = Duration::from_secs_f64(read_consistency_interval); |
| 202 | builder = builder.read_consistency_interval(read_consistency_interval); |
| 203 | } |
| 204 | if let Some(storage_options) = storage_options { |
| 205 | builder = builder.storage_options(storage_options); |
| 206 | } |
| 207 | Ok(Connection::new(builder.execute().await.infer_error()?)) |
| 208 | }) |
| 209 | } |