Skip to content
Merged
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
2 changes: 1 addition & 1 deletion packages/pgsql-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ pgsql proto-fetch [options]
| `--inFile` | Where to save the proto file | *Required* |
| `--outFile` | Generated JS output file | *Required* |
| `--replace-pkg` | Original package name to replace | `protobufjs/minimal` |
| `--with-pkg` | New package name | `@launchql/protobufjs/minimal` |
| `--with-pkg` | New package name | `@constructive-io/protobufjs/minimal` |
| `-h, --help` | Show help | |

#### Examples
Expand Down
107 changes: 106 additions & 1 deletion packages/pgsql-cli/__tests__/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { join, resolve } from 'path';
import { loadModule, parseSync } from 'pgsql-parser';

import { deparseCommand } from '../src/commands/deparse';
import { parseCommand } from '../src/commands/parse';
import { protoFetchCommand } from '../src/commands/proto-fetch';
import { generateProtoJS, replaceTextInProtoJS } from '../src/commands/proto-fetch/helpers';

const sql = `SELECT (ARRAY[1, 2, 3])[2:3] AS slice, 'line one
line two' AS memo FROM t WHERE id = 1`;
Expand Down Expand Up @@ -57,3 +60,105 @@ describe('pgsql deparse', () => {
.toEqual(withoutLocations(JSON.parse(readFileSync(astFile, 'utf-8'))));
});
});

