1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! DDL API implementation - Schema management convenience methods
use crate::engine::Database;
use crate::error::DbxResult;
use arrow::datatypes::{DataType, Schema};
use std::sync::Arc;
impl Database {
/// Create a new table with the given Arrow schema
///
/// This is a convenience wrapper around `execute_sql("CREATE TABLE ...")`.
/// It automatically converts the Arrow schema to SQL DDL.
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("name", DataType::Utf8, true),
/// Field::new("age", DataType::Int32, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// assert!(db.table_exists("users"));
/// # Ok(())
/// # }
/// ```
pub fn create_table(&self, name: &str, schema: Schema) -> DbxResult<()> {
let schema_arc = Arc::new(schema);
// Generate CREATE TABLE SQL from Arrow Schema
let sql = self.generate_create_table_sql(name, &schema_arc);
// Execute SQL FIRST (this will check if table exists)
self.execute_sql(&sql)?;
// THEN store schema (after SQL succeeds)
self.table_schemas
.write()
.unwrap()
.insert(name.to_string(), Arc::clone(&schema_arc));
// Initialize empty table data
self.tables
.write()
.unwrap()
.insert(name.to_string(), vec![]);
// Initialize row counter
self.row_counters
.insert(name.to_string(), std::sync::atomic::AtomicUsize::new(0));
Ok(())
}
/// Drop a table
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// ]);
///
/// db.create_table("temp", schema)?;
/// db.drop_table("temp")?;
/// assert!(!db.table_exists("temp"));
/// # Ok(())
/// # }
/// ```
pub fn drop_table(&self, name: &str) -> DbxResult<()> {
self.execute_sql(&format!("DROP TABLE {}", name))?;
self.table_schemas.write().unwrap().remove(name);
Ok(())
}
/// Check if a table exists
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// assert!(!db.table_exists("users"));
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// ]);
///
/// db.create_table("users", schema)?;
/// assert!(db.table_exists("users"));
/// # Ok(())
/// # }
/// ```
pub fn table_exists(&self, name: &str) -> bool {
self.table_schemas.read().unwrap().contains_key(name)
}
/// Get the schema of a table
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("name", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema.clone())?;
/// let retrieved_schema = db.get_table_schema("users")?;
/// assert_eq!(retrieved_schema.fields().len(), 2);
/// # Ok(())
/// # }
/// ```
pub fn get_table_schema(&self, name: &str) -> DbxResult<Schema> {
self.table_schemas
.read()
.unwrap()
.get(name)
.map(|s| (**s).clone())
.ok_or_else(|| crate::DbxError::Schema(format!("Table '{}' not found", name)))
}
/// List all tables
pub fn list_tables(&self) -> Vec<String> {
self.table_schemas.read().unwrap().keys().cloned().collect()
}
/// Helper: Generate CREATE TABLE SQL from Arrow Schema
fn generate_create_table_sql(&self, name: &str, schema: &Schema) -> String {
let columns: Vec<String> = schema
.fields()
.iter()
.map(|field| {
let sql_type = match field.data_type() {
DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => "INT",
DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64 => {
"INT"
}
DataType::Float32 | DataType::Float64 => "FLOAT",
DataType::Utf8 | DataType::LargeUtf8 => "TEXT",
DataType::Boolean => "BOOLEAN",
DataType::Binary | DataType::LargeBinary => "BLOB",
DataType::Date32 | DataType::Date64 => "DATE",
DataType::Timestamp(_, _) => "TIMESTAMP",
_ => "TEXT", // Default to TEXT for unsupported types
};
format!("{} {}", field.name(), sql_type)
})
.collect();
format!("CREATE TABLE {} ({})", name, columns.join(", "))
}
/// Create a SQL index on table columns
///
/// This is a convenience wrapper around `execute_sql("CREATE INDEX ...")`.
/// For Hash Index (O(1) lookup), use `create_index(table, column)` instead.
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("email", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
/// assert!(db.sql_index_exists("idx_email"));
/// # Ok(())
/// # }
/// ```
pub fn create_sql_index(
&self,
table: &str,
index_name: &str,
columns: Vec<String>,
) -> DbxResult<()> {
// Generate CREATE INDEX SQL
let columns_str = columns.join(", ");
let sql = format!("CREATE INDEX {} ON {} ({})", index_name, table, columns_str);
// Execute SQL
self.execute_sql(&sql)?;
Ok(())
}
/// Drop a SQL index
///
/// This is a convenience wrapper around `execute_sql("DROP INDEX ...")`.
/// For Hash Index, use `drop_index(table, column)` instead.
///
/// Note: The index must have been created with `create_sql_index` to be tracked properly.
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("email", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
/// db.drop_sql_index("users", "idx_email")?;
/// assert!(!db.sql_index_exists("idx_email"));
/// # Ok(())
/// # }
/// ```
pub fn drop_sql_index(&self, table: &str, index_name: &str) -> DbxResult<()> {
// Use table.index_name format for DROP INDEX
let sql = format!("DROP INDEX {}.{}", table, index_name);
self.execute_sql(&sql)?;
Ok(())
}
/// Check if a SQL index exists
///
/// For Hash Index, use `has_index(table, column)` instead.
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("email", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// assert!(!db.sql_index_exists("idx_email"));
///
/// db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
/// assert!(db.sql_index_exists("idx_email"));
/// # Ok(())
/// # }
/// ```
pub fn sql_index_exists(&self, index_name: &str) -> bool {
self.index_registry.read().unwrap().contains_key(index_name)
}
/// List all SQL indexes for a table
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("email", DataType::Utf8, true),
/// Field::new("name", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// db.create_sql_index("users", "idx_email", vec!["email".to_string()])?;
/// db.create_sql_index("users", "idx_name", vec!["name".to_string()])?;
///
/// let indexes = db.list_sql_indexes("users");
/// assert!(indexes.contains(&"idx_email".to_string()));
/// assert!(indexes.contains(&"idx_name".to_string()));
/// # Ok(())
/// # }
/// ```
pub fn list_sql_indexes(&self, table: &str) -> Vec<String> {
self.index_registry
.read()
.unwrap()
.iter()
.filter_map(|(index_name, (tbl, _col))| {
if tbl == table {
Some(index_name.clone())
} else {
None
}
})
.collect()
}
/// Add a column to an existing table
///
/// This is a convenience wrapper around `execute_sql("ALTER TABLE ... ADD COLUMN ...")`.
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("name", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// db.add_column("users", "email", "TEXT")?;
///
/// let updated_schema = db.get_table_schema("users")?;
/// assert_eq!(updated_schema.fields().len(), 3);
/// # Ok(())
/// # }
/// ```
pub fn add_column(&self, table: &str, column_name: &str, data_type: &str) -> DbxResult<()> {
let sql = format!(
"ALTER TABLE {} ADD COLUMN {} {}",
table, column_name, data_type
);
self.execute_sql(&sql)?;
Ok(())
}
/// Drop a column from an existing table
///
/// This is a convenience wrapper around `execute_sql("ALTER TABLE ... DROP COLUMN ...")`.
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("name", DataType::Utf8, true),
/// Field::new("email", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// db.drop_column("users", "email")?;
///
/// let updated_schema = db.get_table_schema("users")?;
/// assert_eq!(updated_schema.fields().len(), 2);
/// # Ok(())
/// # }
/// ```
pub fn drop_column(&self, table: &str, column_name: &str) -> DbxResult<()> {
let sql = format!("ALTER TABLE {} DROP COLUMN {}", table, column_name);
self.execute_sql(&sql)?;
Ok(())
}
/// Rename a column in an existing table
///
/// This is a convenience wrapper around `execute_sql("ALTER TABLE ... RENAME COLUMN ...")`.
///
/// # Example
///
/// ```rust
/// use dbx_core::Database;
/// use arrow::datatypes::{DataType, Field, Schema};
///
/// # fn main() -> dbx_core::DbxResult<()> {
/// let db = Database::open_in_memory()?;
///
/// let schema = Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new("user_name", DataType::Utf8, true),
/// ]);
///
/// db.create_table("users", schema)?;
/// db.rename_column("users", "user_name", "name")?;
///
/// let updated_schema = db.get_table_schema("users")?;
/// assert_eq!(updated_schema.field(1).name(), "name");
/// # Ok(())
/// # }
/// ```
pub fn rename_column(&self, table: &str, old_name: &str, new_name: &str) -> DbxResult<()> {
let sql = format!(
"ALTER TABLE {} RENAME COLUMN {} TO {}",
table, old_name, new_name
);
self.execute_sql(&sql)?;
Ok(())
}
}