frozen-duckdb 0.1.0

Pre-compiled DuckDB binary for fast Rust builds - Drop-in replacement for duckdb-rs
Documentation
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! # Frozen DuckDB CLI Tool
//!
//! A comprehensive command-line interface for managing datasets and frozen DuckDB operations.
//! This tool provides utilities for dataset management, format conversion, performance
//! benchmarking, system information display, and LLM operations via Flock extension.
//!
//! ## Features
//!
//! - **๐Ÿ“ฅ Dataset Management**: Download and generate sample datasets (Chinook, TPC-H)
//! - **๐Ÿ”„ Format Conversion**: Convert between CSV, Parquet, Arrow, and DuckDB formats
//! - **โšก Performance Benchmarking**: Measure and compare operation performance
//! - **โ„น๏ธ System Information**: Display frozen DuckDB configuration and capabilities
//! - **๐Ÿงช Testing Support**: Run comprehensive test suites
//! - **๐Ÿค– LLM Operations**: Text completion, embeddings, semantic search via Flock
//!
//! ## Usage
//!
//! ```bash
//! # Show help
//! frozen-duckdb --help
//!
//! # Download Chinook dataset in CSV format
//! frozen-duckdb download --dataset chinook --format csv
//!
//! # Generate TPC-H dataset in Parquet format
//! frozen-duckdb download --dataset tpch --format parquet
//!
//! # Convert CSV to Parquet
//! frozen-duckdb convert --input data.csv --output data.parquet --input-format csv --output-format parquet
//!
//! # Show system information
//! frozen-duckdb info
//!
//! # Setup Ollama for LLM operations
//! frozen-duckdb flock-setup
//!
//! # Generate text completion
//! frozen-duckdb complete --prompt "Explain recursion in programming"
//!
//! # Generate embeddings for semantic search
//! frozen-duckdb embed --text "Python programming language"
//!
//! # Perform semantic search
//! frozen-duckdb search --query "machine learning" --corpus documents.txt
//! ```
//!
//! ## Environment Setup
//!
//! Before using the CLI, ensure the frozen DuckDB environment is configured:
//!
//! ```bash
//! # Set up environment (required)
//! source prebuilt/setup_env.sh
//!
//! # Verify configuration
//! frozen-duckdb info
//! ```
//!
//! ## Performance Targets
//!
//! The CLI is designed to meet strict performance requirements:
//!
//! - **Startup time**: <100ms
//! - **Dataset generation**: <10s for small datasets
//! - **Format conversion**: <1s for typical files
//! - **Memory usage**: <100MB for most operations
//! - **LLM operations**: <5s for typical requests
//!
//! ## Error Handling
//!
//! The CLI provides clear error messages and exit codes:
//!
//! - **Exit code 0**: Success
//! - **Exit code 1**: General error (invalid arguments, file not found)
//! - **Exit code 2**: Environment not configured
//! - **Exit code 3**: Binary validation failed
//! - **Exit code 4**: Flock extension not available

use anyhow::{Context, Result};
use clap::Parser;
use frozen_duckdb::cli::commands::{Cli, Commands};
use frozen_duckdb::cli::dataset_manager::DatasetManager;
use frozen_duckdb::cli::flock_manager::FlockManager;
use serde_json::{self, Value};
use std::io;
use std::path::Path;
use tracing::{error, info};


fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize tracing based on verbosity
    let subscriber = tracing_subscriber::FmtSubscriber::builder()
        .with_max_level(match cli.verbose {
            0 => tracing::Level::WARN,
            1 => tracing::Level::INFO,
            2 => tracing::Level::DEBUG,
            _ => tracing::Level::TRACE,
        })
        .finish();

    tracing::subscriber::set_global_default(subscriber).expect("Failed to set tracing subscriber");

    match cli.command {
        // === DATASET MANAGEMENT COMMANDS ===
        Commands::Download {
            dataset,
            output_dir,
            format,
        } => {
            let dataset_manager = DatasetManager::new()?;
            match dataset.as_str() {
                "chinook" => {
                    dataset_manager.download_chinook(&output_dir, &format)?;
                }
                "tpch" => {
                    dataset_manager.download_tpch(&output_dir, &format)?;
                }
                _ => {
                    error!("โŒ Unknown dataset: {}", dataset);
                    error!("   Available datasets: chinook, tpch");
                    std::process::exit(1);
                }
            }
        }

        Commands::Convert {
            input,
            output,
            input_format,
            output_format,
        } => {
            let dataset_manager = DatasetManager::new()?;
            dataset_manager.convert_dataset(&input, &output, &input_format, &output_format)?;
        }

        Commands::Info => {
            let dataset_manager = DatasetManager::new()?;
            dataset_manager.show_info()?;
        }

        // === FLOCK/LLM COMMANDS ===
        Commands::FlockSetup {
            ollama_url,
            text_model,
            embedding_model,
            skip_verification,
        } => {
            let flock_manager = FlockManager::new()?;

            // Check if Flock is ready before proceeding
            if !flock_manager.is_flock_ready()? {
                error!("โŒ Flock extension not available");
                error!("   Make sure DuckDB with Flock extension is properly installed");
                std::process::exit(4);
            }

            flock_manager.setup_ollama(&ollama_url, &text_model, &embedding_model, skip_verification)?;
        }

        Commands::Complete {
            prompt,
            input,
            output,
            model,
            max_tokens: _,
            temperature: _,
        } => {
            let flock_manager = FlockManager::new()?;

            // Check if Flock is ready
            if !flock_manager.is_flock_ready()? {
                error!("โŒ Flock extension not available");
                error!("   Run 'frozen-duckdb flock-setup' first");
                std::process::exit(4);
            }

            let text_to_complete = if let Some(prompt_text) = prompt {
                prompt_text
            } else if let Some(input_file) = input {
                // Read from input file
                match std::fs::read_to_string(&input_file) {
                    Ok(content) => content.trim().to_string(),
                    Err(e) => {
                        error!("โŒ Failed to read input file '{}': {}", input_file, e);
                        std::process::exit(1);
                    }
                }
            } else {
                // Read from stdin
                info!("๐Ÿ“ Enter text to complete (Ctrl+D to finish):");
                let mut buffer = String::new();
                io::stdin().read_line(&mut buffer)?;
                buffer.trim().to_string()
            };

            let response = flock_manager.complete_text(&text_to_complete, model.as_str())
                .unwrap_or_else(|_| {
                    error!("โŒ Text completion failed - check if Ollama is running");
                    std::process::exit(1);
                });

            if let Some(output_file) = output {
                match std::fs::write(&output_file, &response) {
                    Ok(_) => info!("โœ… Response written to: {}", output_file),
                    Err(e) => {
                        error!("โŒ Failed to write to output file '{}': {}", output_file, e);
                        std::process::exit(1);
                    }
                }
            } else {
                println!("{}", response);
            }
        }

        Commands::Embed {
            text,
            input,
            output,
            model,
            normalize,
        } => {
            let flock_manager = FlockManager::new()?;

            // Check if Flock is ready
            if !flock_manager.is_flock_ready()? {
                error!("โŒ Flock extension not available");
                error!("   Run 'frozen-duckdb flock-setup' first");
                std::process::exit(4);
            }

            let texts_to_embed = if let Some(text_content) = text {
                vec![text_content.clone()]
            } else if let Some(input_file) = input {
                // Read texts from input file (one per line)
                match std::fs::read_to_string(&input_file) {
                    Ok(content) => content.lines().map(|s| s.to_string()).collect(),
                    Err(e) => {
                        error!("โŒ Failed to read input file '{}': {}", input_file, e);
                        std::process::exit(1);
                    }
                }
            } else {
                error!("โŒ Must provide either --text or --input");
                std::process::exit(1);
            };

            let embeddings = flock_manager.generate_embeddings(texts_to_embed, &model, normalize)
                .expect("Embedding generation not implemented yet");

            if let Some(output_file) = output {
                // Write embeddings as JSON
                let json_data = serde_json::to_string_pretty(&embeddings)
                    .context("Failed to serialize embeddings to JSON")?;
                match std::fs::write(&output_file, json_data) {
                    Ok(_) => info!("โœ… Embeddings written to: {}", output_file),
                    Err(e) => {
                        error!("โŒ Failed to write to output file '{}': {}", output_file, e);
                        std::process::exit(1);
                    }
                }
            } else {
                // Print embeddings to stdout
                println!("{}", serde_json::to_string_pretty(&embeddings)?);
            }
        }

        Commands::Search {
            query,
            corpus,
            threshold,
            limit,
            format,
        } => {
            let flock_manager = FlockManager::new()?;

            // Check if Flock is ready
            if !flock_manager.is_flock_ready()? {
                error!("โŒ Flock extension not available");
                error!("   Run 'frozen-duckdb flock-setup' first");
                std::process::exit(4);
            }

            let results = flock_manager.semantic_search(&query, &corpus, threshold, limit)
                .expect("Semantic search not implemented yet");

            match format.as_str() {
                "json" => {
                    let json_results: Vec<Value> = results
                        .into_iter()
                        .map(|(doc, score)| {
                            serde_json::json!({
                                "document": doc,
                                "similarity_score": score
                            })
                        })
                        .collect();
                    println!("{}", serde_json::to_string_pretty(&json_results)?);
                }
                _ => {
                    // Text format
                    if results.is_empty() {
                        info!("๐Ÿ” No similar documents found above threshold {:.3}", threshold);
                    } else {
                        info!("๐Ÿ” Found {} similar documents:", results.len());
                        for (i, (doc, score)) in results.iter().enumerate() {
                            println!("  {}. \"{}\" (similarity: {:.3})", i + 1, doc, score);
                        }
                    }
                }
            }
        }

        Commands::Filter {
            criteria,
            prompt,
            input,
            output,
            model,
            positive_only,
        } => {
            let flock_manager = FlockManager::new()?;

            // Check if Flock is ready
            if !flock_manager.is_flock_ready()? {
                error!("โŒ Flock extension not available");
                error!("   Run 'frozen-duckdb flock-setup' first");
                std::process::exit(4);
            }

            let filter_criteria = if let Some(custom_prompt) = prompt {
                custom_prompt.clone()
            } else if let Some(criteria_text) = criteria {
                format!("{} Answer yes or no: {{text}}", criteria_text)
            } else {
                error!("โŒ Must provide either --criteria or --prompt");
                std::process::exit(1);
            };

            let results = flock_manager.llm_filter(&filter_criteria, &input, &model, true)
                .expect("LLM filtering not implemented yet");

            if let Some(output_file) = output {
                let json_data = serde_json::to_string_pretty(&results)
                    .context("Failed to serialize filter results to JSON")?;
                match std::fs::write(&output_file, json_data) {
                    Ok(_) => info!("โœ… Filter results written to: {}", output_file),
                    Err(e) => {
                        error!("โŒ Failed to write to output file '{}': {}", output_file, e);
                        std::process::exit(1);
                    }
                }
            } else {
                // Print results to stdout
                if positive_only {
                    info!("โœ… Items that match criteria:");
                    for (item, matches) in results {
                        if matches {
                            println!("โœ… {}", item);
                        }
                    }
                } else {
                    info!("๐Ÿ“Š Filter results:");
                    for (item, matches) in results {
                        let status = if matches { "โœ… MATCH" } else { "โŒ NO MATCH" };
                        println!("{}: {}", status, item);
                    }
                }
            }
        }

        Commands::Summarize {
            input,
            output,
            strategy,
            max_length,
            model,
        } => {
            let flock_manager = FlockManager::new()?;

            // Check if Flock is ready
            if !flock_manager.is_flock_ready()? {
                error!("โŒ Flock extension not available");
                error!("   Run 'frozen-duckdb flock-setup' first");
                std::process::exit(4);
            }

            // Read input texts
            let texts = if Path::new(&input).is_dir() {
                // Read all text files in directory
                let mut all_texts = Vec::new();
                for entry in std::fs::read_dir(&input)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.extension().and_then(|s| s.to_str()) == Some("txt") {
                        if let Ok(content) = std::fs::read_to_string(&path) {
                            all_texts.push(content.trim().to_string());
                        }
                    }
                }
                all_texts
            } else {
                // Read from single file (one text per line)
                match std::fs::read_to_string(&input) {
                    Ok(content) => content.lines().map(|s| s.to_string()).collect(),
                    Err(e) => {
                        error!("โŒ Failed to read input file '{}': {}", input, e);
                        std::process::exit(1);
                    }
                }
            };

            let summary = flock_manager.summarize_texts(texts, &strategy, max_length, &model)
                .expect("Text summarization not implemented yet");

            if let Some(output_file) = output {
                match std::fs::write(&output_file, &summary) {
                    Ok(_) => info!("โœ… Summary written to: {}", output_file),
                    Err(e) => {
                        error!("โŒ Failed to write to output file '{}': {}", output_file, e);
                        std::process::exit(1);
                    }
                }
            } else {
                println!("{}", summary);
            }
        }

        // === UTILITY COMMANDS ===
        Commands::Test => {
            info!("๐Ÿงช Tests have been moved to the test suite");
            info!("   Run tests with: cargo test");
            info!("   Run specific tests with: cargo test <test_name>");
            info!("   Run all tests with: cargo test --all");
        }

        Commands::Benchmark {
            operation,
            iterations,
            size,
        } => {
            info!(
                "Benchmarking {} operation with {} iterations (size: {})",
                operation, iterations, size
            );
            info!("๐Ÿ“Š Performance benchmarking feature coming soon!");
        }
    }

    Ok(())
}