Skip to content

Instantly share code, notes, and snippets.

@benesch
Created June 4, 2023 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benesch/2e77712f81625deeb0e2246098fd8089 to your computer and use it in GitHub Desktop.
Save benesch/2e77712f81625deeb0e2246098fd8089 to your computer and use it in GitHub Desktop.
diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c
index 9000f83a83..09d3f9267d 100644
--- a/src/backend/utils/adt/arrayfuncs.c
+++ b/src/backend/utils/adt/arrayfuncs.c
@@ -477,6 +477,7 @@ ArrayCount(const char *str, int *dim, char typdelim, Node *escontext)
bool in_quotes = false;
bool eoArray = false;
bool empty_array = true;
+ bool seen_level_completed = false;
const char *ptr;
ArrayParseState parse_state = ARRAY_NO_LEVEL;
@@ -576,8 +577,22 @@ ArrayCount(const char *str, int *dim, char typdelim, Node *escontext)
nest_level + 1, MAXDIM)));
temp[nest_level] = 0;
nest_level++;
- if (ndim < nest_level)
- ndim = nest_level;
+ /*
+ * The first closing brace determines the number of
+ * dimensions. If a later element has a different
+ * nesting depth we have a ragged array.
+ */
+ if (ndim < nest_level) {
+ if (seen_level_completed)
+ ereturn(escontext, -1,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("malformed array literal: \"%s\"", str),
+ errdetail("Multidimensional arrays must have "
+ "sub-arrays with matching "
+ "dimensions.")));
+ else
+ ndim = nest_level;
+ }
}
break;
case '}':
@@ -598,7 +613,21 @@ ArrayCount(const char *str, int *dim, char typdelim, Node *escontext)
errmsg("malformed array literal: \"%s\"", str),
errdetail("Unexpected \"%c\" character.",
'}')));
+ /*
+ * Closing braces may occur only when the nesting level
+ * equals the number of dimensions (or immediately
+ * following another closing branch), else we have a
+ * ragged array.
+ */
+ if (nest_level != ndim && parse_state != ARRAY_LEVEL_COMPLETED)
+ ereturn(escontext, -1,
+ (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
+ errmsg("malformed array literal: \"%s\"", str),
+ errdetail("Multidimensional arrays must have "
+ "sub-arrays with matching "
+ "dimensions.")));
parse_state = ARRAY_LEVEL_COMPLETED;
+ seen_level_completed = true;
if (nest_level == 0)
ereturn(escontext, -1,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment