Elffuss BraidHub

kikocis/lancedb public

4a63e77b7e97 · 7.5 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 Ok(Self::inner_new(
72 builder
73 .execute()
74 .await
75 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
76 ))
77 }
78
79 #[napi]
80 pub fn display(&self) -> napi::Result<String> {
81 Ok(self.get_inner()?.to_string())
82 }
83
84 #[napi]
85 pub fn is_open(&self) -> bool {
86 self.inner.is_some()
87 }
88
89 #[napi]
90 pub fn close(&mut self) {
91 self.inner.take();
92 }
93
94 /// List all tables in the dataset.
95 #[napi(catch_unwind)]
96 pub async fn table_names(
97 &self,
98 start_after: Option<String>,
99 limit: Option<u32>,
100 ) -> napi::Result<Vec<String>> {
101 let mut op = self.get_inner()?.table_names();
102 if let Some(start_after) = start_after {
103 op = op.start_after(start_after);
104 }
105 if let Some(limit) = limit {
106 op = op.limit(limit);
107 }
108 op.execute()
109 .await
110 .map_err(|e| napi::Error::from_reason(format!("{}", e)))
111 }
112
113 /// Create table from a Apache Arrow IPC (file) buffer.
114 ///
115 /// Parameters:
116 /// - name: The name of the table.
117 /// - buf: The buffer containing the IPC file.
118 ///
119 #[napi(catch_unwind)]
120 pub async fn create_table(
121 &self,
122 name: String,
123 buf: Buffer,
124 mode: String,
125 storage_options: Option<HashMap<String, String>>,
126 data_storage_options: Option<String>,
127 enable_v2_manifest_paths: Option<bool>,
128 ) -> napi::Result<Table> {
129 let batches = ipc_file_to_batches(buf.to_vec())
130 .map_err(|e| napi::Error::from_reason(format!("Failed to read IPC file: {}", e)))?;
131 let mode = Self::parse_create_mode_str(&mode)?;
132 let mut builder = self.get_inner()?.create_table(&name, batches).mode(mode);
133
134 if let Some(storage_options) = storage_options {
135 for (key, value) in storage_options {
136 builder = builder.storage_option(key, value);
137 }
138 }
139 if let Some(data_storage_option) = data_storage_options.as_ref() {
140 builder = builder.data_storage_version(
141 LanceFileVersion::from_str(data_storage_option)
142 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
143 );
144 }
145 if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
146 builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
147 }
148 let tbl = builder
149 .execute()
150 .await
151 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
152 Ok(Table::new(tbl))
153 }
154
155 #[napi(catch_unwind)]
156 pub async fn create_empty_table(
157 &self,
158 name: String,
159 schema_buf: Buffer,
160 mode: String,
161 storage_options: Option<HashMap<String, String>>,
162 data_storage_options: Option<String>,
163 enable_v2_manifest_paths: Option<bool>,
164 ) -> napi::Result<Table> {
165 let schema = ipc_file_to_schema(schema_buf.to_vec()).map_err(|e| {
166 napi::Error::from_reason(format!("Failed to marshal schema from JS to Rust: {}", e))
167 })?;
168 let mode = Self::parse_create_mode_str(&mode)?;
169 let mut builder = self
170 .get_inner()?
171 .create_empty_table(&name, schema)
172 .mode(mode);
173 if let Some(storage_options) = storage_options {
174 for (key, value) in storage_options {
175 builder = builder.storage_option(key, value);
176 }
177 }
178 if let Some(data_storage_option) = data_storage_options.as_ref() {
179 builder = builder.data_storage_version(
180 LanceFileVersion::from_str(data_storage_option)
181 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
182 );
183 }
184 if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
185 builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
186 }
187 let tbl = builder
188 .execute()
189 .await
190 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
191 Ok(Table::new(tbl))
192 }
193
194 #[napi(catch_unwind)]
195 pub async fn open_table(
196 &self,
197 name: String,
198 storage_options: Option<HashMap<String, String>>,
199 index_cache_size: Option<u32>,
200 ) -> napi::Result<Table> {
201 let mut builder = self.get_inner()?.open_table(&name);
202 if let Some(storage_options) = storage_options {
203 for (key, value) in storage_options {
204 builder = builder.storage_option(key, value);
205 }
206 }
207 if let Some(index_cache_size) = index_cache_size {
208 builder = builder.index_cache_size(index_cache_size);
209 }
210 let tbl = builder
211 .execute()
212 .await
213 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
214 Ok(Table::new(tbl))
215 }
216
217 /// Drop table with the name. Or raise an error if the table does not exist.
218 #[napi(catch_unwind)]
219 pub async fn drop_table(&self, name: String) -> napi::Result<()> {
220 self.get_inner()?
221 .drop_table(&name)
222 .await
223 .map_err(|e| napi::Error::from_reason(format!("{}", e)))
224 }
225}