bestool-psql 1.7.2

psql-inspired client for PostgreSQL
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use std::{
	mem::replace,
	path::{Path, PathBuf},
	sync::{Arc, Mutex},
};

use miette::{IntoDiagnostic, Result, WrapErr};
use redb::{
	Database, ReadableDatabase, ReadableTable, ReadableTableMetadata as _,
	backends::InMemoryBackend,
};
use tracing::{debug, error, info, instrument, warn};

use crate::repl::ReplState;

use super::multi_process::{WorkingDatabase, spawn_sync_task, sync_to_main};

impl super::Audit {
	/// Open or create an audit database at the given path
	pub fn open(path: impl AsRef<Path>, repl_state: Arc<Mutex<ReplState>>) -> Result<Self> {
		let path = path.as_ref();
		Self::open_internal(path, repl_state, true)
	}

	/// Open an audit database without importing from ~/.psql_history
	///
	/// This is useful for tests where we want a clean database.
	/// Note: This bypasses multi-process mode and opens the database directly.
	#[cfg(test)]
	pub fn open_empty(path: impl AsRef<Path>) -> Result<Self> {
		let path = path.as_ref();
		Self::open_internal_simple(path, Arc::new(Mutex::new(ReplState::new())), false)
	}

	/// Open a database directly without multi-process setup (for tests)
	#[cfg(test)]
	fn open_internal_simple(
		path: &Path,
		repl_state: Arc<Mutex<ReplState>>,
		new_db_import_psql_history: bool,
	) -> Result<Self> {
		let is_new_db = !path.exists();
		debug!(?path, is_new_db, "opening audit database (simple mode)");

		let db = Database::create(path).into_diagnostic()?;
		let db = Arc::new(db);

		let audit = Self {
			db,
			repl_state,
			working_info: None,
			sync_thread: None,
		};

		ensure_index_table(&audit)?;

		// Import plain text psql history if this is a new database
		if new_db_import_psql_history && is_new_db {
			let index_len = audit.hist_index_len()?;
			if index_len == 0
				&& let Err(e) = import_psql_history(&audit)
			{
				debug!("could not import psql history: {e}");
			}
		}

		if let Err(e) = cull_db_if_oversize(&audit, path) {
			warn!("failed to cull database: {:?}", e);
		}

		debug!(?audit.db, "opened audit database (simple mode)");

		Ok(audit)
	}

	#[instrument(level = "debug")]
	fn open_internal(
		dir: &Path,
		repl_state: Arc<Mutex<ReplState>>,
		new_db_import_psql_history: bool,
	) -> Result<Self> {
		// Validate that the path is a directory
		if dir.exists() && !dir.is_dir() {
			return Err(miette::miette!(
				"audit path must be a directory, not a file: {:?}",
				dir
			));
		}

		// Create directory if it doesn't exist
		if !dir.exists() {
			std::fs::create_dir_all(dir).into_diagnostic()?;
		}

		// Migrate old database if needed
		Self::migrate_old_database(dir)?;

		let main_path = Self::main_db_path(dir);
		let is_new_main_db = !main_path.exists();

		// Step 1: If main database doesn't exist, create it and import psql history
		if is_new_main_db {
			debug!(?main_path, "creating new main audit database");
			let db = Database::create(&main_path).into_diagnostic()?;
			let db = Arc::new(db);

			let temp_audit = Self {
				db: db.clone(),
				repl_state: repl_state.clone(),
				working_info: None,
				sync_thread: None,
			};

			ensure_index_table(&temp_audit)?;

			if new_db_import_psql_history {
				let index_len = temp_audit.hist_index_len()?;
				if index_len == 0
					&& let Err(e) = import_psql_history(&temp_audit)
				{
					debug!("could not import psql history: {e}");
				}
			}

			// Cull and compact main database if needed before closing
			if let Err(e) = cull_db_if_oversize(&temp_audit, &main_path) {
				warn!("failed to cull main database: {:?}", e);
			}

			drop(temp_audit);
			drop(db);
		}

		// Step 2: Copy main database to working file
		let (working_path, uuid) = WorkingDatabase::generate_path(&main_path);
		let working_info = Arc::new(WorkingDatabase::new(
			main_path.clone(),
			working_path.clone(),
			uuid,
		));

		// Try to open main database and copy it
		let copy_result = (|| -> Result<()> {
			// Open main database read-only with retries to verify it's accessible
			let main_db =
				working_info.open_main_readonly(super::multi_process::MAX_STARTUP_RETRIES, true)?;

			// Close main database before copying to avoid file locking issues on Windows
			drop(main_db);

			// Copy to working file
			working_info.copy_from_main()?;

			Ok(())
		})();

		// Step 3: Open working database read-write
		let working_db = match copy_result {
			Ok(()) => {
				// Successfully copied, open the working database
				Database::create(&working_path).into_diagnostic()?
			}
			Err(e) => {
				// Failed to copy after retries, create empty working database and warn
				warn!(
					"could not access main audit database after {} attempts, creating empty working database: {:?}",
					super::multi_process::MAX_STARTUP_RETRIES,
					e
				);
				Database::create(&working_path).into_diagnostic()?
			}
		};

		let working_db = Arc::new(working_db);

		// Step 4: Spawn background sync task
		let sync_thread = spawn_sync_task(working_db.clone(), working_info.clone());

		let audit = Self {
			db: working_db.clone(),
			repl_state,
			working_info: Some(working_info.clone()),
			sync_thread: Some(Mutex::new(Some(sync_thread))),
		};

		ensure_index_table(&audit)?;

		// Step 5: Spawn orphan database recovery task
		WorkingDatabase::spawn_orphan_recovery(main_path);

		debug!(?audit.db, ?working_path, "opened working audit database");

		Ok(audit)
	}

	/// Compact the database to reclaim space from deleted entries
	///
	/// Note: In multi-process mode (with working databases), this is a no-op since
	/// working databases are ephemeral. Only the main database gets compacted during culling.
	pub fn compact(&mut self) -> Result<()> {
		// In multi-process mode, working databases are ephemeral and don't need compaction
		// They will be deleted on clean shutdown or recovered as orphans on crash
		if self.working_info.is_some() {
			debug!("compact: skipping compact in multi-process mode (working database)");
			return Ok(());
		}

		debug!("compact: compacting database");
		let db = replace(
			&mut self.db,
			Arc::new(
				Database::builder()
					.create_with_backend(InMemoryBackend::new())
					.unwrap(),
			),
		);
		let mut db =
			Arc::try_unwrap(db).map_err(|_| miette::miette!("Failed to unwrap database"))?;
		db.compact().into_diagnostic()?;
		Ok(())
	}

	/// Sync and cleanup on shutdown
	pub(crate) fn shutdown(&self) -> Result<()> {
		debug!("shutdown: starting audit database shutdown sequence");
		if let Some(working_info) = &self.working_info {
			debug!(
				"shutdown: multi-process mode active, working db: {:?}",
				working_info.path
			);

			// Signal shutdown to background task
			debug!("shutdown: signaling background sync thread to stop");
			working_info
				.shutdown
				.store(true, std::sync::atomic::Ordering::Relaxed);

			// Wait for background sync thread to exit and release Arc references
			if let Some(thread_mutex) = &self.sync_thread
				&& let Ok(mut guard) = thread_mutex.lock()
				&& let Some(handle) = guard.take()
			{
				debug!("shutdown: waiting for sync thread to exit");
				drop(guard); // Release lock before joining
				if let Err(e) = handle.join() {
					warn!("shutdown: sync thread panicked: {:?}", e);
				} else {
					debug!("shutdown: sync thread exited successfully");
				}
			} else {
				debug!("shutdown: no sync thread to wait for");
			}

			// Check Arc reference count
			let arc_count = Arc::strong_count(&self.db);
			debug!("shutdown: database Arc reference count: {}", arc_count);

			// Perform final sync
			debug!("shutdown: performing final sync before shutdown");
			match sync_to_main(&self.db, working_info).wrap_err("final sync failed") {
				Ok(()) => {
					debug!("shutdown: final sync completed successfully");
					// Only delete if we hold the only reference to the database
					if arc_count == 1 {
						debug!(
							"shutdown: we hold the only Arc reference, attempting to delete working database"
						);
						// Database will be closed when Arc drops at end of scope
						// Give OS a moment to finalize the file handle
						std::thread::sleep(std::time::Duration::from_millis(50));
						if let Err(e) = working_info.delete() {
							warn!("shutdown: failed to delete working database: {:?}", e);
						} else {
							debug!("shutdown: successfully deleted working database");
						}
					} else {
						debug!(
							"shutdown: cannot delete working database, {} Arc references still exist",
							arc_count
						);
						// Database file will be cleaned up on next startup as an old orphan
					}
				}
				Err(e) => {
					error!(
						"shutdown: failed to sync to main database after {} attempts: {:?}",
						super::multi_process::MAX_EXIT_RETRIES,
						e
					);
					// Only rename if we hold the only reference to the database
					if arc_count == 1 {
						debug!(
							"shutdown: we hold the only Arc reference, attempting to mark as orphaned"
						);
						// Give OS a moment to finalize the file handle
						std::thread::sleep(std::time::Duration::from_millis(50));
						if let Err(e) = working_info.mark_as_orphaned() {
							error!(
								"shutdown: failed to mark working database as orphaned: {:?}",
								e
							);
						} else {
							info!("shutdown: working database marked as orphaned for recovery");
						}
					} else {
						warn!(
							"shutdown: cannot mark working database as orphaned, {} Arc references still exist - will be recovered as crash orphan",
							arc_count
						);
						// Database file will be cleaned up on next startup as an old orphan
					}
				}
			}
		} else {
			debug!("shutdown: no working database to clean up (non-multi-process mode)");
		}
		debug!("shutdown: audit database shutdown sequence complete");
		Ok(())
	}

