What is pg-minify?
pg-minify is an npm package designed to minify SQL queries. It removes unnecessary whitespace, comments, and other non-essential elements from SQL code, making it more compact and potentially improving performance when sending queries to a PostgreSQL database.
What are pg-minify's main functionalities?
Minify SQL Queries
This feature allows you to minify a given SQL query by removing unnecessary whitespace and comments. The example demonstrates how to use pg-minify to minify a simple SQL query.
const pgMinify = require('pg-minify');
const sql = 'SELECT * FROM users WHERE id = $1; -- Get user by ID';
const minifiedSQL = pgMinify(sql);
console.log(minifiedSQL); // Outputs: 'SELECT * FROM users WHERE id=$1;'
Error Handling
pg-minify provides error handling capabilities to catch and handle any issues that arise during the minification process. The example shows how to wrap the minification process in a try-catch block to handle potential errors.
const pgMinify = require('pg-minify');
try {
const sql = 'SELECT * FROM users WHERE id = $1; -- Get user by ID';
const minifiedSQL = pgMinify(sql);
console.log(minifiedSQL);
} catch (error) {
console.error('Error minifying SQL:', error);
}
Other packages similar to pg-minify
sql-minify
sql-minify is another npm package that offers similar functionality to pg-minify. It focuses on reducing the size of SQL queries by removing unnecessary whitespace and comments. However, it may not be as optimized for PostgreSQL-specific syntax as pg-minify.
sql-formatter
sql-formatter is a package that primarily focuses on formatting SQL queries to improve readability. While it can also minify SQL by removing unnecessary elements, its main purpose is to beautify SQL code, making it somewhat different from pg-minify, which focuses solely on minification.
pg-minify
Minifies a PostgreSQL script into a single line:
- Removes both
/*multi-line*/
and --single-line
comments - Concatenates multi-line strings into single-line with
\n
- Removes redundant line gaps: line breaks, tabs and spaces
- Flattens the resulting script into a single line
It also provides basic parsing and error reporting for invalid SQL.
Installing
$ npm install pg-minify
Testing
First, clone the repository and install DEV dependencies.
$ npm test
Testing with coverage:
$ npm run coverage
Usage
var minify = require('pg-minify');
var sql = "SELECT 1; -- comments";
minify(sql);
Error Handling
SQLParsingError is thrown on failed SQL parsing:
try {
minify("SELECT '1");
} catch (error) {
}
API
minify(sql, [options]) ⇒ String
Minifies SQL into a single line, according to the options
.
options.compress ⇒ Boolean
Compresses the SQL to its bare minimum that PostgreSQL can understand,
by removing all unnecessary spaces.
false (default)
- keep minimum spaces, for easier readtrue
- remove all unnecessary spaces
License
Copyright © 2016 Vitaly Tomilov;
Released under the MIT license.