bestool-psql 1.7.16

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
use std::{collections::BTreeMap, ops::ControlFlow, sync::Arc};

use bestool_postgres::pool::PgPool;
use miette::{IntoDiagnostic, Result, bail, miette};
use rustyline::{
	Cmd, Editor, EventHandler, KeyEvent, config::CompletionType, error::ReadlineError,
};
use std::sync::Mutex;
use tracing::{debug, warn};

use crate::{
	audit::Audit,
	completer::SqlCompleter,
	config::Config,
	input::{ReplAction, handle_input},
	result_store::ResultStore,
	schema_cache::SchemaCacheManager,
	snippets::Snippets,
};

pub(crate) use state::ReplContext;
pub use state::ReplState;
pub use transaction::TransactionState;

mod copy;
mod debug;
mod describe;
mod edit;
mod execute;
mod exit;
mod expanded;
mod help;
mod include;
mod list;
mod output;
mod prompt;
mod redaction;
mod result;
mod snippets;
mod state;
mod transaction;
mod vars;
mod write_mode;

#[cfg(test)]
mod tests;

impl ReplAction {
	/// Whether the line this action came from is recorded when it runs.
	///
	/// SnippetSave records its own line afterwards, and a bare `\e` is not
	/// recorded at all: the query it produces is recorded by `handle_edit`.
	pub(crate) fn records_line(&self) -> bool {
		!matches!(self, ReplAction::SnippetSave { .. } | ReplAction::Edit)
	}

	pub(crate) async fn handle(self, ctx: &mut ReplContext<'_>, line: &str) -> ControlFlow<()> {
		let is_edit = matches!(self, ReplAction::Edit);

		if self.records_line() {
			record_line(ctx, line);
		}

		// `\e` only reopens the previous buffer when run back-to-back; any other
		// command resets it so the next `\e` starts from an empty editor.
		if !is_edit {
			ctx.repl_state.lock().unwrap().last_edit_content = None;
		}

		self.dispatch(ctx, line).await
	}

	/// Run the action without touching history.
	///
	/// This is the shared dispatch used both by [`handle`](Self::handle) (after
	/// it records the line in history) and by snippet/include execution, which
	/// replays a script's actions without polluting interactive history.
	pub(crate) async fn dispatch(self, ctx: &mut ReplContext<'_>, line: &str) -> ControlFlow<()> {
		match self {
			ReplAction::ToggleExpanded => expanded::handle_toggle_expanded(ctx),
			ReplAction::Exit => exit::handle_exit(ctx).await,
			ReplAction::ToggleWriteMode { ots } => {
				write_mode::handle_write_mode_toggle(ctx, ots).await
			}
			ReplAction::ToggleRedaction => redaction::handle_toggle_redaction(ctx),
			ReplAction::Edit => edit::handle_edit(ctx).await,
			ReplAction::Copy => copy::handle_copy(),
			ReplAction::IncludeFile { file_path, vars } => {
				include::handle_include(ctx, &file_path, vars).await
			}
			ReplAction::RunSnippet { name, vars } => {
				snippets::handle_run_snippet(ctx, name, vars).await
			}
			ReplAction::SetOutputFile { file_path } => {
				output::handle_set_output(ctx, &file_path).await
			}
			ReplAction::UnsetOutputFile => output::handle_unset_output(ctx).await,
			ReplAction::Debug { what } => debug::handle_debug(ctx, what).await,
			ReplAction::Help => help::handle_help(),
			ReplAction::SetVar { name, value } => vars::handle_set_var(ctx, name, value),
			ReplAction::DefaultVar { name, value } => vars::handle_default_var(ctx, name, value),
			ReplAction::UnsetVar { name } => vars::handle_unset_var(ctx, name),
			ReplAction::LookupVar { pattern } => vars::handle_lookup_var(ctx, pattern),
			ReplAction::GetVar { name } => vars::handle_get_var(ctx, name),
			ReplAction::SnippetSave { name } => {
				snippets::handle_snippet_save(ctx, name, line).await
			}
			ReplAction::SnippetEdit { name } => snippets::handle_snippet_edit(ctx, name).await,
			ReplAction::SnippetList => snippets::handle_snippet_list(ctx).await,
			ReplAction::SnippetRefetch => snippets::handle_snippet_refetch(ctx).await,
			ReplAction::List {
				item,
				pattern,
				detail,
				sameconn,
			} => list::handle_list(ctx, item, pattern, detail, sameconn).await,
			ReplAction::Describe {
				item,
				detail,
				sameconn,
			} => describe::handle_describe(ctx, item, detail, sameconn).await,
			ReplAction::Result { subcommand } => result::handle_result(ctx, subcommand).await,
			ReplAction::Execute {
				input,
				sql,
				modifiers,
			} => execute::handle_execute(ctx, input, sql, modifiers).await,
		}
	}
}

