Elffuss BraidHub

kikocis/lancedb public

85830ec79fd2 · 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 if let Some(storage_options) = storage_options {
134 for (key, value) in storage_options {
135 builder = builder.storage_option(key, value);
136 }
137 }
138 if let Some(data_storage_option) = data_storage_options.as_ref() {
139 builder = builder.data_storage_version(
140 LanceFileVersion::from_str(data_storage_option)
141 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
142 );
143 }
144 if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
145 builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
146 }
147 let tbl = builder
148 .execute()
149 .await
150 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
151 Ok(Table::new(tbl))
152 }
153
154 #[napi(catch_unwind)]
155 pub async fn create_empty_table(
156 &self,
157 name: String,
158 schema_buf: Buffer,
159 mode: String,
160 storage_options: Option<HashMap<String, String>>,
161 data_storage_options: Option<String>,
162 enable_v2_manifest_paths: Option<bool>,
163 ) -> napi::Result<Table> {
164 let schema = ipc_file_to_schema(schema_buf.to_vec()).map_err(|e| {
165 napi::Error::from_reason(format!("Failed to marshal schema from JS to Rust: {}", e))
166 })?;
167 let mode = Self::parse_create_mode_str(&mode)?;
168 let mut builder = self
169 .get_inner()?
170 .create_empty_table(&name, schema)
171 .mode(mode);
172 if let Some(storage_options) = storage_options {
173 for (key, value) in storage_options {
174 builder = builder.storage_option(key, value);
175 }
176 }
177 if let Some(data_storage_option) = data_storage_options.as_ref() {
178 builder = builder.data_storage_version(
179 LanceFileVersion::from_str(data_storage_option)
180 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?,
181 );
182 }
183 if let Some(enable_v2_manifest_paths) = enable_v2_manifest_paths {
184 builder = builder.enable_v2_manifest_paths(enable_v2_manifest_paths);
185 }
186 let tbl = builder
187 .execute()
188 .await
189 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
190 Ok(Table::new(tbl))
191 }
192
193 #[napi(catch_unwind)]
194 pub async fn open_table(
195 &self,
196 name: String,
197 storage_options: Option<HashMap<String, String>>,
198 index_cache_size: Option<u32>,
199 ) -> napi::Result<Table> {
200 let mut builder = self.get_inner()?.open_table(&name);
201 if let Some(storage_options) = storage_options {
202 for (key, value) in storage_options {
203 builder = builder.storage_option(key, value);
204 }
205 }
206 if let Some(index_cache_size) = index_cache_size {
207 builder = builder.index_cache_size(index_cache_size);
208 }
209 let tbl = builder
210 .execute()
211 .await
212 .map_err(|e| napi::Error::from_reason(format!("{}", e)))?;
213 Ok(Table::new(tbl))
214 }
215
216 /// Drop table with the name. Or raise an error if the table does not exist.
217 #[napi(catch_unwind)]
218 pub async fn drop_table(&self, name: String) -> napi::Result<()> {
219 self.get_inner()?
220 .drop_table(&name)
221 .await
222 .map_err(|e| napi::Error::from_reason(format!("{}", e)))
223 }
224}