Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions core/crates/core/src/browse/browse_sql_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,49 @@ pub enum BrowseSqlError {
#[error(transparent)]
Bind(#[from] BindError),
}

impl BrowseSqlError {
// Stable across releases, for an app outside Rust that words the error itself.
pub fn code(&self) -> &'static str {
match self {
Self::NoColumns => "browse.no_columns",
Self::UnknownSortColumn(_) => "browse.unknown_sort_column",
Self::UnsupportedPosition { .. } => "browse.unsupported_position",
Self::SortUnsupported => "browse.sort_unsupported",
Self::StalePagingState => "browse.stale_paging_state",
Self::NullAnchor => "browse.null_anchor",
Self::UnreadableAnchor => "browse.unreadable_anchor",
Self::ShapeMismatch { .. } => "browse.shape_mismatch",
Self::Filter(_) => "browse.filter",
Self::Build(_) => "browse.build",
Self::Bind(_) => "browse.bind",
}
}

// Outermost first, down to the filter's or the statement builder's own code.
pub fn codes(&self) -> Vec<&'static str> {
let mut codes = vec![self.code()];
match self {
Self::Filter(filter) => codes.extend(filter.codes()),
Self::Build(build) => codes.push(build.code()),
_ => {}
}
codes
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::edit::EditParseError;

#[test]
fn a_refused_filter_value_names_the_page_the_filter_and_the_parse() {
let error = BrowseSqlError::Filter(BuildFilterError::Parse {
column: "id".to_owned(),
source: EditParseError::InvalidInteger,
});

assert_eq!(error.codes(), ["browse.filter", "filter.parse", "edit.invalid_integer"]);
}
}
67 changes: 67 additions & 0 deletions core/crates/core/src/filter/build_filter_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,70 @@ pub enum BuildFilterError {
#[error("field {0} has a dot in its name or starts with $, so a filter cannot name it")]
UnaddressableField(String),
}

impl BuildFilterError {
// Stable across releases, for an app outside Rust that words the error itself.
pub fn code(&self) -> &'static str {
match self {
Self::UnknownColumn(_) => "filter.unknown_column",
Self::MissingValue(_) => "filter.missing_value",
Self::BetweenMissingBound => "filter.between_missing_bound",
Self::EmptyInList => "filter.empty_in_list",
Self::WrongValueShape { .. } => "filter.wrong_value_shape",
Self::Parse { .. } => "filter.parse",
Self::Bind(_) => "filter.bind",
Self::OperatorNotAllowed { .. } => "filter.operator_not_allowed",
Self::CombinatorNotAllowed(_) => "filter.combinator_not_allowed",
Self::RawPredicate(_) => "filter.raw_predicate",
Self::RawDocument(_) => "filter.raw_document",
Self::RawNotDocument => "filter.raw_not_document",
Self::UnaddressableField(_) => "filter.unaddressable_field",
}
}

// Outermost first: a value the column cannot take adds the parse error's own code.
pub fn codes(&self) -> Vec<&'static str> {
match self {
Self::Parse { source, .. } => vec![self.code(), source.code()],
_ => vec![self.code()],
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::edit::EditParseError;

#[test]
fn a_value_the_column_cannot_take_names_the_parse_error_too() {
let error = BuildFilterError::Parse {
column: "id".to_owned(),
source: EditParseError::InvalidInteger,
};

assert_eq!(error.codes(), ["filter.parse", "edit.invalid_integer"]);
}

#[test]
fn each_code_is_under_filter() {
let errors = [
BuildFilterError::UnknownColumn("x".to_owned()),
BuildFilterError::MissingValue(FilterOp::Eq),
BuildFilterError::BetweenMissingBound,
BuildFilterError::EmptyInList,
BuildFilterError::WrongValueShape { op: FilterOp::In },
BuildFilterError::OperatorNotAllowed {
column: "x".to_owned(),
op: FilterOp::Ilike,
},
BuildFilterError::CombinatorNotAllowed(Combinator::Or),
BuildFilterError::RawNotDocument,
BuildFilterError::UnaddressableField("a.b".to_owned()),
];

for error in errors {
assert!(error.code().starts_with("filter."), "{}", error.code());
}
}
}
38 changes: 28 additions & 10 deletions core/crates/ffi/src/core_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,43 @@ use tablepro_session::{
};
use tablepro_ssh::{InProcessSsh, SshAuth};
use tablepro_storage::{ConnectionStore, CredentialDemand, KeyringCredentials, SavedConnection, StoragePaths};
use tokio::sync::OnceCell;
use uuid::Uuid;