/// Record a line the operator typed, once, whatever it parses into.
fn record_line(ctx: &mut ReplContext<'_>, line: &str) {
	let history = ctx.rl.history_mut();
	if let Err(e) = history.add_entry(line.into()) {
		debug!("failed to add to history: {e}");
	}
}

pub async fn run(pool: PgPool, config: Arc<Config>) -> Result<()> {
	debug!("getting connection from pool");
	let client = Arc::new(pool.get().await.into_diagnostic()?);

	if config.write {
		debug!("setting session to read-write mode");
		client
			.execute("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", &[])
			.await
			.into_diagnostic()?;
		debug!("opening transaction");
		client.execute("BEGIN", &[]).await.into_diagnostic()?;
	} else {
		debug!("setting session to read-only mode");
		client
			.execute("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", &[])
			.await
			.into_diagnostic()?;
	}

	debug!("executing version query");
	let rows = client
		.query("SELECT version();", &[])
		.await
		.into_diagnostic()?;

	if let Some(row) = rows.first()
		&& let Ok(version) = row.try_get::<_, String>(0)
	{
		eprintln!("{version}");
	}

	let (database_name, db_user, is_superuser): (String, String, bool) = {
		let info_res = client
			.query(
				"SELECT current_database(), current_user, usesuper FROM pg_user WHERE usename = current_user",
				&[],
			)
			.await
			.into_diagnostic()?;
		let info = info_res
			.first()
			.ok_or_else(|| miette!("Unable to fetch connection information"))?;
		(info.get(0), info.get(1), info.get(2))
	};

	let backend_pid: i32 = client
		.query_one("SELECT pg_backend_pid()", &[])
		.await
		.into_diagnostic()?
		.get(0);
	debug!(pid=%backend_pid, "main connection backend PID");

	debug!("getting monitor connection from pool");
	let monitor_client = Arc::new(pool.get().await.into_diagnostic()?);
	debug!("monitor connection established");

	let sys_user = std::env::var("USER")
		.or_else(|_| std::env::var("USERNAME"))
		.unwrap_or_else(|_| "unknown".to_string());

	let repl_state = ReplState {
		config: config.clone(),
		output_file: None,
		sys_user,
		db_user,
		expanded_mode: false,
		write_mode: false,
		redact_mode: config.redact_mode,
		statement_source: crate::audit::QuerySource::Typed,
		ots: None,
		vars: BTreeMap::new(),
		snippets: Snippets::new(),
		transaction_state: TransactionState::None,
		result_store: ResultStore::new(),
		initial_content: None,
		last_edit_content: None,
		write_mode_active_at: None,
	};

	let repl_state = Arc::new(Mutex::new(repl_state));
	let audit = Audit::open(config.audit_path.as_ref().unwrap(), Arc::clone(&repl_state))?;

	debug!("initializing schema cache");
	let schema_cache_manager = SchemaCacheManager::new(pool.clone());

	debug!("spawning schema cache refresh");
	let schema_cache_manager_clone = schema_cache_manager.clone();
	tokio::spawn(async move {
		if let Err(e) = schema_cache_manager_clone.refresh().await {
			warn!("failed to refresh schema cache on startup: {}", e);
		}
	});

	let cache_arc = schema_cache_manager.cache_arc();

	let completer = SqlCompleter::new(config.theme)
		.with_schema_cache(cache_arc)
		.with_repl_state(repl_state.clone());
	let mut rl: Editor<SqlCompleter, Audit> = Editor::with_history(
		rustyline::Config::builder()
			.auto_add_history(false)
			.enable_signals(false)
			.completion_type(CompletionType::List)
			.build(),
		audit,
	)
	.into_diagnostic()?;
	rl.set_helper(Some(completer));

	// Bind Alt+Enter to insert a literal newline
	rl.bind_sequence(KeyEvent::alt('\r'), EventHandler::Simple(Cmd::Newline));

	let timeout_watcher = match rl.create_external_printer() {
		Ok(printer) => Some(tokio::spawn(write_mode::watch_write_mode_idle_timeout(
			Arc::clone(&client),
			Arc::clone(&monitor_client),
			backend_pid,
			Arc::clone(&repl_state),
			printer,
		))),
		Err(e) => {
			warn!("could not create external printer for write-mode timeout watcher: {e}");
			None
		}
	};

	if config.write {
		let mut ctx = ReplContext {
			config: &config,
			client: &client,
			monitor_client: &monitor_client,
			backend_pid,
			repl_state: &repl_state,
			rl: &mut rl,
			pool: &pool,
			schema_cache_manager: &schema_cache_manager,
			redact_mode: config.redact_mode,
		};

		if (ReplAction::ToggleWriteMode { ots: None })
			.handle(&mut ctx, "")
			.await
			.is_break()
		{
			bail!("Write mode aborted");
		}
	}

	let mut buffer = String::new();

	loop {
		let transaction_state = TransactionState::check(&monitor_client, backend_pid).await;

		let initial_content = {
			let mut state = repl_state.lock().unwrap();
			// Update transaction state in ReplState so the highlighter can access it
			state.transaction_state = transaction_state;
			state.initial_content.take()
		};

		let prompt = prompt::build_prompt(
			&database_name,
			is_superuser,
			buffer.is_empty(),
			transaction_state,
		);

		let readline = if let Some(initial) = initial_content {
			rl.readline_with_initial(&prompt, (&initial, ""))
		} else {
			rl.readline(&prompt)
		};

		match readline {
			Ok(line) => {
				let line = line.trim();
				if line.is_empty() && buffer.is_empty() {
					continue;
				}

				let (new_buffer, actions) =
					{ handle_input(&buffer, line, &repl_state.lock().unwrap()) };
				buffer = new_buffer;

				let mut ctx = ReplContext {
					config: &config,
					client: &client,
					monitor_client: &monitor_client,
					backend_pid,
					repl_state: &repl_state,
					rl: &mut rl,
					pool: &pool,
					schema_cache_manager: &schema_cache_manager,
					redact_mode: repl_state.lock().unwrap().redact_mode,
				};

				// Handle all actions
				let mut should_exit = false;
				if actions.is_empty() {
					// No actions to execute, but still add to history
					record_line(&mut ctx, line);
					// A buffered (incomplete) line is still a non-`\e` command,
					// so it resets the editor-reopen chain.
					ctx.repl_state.lock().unwrap().last_edit_content = None;
				} else {
					// One line, one record, however many statements it parsed
					// into: what the operator typed is one thing, and recording
					// it once per statement would both log and recall it several
					// times over.
					if actions.iter().any(|s| s.action.records_line()) {
						record_line(&mut ctx, line);
					}
					// `\e` only reopens its previous buffer when run back to back,
					// so only a line that is nothing but `\e` leaves the seed
					// standing. A line that merely ends in one has run something
					// else in between.
					let only_edit =
						actions.len() == 1 && matches!(actions[0].action, ReplAction::Edit);
					if !only_edit {
						ctx.repl_state.lock().unwrap().last_edit_content = None;
					}

					for statement in actions {
						if statement.action.dispatch(&mut ctx, line).await.is_break() {
							should_exit = true;
							break;
						}
					}
				}

				if should_exit {
					break;
				}
			}
			Err(ReadlineError::Interrupted) => {
				debug!("CTRL-C");
				buffer.clear();
			}
			Err(ReadlineError::Eof) => {
				debug!("CTRL-D");
				let mut ctx = ReplContext {
					config: &config,
					client: &client,
					monitor_client: &monitor_client,
					backend_pid,
					repl_state: &repl_state,
					rl: &mut rl,
					pool: &pool,
					schema_cache_manager: &schema_cache_manager,
					redact_mode: repl_state.lock().unwrap().redact_mode,
				};

				if exit::handle_exit(&mut ctx).await.is_break() {
					break;
				}
			}
			Err(err) => {
				eprintln!("Error: {:?}", err);
				break;
			}
		}
	}

	if let Some(handle) = timeout_watcher {
		handle.abort();
	}

	Ok(())
}