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
62 changes: 32 additions & 30 deletions PUBLISH.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
# Publishing Guide

## Keeping the C source in sync

Each `versions/<n>/package.json` pins its libpg_query source in `x-publish`
(`libpgQueryRepo`, `libpgQueryTag`, `libpgQueryCommit`), and the Docker build uses
`emscripten/emsdk:6.0.3`. Every generated Makefile and the protobufs come from those pins,
and the pins ship in the published package.json.

To move a version to new C code, do all of this in one commit:

```bash
# 1. edit x-publish.libpgQueryCommit (full 40-char SHA) in versions/<n>/package.json
pnpm copy:templates # regenerate the Makefiles
pnpm fetch:protos # protos/<n>/pg_query.proto at the new commit
pnpm build:types && pnpm build:enums
cd versions/<n> && pnpm build && pnpm test
```

If you skip the build when publishing, `versions/<n>/wasm/` must have been built after the
last pin change, or the package will name one commit and ship another. After publishing,
`npm view libpg-query@pg<n> x-publish` should show the commit you expect.

`publish:pkg` also writes `x-publish.wasmSha256`, the sha256 of `wasm/libpg-query.wasm` and
`wasm/libpg-query.js`, into the published package.json. To verify a release, check out the
`gitHead` it was published from, run `pnpm wasm:build` in `versions/<n>`, and compare
`sha256sum wasm/libpg-query.*` with `npm view libpg-query@<version> x-publish.wasmSha256`.

## Automated Publishing (Recommended)

### Version Packages (libpg-query)
Expand All @@ -14,7 +40,7 @@ This interactive script will:
- Ask if you want to skip the build step (useful if already built)
- Always run tests (even if build is skipped)
- Publish each selected version
- Optionally promote pg17 to latest
- Optionally promote pg17 to latest (`latest` is currently pg18; to keep it there, answer no)

### Types Packages
```bash
Expand Down Expand Up @@ -56,16 +82,6 @@ PARSER_BUILD_TYPE=full pnpm run publish:parser
PARSER_BUILD_TYPE=lts pnpm run publish:parser
```

#### Latest Only (version 17)
```bash
PARSER_BUILD_TYPE=latest pnpm run publish:parser
```

#### Legacy Build (versions 13-15)
```bash
PARSER_BUILD_TYPE=legacy pnpm run publish:parser
```

This command will:
- Navigate to the parser directory
- Build the parser with the specified configuration
Expand Down Expand Up @@ -241,19 +257,15 @@ pnpm publish
The parser package is now a simple distribution package that copies pre-built WASM files. No TypeScript compilation needed!

#### Available Build Types:
- **full**: All versions (13, 14, 15, 16, 17) - Default
- **lts**: LTS versions only (16, 17)
- **latest**: Latest version only (17)
- **legacy**: Legacy versions (13, 14, 15)
- **full**: All versions (13, 14, 15, 16, 17, 18) - Default
- **lts**: LTS versions only (15, 16, 17, 18)

```bash
# Full build (default)
npm run build

# Specific builds
# LTS build
npm run build:lts
npm run build:latest
npm run build:legacy

# Or using environment variable
PARSER_BUILD_TYPE=lts npm run build
Expand All @@ -275,11 +287,11 @@ The templates automatically adjust to include only the versions specified in the
**Important**: Before building the parser package, ensure that the version packages are built first:
```bash
# Build all version packages first
pnpm build # builds libpg-query versions
pnpm build:versions

# Then build the parser with desired configuration
cd parser
npm run build:lts # or build:full, build:latest, etc.
npm run build:lts # or build:full
```

### Types Bundling
Expand All @@ -299,10 +311,6 @@ npm publish
# Publish LTS version with lts tag
npm run build:lts
npm publish --tag lts

# Publish legacy version with legacy tag
npm run build:legacy
npm publish --tag legacy
```

### What it does
Expand All @@ -318,12 +326,6 @@ npm publish --tag legacy
# Install latest (full build)
npm install @pgsql/parser

# Install LTS version
npm install @pgsql/parser@lts

# Install legacy version
npm install @pgsql/parser@legacy