	/// Get the default audit database directory
	pub fn default_path() -> Result<PathBuf> {
		let history_dir = {
			// On Linux, use dirs::state_dir() which returns ~/.local/state
			#[cfg(not(any(target_os = "macos", target_os = "windows")))]
			{
				if let Some(dir) = dirs::state_dir() {
					dir.join("bestool-psql")
				} else if let Some(dir) = std::env::var_os("XDG_STATE_HOME") {
					PathBuf::from(dir).join("bestool-psql")
				} else if let Some(home) = std::env::var_os("HOME") {
					PathBuf::from(home)
						.join(".local")
						.join("state")
						.join("bestool-psql")
				} else {
					return Err(miette::miette!("Could not determine home directory"));
				}
			}
			// On macOS and Windows, use dirs::data_local_dir()
			#[cfg(any(target_os = "macos", target_os = "windows"))]
			{
				if let Some(dir) = dirs::data_local_dir() {
					dir.join("bestool-psql")
				} else {
					// Fallback to hardcoded paths
					#[cfg(target_os = "macos")]
					{
						if let Some(home) = std::env::var_os("HOME") {
							PathBuf::from(home)
								.join("Library")
								.join("Application Support")
								.join("bestool-psql")
						} else {
							return Err(miette::miette!("Could not determine home directory"));
						}
					}
					#[cfg(target_os = "windows")]
					{
						if let Some(localappdata) = std::env::var_os("LOCALAPPDATA") {
							PathBuf::from(localappdata).join("bestool-psql")
						} else {
							return Err(miette::miette!(
								"Could not determine LOCALAPPDATA directory"
							));
						}
					}
				}
			}
		};

		std::fs::create_dir_all(&history_dir).into_diagnostic()?;
		Ok(history_dir)
	}

	/// Get the default audit database directory for help text
	pub fn help_text_default_dir() -> String {
		if let Ok(path) = Self::default_path() {
			return path.display().to_string();
		}

		#[cfg(target_os = "macos")]
		{
			"~/Library/Application Support/bestool-psql".into()
		}
		#[cfg(target_os = "windows")]
		{
			"%LOCALAPPDATA%\\bestool-psql".into()
		}
		#[cfg(not(any(target_os = "macos", target_os = "windows")))]
		{
			"~/.local/state/bestool-psql".into()
		}
	}

	/// Get the main database file path from a directory
	pub fn main_db_path(dir: &Path) -> PathBuf {
		dir.join("audit-main.redb")
	}

	/// Migrate old history.redb to audit-main.redb if it exists
	fn migrate_old_database(dir: &Path) -> Result<()> {
		let old_path = dir.join("history.redb");
		let new_path = Self::main_db_path(dir);

		if old_path.exists() && !new_path.exists() {
			// Try to open the old database exclusively to check if it's in use
			match Database::create(&old_path) {
				Ok(_db) => {
					// Successfully opened exclusively, safe to migrate
					drop(_db);
					info!("migrating audit database from history.redb to audit-main.redb");
					std::fs::rename(&old_path, &new_path).into_diagnostic()?;
				}
				Err(_) => {
					// Database is in use by another process
					return Err(miette::miette!(
						"Cannot migrate audit database: history.redb is currently in use.\n\
						Please close all other bestool-psql instances and try again."
					));
				}
			}
		}

		Ok(())
	}
}

/// Ensure the index table exists and is populated from the history table
#[instrument(level = "trace", skip(audit))]
fn ensure_index_table(audit: &super::Audit) -> Result<()> {
	let db = &audit.db;
	let read_txn = db.begin_read().into_diagnostic()?;

	// Check if index table exists and has entries
	if let Ok(index_table) = read_txn.open_table(super::INDEX_TABLE)
		&& index_table.len().into_diagnostic()? > 0
	{
		// Index table already populated
		return Ok(());
	}

	// Need to build index from history table
	let history_table = match read_txn.open_table(super::HISTORY_TABLE) {
		Ok(table) => table,
		Err(_) => return Ok(()), // No history yet
	};

	let mut timestamps = Vec::new();
	for item in history_table.iter().into_diagnostic()? {
		let (timestamp, _) = item.into_diagnostic()?;
		timestamps.push(timestamp.value());
	}
	drop(history_table);
	drop(read_txn);

	if timestamps.is_empty() {
		return Ok(());
	}

	// Timestamps are already sorted because redb stores them in order
	let write_txn = db.begin_write().into_diagnostic()?;
	{
		let mut index_table = write_txn.open_table(super::INDEX_TABLE).into_diagnostic()?;
		for (idx, timestamp) in timestamps.into_iter().enumerate() {
			index_table
				.insert(idx as u64, timestamp)
				.into_diagnostic()?;
		}
	}
	write_txn.commit().into_diagnostic()?;

	Ok(())
}

