Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(workspace): gracefully handle failing db connections #194

Merged
4 changes: 4 additions & 0 deletions crates/pg_cli/src/cli_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ pub struct CliOptions {
#[bpaf(long("use-server"), switch, fallback(false))]
pub use_server: bool,

/// Skip connecting to the database and only run checks that don't require a database connection.
#[bpaf(long("skip-db"), switch, fallback(false))]
pub skip_db: bool,

/// Print additional diagnostics, and some diagnostics show more information. Also, print out what files were processed and which ones were modified.
#[bpaf(long("verbose"), switch, fallback(false))]
pub verbose: bool,
Expand Down
3 changes: 3 additions & 0 deletions crates/pg_cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,10 @@ pub enum PgLspCommand {
Check {
#[bpaf(external(partial_configuration), hide_usage, optional)]
configuration: Option<PartialConfiguration>,

#[bpaf(external, hide_usage)]
cli_options: CliOptions,

/// Use this option when you want to format code piped from `stdin`, and print the output to `stdout`.
///
/// The file doesn't need to exist on disk, what matters is the extension of the file. Based on the extension, we know how to check the code.
Expand Down Expand Up @@ -286,6 +288,7 @@ pub(crate) trait CommandRunner: Sized {
configuration,
vcs_base_path,
gitignore_matches,
skip_db: cli_options.skip_db,
})?;

let execution = self.get_execution(cli_options, console, workspace)?;
Expand Down
1 change: 1 addition & 0 deletions crates/pg_cli/src/execute/process_file/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub(crate) fn check_with_guard<'ctx>(
let (only, skip) = (Vec::new(), Vec::new());

let max_diagnostics = ctx.remaining_diagnostics.load(Ordering::Relaxed);

let pull_diagnostics_result = workspace_file
.guard()
.pull_diagnostics(
Expand Down
2 changes: 2 additions & 0 deletions crates/pg_cli/src/execute/traverse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ pub(crate) fn traverse(
let skipped = skipped.load(Ordering::Relaxed);
let suggested_fixes_skipped = printer.skipped_fixes();
let diagnostics_not_printed = printer.not_printed_diagnostics();

Ok(TraverseResult {
summary: TraversalSummary {
changed,
Expand Down Expand Up @@ -381,6 +382,7 @@ impl<'ctx> DiagnosticsPrinter<'ctx> {
}
}
}

diagnostics_to_print
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/pg_cli/src/reporter/gitlab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use std::{
};

pub struct GitLabReporter {
pub execution: Execution,
pub diagnostics: DiagnosticsPayload,
pub(crate) execution: Execution,
pub(crate) diagnostics: DiagnosticsPayload,
}

impl Reporter for GitLabReporter {
Expand Down
14 changes: 7 additions & 7 deletions crates/pg_completions/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ mod tests {
position: (position as u32).into(),
text,
tree: Some(&tree),
schema: &pg_schema_cache::SchemaCache::new(),
schema: &pg_schema_cache::SchemaCache::default(),
};

let ctx = CompletionContext::new(&params);
Expand Down Expand Up @@ -298,7 +298,7 @@ mod tests {
position: (position as u32).into(),
text,
tree: Some(&tree),
schema: &pg_schema_cache::SchemaCache::new(),
schema: &pg_schema_cache::SchemaCache::default(),
};

let ctx = CompletionContext::new(&params);
Expand Down Expand Up @@ -332,7 +332,7 @@ mod tests {
position: (position as u32).into(),
text,
tree: Some(&tree),
schema: &pg_schema_cache::SchemaCache::new(),
schema: &pg_schema_cache::SchemaCache::default(),
};

let ctx = CompletionContext::new(&params);
Expand All @@ -357,7 +357,7 @@ mod tests {
position: (position as u32).into(),
text,
tree: Some(&tree),
schema: &pg_schema_cache::SchemaCache::new(),
schema: &pg_schema_cache::SchemaCache::default(),
};

let ctx = CompletionContext::new(&params);
Expand Down Expand Up @@ -385,7 +385,7 @@ mod tests {
position: (position as u32).into(),
text,
tree: Some(&tree),
schema: &pg_schema_cache::SchemaCache::new(),
schema: &pg_schema_cache::SchemaCache::default(),
};

let ctx = CompletionContext::new(&params);
Expand All @@ -411,7 +411,7 @@ mod tests {
position: (position as u32).into(),
text,
tree: Some(&tree),
schema: &pg_schema_cache::SchemaCache::new(),
schema: &pg_schema_cache::SchemaCache::default(),
};

let ctx = CompletionContext::new(&params);
Expand All @@ -436,7 +436,7 @@ mod tests {
position: (position as u32).into(),
text,
tree: Some(&tree),
schema: &pg_schema_cache::SchemaCache::new(),
schema: &pg_schema_cache::SchemaCache::default(),
};

let ctx = CompletionContext::new(&params);
Expand Down
14 changes: 5 additions & 9 deletions crates/pg_configuration/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ pub struct DatabaseConfiguration {
/// The name of the database.
#[partial(bpaf(long("database")))]
pub database: String,

/// The connection timeout in seconds.
#[partial(bpaf(long("conn_timeout_secs"), fallback(Some(10)), debug_fallback))]
pub conn_timeout_secs: u16,
}

impl Default for DatabaseConfiguration {
Expand All @@ -36,15 +40,7 @@ impl Default for DatabaseConfiguration {
username: "postgres".to_string(),
password: "postgres".to_string(),
database: "postgres".to_string(),
conn_timeout_secs: 10,
}
}
}

impl DatabaseConfiguration {
pub fn to_connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database
)
}
}
1 change: 1 addition & 0 deletions crates/pg_configuration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ impl PartialConfiguration {
username: Some("postgres".to_string()),
password: Some("postgres".to_string()),
database: Some("postgres".to_string()),
conn_timeout_secs: Some(10),
}),
}
}
Expand Down
16 changes: 13 additions & 3 deletions crates/pg_lsp/src/handlers/completions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::session::Session;
use anyhow::Result;
use pg_workspace::workspace;
use pg_workspace::{workspace, WorkspaceError};
use tower_lsp::lsp_types::{self, CompletionItem, CompletionItemLabelDetails};

