Skip to content

Commit ae884fe

Browse files
authored
Merge pull request #7 from supabase-community/fix/large-sql-memory-error
fix: memory error when parsing large sql
2 parents 34f3852 + b6b8df5 commit ae884fe

File tree

8 files changed

+5750
-3
lines changed

8 files changed

+5750
-3
lines changed

packages/pg-parser/Makefile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ LDFLAGS = -Wl,--gc-sections,--strip-all \
1616
--no-entry \
1717
-sFILESYSTEM=0 \
1818
-sEXPORT_NAME="$(WASM_MODULE_NAME)" \
19-
-sEXPORTED_RUNTIME_METHODS=ccall,cwrap,getValue,UTF8ToString \
19+
-sEXPORTED_RUNTIME_METHODS="['HEAP8','getValue','UTF8ToString','stringToUTF8']" \
20+
-sEXPORTED_FUNCTIONS="['_malloc', '_free']" \
2021
-sMODULARIZE=1 \
2122
-sEXPORT_ES6=1
2223

packages/pg-parser/src/pg-parser.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1+
/// <reference path="../test/types/sql.d.ts" />
2+
13
import { stripIndent } from 'common-tags';
24
import { describe, expect, it } from 'vitest';
35
import { PgParser } from './pg-parser.js';
46
import type { ParseResult } from './types/index.js';
57
import { isParseResultVersion, unwrapParseResult } from './util.js';
68

9+
import sqlDump from '../test/fixtures/dump.sql';
10+
711
describe('pg-parser', () => {
812
it('parses sql in v15', async () => {
913
const pgParser = new PgParser({ version: 15 });
@@ -28,6 +32,17 @@ describe('pg-parser', () => {
2832
expect(create).toThrow('unsupported version');
2933
});
3034

35+
it('parses large sql', async () => {
36+
const pgParser = new PgParser();
37+
const result = await unwrapParseResult(pgParser.parse(sqlDump));
38+
39+
if (!result.stmts) {
40+
throw new Error('stmts not found');
41+
}
42+
43+
expect(result.stmts.length).toBeGreaterThan(0);
44+
});
45+
3146
it('parses sql into ast', async () => {
3247
const pgParser = new PgParser();
3348
const result = await unwrapParseResult(pgParser.parse('SELECT 1+1 as sum'));

packages/pg-parser/src/pg-parser.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,14 @@ export class PgParser<Version extends SupportedVersion = 17> {
7373
async parse(sql: string) {
7474
const module = await this.#module;
7575

76-
const resultPtr = module.ccall('parse_sql', 'number', ['string'], [sql]);
76+
const sqlPtr = module._malloc(sql.length + 1); // +1 for null terminator
77+
module.stringToUTF8(sql, sqlPtr, sql.length + 1);
78+
79+
const resultPtr = module._parse_sql(sqlPtr);
80+
module._free(sqlPtr);
81+
7782
const parseResult = await this.#parsePgQueryParseResult(resultPtr);
78-
module.ccall('free_parse_result', undefined, ['number'], [resultPtr]);
83+
module._free_parse_result(resultPtr);
7984

8085
return parseResult;
8186
}

0 commit comments

Comments
 (0)