Elffuss BraidHub

kikocis/lancedb public

f371856ec79a · 7.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The LanceDB Authors
3
4use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration};
5
6use arrow::{datatypes::Schema, ffi_stream::ArrowArrayStreamReader, pyarrow::FromPyArrow};
7use lancedb::connection::{Connection as LanceConnection, CreateTableMode, LanceFileVersion};
8use pyo3::{
9 exceptions::{PyRuntimeError, PyValueError},
10 pyclass, pyfunction, pymethods, Bound, PyAny, PyRef, PyResult, Python,
11};
12use pyo3_asyncio_0_21::tokio::future_into_py;
13
14use crate::{error::PythonErrorExt, table::Table};
15
16#[pyclass]
17pub struct Connection {
18 inner: Option<LanceConnection>,
19}
20
21impl 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
33impl 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]
45impl 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]
190pub fn connect(
191 py: Python,
192 uri: String,
193 api_key: Option<String>,
194 region: Option<String>,
195 host_override: Option<String>,
196 read_consistency_interval: Option<f64>,
197 storage_options: Option<HashMap<String, String>>,
198) -> PyResult<Bound<'_, PyAny>> {
199 future_into_py(py, async move {
200 let mut builder = lancedb::connect(&uri);
201 if let Some(api_key) = api_key {
202 builder = builder.api_key(&api_key);
203 }
204 if let Some(region) = region {
205 builder = builder.region(&region);
206 }
207 if let Some(host_override) = host_override {
208 builder = builder.host_override(&host_override);
209 }
210 if let Some(read_consistency_interval) = read_consistency_interval {
211 let read_consistency_interval = Duration::from_secs_f64(read_consistency_interval);
212 builder = builder.read_consistency_interval(read_consistency_interval);
213 }
214 if let Some(storage_options) = storage_options {
215 builder = builder.storage_options(storage_options);
216 }
217 Ok(Connection::new(builder.execute().await.infer_error()?))
218 })
219}