Skip to content

Commit

Permalink
fix(cursors): better cursor validation (#499)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjie committed Aug 7, 2019
1 parent 4fa78b1 commit 834687d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
30 changes: 24 additions & 6 deletions packages/graphile-build-pg/src/queryFromResolveDataFactory.js
Expand Up @@ -306,18 +306,26 @@ exists(
}
if (options.withPagination || options.withPaginationAsFields) {
queryBuilder.setCursorComparator((cursorValue, isAfter) => {
function badCursor() {
queryBuilder.whereBound(sql.fragment`false`, isAfter);
}
const orderByExpressionsAndDirections = queryBuilder.getOrderByExpressionsAndDirections();
if (
orderByExpressionsAndDirections.length > 0 &&
queryBuilder.isOrderUnique()
) {
const sqlCursors = cursorValue[getPgCursorPrefix().length].map(val =>
sql.value(val)
);
if (!Array.isArray(sqlCursors)) {
queryBuilder.whereBound(sql.literal(false), isAfter);
const rawPrefixes = cursorValue.slice(0, cursorValue.length - 1);
const rawCursors = cursorValue[cursorValue.length - 1];
if (rawPrefixes.length !== getPgCursorPrefix().length) {
badCursor();
return;
}
if (!Array.isArray(rawCursors)) {
badCursor();
return;
}
let sqlFilter = sql.fragment`false`;
const sqlCursors = rawCursors.map(val => sql.value(val));
for (let i = orderByExpressionsAndDirections.length - 1; i >= 0; i--) {
const [sqlExpression, ascending] = orderByExpressionsAndDirections[i];
// If ascending and isAfter then >
Expand All @@ -339,6 +347,16 @@ OR\
)\
)`;
}

// Check the cursor prefixes apply
// TODO:v5: we should be able to do this in JS-land rather than SQL-land
sqlFilter = sql.fragment`(((${sql.join(
getPgCursorPrefix(),
", "
)}) = (${sql.join(
rawPrefixes.map(val => sql.value(val)),
", "
)})) AND (${sqlFilter}))`;
queryBuilder.whereBound(sqlFilter, isAfter);
} else if (
cursorValue[0] === "natural" &&
Expand All @@ -354,7 +372,7 @@ OR\
});
}
} else {
throw new Error("Cannot use cursors without orderBy");
throw new Error("Cannot use 'before'/'after' without unique 'orderBy'");
}
});

Expand Down
6 changes: 3 additions & 3 deletions yarn.lock
Expand Up @@ -4482,9 +4482,9 @@ fsevents@^1.2.7:
node-pre-gyp "^0.12.0"

fstream@^1.0.0, fstream@^1.0.2:
version "1.0.11"
resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.11.tgz#5c1fb1f117477114f0632a0eb4b71b3cb0fd3171"
integrity sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE=
version "1.0.12"
resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.12.tgz#4e8ba8ee2d48be4f7d0de505455548eae5932045"
integrity sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==
dependencies:
graceful-fs "^4.1.2"
inherits "~2.0.0"
Expand Down

0 comments on commit 834687d

Please sign in to comment.