use crate::cancel_token::{CancelToken, token};
use crate::drivers::{self, DriverInfo};
use crate::error::CoreError;
use crate::history::QueryHistoryStore;
use crate::host::{HostConfig, HostSecretStore, HostSecrets};
use crate::library::{ConnectionLibrary, ConnectionRecord, ConnectionSecrets, apply, blank, parse_id, tls_config};
use crate::prompter::{HostPrompter, HostPrompterBridge};
use crate::runtime::{self, on_runtime};
use crate::session::DatabaseSession;

/// The library's root: the linked engines, the runtime and what the app
/// passed in. An app makes one and keeps it.
// An app makes one and keeps it.
#[derive(uniffi::Object)]
pub struct Core {
registry: Arc<DriverRegistry>,
connector: Arc<DriverConnector>,
deadlines: Arc<DefaultDeadlines>,
vault: Arc<dyn SecretVault>,
items: Arc<dyn SecretItems>,
paths: Option<StoragePaths>,
store: Option<ConnectionStore>,
// Opened on first use, so a core that never shows history never migrates or prunes it.
history: Arc<OnceCell<Arc<QueryHistoryStore>>>,
pub(crate) tasks: Tasks,
pub(crate) ssh: Arc<InProcessSsh>,
}

/// A database file to open.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct FileOpenRequest {
/// An absolute path.
// Absolute.
pub path: String,
/// The engine to open it with. `None` lets the file's first bytes
/// decide, then its name.
// None lets the file's first bytes decide the engine, then its name.
pub driver_id: Option<String>,
pub read_only: bool,
/// Make a new database at `path`, which must not exist yet.
// `path` must not exist yet.
pub create: bool,
}

Expand All @@ -71,7 +73,6 @@ impl Core {
Ok(Self::build(config, vault, items, tasks))
}

/// Every engine linked in, by name.
pub fn drivers(&self) -> Vec<DriverInfo> {
let mut drivers: Vec<DriverInfo> = self
.registry
Expand All @@ -91,6 +92,20 @@ impl Core {
)))
}

// Every caller shares one store. A failed open is tried again on the next call.
pub async fn history(&self) -> Result<Arc<QueryHistoryStore>, CoreError> {
let paths = self.paths.clone().ok_or_else(no_storage)?;
let history = self.history.clone();
let tasks = self.tasks.clone();
on_runtime(&self.tasks, async move {
history
.get_or_try_init(|| QueryHistoryStore::open(paths, tasks))
.await
.cloned()
})
.await
}

pub async fn open_file(
&self,
request: FileOpenRequest,
Expand Down Expand Up @@ -277,17 +292,20 @@ impl Core {
ssh: ssh.clone(),
liveness,
};
let store = config
let paths = config
.storage_dir
.filter(|dir| !dir.trim().is_empty())
.map(|dir| ConnectionStore::new(&storage_paths(Path::new(&dir))));
.map(|dir| storage_paths(Path::new(&dir)));
let store = paths.as_ref().map(ConnectionStore::new);
Arc::new(Self {
registry: Arc::new(drivers::registry()),
connector: Arc::new(DriverConnector::new(services, deadlines.clone())),
deadlines,
vault,
items,
paths,
store,
history: Arc::default(),
tasks,
ssh,
})
Expand Down
98 changes: 98 additions & 0 deletions core/crates/ffi/src/definition.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
use tablepro_core::meta::{ObjectDefinition, ObjectInfo, ObjectKind};

use crate::catalog::{ObjectEntry, ObjectKindTag};
use crate::error::CoreError;

// `database`: where `sql` runs when it names none. `opens_in_editor`: false when an editor run would not make it.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ObjectSource {
pub sql: String,
pub database: Option<String>,
pub opens_in_editor: bool,
}

impl From<ObjectDefinition> for ObjectSource {
fn from(definition: ObjectDefinition) -> Self {
Self {
sql: definition.sql,
database: definition.database,
opens_in_editor: definition.refusal.is_none(),
}
}
}

// A key's kind and a kind this build does not name carry too little for a driver to find the object by.
impl TryFrom<ObjectEntry> for ObjectInfo {
type Error = CoreError;

fn try_from(entry: ObjectEntry) -> Result<Self, Self::Error> {
let kind = match entry.kind {
ObjectKindTag::Table => ObjectKind::Table,
ObjectKindTag::PartitionedTable => ObjectKind::PartitionedTable,
ObjectKindTag::View => ObjectKind::View,
ObjectKindTag::MaterializedView => ObjectKind::MaterializedView,
ObjectKindTag::ForeignTable => ObjectKind::ForeignTable,
ObjectKindTag::Sequence => ObjectKind::Sequence,
ObjectKindTag::Function => ObjectKind::Function,
ObjectKindTag::Procedure => ObjectKind::Procedure,
ObjectKindTag::Trigger => ObjectKind::Trigger,
ObjectKindTag::Dictionary => ObjectKind::Dictionary,
ObjectKindTag::Key | ObjectKindTag::Other => {
return Err(CoreError::failed(
"ffi.no_definition",
"a key or an object of an unknown kind has no definition to read",
));
}
};
Ok(Self {
schema: entry.schema,
name: entry.name,
kind,
parent_table: entry.parent_table,
})
}
}

