Skip to content
Closed
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
5 changes: 4 additions & 1 deletion assets/keymaps/default-linux.json
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,10 @@
"alt-ctrl-z": "studio_review::RevertAndNext",
"ctrl-shift-enter": "studio_review::Merge",
"ctrl-shift-m": "studio_review::Summarize",
"ctrl-shift-v": "studio_review::SwitchLayout"
"ctrl-shift-v": "studio_review::SwitchLayout",
"ctrl-alt-c": "studio_review::ShowConflicts",
"ctrl-alt-shift-left": "studio_review::KeepTarget",
"ctrl-alt-shift-right": "studio_review::KeepSource"
}
},
{
Expand Down
5 changes: 4 additions & 1 deletion assets/keymaps/default-macos.json
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,10 @@
"alt-cmd-z": "studio_review::RevertAndNext",
"cmd-shift-enter": "studio_review::Merge",
"cmd-shift-m": "studio_review::Summarize",
"cmd-shift-v": "studio_review::SwitchLayout"
"cmd-shift-v": "studio_review::SwitchLayout",
"alt-cmd-c": "studio_review::ShowConflicts",
"alt-cmd-[": "studio_review::KeepTarget",
"alt-cmd-]": "studio_review::KeepSource"
}
},
{
Expand Down
5 changes: 4 additions & 1 deletion assets/keymaps/default-windows.json
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,10 @@
"alt-ctrl-z": "studio_review::RevertAndNext",
"ctrl-shift-enter": "studio_review::Merge",
"ctrl-shift-m": "studio_review::Summarize",
"ctrl-shift-v": "studio_review::SwitchLayout"
"ctrl-shift-v": "studio_review::SwitchLayout",
"ctrl-alt-c": "studio_review::ShowConflicts",
"ctrl-alt-shift-left": "studio_review::KeepTarget",
"ctrl-alt-shift-right": "studio_review::KeepSource"
}
},
{
Expand Down
88 changes: 88 additions & 0 deletions crates/gq_language/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2266,6 +2266,73 @@ pub fn edge_page_without(
})
}

