diff --git a/diesel/src/pg/expression/operators.rs b/diesel/src/pg/expression/operators.rs index dc6100694b98..f2d0934482b6 100644 --- a/diesel/src/pg/expression/operators.rs +++ b/diesel/src/pg/expression/operators.rs @@ -107,7 +107,9 @@ where &'b self, mut out: crate::query_builder::AstPass<'_, 'b, Pg>, ) -> crate::result::QueryResult<()> { + out.push_sql("("); self.array_expr.walk_ast(out.reborrow())?; + out.push_sql(")"); out.push_sql("["); self.index_expr.walk_ast(out.reborrow())?; out.push_sql("]"); @@ -115,15 +117,40 @@ where } } +// we cannot use the additional +// parenthesis for updates +#[derive(Debug)] +pub struct UpdateArrayIndex(ArrayIndex); + +impl QueryFragment for UpdateArrayIndex +where + L: QueryFragment, + R: QueryFragment, +{ + fn walk_ast<'b>( + &'b self, + mut out: crate::query_builder::AstPass<'_, 'b, Pg>, + ) -> crate::result::QueryResult<()> { + self.0.array_expr.walk_ast(out.reborrow())?; + out.push_sql("["); + self.0.index_expr.walk_ast(out.reborrow())?; + out.push_sql("]"); + Ok(()) + } +} + impl AssignmentTarget for ArrayIndex where L: Column, { type Table = ::Table; - type QueryAstNode = ArrayIndex, R>; + type QueryAstNode = UpdateArrayIndex, R>; fn into_target(self) -> Self::QueryAstNode { - ArrayIndex::new(UncorrelatedColumn(self.array_expr), self.index_expr) + UpdateArrayIndex(ArrayIndex::new( + UncorrelatedColumn(self.array_expr), + self.index_expr, + )) } } diff --git a/diesel_tests/tests/index.rs b/diesel_tests/tests/index.rs new file mode 100644 index 000000000000..3bbfb3913490 --- /dev/null +++ b/diesel_tests/tests/index.rs @@ -0,0 +1,13 @@ +#[cfg(feature = "postgres")] +#[test] +fn test_array_index() { + use diesel::dsl::array_append; + use diesel::sql_types::{Array, Integer}; + use diesel::{PgArrayExpressionMethods, RunQueryDsl}; + let connection = &mut crate::schema::connection(); + let result = diesel::select(array_append::, Integer, _, _>(vec![1, 2, 3], 4).index(4)) + .get_result::(connection) + .unwrap(); + + assert_eq!(4, result); +} diff --git a/diesel_tests/tests/lib.rs b/diesel_tests/tests/lib.rs index 3df6e6e4f056..07743347201f 100644 --- a/diesel_tests/tests/lib.rs +++ b/diesel_tests/tests/lib.rs @@ -28,6 +28,7 @@ mod filter_operators; mod find; mod group_by; mod having; +mod index; mod insert; mod insert_from_select; mod instrumentation;