#[instrument(level = "trace", skip(audit, path))]
fn cull_db_if_oversize(audit: &super::Audit, path: &Path) -> Result<()> {
	let db = &audit.db;
	const MAX_SIZE: u64 = 100 * 1024 * 1024; // 100MB
	const TARGET_SIZE: u64 = 90 * 1024 * 1024; // 90MB
	const CULL_BATCH: usize = 100; // Remove 100 entries at a time

	let Ok(metadata) = std::fs::metadata(path) else {
		return Ok(());
	};

	if metadata.len() > MAX_SIZE {
		let size_mb = metadata.len() / (1024 * 1024);
		info!(size_mb, "audit database is too large, reducing size");

		// Remove oldest entries in batches until we reach target size
		loop {
			let index_len = audit.hist_index_len()?;
			if index_len == 0 {
				break;
			}

			if let Ok(metadata) = std::fs::metadata(path)
				&& metadata.len() <= TARGET_SIZE
			{
				break;
			}

			let to_remove = CULL_BATCH.min(index_len as usize) as u64;

			// Read timestamps to remove
			let mut old_timestamps = Vec::with_capacity(to_remove as usize);
			for i in 0..to_remove {
				if let Some(timestamp) = audit.hist_index_get(i)? {
					old_timestamps.push(timestamp);
				}
			}

			// Remove from history table
			let write_txn = db.begin_write().into_diagnostic()?;
			{
				let mut history_table = write_txn
					.open_table(super::HISTORY_TABLE)
					.into_diagnostic()?;
				for ts in &old_timestamps {
					history_table.remove(*ts).into_diagnostic()?;
				}
			}
			write_txn.commit().into_diagnostic()?;

			// Rebuild index by removing prefix
			audit.hist_index_remove_prefix(to_remove)?;
		}

		let final_size_mb = std::fs::metadata(path)
			.map(|m| m.len() / (1024 * 1024))
			.unwrap_or(0);
		let final_len = audit.hist_index_len()?;
		debug!(
			size_mb = final_size_mb,
			entries = final_len,
			"culled audit database"
		);
	}

	Ok(())
}

/// Import entries from plain text psql history file (~/.psql_history)
#[instrument(level = "trace", skip(audit))]
fn import_psql_history(audit: &super::Audit) -> Result<()> {
	let db = &audit.db;
	let psql_history_path = if let Some(home) = std::env::var_os("HOME") {
		PathBuf::from(home).join(".psql_history")
	} else if let Some(userprofile) = std::env::var_os("USERPROFILE") {
		// Windows fallback
		PathBuf::from(userprofile).join(".psql_history")
	} else {
		return Ok(()); // No home directory, skip import
	};

	if !psql_history_path.exists() {
		debug!("no psql history file found at {psql_history_path:?}");
		return Ok(());
	}

	info!("importing psql history from {psql_history_path:?}");

	let content = std::fs::read_to_string(&psql_history_path).into_diagnostic()?;
	let lines: Vec<&str> = content.lines().collect();

	if lines.is_empty() {
		return Ok(());
	}

	let mut timestamp = 0u64;
	let mut count = 0usize;

	let write_txn = db.begin_write().into_diagnostic()?;
	{
		let mut history_table = write_txn
			.open_table(super::HISTORY_TABLE)
			.into_diagnostic()?;

		for line in lines {
			let line = line.trim();
			if line.is_empty() {
				continue;
			}

			// Create entry with default values
			let entry = super::AuditEntry {
				query: line.to_string(),
				db_user: String::new(),
				sys_user: String::new(),
				writemode: true,
				tailscale: Vec::new(),
				ots: None,
				recall: true,
				instance_id: None,
			};

			let json = serde_json::to_string(&entry).into_diagnostic()?;
			history_table
				.insert(timestamp, json.as_str())
				.into_diagnostic()?;
			timestamp += 1;
			count += 1;
		}
	}
	write_txn.commit().into_diagnostic()?;

	// Build index
	for i in 0..count {
		audit.hist_index_push(i as u64)?;
	}

	info!("imported {} entries from psql history", count);
	Ok(())
}