/// Which edges of one type [`edges_of`] reads.
#[derive(Debug, Clone, Copy)]
pub enum EdgesOf<'a> {
/// Those whose `@id` is one of these.
Ids(&'a [String]),
/// Those from the node with this `@id`.
From(&'a str),
}

/// Edges of one type by their ids or their source, in one read, with [`edge_page_without`]'s
/// columns: `edge_id`, `from_id`, `to_id`, then each property a projection can read in its
/// [`edge_property_column`]; at most `limit` rows. A merge conflict's sides are read with it
/// (spec 039): the edges a branch and its target hold of the conflict, each at its own head.
pub fn edges_of(
schema: &SchemaModel,
edge_name: &str,
of: EdgesOf<'_>,
limit: u32,
) -> Result<BuiltQuery, BuildError> {
let edge = edge(schema, edge_name)?;
let mut params = Params::new();
let mut clauses = vec![
format!("$a: {}", edge.from),
format!("$a {EDGE_VAR}:{} $b", edge.traversal()),
];
clauses.push(match of {
EdgesOf::Ids(ids) => {
let ids = params.add("ids", "[String]", Value::from(ids.to_vec()));
format!("{EDGE_VAR}.@id in {ids}")
}
EdgesOf::From(id) => {
let id = params.add("from", "String", Value::String(id.to_owned()));
format!("$a.@id = {id}")
}
});
let mut columns = vec![
format!("{EDGE_VAR}.@id as edge_id"),
"$a.@id as from_id".to_owned(),
"$b.@id as to_id".to_owned(),
];
for property in edge.properties.iter().filter(|p| p.projectable()) {
columns.push(format!(
"{EDGE_VAR}.{} as {}",
property.name,
edge_property_column(&property.name)
));
}
let text = format!(
"query studio_edges_of({sig}) {{\n match {{\n {clauses}\n }}\n return {{ {columns} }}\n order {{ {EDGE_VAR}.@id }}\n limit {limit}\n}}\n",
sig = params.signature(),
clauses = clauses.join("\n "),
columns = columns.join(", "),
limit = limit.max(1),
);
Ok(BuiltQuery {
name: "studio_edges_of".into(),
text,
params: params.values,
depends: Depends::Types {
nodes: vec![edge.from.clone(), edge.to.clone()],
edges: vec![edge.name.clone()],
},
seeds: None,
empty_without: None,
})
}

/// How many edges of a type match the filters. An edge binding cannot be counted bare, so this
/// counts its `@id`.
pub fn edge_count(
Expand Down Expand Up @@ -4154,6 +4221,27 @@ mod tests {
assert!(neighbour_count(&schema, "Person", &works_at, "x", &condition).is_err());
}

/// A conflict's edges are read by their ids or from their source, with the edge's id and
/// both ends, and the queries type-check (spec 039).
#[test]
fn edges_are_read_by_id_or_from_their_source() {
let schema = dev();
let ids = ["e1".to_owned(), "e2".to_owned()];
let by_id = edges_of(&schema, "WorksAt", EdgesOf::Ids(&ids), 2).unwrap();
assert_compiles(&by_id);
assert!(by_id.text.contains("$e.@id in $ids"), "{}", by_id.text);
assert_eq!(by_id.params["ids"], json!(["e1", "e2"]));
let from = edges_of(&schema, "WorksAt", EdgesOf::From("ada"), 50).unwrap();
assert_compiles(&from);
assert!(from.text.contains("$a.@id = $from"), "{}", from.text);
assert!(
from.text
.contains("$e.@id as edge_id, $a.@id as from_id, $b.@id as to_id")
);
assert!(from.text.contains("limit 50"));
assert!(edges_of(&schema, "Nope", EdgesOf::From("ada"), 1).is_err());
}

fn assert_compiles(query: &BuiltQuery) {
let schema = dev();
let result = check(&schema, &query.text);
Expand Down
160 changes: 160 additions & 0 deletions crates/graph_store/src/fixes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,99 @@ fn revert_edge(
}
}

/// What one side of a merge conflict holds of an entity (spec 039): its properties as read, a
/// property a read could not return (a Blob, a vector) left out, which is not a null.
pub type SideImage = Map<String, Value>;

/// The mutation that makes the branch `have` was read on hold what the other side holds of
/// entity `id` (`want`), so the merge finds the two sides alike and takes it (spec 039,
/// "Keep main's" and "Keep this branch's"). Omnigraph compares a conflicting row whole, so the
/// row is made alike, not only the properties both sides changed.
///
/// - Both hold it: set every property whose values differ, bound to each value `have` holds,
/// so a row changed since is left alone whole (zero affected rows), never set in part.
/// - Only `want` holds it: insert it with its values; a node without a key cannot be, since it
/// would come back under another id. An edge cannot be either: an insert cannot give it its
/// id (E26).
/// - Only `have` holds it: delete it.
///
/// Properties held by one image and not the other (outside one side's schema, or not read) are
/// not compared. A differing value a mutation cannot set (a Blob, a vector) makes it
/// unavailable, with why.
pub fn take_side(
schema: &SchemaModel,
is_edge: bool,
type_name: &str,
id: &str,
want: Option<&SideImage>,
have: Option<&SideImage>,
) -> Result<BuiltQuery, RevertUnavailable> {
let unavailable = |error: gq_language::BuildError| RevertUnavailable(error.to_string());
if is_edge {
let Some(edge) = schema.edge(type_name) else {
return Err(RevertUnavailable(format!(
"The current schema has no relationship {type_name}."
)));
};
return match (want, have) {
(None, Some(_)) => delete_edge(schema, &edge.name, id).map_err(unavailable),
(None, None) => Err(RevertUnavailable("Neither side holds it.".into())),
(Some(_), _) => Err(RevertUnavailable(
"A relationship cannot be changed or brought back under its own id: \
remove it on one side instead."
.into(),
)),
};
}
let Some(node) = schema.node(type_name) else {
return Err(RevertUnavailable(format!(
"The current schema has no type {type_name}."
)));
};
match (want, have) {
(None, None) => Err(RevertUnavailable("Neither side holds it.".into())),
(None, Some(_)) => delete_node(schema, &node.name, id).map_err(unavailable),
(Some(_), None) if node.key.is_none() => Err(RevertUnavailable(format!(
"{} has no key, so it would come back under another id.",
node.name
))),
(Some(want), None) => {
let values = restorable(&node.properties, want)?;
insert_node(schema, &node.name, &values).map_err(unavailable)
}
(Some(want), Some(have)) => {
let mut cells = Vec::new();
for property in &node.properties {
let (Some(wanted), Some(held)) =
(want.get(&property.name), have.get(&property.name))
else {
continue;
};
if gq_language::input::same_value(wanted, held) {
continue;
}
if !property.editable_in_cell() {
return Err(RevertUnavailable(format!(
"{} cannot be set from the review.",
property.name
)));
}
cells.push((property.name.clone(), held.clone(), wanted.clone()));
}
if cells.is_empty() {
return Err(RevertUnavailable(
"Both sides already hold the same values.".into(),
));
}
let row = RowEdit {
id: id.to_owned(),
cells,
};
update_rows(schema, &node.name, &[row]).map_err(unavailable)
}
}
}

/// Joins mutations into one, renaming each part's parameters `$name` to `$name_<i>` so they
/// cannot collide. A single part is returned unchanged.
///
Expand Down Expand Up @@ -359,6 +452,73 @@ mod tests {
assert!(!revert_deletes(&one));
}

/// A conflict's side is taken by making the other side's row alike (spec 039): every
/// differing property set in one statement bound to the values held, a row only one side
/// holds inserted or deleted, and a relationship only removed.
#[test]
fn taking_a_side_makes_the_other_rows_alike() {
let image = |v: Value| v.as_object().unwrap().clone();
let main = image(json!({"slug": "ada", "name": "Ada", "title": "CTO", "tags": ["x"]}));
let here = image(json!({"slug": "ada", "name": "Ada", "title": "CEO", "tags": ["y"]}));
let query = take_side(&schema(), false, "Person", "ada", Some(&main), Some(&here)).unwrap();
assert_compiles(&query);
assert_eq!(
query.text.matches("update Person").count(),
1,
"{}",
query.text
);
assert!(
query.text.contains("set { title: $new0_0, tags: $new0_1 }"),
"{}",
query.text
);
assert!(
query
.text
.contains("where @id = $id0 and title = $old0_0\n"),
"{}",
query.text
);
assert_eq!(query.params["new0_0"], json!("CTO"));
assert_eq!(query.params["old0_0"], json!("CEO"));
assert_eq!(query.params["new0_1"], json!(["x"]));

// A property one side did not read is not compared, and one alike asks for nothing.
let partial = image(json!({"slug": "ada", "name": "Ada"}));
assert!(
take_side(
&schema(),
false,
"Person",
"ada",
Some(&partial),
Some(&here)
)
.is_err()
);

// Only the wanted side holds it: inserted with its values; only the other: deleted.
let insert = take_side(&schema(), false, "Person", "ada", Some(&main), None).unwrap();
assert_compiles(&insert);
assert!(insert.text.contains("insert Person"), "{}", insert.text);
let delete = take_side(&schema(), false, "Person", "ada", None, Some(&here)).unwrap();
assert_compiles(&delete);
assert!(
delete.text.contains("delete Person where @id = $id"),
"{}",
delete.text
);

// A relationship is only removed.
let edge = image(json!({"role": "x"}));
let remove = take_side(&schema(), true, "WorksAt", "e1", None, Some(&edge)).unwrap();
assert_compiles(&remove);
let refused = take_side(&schema(), true, "WorksAt", "e1", Some(&edge), Some(&edge));
assert!(refused.unwrap_err().0.contains("remove it on one side"));
assert!(take_side(&schema(), false, "Nobody", "x", None, Some(&here)).is_err());
}

#[test]
fn added_and_removed_nodes_revert_with_delete_and_insert() {
let added = change(
Expand Down
27 changes: 27 additions & 0 deletions crates/graph_store/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4161,6 +4161,33 @@ impl GraphSession {
)
}

/// One page of `branch`'s change feed of the types `types` only, from `start` or from
/// `page_token` to continue: a review reads who set the target's side of a conflict with it
/// (spec 039), the feed having no filter by entity (E62).
pub fn typed_changes(
&mut self,
branch: &str,
start: &str,
page_token: Option<String>,
types: Vec<String>,
limit: u32,
cx: &mut Context<Self>,
) -> Task<Result<ChangeFeedOutput, ReadError>> {
let (client, graph, branch) = (self.client(cx), self.graph_id.clone(), branch.to_owned());
let start = start.to_owned();
self.counted_read(
"changes",
async move {
let at = match &page_token {
Some(token) => FeedAt::Page(token),
None => FeedAt::Start(&start),
};
client.changes(&graph, &branch, at, &types, limit).await
},
cx,
)
}

/// One page of the net changes from commit `from` to commit `to`.
pub fn diff(
&mut self,
Expand Down
7 changes: 3 additions & 4 deletions crates/review/src/conflicts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,10 @@ pub fn conflict_wording(kind: MergeConflictKind, here: Option<NetChange>, target
}
}

/// What to do about conflicts, after the list.
/// What to do about conflicts, after the list (spec 039): each conflict's card offers the
/// decisions.
pub fn resolution_hint(source: &str, target: &str) -> String {
format!(
"Fix each entity on {source} with ordinary edits so it agrees with {target}, then merge."
)
format!("Show conflicts to keep {target}'s or {source}'s version of each, then merge again.")
}

#[cfg(test)]
Expand Down
Loading
Loading