#[cfg(test)]
mod tests {
use tablepro_core::meta::EditorRefusal;

use super::*;

fn entry(kind: ObjectKindTag) -> ObjectEntry {
ObjectEntry {
schema: Some("public".to_owned()),
name: "audit".to_owned(),
kind,
parent_table: Some("orders".to_owned()),
}
}

#[test]
fn a_trigger_keeps_its_table_on_the_way_in() {
let info = ObjectInfo::try_from(entry(ObjectKindTag::Trigger)).unwrap();

assert_eq!(info, ObjectInfo::trigger(Some("public".to_owned()), "audit", "orders"));
}

#[test]
fn a_key_and_an_unknown_kind_are_refused() {
for kind in [ObjectKindTag::Key, ObjectKindTag::Other] {
let refused = ObjectInfo::try_from(entry(kind)).unwrap_err();

assert_eq!(refused.code(), "ffi.no_definition");
}
}

#[test]
fn a_refusal_keeps_the_text_out_of_the_editor() {
let source = ObjectSource::from(ObjectDefinition {
sql: "CREATE PROCEDURE p AS SELECT 1".to_owned(),
database: Some("shop".to_owned()),
refusal: Some(EditorRefusal::SplitsApart),
});

assert!(!source.opens_in_editor);
assert_eq!(source.database.as_deref(), Some("shop"));
}
}
13 changes: 12 additions & 1 deletion core/crates/ffi/src/editor.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::sync::Arc;
use std::time::Duration;

use tablepro_core::{ByteLimit, EditorSession, EditorSessionState, RowLimit, RunOptions, UserSql};
use tablepro_core::{ByteLimit, CallOptions, EditorSession, EditorSessionState, RowLimit, RunOptions, UserSql};
use tablepro_session::runtime::{Tasks, catch_panic};

use crate::cancel_token::{CancelToken, token};
use crate::error::CoreError;
use crate::run::{QueryRun, RunListener, RunOutcome, RunSink, RunState, TransactionStateTag};
use crate::runtime::on_runtime;
Expand Down Expand Up @@ -70,6 +71,16 @@ impl QueryEditor {
self.editor.state() == EditorSessionState::Lost
}

// Where a definition names no database of its own, its text has to run in the one it was read from.
pub async fn use_database(&self, database: String, cancel: Option<Arc<CancelToken>>) -> Result<(), CoreError> {
let editor = self.editor.clone();
let cancel = token(cancel);
on_runtime(&self.tasks, async move {
Ok(editor.use_database(&database, CallOptions::new(None, cancel)).await?)
})
.await
}

/// Closes the editor's connection, ending its transaction.
pub async fn close(&self) -> Result<(), CoreError> {
let editor = self.editor.clone();
Expand Down
23 changes: 23 additions & 0 deletions core/crates/ffi/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,14 @@ impl From<&OperationError> for CoreError {
OperationError::Driver(driver) => Self::Failed {
info: ErrorInfo::wrapping(&[error.code()], driver, error.to_string()).into(),
},
// The filter's own code says which rule the app has to word, down to a value the column cannot take.
OperationError::Browse(browse) => {
let mut codes = vec![error.code()];
codes.extend(browse.codes());
Self::Failed {
info: ErrorInfo::plain(&codes, error.to_string()).into(),
}
}
other => Self::Failed {
info: ErrorInfo::plain(&[other.code()], other.to_string()).into(),
},
Expand Down Expand Up @@ -360,6 +368,21 @@ mod tests {
}
}

#[test]
fn a_refused_filter_names_the_rule_the_app_words() {
let error = OperationError::Browse(tablepro_core::browse::BrowseSqlError::Filter(
tablepro_core::filter::BuildFilterError::UnknownColumn("ghost".to_owned()),
));

let info = info(error.into());

assert_eq!(
info.codes,
["operation.browse", "browse.filter", "filter.unknown_column"]
);
assert_eq!(info.code, "filter.unknown_column");
}

#[test]
fn a_config_error_carries_its_own_code() {
let info = info(OperationError::Driver(DriverError::Config(ConfigError::RelativePath)).into());
Expand Down
Loading
Loading