heliosdb-nano 3.60.3

PostgreSQL-compatible embedded database with TDE + ZKE encryption, HNSW vector search, Product Quantization, git-like branching, time-travel queries, materialized views, row-level security, and 50+ enterprise features
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
//! Git Hooks Integration
//!
//! Provides shell script generation and installation for Git hooks that
//! automatically synchronize database branches with Git branches.
//!
//! ## Supported Hooks
//!
//! - **post-checkout**: Auto-switch DB branch when Git branch changes
//! - **pre-commit**: Validate schema before committing
//! - **post-merge**: Apply pending migrations and sync state after merge

#![allow(dead_code)]
#![allow(unused_variables)]

use crate::{Error, Result};
use std::fs;
// PermissionsExt (chmod) is unix-only; on Windows hooks are written without an exec bit (no-op).
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;

/// Hook type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookType {
    /// Runs after git checkout
    PostCheckout,
    /// Runs before git commit
    PreCommit,
    /// Runs after git merge
    PostMerge,
}

impl HookType {
    /// Get hook filename
    pub fn filename(&self) -> &'static str {
        match self {
            HookType::PostCheckout => "post-checkout",
            HookType::PreCommit => "pre-commit",
            HookType::PostMerge => "post-merge",
        }
    }

    /// Get all hook types
    pub fn all() -> &'static [HookType] {
        &[HookType::PostCheckout, HookType::PreCommit, HookType::PostMerge]
    }
}

/// Hook status
#[derive(Debug, Clone)]
pub struct HookStatus {
    pub hook_type: HookType,
    pub installed: bool,
    pub path: PathBuf,
    pub is_helios_hook: bool,
}

/// Hook configuration
#[derive(Debug, Clone)]
pub struct HookConfig {
    /// Database path/connection
    pub database: String,
    /// Migration directory (optional)
    pub migration_dir: Option<String>,
    /// Enable verbose output
    pub verbose: bool,
}

impl Default for HookConfig {
    fn default() -> Self {
        Self {
            database: String::new(),
            migration_dir: None,
            verbose: false,
        }
    }
}

/// Git hooks manager
pub struct HookManager {
    /// Git repository root
    repo_path: PathBuf,
    /// Hook configuration
    config: HookConfig,
}

impl HookManager {
    /// Create a new hook manager
    pub fn new(repo_path: PathBuf, config: HookConfig) -> Self {
        Self { repo_path, config }
    }

    /// Get hooks directory path
    fn hooks_dir(&self) -> PathBuf {
        self.repo_path.join(".git").join("hooks")
    }

    /// Get path for a specific hook
    fn hook_path(&self, hook_type: HookType) -> PathBuf {
        self.hooks_dir().join(hook_type.filename())
    }

