### Install from Source
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
Steps to clone the repository, configure, build, and install pgFormatter from its source code.
```bash
git clone https://github.com/darold/pgFormatter.git
cd pgFormatter
perl Makefile.PL
make
make test
sudo make install
```
--------------------------------
### pg_format.conf Configuration Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Example configuration file for pgformatter, specifying formatting options like spaces, keyword casing, and API enablement.
```plaintext
spaces=4
keyword-case=2
type-case=1
function-case=0
anonymize=0
nocomment=0
nogrouping=0
comma=end
format=html
wrap-limit=0
wrap-after=0
maxlength=100000
enable_api=1
```
--------------------------------
### Complete Configuration Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
A comprehensive example of a pgFormatter configuration file, showing settings for indentation, case transformations, comma positioning, output format, and comment handling.
```ini
####
# PostgreSQL formatter configuration
# Copy to ~/.pg_format or .pg_format or $XDG_CONFIG_HOME/pg_format/pg_format.conf
####
# Number of spaces for indentation
spaces=4
# Case transformations (0=unchanged, 1=lowercase, 2=uppercase, 3=capitalized)
keyword-case=2
type-case=1
function-case=0
# Comma position in parameter lists (start or end)
comma=end
# Output format (text or html)
format=text
# Remove comments from SQL
nocomment=0
```
--------------------------------
### Development Configuration File
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Example of a `.pg_format` configuration file to set default formatting options for a project.
```text
spaces=4
keyword-case=2
type-case=1
function-case=0
wrap-limit=120
wrap-comment=1
```
--------------------------------
### custom_css_file.css Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Example of a custom CSS file to override the default styles for HTML output, allowing for custom coloring of SQL elements.
```css
.kw1 { color: blue; font-weight: bold; }
.kw2 { color: purple; }
.st0 { color: green; }
```
--------------------------------
### Configuration File Format Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
A sample configuration file demonstrating various settings for indentation, case transformations, formatting style, and special options.
```ini
####
# pgFormatter configuration
####
# Indentation
spaces=4
tabs=0
# Case transformations
keyword-case=2
function-case=0
type-case=1
# Formatting style
comma=end
comma-break=0
nogrouping=0
format-type=0
keep-newline=0
# Comments
nocomment=0
wrap-comment=0
# Line wrapping
wrap-limit=0
wrap-after=0
# Special options
anonymize=0
numbering=0
no-extra-line=0
no-space-function=0
redundant-parenthesis=0
# Code protection
separator='
placeholder=
multiline=0
# Database-specific
extra-keyword=
extra-function=
```
--------------------------------
### Command-line Override Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Demonstrates how command-line options override settings in the configuration file. Explicitly provided options have the highest priority.
```bash
# Config file has: keyword-case=1
# This command overrides it:
pg_format --keyword-case 2 query.sql
# Result: keyword-case=2 is used
```
--------------------------------
### Example of Statement Numbering
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Demonstrates how the `numbering` option adds sequential comments before each SQL statement.
```sql
Input:
SELECT * FROM users; DELETE FROM old_data;
Output:
-- Statement 1
SELECT * FROM users;
-- Statement 2
DELETE FROM old_data;
```
--------------------------------
### Deploy as CGI Web Service
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
Install pgFormatter as a CGI script to enable web-based SQL formatting. Ensure correct permissions and path.
```bash
# Install as CGI script
cp pg_format /usr/lib/cgi-bin/pg_format.cgi
chmod +x /usr/lib/cgi-bin/pg_format.cgi
# Then access http://localhost/cgi-bin/pg_format.cgi
```
--------------------------------
### pgFormatter Configuration File Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cli.md
Illustrates the format of a pgFormatter configuration file, where each line specifies a key-value pair. These settings are applied unless overridden by command-line options.
```ini
spaces=4
keyword-case=2
type-case=1
function-case=0
comma=end
format=text
```
--------------------------------
### File Upload Form Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
HTML form example for uploading SQL or text files to be formatted by the pgformatter CGI script, including an option for anonymization.
```html
```
--------------------------------
### Example of Column List Wrapping with wrap-after
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Illustrates the effect of `wrap-after` on formatting column and table lists. This example shows wrapping after 2 columns.
```sql
Input:
SELECT a, b, c, d, e FROM t1, t2, t3 WHERE x = 1 AND y = 2
Output:
SELECT
a, b,
c, d,
e
FROM
t1, t2,
t3
WHERE
x = 1
AND y = 2
```
--------------------------------
### Use Docker Image for Formatting
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Examples of using the pgformatter Docker image to format SQL from stdin, a file, or with specific options.
```bash
# From stdin
cat query.sql | docker run --rm -i my-pgformatter -
# From file
docker run --rm -v $(pwd):/work my-pgformatter /work/query.sql
# With options
docker run --rm -i my-pgformatter -u 2 -s 2 -
```
--------------------------------
### Get and Set SQL Query
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Demonstrates the accessor method for getting the current SQL query and setting a new one. Setting the query automatically triggers preprocessing.
```perl
my $current_query = $beautifier->query();
$beautifier->query('SELECT * FROM table WHERE id = 1');
```
```perl
# Setting query automatically processes it
my $query = $beautifier->query('SELECT * FROM users');
# Query is now preprocessed and ready for beautify()
```
--------------------------------
### CLI Examples for Format Output Type
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Demonstrates command-line flags to set the output format to plain text or HTML. Use '-F' or '--format' followed by 'text' or 'html'.
```bash
pg_format -F text query.sql # Plain text
pg_format -F html query.sql # HTML
pg_format --format text query.sql
pg_format --format html query.sql
```
--------------------------------
### Basic SQL Formatting Example
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Demonstrates basic SQL query formatting using the pgFormatter::Beautify module. It shows how to set indentation width and keyword casing, then prints the formatted content.
```perl
use pgFormatter::Beautify;
my $fmt = pgFormatter::Beautify->new(
spaces => 4,
uc_keywords => 2, # uppercase
);
$fmt->query('SELECT id, name, email FROM users WHERE status=1 ORDER BY name');
$fmt->beautify();
print $fmt->content();
# Output:
# SELECT
# id,
# name,
# email
# FROM
# users
# WHERE
# status = 1
# ORDER BY
# name
```
--------------------------------
### HTML Output Example for Format Type
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Provides an example of the HTML output generated by pgFormatter when the format type is set to 'html'. This output includes CSS classes for styling.
```html
SELECT * FROM users;
```
--------------------------------
### CLI Examples for Case Transformation
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Demonstrates how to use command-line flags to set keyword, function, and type case transformations. Each flag corresponds to an integer value (0-3) for specific casing.
```bash
# Keyword case options
pg_format -u 0 query.sql # unchanged (keep original)
pg_format -u 1 query.sql # lowercase
pg_format -u 2 query.sql # UPPERCASE
pg_format -u 3 query.sql # Capitalized
# Function case options
pg_format -f 0 query.sql # unchanged
pg_format -f 1 query.sql # lowercase
pg_format -f 2 query.sql # UPPERCASE
pg_format -f 3 query.sql # Capitalized
# Type case options
pg_format -U 0 query.sql # unchanged
pg_format -U 1 query.sql # lowercase
pg_format -U 2 query.sql # UPPERCASE
pg_format -U 3 query.sql # Capitalized
```
--------------------------------
### SQL Case Transformation Output Examples
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Illustrates the output of SQL formatting with different case transformation settings. Compares 'unchanged', 'uppercase', and 'capitalized' for keywords, functions, and types.
```sql
-- Input SQL:
select count(*) as cnt, lower(name) from users where id=1 group by id order by cnt;
-- Output with uc_keywords=0, uc_functions=0, uc_types=0:
select
count(*) as cnt,
lower(name)
from
users
where
id = 1
group by
id
order by
cnt
-- Output with uc_keywords=2, uc_functions=2, uc_types=2:
SELECT
COUNT(*) AS cnt,
LOWER(name)
FROM
users
WHERE
id = 1
GROUP BY
id
ORDER BY
cnt
-- Output with uc_keywords=3, uc_functions=3, uc_types=3:
Select
Count(*) As cnt,
Lower(name)
From
users
Where
id = 1
Group By
id
Order By
cnt
```
--------------------------------
### Example of Line Wrapping with wrap-limit
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Demonstrates how `wrap-limit` affects query formatting. Long column names are wrapped to fit the specified limit.
```sql
Input:
SELECT very_long_column_name_1, very_long_column_name_2 FROM table
Output:
SELECT
very_long_column_name_1,
very_long_column_name_2
FROM
table
```
--------------------------------
### Exit Code Examples
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Demonstrates the usage of pg_format command with different arguments and their corresponding exit codes, indicating success or specific error conditions.
```bash
pg_format query.sql
# Exit code: 0 (success)
```
```bash
pg_format -u 9 query.sql
# Exit code: 2 (invalid case value)
```
```bash
pg_format --help
# Exit code: 0 (help displayed successfully)
```
```bash
pg_format --invalid-option
# Exit code: 1 (invalid option error)
```
--------------------------------
### Custom Configuration via pg_format.conf
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Example of a custom pg_format.conf file to set formatting preferences like spaces, keyword casing, and API enablement. Changes require restarting the CGI script.
```plaintext
spaces=2
keyword-case=1
function-case=2
maxlength=50000
enable_api=1
```
--------------------------------
### JSON API Request and Response
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Example of making a POST request to the pgformatter JSON API with content and formatting options, and the expected JSON response.
```bash
curl -X POST http://example.com/cgi-bin/pg_format.cgi \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{
"content": "SELECT * FROM users WHERE id=1",
"spaces": 4,
"uc_keyword": 2
}'
# Response
{
"status": "success",
"result": "SELECT\n *\nFROM\n users\nWHERE\n id = 1",
"error": null
}
```
--------------------------------
### SQL Comma Positioning Output Examples
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Compares the output of SQL formatting with commas placed at the end of lines versus the beginning. Demonstrates the visual difference in code structure.
```sql
-- Input:
SELECT id, name, email, created_at FROM users WHERE status = 1;
-- Output with comma=end (default):
SELECT
id,
name,
email,
created_at
FROM
users
WHERE
status = 1
-- Output with comma=start:
SELECT
id
, name
, email
, created_at
FROM
users
WHERE
status = 1
```
--------------------------------
### CLI Examples for Comma Positioning
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Shows command-line usage for controlling comma placement in formatted SQL. Use '-e' or '--comma-end' for end-of-line commas and '-b' or '--comma-start' for beginning-of-line commas.
```bash
# Comma at end (default)
pg_format -e query.sql
pg_format --comma-end query.sql
# Comma at start
pg_format -b query.sql
pg_format --comma-start query.sql
```
--------------------------------
### Perl API Examples for Case Transformation
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Shows how to configure case transformations (keywords, functions, types) using the pgFormatter::Beautify Perl API. Instantiate the beautifier with specific options for desired casing.
```perl
use pgFormatter::Beautify;
# Uppercase keywords, lowercase types, default functions
my $fmt = pgFormatter::Beautify->new(
uc_keywords => 2, # KEYWORDS
uc_functions => 0, # unchanged
uc_types => 1, # lowercase
);
# All uppercase
my $fmt = pgFormatter::Beautify->new(
uc_keywords => 2, # KEYWORDS
uc_functions => 2, # FUNCTIONS
uc_types => 2, # TYPES
);
# Capitalized
my $fmt = pgFormatter::Beautify->new(
uc_keywords => 3, # Keywords
uc_functions => 3, # Functions
uc_types => 3, # Types
);
```
--------------------------------
### Using Configuration File via CLI (Perl)
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cli.md
Example of invoking pgFormatter using the Perl API, specifying a custom configuration file ('/etc/pgformat.conf') and an input SQL file ('query.sql').
```perl
#!/usr/bin/env perl
use pgFormatter::CLI;
my $cli = pgFormatter::CLI->new();
@ARGV = ('--config', '/etc/pgformat.conf', 'query.sql');
$cli->run();
```
--------------------------------
### Placeholder Regex Examples
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Illustrates different Perl regular expressions that can be used to define placeholders for protecting specific code sections during formatting.
```perl
# Example: Protect <<...>> syntax
my $placeholder = '<<[^>]+>>';
```
```perl
# Example: Protect URLs in comments
my $placeholder = 'https?://\S+';
```
```perl
# Example: Protect template variables
my $placeholder = '\$\{[^}]+\}';
```
--------------------------------
### Automated Code Style with Pre-commit Hook
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
Integrate pgFormatter into a Git pre-commit hook to automatically format SQL files before committing. This example sets a wrap limit of 120 characters.
```bash
# In pre-commit hook
pg_format -i --wrap-limit 120 "*.sql"
```
--------------------------------
### Get Help and Debug pgFormatter
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Access help information (--help, -h) and version details (--version, -v). Enable debug mode (-d) for verbose output, which can be redirected to a log file.
```bash
# Show help
pg_format --help
pg_format -h
```
```bash
# Show version
pg_format --version
pg_format -v
```
```bash
# Debug mode (verbose output)
pg_format -d query.sql
```
```bash
# Debug with file
pg_format -d -o formatted.sql query.sql 2> debug.log
```
--------------------------------
### Combine pgFormatter Options for Specific Outputs
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Examples of combining multiple flags to achieve specific formatting styles like production-ready, safe sharing (anonymized), code review, readable, or compact formats.
```bash
# Production-ready formatting
pg_format -i -u 2 -U 1 -w 100 -C query.sql
```
```bash
# Safe sharing (anonymize)
pg_format -a -n -o safe.sql query.sql
```
```bash
# Code review formatting
pg_format -u 2 -f 2 -w 80 -o review.sql query.sql
```
```bash
# Readable format (2 spaces, capitalized)
pg_format -s 2 -u 3 -f 3 -U 3 query.sql
```
```bash
# Compact format (2 spaces, no grouping, wrap after 2)
pg_format -s 2 -g -W 2 query.sql
```
--------------------------------
### Separator Regex Examples
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Shows examples of Perl regular expressions used to define separators for detecting dynamic code blocks. The default is a single quote.
```perl
# Default: single quote
my $separator = "'";
```
```perl
# Alternative: dollar quote
my $separator = "$$";
```
```perl
# Custom: any string (usually short)
my $separator = "DELIMITER";
```
--------------------------------
### Load configuration from file
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Use the -c or --config option to load formatting configuration from a specified file.
```bash
pg_format -c ~/.my_pgformat query.sql
pg_format --config /etc/pgformat.conf query.sql
```
--------------------------------
### Build and Run Docker Image
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
Build a Docker image for pgFormatter and run it to format SQL input from stdin.
```bash
docker build -t pgformatter .
docker run --rm -i pgformatter -
```
--------------------------------
### content()
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Accessor to get the formatted SQL content after beautification. It can also be used to set new content.
```APIDOC
## content()
### Description
Accessor to get the formatted SQL content after beautification. It can also be used to set new content.
### Method
GET/SET
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **$new_value** (string) - Optional - Content to set
### Request Example
```perl
my $formatted_sql = $beautifier->content();
$beautifier->content($new_content);
```
### Response
#### Success Response (200)
- **formatted_sql** (string) - The formatted SQL string.
#### Response Example
```perl
"SELECT * FROM \"users\" WHERE id = 1"
```
```
--------------------------------
### Get Formatted Content in HTML
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Formats the SQL query and retrieves the result as HTML, suitable for syntax highlighting.
```perl
# Get formatted content in HTML format
$beautifier->format('html');
$beautifier->beautify();
my $html = $beautifier->content();
```
--------------------------------
### Apply Development Configuration
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Command to apply the project's `.pg_format` configuration to all SQL files in the current directory.
```bash
pg_format -i *.sql
```
--------------------------------
### pgFormatter::Beautify->query
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Accessor method to get or set the SQL query to be formatted. It performs preprocessing of the query.
```APIDOC
## pgFormatter::Beautify->query
### Description
Accessor method to get or set the SQL query to be formatted. Performs initial preprocessing of the query including escaping, constant preservation, and dynamic code handling.
### Method
query
### Parameters
- **$new_value** (string) - Optional - SQL query to set
### Returns
string (processed query if setting, current query if getting)
### Preprocessing Steps:
1. Stores COMMENT constants between quotes
2. Escapes backslashes, single quotes, and double quotes
3. Stores alias constants (double-quoted identifiers)
4. Escapes quotes in comments
5. Preserves single-quoted constants
6. Hides format() function arguments
7. Extracts and preserves function code blocks
8. Preserves dollar-quoted constants
9. Applies placeholder regex to protect specified code sections
10. Removes dynamic code and operators
### Usage Examples:
```perl
$beautifier->query(); # Get current query
$beautifier->query('SELECT * FROM table WHERE id = 1'); # Set query
# Setting query automatically processes it
my $query = $beautifier->query('SELECT * FROM users');
# Query is now preprocessed and ready for beautify()
```
```
--------------------------------
### Manage pgFormatter Configuration Files
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Demonstrates how to specify a custom configuration file (-c), disable all config file loading (-X), or rely on default search paths (./.pg_format or ~/.pg_format) and XDG config directory.
```bash
# Use specific config file
pg_format -c ~/.pgformat_custom query.sql
```
```bash
# Don't load any config files
pg_format -X query.sql
```
```bash
# Use default config file search (if exists)
pg_format query.sql # Loads ./.pg_format or ~/.pg_format
```
```bash
# Use XDG config directory
pg_format query.sql # Loads $XDG_CONFIG_HOME/pg_format/pg_format.conf
```
--------------------------------
### Example of Query Anonymization
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Shows how the `anonymize` option transforms sensitive string literals into hashed values within a SQL query.
```sql
Input:
SELECT * FROM users WHERE email = 'user@example.com' AND password = 'secret123'
Output:
SELECT * FROM users WHERE email = '1a2b3c4d' AND password = '5e6f7g8h'
```
--------------------------------
### Format SQL Files with pgFormatter
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Demonstrates basic command-line usage for formatting single or multiple SQL files, saving to a new file, or processing from standard input.
```bash
# Format a single file
pg_format query.sql
```
```bash
# Format and save to new file
pg_format -o formatted.sql query.sql
```
```bash
# Format multiple files (each processed independently)
pg_format *.sql
```
```bash
# Format from stdin
echo "SELECT * FROM users" | pg_format
```
```bash
# Interactive stdin
pg_format
SELECT * FROM users;
```
--------------------------------
### Get Default CSS Styles
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Retrieves the default CSS styles used for HTML output. These styles can be overridden by providing a custom_css_file.css.
```perl
my $css = $cgi->default_styles();
```
```perl
my $css = $cgi->default_styles();
print "";
```
--------------------------------
### All CLI Methods
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/README.md
Lists all available methods for the Command Line Interface (CLI). These are used when running pgFormatter from the terminal.
```text
new() run() get_command_line_args()
validate_args() load_sql() beautify()
save_output() show_help_and_die() logmsg()
```
--------------------------------
### Basic Configuration File
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Sets basic formatting options like spaces, keyword case, and comma placement in the .pg_format configuration file.
```config
spaces=4
keyword-case=2
type-case=1
function-case=0
comma=end
```
--------------------------------
### Get and Set Formatted SQL Content
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Access the formatted SQL result after beautification. Can also be used to set content manually.
```perl
my $formatted_sql = $beautifier->content();
$beautifier->content($new_content); # Also supports setting
```
--------------------------------
### Oracle-Style Formatting Configuration
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Configure pgformatter for Oracle-style formatting, which includes a specific number of spaces and comma placement at the start of lines.
```ini
spaces=3
keyword-case=0
comma=start
```
--------------------------------
### Run the pgFormatter CLI
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cli.md
Execute the main entry point of the CLI to process SQL formatting. This method orchestrates argument parsing, input loading, beautification, and output writing.
```perl
my $cli = pgFormatter::CLI->new();
$cli->run();
```
--------------------------------
### JSON API Request using curl
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Example of sending a POST request to the pgformatter CGI script with JSON payload using curl.
```bash
curl -X POST http://localhost/cgi-bin/pg_format.cgi \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{
"content": "SELECT * FROM users WHERE id=1",
"spaces": 4,
"uc_keyword": 2,
"uc_function": 0,
"uc_type": 1
}'
```
--------------------------------
### Run Tests
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
Execute the test suite for pgFormatter using the make command.
```bash
make test
```
--------------------------------
### Basic Formatting from Stdin (Perl)
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cli.md
Demonstrates the simplest way to use pgFormatter via its Perl API, reading SQL from standard input and writing formatted SQL to standard output.
```perl
#!/usr/bin/env perl
use pgFormatter::CLI;
my $cli = pgFormatter::CLI->new();
$cli->run(); # Reads from stdin, writes to stdout
```
--------------------------------
### Compact Formatting Configuration
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Use this configuration to achieve a more compact output format. It sets the number of spaces, keyword case, and line wrapping limits.
```ini
spaces=2
keyword-case=1
wrap-limit=100
wrap-after=3
```
--------------------------------
### HTML Web Interface Access
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Examples of accessing the pgformatter CGI script via a web browser and using curl to send POST data for formatting.
```bash
# Access in browser
http://example.com/cgi-bin/pg_format.cgi
# POST with form data
curl -X POST http://example.com/cgi-bin/pg_format.cgi \
-d "content=SELECT+*+FROM+users"
-d "spaces=2"
```
--------------------------------
### sanitize_params
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Validates and corrects parameter values to acceptable ranges, resetting invalid values to defaults. It can also truncate query content and load example queries.
```APIDOC
## sanitize_params
### Description
Validates and corrects parameter values to acceptable ranges, resetting invalid values to defaults. It can also truncate query content and load example queries.
### Method
Perl Method
### Endpoint
N/A
### Parameters
None
### Request Example
```perl
$cgi->sanitize_params();
```
### Response
#### Success Response
void
### Response Example
void
```
--------------------------------
### JSON API Response Format
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Example of the JSON response returned by the pgFormatter CGI API. It includes the status, the formatted SQL result, and any error messages.
```json
{
"status": "success",
"result": "SELECT\n *\nFROM\n users",
"error": null
}
```
--------------------------------
### JSON API Request Format
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Example of the JSON payload expected by the pgFormatter CGI API for formatting SQL queries. Includes various formatting options.
```json
{
"content": "SELECT * FROM users",
"spaces": 4,
"uc_keyword": 2,
"uc_function": 0,
"uc_type": 1,
"format": "text",
"anonymize": 0,
"nocomment": 0,
"comma": "end",
"comma_break": 0,
"wrap_after": 0,
"separator": "",
"format_type": 0,
"numbering": 0,
"redshift": 0,
"keep_newline": 0,
"nogrouping": 0,
"no_space_function": 0,
"redundant_parenthesis": 0,
"colorize": 0
}
```
--------------------------------
### Internal Beautifier Configuration Hash
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
An example of the internal hash used by pgformatter to store and manage formatting configurations. It includes settings for input/output, formatting options, case transformations, and more.
```perl
my $self = {
# Input/Output
query => '',
content => '',
format => 'text',
# Formatting options
spaces => 4,
space => ' ',
break => "\n",
# Case transformations
uc_keywords => 2,
uc_functions => 0,
uc_types => 1,
# Comma and spacing
comma => 'end',
comma_break => 0,
no_space_function => 0,
# Comments
no_comments => 0,
wrap_comment => 0,
# Line wrapping
wrap_limit => 0,
wrap_after => 0,
# Special handling
placeholder => undef,
placeholder_values => [],
multiline => 0,
separator => "'",
no_grouping => 0,
numbering => 0,
format_type => 0,
no_extra_line => 0,
keep_newline => 0,
redundant_parenthesis=> 0,
colorize => 1,
# Dictionaries
keywords => [],
functions => [],
dict => {}, # SQL dictionaries
# Internal state
_level => 0,
_new_line => 1,
_is_in_function => 0,
# ... many other internal state variables
};
```
--------------------------------
### Create a new pgFormatter::CGI instance
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Initializes a new CGI instance for pgFormatter. This method sets up the configuration and prepares the object for use.
```perl
my $cgi = pgFormatter::CGI->new();
```
--------------------------------
### show_help_and_die
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cli.md
Displays help message with all options and exits the program. Can optionally print an error message to STDERR before displaying help.
```APIDOC
## show_help_and_die
### Description
Displays help message with all options and exits program.
### Method
```perl
$cli->show_help_and_die($status, $format, @args)
```
### Parameters:
#### Path Parameters
- **$status** (integer) - Required - Exit code (0 for normal, >0 for error)
- **$format** (string) - Optional - Error message format string (printf style)
- **@args** (list) - Optional - Arguments for format string
### Returns
void (exits program)
### Behavior:
- If $status is non-zero, prints error message to STDERR before help
- Prints full help text to STDERR (if $status != 0) or STDOUT (if $status == 0)
- Exits with provided $status code
### Usage Example:
```perl
$cli->show_help_and_die(0) if $cfg{'help'};
$cli->show_help_and_die(2, "Invalid option: %s", $option);
```
```
--------------------------------
### Comma Position String Values
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Defines string values for comma positioning options. Use 'end' for commas at the end of a line (default) or 'start' for commas at the beginning of a line.
```perl
'end' => Comma at end of line (default)
'start' => Comma at beginning of line
```
--------------------------------
### Using Extra Keywords for Database-Specific Formatting
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Load custom keywords or internal RedShift keywords for formatting. This can be done via a configuration file or directly on the command line.
```bash
# Use instead:
pg_format --extra-keyword redshift query.sql
```
```bash
# In config file
extra-keyword=/opt/pgformat/epas.kw
extra-keyword=redshift
# On command line
pg_format --extra-keyword /opt/pgformat/keywords.txt query.sql
pg_format --extra-keyword redshift query.sql
```
--------------------------------
### Control Comma Positioning with pgFormatter
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Demonstrates options for comma placement: at the end of a line (default), at the start of a line (-b), or adding a newline after each comma in INSERT statements (-B).
```bash
# Comma at end of line (default)
pg_format -e query.sql
```
```bash
# Comma at start of line
pg_format -b query.sql
```
```bash
# Add newline after each comma in INSERT
pg_format -B query.sql
```
```bash
# Both: comma at start AND newline in INSERT
pg_format -b -B query.sql
```
--------------------------------
### Build Docker Image for pgformatter
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Command to build a Docker image tagged as 'my-pgformatter' from the current directory.
```bash
docker build -t my-pgformatter .
```
--------------------------------
### Access Configuration Settings
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Demonstrates how to access configuration settings after they have been loaded. Settings are stored in the CGI object's hash.
```perl
my $cgi = pgFormatter::CGI->new();
# set_config() is called automatically in new()
# Access settings:
print $cgi->{'spaces'}; # 4
print $cgi->{'uc_keyword'}; # 2
```
--------------------------------
### Generate Formatted SQL Documentation
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Bash script to generate HTML documentation for SQL files by formatting them with pgformatter.
```bash
#!/bin/bash
# Generate formatted SQL documentation
mkdir -p docs/sql
for sql_file in *.sql; do
base=$(basename "$sql_file" .sql)
pg_format -F html "$sql_file" > "docs/sql/${base}.html"
done
echo "Documentation generated in docs/sql/"
```
--------------------------------
### Control Comma Placement
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/configuration.md
Determine whether commas in parameter lists appear at the start or end of lines. Set in a config file or using -e/--comma-end or -b/--comma-start.
```properties
comma=end
```
```bash
pg_format -e query.sql
pg_format -b query.sql
pg_format --comma-end query.sql
pg_format --comma-start query.sql
```
--------------------------------
### Command-Line Interface
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
The Command-Line Interface allows users to format SQL files directly from the terminal or via standard input.
```APIDOC
## Command-Line Interface
### Description
Format SQL files or standard input using the `pg_format` command.
### Usage
```bash
pg_format [options] file.sql
pg_format [options] -
cat query.sql | pg_format [options]
```
### Key Methods
- `pgFormatter::CLI->new()`
- `$cli->run()`
```
--------------------------------
### Configure Line Wrapping with pgFormatter
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Demonstrates setting the maximum line width for code wrapping (-w) and column list wrapping (-W). Multiple wrap limits can be applied simultaneously.
```bash
# Wrap at 80 characters
pg_format -w 80 query.sql
```
```bash
# Wrap at 120 characters
pg_format -w 120 query.sql
```
```bash
# Wrap column lists after 4 items
pg_format -W 4 query.sql
```
```bash
# Wrap code at 100 chars AND comments at 80 chars
pg_format -w 100 -C -w 80 query.sql # Both wrap-limits apply
```
```bash
# Wrap with different settings
pg_format -w 100 -W 3 query.sql # Code wrapped at 100, lists after 3 cols
```
--------------------------------
### Create pgFormatter::Beautify Instance
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Creates a new Beautify formatter instance with specified options. This is the primary way to initialize the formatter with custom settings.
```perl
my $beautifier = pgFormatter::Beautify->new(
query => 'SELECT * FROM users',
spaces => 4,
uc_keywords => 2,
format => 'text'
);
```
--------------------------------
### Production Deployment Configuration (Lowercase)
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Configuration optimized for production, enforcing lowercase keywords and specific wrapping limits.
```config
spaces=4
keyword-case=1
type-case=1
function-case=1
comma=end
wrap-limit=100
no-extra-line=1
```
--------------------------------
### Perl API: Simple SQL Formatting
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Demonstrates basic SQL query formatting using the pgFormatter::Beautify Perl module.
```perl
#!/usr/bin/perl
use strict;
use warnings;
use pgFormatter::Beautify;
my $fmt = pgFormatter::Beautify->new();
$fmt->query('SELECT id, name FROM users WHERE id = 1');
$fmt->beautify();
print $fmt->content();
```
--------------------------------
### Basic Beautify Usage
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Demonstrates basic usage of the pgFormatter::Beautify class with default options. The query is set, beautified, and the formatted content is printed.
```perl
my $beautifier = pgFormatter::Beautify->new();
$beautifier->query('SELECT id, name FROM users');
$beautifier->beautify();
print $beautifier->content();
```
--------------------------------
### pgFormatter::Beautify->new
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Creates a new pgFormatter::Beautify instance. This method initializes the formatter with specified options for SQL query beautification.
```APIDOC
## pgFormatter::Beautify->new
### Description
Creates a new Beautify formatter instance with specified options.
### Method
new
### Parameters (hash)
- **break** (string) - Optional - Line break character
- **colorize** (boolean) - Optional - Apply CSS styles to HTML output
- **comma** ('end' or 'start') - Optional - Comma position in parameter lists
- **comma_break** (boolean) - Optional - Add newline after each comma in INSERT
- **format** ('text' or 'html') - Optional - Output format
- **format_type** (boolean) - Optional - Use alternative formatting for some statements
- **functions** (arrayref) - Optional - List of function names to recognize
- **keep_newline** (boolean) - Optional - Preserve empty lines in PL/pgSQL
- **keywords** (arrayref) - Optional - List of keyword names to recognize
- **maxlength** (integer) - Optional - Maximum query length (0 = no limit)
- **multiline** (boolean) - Optional - Use multi-line regex for placeholders
- **no_comments** (boolean) - Optional - Remove all comments from query
- **no_extra_line** (boolean) - Optional - Don't add extra line at end of output
- **no_grouping** (boolean) - Optional - Add newline between statements in transaction
- **no_space_function** (boolean) - Optional - Remove space before function call parenthesis
- **numbering** (boolean) - Optional - Add statement numbering as comment
- **placeholder** (string) - Optional - Regex pattern for code that must not be changed
- **query** (string) - Optional - SQL query to format
- **redshift** (boolean) - Optional - Add RedShift keywords (use extra_keyword instead)
- **redundant_parenthesis** (boolean) - Optional - Keep redundant parenthesis in DML
- **rules** (hashref) - Optional - Custom formatting rules
- **separator** (string) - Optional - Dynamic code separator (for EXECUTE, format())
- **space** (string) - Optional - Indentation character (' ' or "\t")
- **spaces** (integer) - Optional - Number of spaces for indentation
- **uc_functions** (0-3) - Optional - Function name case: 0=unchanged, 1=lower, 2=upper, 3=capitalized
- **uc_keywords** (0-3) - Optional - Keyword case: 0=unchanged, 1=lower, 2=upper, 3=capitalized
- **uc_types** (0-3) - Optional - Type case: 0=unchanged, 1=lower, 2=upper, 3=capitalized
- **wrap** (hashref) - Optional - Wrapping configuration
- **wrap_after** (integer) - Optional - Wrap column lists after N columns (0 = each on own line)
- **wrap_comment** (boolean) - Optional - Apply wrapping to comments
- **wrap_limit** (integer) - Optional - Wrap queries at character length (0 = no wrap)
### Returns
blessed pgFormatter::Beautify object
### Behavior
- Calls `set_defaults()` to initialize defaults
- Calls `_refresh_functions_re()` to compile function regex
- Initializes internal state variables for parsing
### Throws
Dies if invalid `comma` value (resets to 'end')
### Usage Examples
```perl
# Basic usage with defaults
my $beautifier = pgFormatter::Beautify->new();
$beautifier->query('SELECT id, name FROM users');
$beautifier->beautify();
print $beautifier->content();
# With custom options
my $fmt = pgFormatter::Beautify->new(
spaces => 2,
uc_keywords => 1, # lowercase
format => 'html'
);
$fmt->query('SELECT * FROM table');
$fmt->beautify();
print $fmt->content();
# With placeholder protection
my $fmt = pgFormatter::Beautify->new(
placeholder => '<<[^>]+>>' # Protect <<...>> syntax
);
```
```
--------------------------------
### Development Configuration (All Changes Visible)
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Configuration for development environments, ensuring all changes are visible with specific casing and newline settings.
```config
spaces=4
keyword-case=0
function-case=0
type-case=0
comma=end
keep-newline=1
nocomment=0
```
--------------------------------
### Batch Format SQL Files
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
Iterate through all .sql files in the current directory and format them in-place using the -i option.
```bash
for f in *.sql;
do
pg_format -i "$f"
done
```
--------------------------------
### Specify output file
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/types-and-enums.md
Use the -o or --output option to direct formatted output to a file. Use '-' for stdout.
```bash
pg_format -o formatted.sql query.sql
pg_format --output result.sql query.sql
```
--------------------------------
### All Beautify Methods
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/README.md
Lists all available methods for the Beautify API. These are the functions used to interact with the formatter.
```text
new() query() content()
beautify() anonymize() format()
wrap_lines() add_functions() add_keywords()
tokenize_sql() highlight_code() set_defaults()
set_dicts()
```
--------------------------------
### Control Keyword Case with pgFormatter
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/usage-examples.md
Shows how to adjust the casing of SQL keywords (uppercase, lowercase, capitalized) and functions using the -u, -f, and -U flags.
```bash
# Default: uppercase keywords
pg_format query.sql
```
```bash
# Lowercase keywords
pg_format -u 1 query.sql
```
```bash
# Capitalized keywords
pg_format -u 3 query.sql
```
```bash
# Uppercase keywords and functions
pg_format -u 2 -f 2 query.sql
```
```bash
# All uppercase (keywords, functions, types)
pg_format -u 2 -f 2 -U 2 query.sql
```
```bash
# Preserve original case
pg_format -u 0 -f 0 -U 0 query.sql
```
--------------------------------
### Format File with Specific Options (Perl)
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cli.md
Shows how to format a specific SQL file ('query.sql') to another file ('formatted.sql') using the Perl API, with custom settings for indentation, keyword case, and function case.
```perl
#!/usr/bin/env perl
use pgFormatter::CLI;
my $cli = pgFormatter::CLI->new();
$cli->{'cfg'} = {
'input' => 'query.sql',
'output' => 'formatted.sql',
'spaces' => 2,
'keyword-case' => 1, # lowercase
'function-case' => 2, # uppercase
};
$cli->load_sql();
$cli->beautify();
$cli->save_output();
```
--------------------------------
### set_config
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-cgi.md
Loads configuration from a file named `pg_format.conf` if it exists in the same directory as the CGI script. It also sets default configuration values.
```APIDOC
## set_config
### Description
Loads configuration from file (if exists) and sets default values.
### Method
None (called internally or implicitly)
### Parameters
None
### Returns
void
### Configuration File
- Filename: `pg_format.conf` (in same directory as CGI script)
- Format: `key=value` (one per line)
- Example:
```
spaces=4
keyword-case=2
type-case=1
function-case=0
```
### Configuration Keys
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| spaces | integer | 4 | Indentation width |
| uc_keyword | 0-3 | 2 | Keyword case |
| uc_function | 0-3 | 0 | Function case |
| uc_type | 0-3 | 1 | Type case |
| nocomment | boolean | 0 | Remove comments |
| nogrouping | boolean | 0 | No grouping |
| anonymize | boolean | 0 | Anonymize literals |
| separator | string | '' | Code separator |
| comma | 'start' or 'end' | 'end' | Comma position |
| format | 'text' or 'html' | 'html' | Output format |
| comma_break | boolean | 0 | Break on comma |
| format_type | boolean | 0 | Alternative formatting |
| wrap_after | integer | 0 | Wrap after N columns |
| numbering | boolean | 0 | Statement numbering |
| redshift | boolean | 0 | RedShift keywords |
| colorize | boolean | 1 | Enable coloring |
| keep_newline | boolean | 0 | Keep empty lines |
| extra_function | string | '' | Extra functions file |
| extra_keyword | string | '' | Extra keywords file |
| no_space_function | boolean | 0 | No space before ( |
| redundant_parenthesis | boolean | 0 | Keep parenthesis |
| maxlength | integer | 100000 | Max query size |
| enable_api | boolean | 1 | Enable JSON API |
### Predefined Settings
| Setting | Purpose |
|---------|---------|
| program_name | 'pgFormatter' |
| project_url | GitHub project URL |
| download_url | Download page URL |
| bottom_ad_file | Optional ad content |
| head_track_file | Optional analytics code |
| css_file | Custom CSS override |
### Usage Example
```perl
my $cgi = pgFormatter::CGI->new();
# set_config() is called automatically in new()
# Access settings:
print $cgi->{'spaces'}; # 4
print $cgi->{'uc_keyword'}; # 2
```
```
--------------------------------
### Set Output Format to HTML
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/api-reference-beautify.md
Configures the beautifier to output formatted SQL as HTML, enabling syntax highlighting.
```perl
$beautifier->format('html');
$beautifier->beautify();
print $beautifier->content(); # HTML with spans for coloring
```
--------------------------------
### CLI Usage for SQL Formatting
Source: https://github.com/darold/pgformatter/blob/master/_autodocs/overview.md
Format SQL files directly from the command line using pg_format. You can specify options and provide a file path or use '-' for standard input.
```bash
pg_format [options] file.sql
```
```bash
pg_format [options] - # stdin
```
```bash
cat query.sql | pg_format [options]
```