# Use version-specific imports:
# import { parse } from '@pgsql/parser/v17'
# import { parse } from '@pgsql/parser/v16'
Expand Down
8 changes: 4 additions & 4 deletions REPO_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ Versions with `x-publish.fullApi: true` (currently 18) are generated from the
full-API templates in `templates/full/` and export the full API
(parse, parsePlPgSQL, scan, fingerprint, normalize + sync variants);
the other versions use the slim (parse-only) templates.
⚠️ Note: the Makefiles for 15/17/18 have been hand-edited to point at
constructive-io/libpg_query branches; `copy:templates` regenerates Makefiles
with the pganalyze repo URL, so re-apply the repo override if you regenerate.
Each version's libpg_query source (repo, branch/tag and exact commit) comes from
`x-publish` in its package.json, so `copy:templates` regenerates every Makefile
as-is — 15/17/18 point at constructive-io/libpg_query branches, pinned by commit.

## Code Duplication 📋

Expand All @@ -21,7 +21,7 @@ with the pganalyze repo URL, so re-apply the repo override if you regenerate.
- `versions/*/src/index.ts` are nearly identical except for version numbers
- `versions/*/src/wasm_wrapper.c` are identical
- `versions/*/Makefile` differ only in:
- `LIBPG_QUERY_TAG` version
- `LIBPG_QUERY_REPO` / `LIBPG_QUERY_TAG` / `LIBPG_QUERY_COMMIT`
- Version 13 has an extra emscripten patch