#[tracing::instrument(level = "trace", skip_all)]
Expand All @@ -26,12 +26,22 @@ pub fn get_completions(
pg_lsp_converters::negotiated_encoding(client_capabilities),
)?;

let completion_result = session
let completion_result = match session
.workspace
.get_completions(workspace::CompletionParams {
path,
position: offset,
})?;
}) {
Ok(result) => result,
Err(e) => match e {
WorkspaceError::DatabaseConnectionError(_) => {
return Ok(lsp_types::CompletionResponse::Array(vec![]));
}
_ => {
return Err(e.into());
}
},
};

let items: Vec<CompletionItem> = completion_result
.into_iter()
Expand Down
1 change: 1 addition & 0 deletions crates/pg_lsp/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,7 @@ impl Session {
configuration: fs_configuration,
vcs_base_path,
gitignore_matches,
skip_db: false,
});

if let Err(error) = result {
Expand Down
4 changes: 0 additions & 4 deletions crates/pg_schema_cache/src/schema_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ pub struct SchemaCache {
}

impl SchemaCache {
pub fn new() -> SchemaCache {
SchemaCache::default()
}

pub async fn load(pool: &PgPool) -> Result<SchemaCache, sqlx::Error> {
let (schemas, tables, functions, types, versions, columns) = futures_util::try_join!(
Schema::load(pool),
Expand Down
16 changes: 7 additions & 9 deletions crates/pg_workspace/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::{
num::NonZeroU64,
path::{Path, PathBuf},
sync::{RwLock, RwLockReadGuard, RwLockWriteGuard},
time::Duration,
};

use ignore::gitignore::{Gitignore, GitignoreBuilder};
Expand Down Expand Up @@ -266,6 +267,7 @@ pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub database: String,
pub conn_timeout_secs: Duration,
}

impl Default for DatabaseSettings {
Expand All @@ -276,19 +278,11 @@ impl Default for DatabaseSettings {
username: "postgres".to_string(),
password: "postgres".to_string(),
database: "postgres".to_string(),
conn_timeout_secs: Duration::from_secs(10),
}
}
}

impl DatabaseSettings {
pub fn to_connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database
)
}
}

impl From<PartialDatabaseConfiguration> for DatabaseSettings {
fn from(value: PartialDatabaseConfiguration) -> Self {
let d = DatabaseSettings::default();
Expand All @@ -298,6 +292,10 @@ impl From<PartialDatabaseConfiguration> for DatabaseSettings {
username: value.username.unwrap_or(d.username),
password: value.password.unwrap_or(d.password),
database: value.database.unwrap_or(d.database),
conn_timeout_secs: value
.conn_timeout_secs
.map(|s| Duration::from_secs(s.into()))
.unwrap_or(d.conn_timeout_secs),
}
}
}
Expand Down
4 changes: 1 addition & 3 deletions crates/pg_workspace/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ pub struct UpdateSettingsParams {
pub vcs_base_path: Option<PathBuf>,
pub gitignore_matches: Vec<String>,
pub workspace_directory: Option<PathBuf>,
pub skip_db: bool,
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
Expand Down Expand Up @@ -119,9 +120,6 @@ pub trait Workspace: Send + Sync + RefUnwindSafe {
params: CompletionParams,
) -> Result<pg_completions::CompletionResult, WorkspaceError>;

/// Refresh the schema cache for this workspace
fn refresh_schema_cache(&self) -> Result<(), WorkspaceError>;

/// Update the global settings for this workspace
fn update_settings(&self, params: UpdateSettingsParams) -> Result<(), WorkspaceError>;

Expand Down
4 changes: 0 additions & 4 deletions crates/pg_workspace/src/workspace/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,6 @@ where
self.request("pglsp/get_file_content", params)
}

fn refresh_schema_cache(&self) -> Result<(), WorkspaceError> {
self.request("pglsp/refresh_schema_cache", ())
}

fn pull_diagnostics(
&self,
params: super::PullDiagnosticsParams,
Expand Down
Loading