Elffuss BraidHub

kikocis/lancedb public

main · 8.0 KiBRawPermalink
1// Copyright 2024 Lance Developers.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::str::FromStr;
17
18use napi::bindgen_prelude::*;
19use napi_derive::*;
20
21use crate::table::Table;
22use crate::ConnectionOptions;
23use lancedb::connection::{
24 ConnectBuilder, Connection as LanceDBConnection, CreateTableMode, LanceFileVersion,
25};
26use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema};
27
28#[napi]
29pub struct Connection {
30 inner: Option<LanceDBConnection>,
31}
32
33impl Connection {
34 pub(crate) fn inner_new(inner: LanceDBConnection) -> Self {
35 Self { inner: Some(inner) }
36 }
37
38 fn get_inner(&self) -> napi::Result<&LanceDBConnection> {
39 self.inner
40 .as_ref()
41 .ok_or_else(|| napi::Error::from_reason("Connection is closed"))
42 }
43}
44
45impl Connection {
46 fn parse_create_mode_str(mode: &str) -> napi::Result<CreateTableMode> {
47 match mode {
48 "create" => Ok(CreateTableMode::Create),
49 "overwrite" => Ok(CreateTableMode::Overwrite),
50 "exist_ok" => Ok(CreateTableMode::exist_ok(|builder| builder)),
51 _ => Err(napi::Error::from_reason(format!("Invalid mode {}", mode))),
52 }
53 }
54}
55
56#[napi]
57impl Connection {
58 /// Create a new Connection instance from the given URI.
59 #[napi(factory)]
60 pub async fn new(uri: String, options: ConnectionOptions) -> napi::Result<Self> {
61 let mut builder = ConnectBuilder::new(&uri);
62 if let Some(interval) = options.read_consistency_interval {
63 builder =
64 builder.read_consistency_interval(std::time::Duration::from_secs_f64(interval));
65 }
66 if let Some(storage_options) = options.storage_options {
67 for (key, value) in storage_options {
68 builder = builder.storage_option(key, value);
69 }
70 }
71
72 let client_config = options.client_config.unwrap_or_default();
73 builder = builder.client_config(client_config.into());
74
75 if let Some(api_key) = options.api_key {
76 builder = builder.api_key(&api_key);
77 }
78
79 if let Some(region) = options.region {
80 builder = builder.region(&region);
81 } else {
82 builder = builder.region("us-east-1");
83 }
84
85 if let Some(host_override) = options.host_override {
86 builder = builder.host_override(&host_override);
87 }
88
89 Ok(Self::inner_new(
90 builder
91 .execute()
92 .await
93 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
94 ))
95 }
96
97 #[napi]
98 pub fn display(&self) -> napi::Result<String> {
99 Ok(self.get_inner()?.to_string())
100 }
101
102 #[napi]
103 pub fn is_open(&self) -> bool {
104 self.inner.is_some()
105 }
106
107 #[napi]
108 pub fn close(&mut self) {
109 self.inner.take();
110 }
111
112 /// List all tables in the dataset.
113 #[napi(catch_unwind)]
114 pub async fn table_names(
115 &self,
116 start_after: Option<String>,
117 limit: Option<u32>,
118 ) -> napi::Result<Vec<String>> {
119 let mut op = self.get_inner()?.table_names();
120 if let Some(start_after) = start_after {
121 op = op.start_after(start_after);
122 }
123 if let Some(limit) = limit {
124 op = op.limit(limit);
125 }
126 op.execute()
127 .await
128 .map_err(|e| napi::Error::from_reason(format!("{}", e)))
129 }
130
131 /// Create table from a Apache Arrow IPC (file) buffer.
132 ///
133 /// Parameters:
134 /// - name: The name of the table.
135 /// - buf: The buffer containing the IPC file.
136 ///
137 #[napi(catch_unwind)]
138 pub async fn create_table(
139 &self,
140 name: String,
141 buf: Buffer,
142 mode: String,
143 storage_options: Option<HashMap<String, String>>,
144 data_storage_options: Option<String>,
145 enable_v2_manifest_paths: Option<bool>,
146 ) -> napi::Result<Table> {
147 let batches = ipc_file_to_batches(buf.to_vec())
148 .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?;
149 let mode = Self::parse_create_mode_str(&mode)?;
150 let mut builder = self.get_inner()?.create_table(&name, batches).mode(mode);
151
152 if let Some(storage_options) = storage_options {
153 for (key, value) in storage_options {
154 builder = builder.storage_option(key, value);
155 }
156 }
157 if let Some(data_storage_option) = data_storage_options.as_ref() {
158 builder = builder.data_storage_version(
159 LanceFileVersion::from_str(data_storage_option)
160 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
161 );
162 }
163 if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
164 builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
165 }
166 let tbl = builder
167 .execute()
168 .await
169 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
170 Ok(Table::new(tbl))
171 }
172
173 #[napi(catch_unwind)]
174 pub async fn create_empty_table(
175 &self,
176 name: String,
177 schema_buf: Buffer,
178 mode: String,
179 storage_options: Option<HashMap<String, String>>,
180 data_storage_options: Option<String>,
181 enable_v2_manifest_paths: Option<bool>,
182 ) -> napi::Result<Table> {
183 let schema = ipc_file_to_schema(schema_buf.to_vec()).map_err(|e| {
184 napi::Error::from_reason(format!("Failed to marshal schema from JS to Rust: {}", e))
185 })?;
186 let mode = Self::parse_create_mode_str(&mode)?;
187 let mut builder = self
188 .get_inner()?
189 .create_empty_table(&name, schema)
190 .mode(mode);
191 if let Some(storage_options) = storage_options {
192 for (key, value) in storage_options {
193 builder = builder.storage_option(key, value);
194 }
195 }
196 if let Some(data_storage_option) = data_storage_options.as_ref() {
197 builder = builder.data_storage_version(
198 LanceFileVersion::from_str(data_storage_option)
199 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
200 );
201 }
202 if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
203 builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
204 }
205 let tbl = builder
206 .execute()
207 .await
208 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
209 Ok(Table::new(tbl))
210 }
211
212 #[napi(catch_unwind)]
213 pub async fn open_table(
214 &self,
215 name: String,
216 storage_options: Option<HashMap<String, String>>,
217 index_cache_size: Option<u32>,
218 ) -> napi::Result<Table> {
219 let mut builder = self.get_inner()?.open_table(&name);
220 if let Some(storage_options) = storage_options {
221 for (key, value) in storage_options {
222 builder = builder.storage_option(key, value);
223 }
224 }
225 if let Some(index_cache_size) = index_cache_size {
226 builder = builder.index_cache_size(index_cache_size);
227 }
228 let tbl = builder
229 .execute()
230 .await
231 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
232 Ok(Table::new(tbl))
233 }
234
235 /// Drop table with the name. Or raise an error if the table does not exist.
236 #[napi(catch_unwind)]
237 pub async fn drop_table(&self, name: String) -> napi::Result<()> {
238 self.get_inner()?
239 .drop_table(&name)
240 .await
241 .map_err(|e| napi::Error::from_reason(format!("{}", e)))
242 }
243}