    /// Generate post-checkout hook script
    fn generate_post_checkout(&self) -> String {
        let db_arg = if self.config.database.is_empty() {
            String::new()
        } else {
            format!("--database \"{}\"", self.config.database)
        };

        format!(
            r#"#!/bin/sh
# HeliosDB-Nano Git Hook: post-checkout
# Auto-switch database branch when Git branch changes
#
# Arguments:
#   $1 - ref of previous HEAD
#   $2 - ref of new HEAD
#   $3 - flag: 1 = branch checkout, 0 = file checkout

PREV_HEAD="$1"
NEW_HEAD="$2"
CHECKOUT_TYPE="$3"

# Only run on branch checkouts, not file checkouts
if [ "$CHECKOUT_TYPE" != "1" ]; then
    exit 0
fi

# Get current Git branch
GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)

if [ -z "$GIT_BRANCH" ]; then
    exit 0
fi

# Sync database with Git branch
if command -v helios >/dev/null 2>&1; then
    helios git sync {db_arg} 2>/dev/null || true
    {verbose}
fi
"#,
            db_arg = db_arg,
            verbose = if self.config.verbose {
                "echo \"[HeliosDB] Synced to branch: $GIT_BRANCH\""
            } else {
                ""
            }
        )
    }

    /// Generate pre-commit hook script
    fn generate_pre_commit(&self) -> String {
        let db_arg = if self.config.database.is_empty() {
            String::new()
        } else {
            format!("--database \"{}\"", self.config.database)
        };

        let migration_check = self
            .config
            .migration_dir
            .as_ref()
            .map(|dir| {
                format!(
                    r#"
# Validate migrations
if [ -d "{dir}" ]; then
    helios migration validate --dir "{dir}" {db_arg}
    if [ $? -ne 0 ]; then
        echo "[HeliosDB] Migration validation failed"
        exit 1
    fi
fi
"#,
                    dir = dir,
                    db_arg = db_arg
                )
            })
            .unwrap_or_default();

        format!(
            r#"#!/bin/sh
# HeliosDB-Nano Git Hook: pre-commit
# Validate schema and migrations before commit

{migration_check}

# Validate schema consistency
if command -v helios >/dev/null 2>&1; then
    helios schema validate {db_arg} 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "[HeliosDB] Schema validation failed"
        exit 1
    fi
fi

exit 0
"#,
            migration_check = migration_check,
            db_arg = db_arg
        )
    }

    /// Generate post-merge hook script
    fn generate_post_merge(&self) -> String {
        let db_arg = if self.config.database.is_empty() {
            String::new()
        } else {
            format!("--database \"{}\"", self.config.database)
        };

        format!(
            r#"#!/bin/sh
# HeliosDB-Nano Git Hook: post-merge
# Sync database state after merge

# Get current Git branch
GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)

if [ -z "$GIT_BRANCH" ]; then
    exit 0
fi

if command -v helios >/dev/null 2>&1; then
    # Apply any pending migrations
    helios migration apply {db_arg} --auto 2>/dev/null || true

    # Sync database state
    helios git sync {db_arg} 2>/dev/null || true
    {verbose}
fi

exit 0
"#,
            db_arg = db_arg,
            verbose = if self.config.verbose {
                "echo \"[HeliosDB] Synced after merge on branch: $GIT_BRANCH\""
            } else {
                ""
            }
        )
    }

    /// Generate hook script for a given type
    pub fn generate(&self, hook_type: HookType) -> String {
        match hook_type {
            HookType::PostCheckout => self.generate_post_checkout(),
            HookType::PreCommit => self.generate_pre_commit(),
            HookType::PostMerge => self.generate_post_merge(),
        }
    }

    /// Install a specific hook
    pub fn install(&self, hook_type: HookType) -> Result<()> {
        let hooks_dir = self.hooks_dir();

        // Create hooks directory if it doesn't exist
        if !hooks_dir.exists() {
            fs::create_dir_all(&hooks_dir)
                .map_err(|e| Error::io(format!("Failed to create hooks directory: {}", e)))?;
        }

        let hook_path = self.hook_path(hook_type);

        // Check if existing hook is not ours
        if hook_path.exists() {
            let content = fs::read_to_string(&hook_path)
                .map_err(|e| Error::io(format!("Failed to read existing hook: {}", e)))?;

            if !content.contains("HeliosDB-Nano Git Hook") {
                // Backup existing hook
                let backup_path = hook_path.with_extension("backup");
                fs::rename(&hook_path, &backup_path)
                    .map_err(|e| Error::io(format!("Failed to backup existing hook: {}", e)))?;
                tracing::info!("Backed up existing {} hook to {:?}", hook_type.filename(), backup_path);
            }
        }

        // Write hook script
        let script = self.generate(hook_type);
        fs::write(&hook_path, &script).map_err(|e| Error::io(format!("Failed to write hook: {}", e)))?;

        // Make executable (Unix only)
        #[cfg(unix)]
        {
            let mut perms = fs::metadata(&hook_path)
                .map_err(|e| Error::io(format!("Failed to get hook permissions: {}", e)))?
                .permissions();
            perms.set_mode(0o755);
            fs::set_permissions(&hook_path, perms)
                .map_err(|e| Error::io(format!("Failed to set hook permissions: {}", e)))?;
        }

        tracing::info!("Installed {} hook at {:?}", hook_type.filename(), hook_path);
        Ok(())
    }

    /// Install all hooks
    pub fn install_all(&self) -> Result<()> {
        for hook_type in HookType::all() {
            self.install(*hook_type)?;
        }
        Ok(())
    }

    /// Uninstall a specific hook
    pub fn uninstall(&self, hook_type: HookType) -> Result<()> {
        let hook_path = self.hook_path(hook_type);

        if hook_path.exists() {
            // Check if it's our hook
            let content =
                fs::read_to_string(&hook_path).map_err(|e| Error::io(format!("Failed to read hook: {}", e)))?;

            if content.contains("HeliosDB-Nano Git Hook") {
                fs::remove_file(&hook_path).map_err(|e| Error::io(format!("Failed to remove hook: {}", e)))?;

                // Restore backup if exists
                let backup_path = hook_path.with_extension("backup");
                if backup_path.exists() {
                    fs::rename(&backup_path, &hook_path)
                        .map_err(|e| Error::io(format!("Failed to restore backup hook: {}", e)))?;
                    tracing::info!("Restored backup {} hook", hook_type.filename());
                }

                tracing::info!("Uninstalled {} hook", hook_type.filename());
            } else {
                tracing::warn!(
                    "{} hook exists but is not a HeliosDB hook, skipping",
                    hook_type.filename()
                );
            }
        }

        Ok(())
    }

    /// Uninstall all hooks
    pub fn uninstall_all(&self) -> Result<()> {
        for hook_type in HookType::all() {
            self.uninstall(*hook_type)?;
        }
        Ok(())
    }

    /// Get status of all hooks
    pub fn status(&self) -> Vec<HookStatus> {
        HookType::all()
            .iter()
            .map(|&hook_type| {
                let path = self.hook_path(hook_type);
                let installed = path.exists();
                let is_helios_hook = if installed {
                    fs::read_to_string(&path)
                        .map(|c| c.contains("HeliosDB-Nano Git Hook"))
                        .unwrap_or(false)
                } else {
                    false
                };

                HookStatus {
                    hook_type,
                    installed,
                    path,
                    is_helios_hook,
                }
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_hook_type_filename() {
        assert_eq!(HookType::PostCheckout.filename(), "post-checkout");
        assert_eq!(HookType::PreCommit.filename(), "pre-commit");
        assert_eq!(HookType::PostMerge.filename(), "post-merge");
    }

    #[test]
    fn test_generate_post_checkout() {
        let config = HookConfig {
            database: "/path/to/db".to_string(),
            verbose: true,
            ..Default::default()
        };

        let manager = HookManager::new(PathBuf::from("/tmp"), config);
        let script = manager.generate(HookType::PostCheckout);

        assert!(script.contains("HeliosDB-Nano Git Hook"));
        assert!(script.contains("post-checkout"));
        assert!(script.contains("helios git sync"));
    }

    #[test]
    fn test_hook_manager_creation() {
        let config = HookConfig::default();
        let manager = HookManager::new(PathBuf::from("/tmp/repo"), config);
        assert_eq!(manager.hooks_dir(), PathBuf::from("/tmp/repo/.git/hooks"));
    }
}