Write a Custom PostgreSQL Lint Rule with @pgsql/lint

Dan Lynch

Dan Lynch

lesson header image

C3 checks references inside a function. Suppose your team also wants every function definition to name its schema. Write a separate rule for the name in CREATE FUNCTION.

Inspect the function definition

Save this as lint-rules.mjs:

javascript
import { defineRule } from '@pgsql/lint';

const id = 'qualified-function-name';

export const qualifiedFunctionName = defineRule({
	id,
	code: 'TEAM1',
	title: 'Function definitions must name their schema',
	reasonRequired: true,
	run(unit) {
		const name = unit.createFnStmt?.funcname;
		if (!Array.isArray(name) || name.length !== 1) return [];
		return [{ ruleId: id, line: 1, message: 'Use CREATE FUNCTION schema.name(...).' }];
	},
});

run receives the parsed function definition. Here, one name part means the function name has no schema. Return no findings for a qualified name, or report line 1 of the definition for an unqualified name. When linting a file, the linter translates that line into a file line number.

Assemble your linter

Save this as lint-sql.mjs at the project root:

javascript
import { createLinter, requireQualifiedRefs } from '@pgsql/lint';

import { qualifiedFunctionName } from './lint-rules.mjs';

const linter = createLinter({ rules: [requireQualifiedRefs, qualifiedFunctionName] });
const reports = await linter.lintFiles(['migrations']);
if (reports.length === 0) throw new Error('No SQL migrations found.');

for (const report of reports) {
	for (const finding of report.findings) {
		if (finding.acknowledged) continue;
		console.error(`${report.file}:${finding.line} ${finding.severity}: ${finding.message}`);
		if (finding.severity === 'error') process.exitCode = 1;
	}
}

createLinter runs the rules you pass in. Use [...LINT_RULES, qualifiedFunctionName] with the exported LINT_RULES if you want all built-ins. The stock CLI doesn't load your JavaScript module: run node lint-sql.mjs instead. You can share rules by exporting them from a package and importing them into another project's linter.

With the migration from lesson 1, the script passes. Remove app_public. from the function name but leave FROM app_public.documents intact. Run the script again: the custom rule reports the finding and exits with status 1. Restore the qualified name before continuing.

Next, run your linter in CI.