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
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ jobs:
run: pnpm run build
working-directory: ${{ matrix.package.path }}

- name: Check native/WASM parse parity 🔍
if: matrix.package.version == '18'
run: node scripts/native-parity.js

- name: Upload WASM Artifacts 📦
uses: actions/upload-artifact@v4
with:
Expand Down
82 changes: 82 additions & 0 deletions scripts/native-parity.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pg_query.h"

static void print_json_string(const char *s, size_t len) {
putchar('"');
for (size_t i = 0; i < len; i++) {
unsigned char c = s[i];
if (c == '"' || c == '\\') {
putchar('\\');
putchar(c);
} else if (c < 0x20) {
printf("\\u%04x", c);
} else {
putchar(c);
}
}
putchar('"');
}

static char *read_file(const char *path, size_t *len) {
FILE *file = fopen(path, "rb");
if (!file || fseek(file, 0, SEEK_END) != 0) return NULL;
long size = ftell(file);
if (size < 0 || fseek(file, 0, SEEK_SET) != 0) return NULL;
char *buf = malloc((size_t)size + 1);
if (!buf || fread(buf, 1, (size_t)size, file) != (size_t)size) return NULL;
fclose(file);
*len = (size_t)size;
buf[*len] = '\0';
return buf;
}

static void split(const char *buf) {
PgQuerySplitResult result = pg_query_split_with_scanner(buf);
if (result.error) {
puts("{\"error\":true}");
} else {
printf("{\"stmts\":[");
for (int i = 0; i < result.n_stmts; i++) {
if (i) putchar(',');
print_json_string(buf + result.stmts[i]->stmt_location, result.stmts[i]->stmt_len);
}
puts("]}");
}
pg_query_free_split_result(result);
}

static void parse(const char *buf, size_t len) {
for (const char *p = buf; p < buf + len; p += strlen(p) + 1) {
PgQueryParseResult result = pg_query_parse(p);
if (result.error) {
printf("{\"error\":{\"message\":");
print_json_string(result.error->message, strlen(result.error->message));
printf(",\"cursorpos\":%d}}\n", result.error->cursorpos);
} else {
printf("{\"parse\":%s}\n", result.parse_tree);
}
pg_query_free_parse_result(result);
}
}

int main(int argc, char **argv) {
if (argc != 3 || (strcmp(argv[1], "split") && strcmp(argv[1], "parse"))) {
fprintf(stderr, "usage: %s split|parse <file>\n", argv[0]);
return 1;
}
size_t len;
char *buf = read_file(argv[2], &len);
if (!buf) {
perror(argv[2]);
return 1;
}
if (strcmp(argv[1], "split") == 0) {
split(buf);
} else {
parse(buf, len);
}
free(buf);
return 0;
}
97 changes: 97 additions & 0 deletions scripts/native-parity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
const { execFileSync } = require('child_process');
const fs = require('fs');
const glob = require('glob');
const os = require('os');
const path = require('path');

const versionDir = path.join(__dirname, '../versions/18');
const { libpgQueryCommit: commit } = require(path.join(versionDir, 'package.json'))['x-publish'];
const source = path.join(versionDir, '.cache/emscripten-wasm/libpg_query', commit);

async function main() {
if (!fs.existsSync(source)) {
throw new Error(`Missing ${source}; run pnpm build in versions/18 first`);
}

const work = fs.mkdtempSync(path.join(os.tmpdir(), 'libpg-query-native-'));
try {
await checkParity(work);
} finally {
fs.rmSync(work, { recursive: true, force: true });
}
}

async function checkParity(work) {
execFileSync('bash', ['-o', 'pipefail', '-c', 'git -C "$1" archive "$2" | tar -x -C "$3"', '--', source, commit, work]);
execFileSync('make', ['-j', String(os.availableParallelism()), 'build'], {
cwd: work,
stdio: ['ignore', 'ignore', 'inherit'],
});
const driver = path.join(work, 'parity-driver');
execFileSync('cc', [
'-O2', '-I', work, path.join(__dirname, 'native-parity.c'),
path.join(work, 'libpg_query.a'), '-pthread', '-o', driver,
]);

const files = glob.sync('test/{sql/**/*.{sql,psql},plpgsql_samples.sql}', { cwd: work }).sort();
const statements = [];
let skippedFiles = 0;
for (const file of files) {
const split = JSON.parse(execFileSync(driver, ['split', path.join(work, file)], { maxBuffer: 128 * 1024 ** 2 }));
if (split.error) {
skippedFiles++; // Some fixtures intentionally contain unscannable SQL.
continue;
}
split.stmts.forEach((sql, i) => statements.push({ key: `${file}#${i + 1}`, sql }));
}
if (!statements.length) throw new Error('No libpg_query test statements found');

const input = path.join(work, 'statements.bin');
fs.writeFileSync(input, statements.map(({ sql }) => sql).join('\0') + '\0');
const output = path.join(work, 'native.jsonl');
const fd = fs.openSync(output, 'w');
try {
execFileSync(driver, ['parse', input], { stdio: ['ignore', fd, 'inherit'] });
} finally {
fs.closeSync(fd);
}
const native = fs.readFileSync(output, 'utf8').trimEnd().split('\n');
if (native.length !== statements.length) {
throw new Error(`Native parser returned ${native.length} results for ${statements.length} statements`);
}

const wasm = require(path.join(versionDir, 'wasm/index.cjs'));
await wasm.loadModule();

let differences = 0;
statements.forEach(({ key, sql }, i) => {
// FETCH_ALL is LONG_MAX: 64-bit on the native runner, 32-bit on wasm32.
const expected = JSON.parse(native[i].replace(
/("(?:howMany|how_many)"\s*:\s*)9223372036854775807(?=\s*[,}])/g,
(_, field) => field + '2147483647',
));
if (expected.error) {
// SqlError exposes a zero-based cursor and reports a missing cursor as 0.
expected.error.cursorpos = Math.max(0, expected.error.cursorpos - 1);
}
let actual;
try {
actual = { parse: wasm.parseSync(sql) };
} catch (err) {
actual = { error: { message: err.message, cursorpos: err.sqlDetails?.cursorPosition } };
}
const a = JSON.stringify(expected);
const b = JSON.stringify(actual);
if (a === b) return;
differences++;
if (differences <= 10) console.error(key, { native: a.slice(0, 300), wasm: b.slice(0, 300) });
});

console.log(`Native parity: ${statements.length} statements from ${files.length - skippedFiles} files (${skippedFiles} unscannable) @ ${commit.slice(0, 7)}, ${differences} differences`);
if (differences) process.exitCode = 1;
}

main().catch((err) => {
console.error(err);
process.exitCode = 1;
});
Loading