describe('pgsql proto-fetch', () => {
it('resolves standard protobuf imports from the installed runtime', async () => {
const inFile = join(dir, 'descriptor-user.proto');
const outFile = join(dir, 'descriptor-user.js');
writeFileSync(inFile, `
syntax = "proto2";
import "google/protobuf/descriptor.proto";
message Example {
optional google.protobuf.FileDescriptorProto descriptor = 1;
}
`);

await generateProtoJS(inFile, outFile);

expect(readFileSync(outFile, 'utf-8')).toContain('$root.google.protobuf.FileDescriptorProto');
});

it('resolves bundled Google API imports from the installed runtime', async () => {
const inFile = join(dir, 'annotations-user.proto');
const outFile = join(dir, 'annotations-user.js');
writeFileSync(inFile, `
syntax = "proto3";
import "google/api/annotations.proto";
message Example { google.api.HttpRule rule = 1; }
`);

await generateProtoJS(inFile, outFile);

const output = readFileSync(outFile, 'utf-8');
expect(output).toContain('$root.google.api.HttpRule');
expect(output).toContain('$root.google.protobuf.MethodOptions');
});

it.each([
'google/protobuf/descriptor.proto',
'google/protobuf/timestamp.proto',
'google/api/annotations.proto',
])('does not substitute a bundled proto for a missing input (%s)', async inFile => {
const outFile = join(dir, 'missing.js');

await expect(generateProtoJS(inFile, outFile)).rejects.toMatchObject({ code: 'ENOENT', path: inFile });
});

it('round-trips a qualified extension name', async () => {
const inFile = join(dir, 'example.proto');
const outFile = join(dir, 'example.js');
writeFileSync(inFile, `
syntax = "proto2";
package demo;
message Example { extensions 100 to max; }
extend Example { optional string extra = 100; }
`);

await generateProtoJS(inFile, outFile);
await replaceTextInProtoJS(outFile, 'protobufjs/minimal', require.resolve('@constructive-io/protobufjs/minimal'));

const { Example } = require(outFile).demo;
const value = { '.demo.extra': 'extension' };
expect(Example.toObject(Example.decode(Example.encode(value).finish()))).toEqual(value);
});

it.each(['first-name', 'first name', '2fa', 'class', '__proto__', 'constructor', 'toJSON'])('rejects an unsupported alias (%s)', async name => {
const inFile = join(dir, 'example.proto');
const outFile = join(dir, 'example.js');
writeFileSync(inFile, `
syntax = "proto3";
message Example { string label = 1 [json_name = "${name}"]; }
`);

await expect(generateProtoJS(inFile, outFile)).rejects.toThrow(
`Invalid JSON field name ${JSON.stringify(name)} on label`
);
});

it.each([
[undefined, '@constructive-io/protobufjs/minimal'],
['@custom/protobufjs', '@custom/protobufjs'],
])('generates a module with the requested runtime (%s)', async (withPkg, runtime) => {
const inFile = join(dir, 'test input.proto');
const outFile = join(dir, 'test output.js');
writeFileSync(inFile, 'syntax = "proto3"; message Example { string text = 1; }');

await protoFetchCommand({ inFile, outFile, 'with-pkg': withPkg });

expect(readFileSync(outFile, 'utf-8')).toContain(`require("${runtime}")`);
});

it('round-trips a PostgreSQL AST using its JSON field names', async () => {
const inFile = resolve(__dirname, '../../../__fixtures__/proto/18-latest.proto');
const outFile = join(dir, 'pg-query.js');
await protoFetchCommand({ inFile, outFile, 'with-pkg': require.resolve('@constructive-io/protobufjs/minimal') });

const { ParseResult } = require(outFile).pg_query;
await loadModule();
const ast = parseSync('SELECT 42');
const message = ParseResult.fromObject(ast);
const decoded = ParseResult.decode(ParseResult.encode(message).finish());

expect(ParseResult.toObject(decoded, { enums: String, longs: Number })).toEqual(ast);
}, 20_000);
});
8 changes: 4 additions & 4 deletions packages/pgsql-cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@pgsql/cli",
"version": "18.3.12",
"version": "18.3.13",
"description": "Unified CLI for PostgreSQL AST parsing, deparsing, and code generation",
"author": "Constructive <developers@constructive.io>",
"main": "index.js",
Expand Down Expand Up @@ -45,16 +45,16 @@
"database"
],
"dependencies": {
"@launchql/protobufjs": "7.2.6",
"@launchql/protobufjs-cli": "1.1.5",
"chalk": "^4.1.0",
"glob": "8.0.3",
"minimist": "1.2.8",
"mkdirp": "3.0.1",
"nested-obj": "^0.2.2",
"pg-proto-parser": "workspace:*",
"pgsql-deparser": "workspace:*",
"pgsql-parser": "workspace:*"
"pgsql-parser": "workspace:*",
"@constructive-io/protobufjs": "7.6.6",
"@constructive-io/protobufjs-cli": "1.3.3"
},
"devDependencies": {
"@types/minimist": "^1.2.5",
Expand Down
8 changes: 5 additions & 3 deletions packages/pgsql-cli/src/commands/proto-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export async function protoFetchCommand(argv: any) {
const inFile = argv.inFile;
const outFile = argv.outFile;
const replacePkg = argv['replace-pkg'] || 'protobufjs/minimal';
const withPkg = argv['with-pkg'] || '@launchql/protobufjs/minimal';
const withPkg = argv['with-pkg'] || '@constructive-io/protobufjs/minimal';

if (!inFile || !outFile) {
console.error(chalk.red('Error: --inFile and --outFile are required'));
Expand All @@ -31,8 +31,10 @@ export async function protoFetchCommand(argv: any) {
console.log(chalk.blue('Generating JavaScript from proto file...'));
await generateProtoJS(inFile, outFile);

console.log(chalk.blue(`Replacing package references...`));
await replaceTextInProtoJS(outFile, replacePkg, withPkg);
if (replacePkg !== withPkg) {
console.log(chalk.blue(`Replacing package references...`));
await replaceTextInProtoJS(outFile, replacePkg, withPkg);
}

console.log(chalk.green(`✓ All operations completed successfully`));
console.log(chalk.green(`✓ Generated file: ${outFile}`));
Expand Down
6 changes: 3 additions & 3 deletions packages/pgsql-cli/src/commands/proto-fetch/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { exec } from 'child_process';
import fs from 'fs';
import https from 'https';
import { sync as mkdirp } from 'mkdirp';
import { dirname } from 'path';
import { main as pbjs } from '@constructive-io/protobufjs-cli/pbjs';

// Download .proto file if URL
export const downloadProtoFile = (protoUrl: string, filePath: string): Promise<void> => {
Expand Down Expand Up @@ -34,10 +34,10 @@ export const downloadProtoFile = (protoUrl: string, filePath: string): Promise<v

// Generate JavaScript from proto file using pbjs
export const generateProtoJS = (inFile: string, outFile: string): Promise<void> => new Promise((resolve, reject) => {
const command = `pbjs --keep-case -t static-module -o ${outFile} ${inFile}`;
fs.accessSync(inFile, fs.constants.R_OK);
mkdirp(dirname(outFile));

exec(command, (error, _stdout, _stderr) => {
pbjs(['--keep-case', '-t', 'static-module', '-o', outFile, '--', inFile], (error) => {
if (error) {
console.error(`Error during code generation: ${error.message}`);
reject(error);
Expand Down
6 changes: 2 additions & 4 deletions packages/pgsql-cli/src/utils/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,15 +162,13 @@ ${chalk.yellow('Options:')}
--inFile <file> Where to save the proto file
--outFile <file> Generated JS output file
--replace-pkg <old> Original package name to replace
--with-pkg <new> New package name
--with-pkg <new> New package name (default: @constructive-io/protobufjs/minimal)
-h, --help Show help

${chalk.yellow('Examples:')}
pgsql proto-fetch --url https://raw.githubusercontent.com/pganalyze/libpg_query/16-latest/protobuf/pg_query.proto \\
--inFile pg_query.proto \\
--outFile pg_query.js \\
--replace-pkg "protobufjs/minimal" \\
--with-pkg "@launchql/protobufjs/minimal"
--outFile pg_query.js
`);
}

Expand Down
37 changes: 36 additions & 1 deletion packages/proto-parser/__tests__/runtime-schema.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
import { parseAndSnap } from '../test-utils';
import { readFileSync } from 'fs';
import { parse } from '@constructive-io/protobufjs';

import { ProtoStore } from '../src/store';
import { getFieldName } from '../src/utils';
import { getStore, getTestProtoPath, parseAndSnap } from '../test-utils';

describe('runtime-schema', () => {
it('preserves PG18 JSON names and the JsonAggConstructor fields', () => {
const { root } = parse(readFileSync(getTestProtoPath('18-latest.proto'), 'utf8'));
const selectStmt = root.lookupType('pg_query.Node').fields.SelectStmt;
expect(selectStmt?.name).toBe('SelectStmt');
expect(getFieldName(selectStmt, selectStmt.name)).toBe('SelectStmt');

const schema = new ProtoStore(root).getRuntimeSchema();
expect(schema.find(node => node.name === 'SelectStmt')).toMatchObject({ isNode: true });
expect(schema.find(node => node.name === 'JsonAggConstructor').fields).toEqual(
expect.arrayContaining([expect.objectContaining({ name: 'agg_filter', type: 'Node' })])
);
for (const name of ['JsonObjectAgg', 'JsonArrayAgg']) {
expect(schema.find(node => node.name === name).fields).toEqual(
expect.arrayContaining([expect.objectContaining({ name: 'constructor', type: 'JsonAggConstructor' })])
);
}
});

it('uses explicit JSON field names rather than protobufjs camelCase names', () => {
const schema = getStore({}).getRuntimeSchema();
const jsonObjectAgg = schema.find(node => node.name === 'JsonObjectAgg');

expect(jsonObjectAgg.fields).toMatchObject([
{ name: 'absent_on_null' },
{ name: 'arg' },
{ name: 'constructor' },
{ name: 'unique' },
]);
});

it('json format enabled', () => {
parseAndSnap('runtime-schema/json/enabled', {
runtimeSchema: {
Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/__tests__/utilities.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Type } from '@launchql/protobufjs';
import { Type } from '@constructive-io/protobufjs';

import { ProtoStore } from '../src/store';
import { getDependencies, getDependents, getUndefinedKey } from '../src/utils';
Expand Down
4 changes: 2 additions & 2 deletions packages/proto-parser/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pg-proto-parser",
"version": "1.32.8",
"version": "1.32.9",
"description": "Generate TypeScript from the PostgreSQL protobuf definitions",
"author": "Constructive <developers@constructive.io>",
"main": "index.js",
Expand Down Expand Up @@ -46,10 +46,10 @@
"@babel/parser": "^7.23.6",
"@babel/traverse": "7.28.5",
"@babel/types": "7.28.5",
"@launchql/protobufjs": "7.2.6",
"case": "1.6.3",
"deepmerge": "4.3.1",
"nested-obj": "^0.2.2",
"@constructive-io/protobufjs": "7.6.6",
"strfy-js": "^3.1.5"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/ast/enums/enums-json.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Enum } from '@launchql/protobufjs';
import { Enum } from '@constructive-io/protobufjs';

type EnumValueToName = Record<string, Record<number, string>>;
type EnumNameToValue = Record<string, Record<string, number>>;
Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/ast/enums/enums.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as t from '@babel/types';
import { Enum } from '@launchql/protobufjs';
import { Enum } from '@constructive-io/protobufjs';

import { createNamedImport } from '../../utils';

Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/ast/types/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as t from '@babel/types';
import { Field,Type } from '@launchql/protobufjs';
import { Field,Type } from '@constructive-io/protobufjs';

import { NODE_TYPE } from '../../constants';
import { PgProtoParserOptions } from '../../options';
Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/parser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { parse } from '@launchql/protobufjs';
import { parse } from '@constructive-io/protobufjs';
import { readFileSync } from 'fs';

import {
Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/runtime-schema/generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Field, Namespace,Type } from '@launchql/protobufjs';
import { Field, Namespace,Type } from '@constructive-io/protobufjs';

import { FieldSpec,NodeSpec } from './types';

Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as t from '@babel/types';
import { Enum, Field, Namespace, ReflectionObject,Service, Type } from '@launchql/protobufjs';
import { Enum, Field, Namespace, ReflectionObject,Service, Type } from '@constructive-io/protobufjs';
import { mkdirSync } from 'fs';
import { dirname,join } from 'path';
import { jsStringify } from 'strfy-js';
Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/utils/deps.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Enum, Field,Type } from '@launchql/protobufjs';
import { Enum, Field,Type } from '@constructive-io/protobufjs';

import { NODE_TYPE } from '../constants';
import { isPrimitiveType } from './types';
Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/src/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Enum, Field, ReflectionObject } from '@launchql/protobufjs';
import { Enum, Field, ReflectionObject } from '@constructive-io/protobufjs';
import { writeFileSync } from 'fs';
import { basename,extname } from 'path';

Expand Down
2 changes: 1 addition & 1 deletion packages/proto-parser/test-utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { sync as glob } from 'glob'
import { getOptionsWithDefaults, PgProtoParserOptions } from '../src/options';
import { prettyPrint } from 'recast';
import { ProtoStore } from '../src/store';
import { parse } from '@launchql/protobufjs';
import { parse } from '@constructive-io/protobufjs';

export const printAst = (ast: any) => {
const results = generate(ast);
Expand Down
Loading
Loading