## Consistency Issues 🔧
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
"build:parser": "pnpm --filter @pgsql/parser build",
"build:parser:lts": "PARSER_BUILD_TYPE=lts pnpm --filter @pgsql/parser build",
"build:parser:full": "PARSER_BUILD_TYPE=full pnpm --filter @pgsql/parser build",
"build:parser:legacy": "PARSER_BUILD_TYPE=legacy pnpm --filter @pgsql/parser build",
"test:parser": "pnpm --filter @pgsql/parser test",
"publish:parser": "pnpm --filter @pgsql/parser publish"
},
Expand Down
41 changes: 23 additions & 18 deletions scripts/copy-templates.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,27 @@ function loadVersionConfigs() {
console.log(`Found ${packageFiles.length} package.json files\n`);

packageFiles.forEach(packageFile => {
try {
const packageData = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
const version = packageData['x-publish']?.pgVersion;
const libpgQueryTag = packageData['x-publish']?.libpgQueryTag;
const fullApi = packageData['x-publish']?.fullApi === true;

if (version && libpgQueryTag) {
configs[version] = {
tag: libpgQueryTag,
hasEmscriptenPatch: version === '13', // Only version 13 needs the patch
fullApi
};
console.log(` Version ${version}: tag ${libpgQueryTag}${fullApi ? ' (full API)' : ''}`);
} else {
console.warn(` Warning: Missing x-publish data in ${packageFile}`);
const packageData = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
const version = packageData['x-publish']?.pgVersion;
const libpgQueryTag = packageData['x-publish']?.libpgQueryTag;
const libpgQueryRepo = packageData['x-publish']?.libpgQueryRepo;
const libpgQueryCommit = packageData['x-publish']?.libpgQueryCommit;
const fullApi = packageData['x-publish']?.fullApi === true;

if (version && libpgQueryTag) {
if (!libpgQueryRepo || !/^[0-9a-f]{40}$/.test(libpgQueryCommit || '')) {
throw new Error(`${packageFile}: x-publish needs libpgQueryRepo and a full 40-char libpgQueryCommit`);
}
} catch (error) {
console.error(` Error reading ${packageFile}: ${error.message}`);
configs[version] = {
tag: libpgQueryTag,
repo: libpgQueryRepo,
commit: libpgQueryCommit,
hasEmscriptenPatch: version === '13', // Only version 13 needs the patch
fullApi
};
console.log(` Version ${version}: ${libpgQueryTag} @ ${libpgQueryCommit.slice(0, 7)}${fullApi ? ' (full API)' : ''}`);
} else {
console.warn(` Warning: Missing x-publish data in ${packageFile}`);
}
});

Expand Down Expand Up @@ -106,6 +109,8 @@ function copyTemplates() {
// Process Makefile template
const makefileTemplate = fs.readFileSync(path.join(templatesDir, 'Makefile.template'), 'utf8');
let makefileContent = makefileTemplate.replace(/{{VERSION_TAG}}/g, config.tag);
makefileContent = makefileContent.replace(/{{LIBPG_QUERY_REPO}}/g, config.repo);
makefileContent = makefileContent.replace(/{{LIBPG_QUERY_COMMIT}}/g, config.commit);
makefileContent = makefileContent.replace(
/{{EXPORTED_FUNCTIONS}}/g,
config.fullApi ? FULL_EXPORTED_FUNCTIONS : SLIM_EXPORTED_FUNCTIONS
Expand All @@ -132,7 +137,7 @@ function copyTemplates() {

// Write Makefile with header
fs.writeFileSync(path.join(versionDir, 'Makefile'), MAKEFILE_HEADER + makefileContent);
console.log(` ✓ Generated Makefile with tag ${config.tag}`);
console.log(` ✓ Generated Makefile with ${config.tag} @ ${config.commit.slice(0, 7)}`);
}

console.log('\n✅ Template copying completed!');
Expand Down
43 changes: 25 additions & 18 deletions scripts/fetch-protos.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ function getVersionMappings() {
pgVersion: pkg['x-publish'].pgVersion,
packageVersion: pkg.version,
distTag: pkg['x-publish'].distTag,
libpgQueryTag: pkg['x-publish'].libpgQueryTag
libpgQueryTag: pkg['x-publish'].libpgQueryTag,
libpgQueryRepo: pkg['x-publish'].libpgQueryRepo,
libpgQueryCommit: pkg['x-publish'].libpgQueryCommit
});
}
}
Expand All @@ -27,24 +29,24 @@ function getVersionMappings() {
return mappings;
}

// Download file from URL
// Download file from URL; dest is only written after a complete 200 response
function downloadFile(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
console.log('Downloading', url, 'to', dest);
https.get(url, (response) => {
if (response.statusCode === 200) {
response.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
} else {
if (response.statusCode !== 200) {
response.resume();
reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`));
return;
}
}).on('error', (err) => {
reject(err);
});
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
fs.writeFileSync(dest, Buffer.concat(chunks));
resolve();
});
response.on('error', reject);
}).on('error', reject);
});
}

Expand All @@ -61,19 +63,20 @@ async function fetchProtos() {
console.log('Fetching protobuf files for all versions...\n');

for (const mapping of mappings) {
const { pgVersion, libpgQueryTag } = mapping;
const { pgVersion, libpgQueryTag, libpgQueryRepo, libpgQueryCommit } = mapping;
const versionDir = path.join(protosDir, pgVersion);

// Create version directory
if (!fs.existsSync(versionDir)) {
fs.mkdirSync(versionDir, { recursive: true });
}

// Use the libpgQueryTag from the Makefile
const url = `https://raw.githubusercontent.com/pganalyze/libpg_query/refs/tags/${libpgQueryTag}/protobuf/pg_query.proto`;
// The same repo and commit the WASM is built from
const repoPath = new URL(libpgQueryRepo).pathname.replace(/^\/|\.git$/g, '');
const url = `https://raw.githubusercontent.com/${repoPath}/${libpgQueryCommit}/protobuf/pg_query.proto`;
const destPath = path.join(versionDir, 'pg_query.proto');

console.log(`Fetching protobuf for PostgreSQL ${pgVersion} with tag ${libpgQueryTag}...`);
console.log(`Fetching protobuf for PostgreSQL ${pgVersion} from ${repoPath} ${libpgQueryTag} @ ${libpgQueryCommit.slice(0, 7)}...`);

try {
await downloadFile(url, destPath);
Expand All @@ -82,6 +85,7 @@ async function fetchProtos() {
console.log(` Saved to: ${destPath}\n`);
} catch (error) {
console.log(`❌ Failed to fetch protobuf for PostgreSQL ${pgVersion}: ${error.message}\n`);
process.exitCode = 1;
}
}

Expand All @@ -90,7 +94,10 @@ async function fetchProtos() {

// Run the script
if (require.main === module) {
fetchProtos().catch(console.error);
fetchProtos().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}

module.exports = { fetchProtos, getVersionMappings };
18 changes: 17 additions & 1 deletion scripts/publish-single-version.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { execSync } = require('child_process');

const pkgPath = path.join(process.cwd(), 'package.json');
Expand All @@ -22,7 +23,22 @@ if (!original.name || !original.version) {
process.exit(1);
}

const modified = { ...original, name: publishName };
// Hashes of the Emscripten outputs, so anyone can rebuild from the x-publish pins and compare.
const wasmSha256 = {};
for (const file of ['wasm/libpg-query.wasm', 'wasm/libpg-query.js']) {
const filePath = path.join(process.cwd(), file);
if (!fs.existsSync(filePath)) {
console.error(`❌ ${file} not found; build this version first.`);
process.exit(1);
}
wasmSha256[file] = crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
}

const modified = {
...original,
name: publishName,
'x-publish': { ...publishMeta, wasmSha256 }
};

try {
console.log(`📦 Publishing ${publishName}@${original.version} with tag '${distTag}'...`);
Expand Down
Loading
Loading