Code Monkey home page Code Monkey logo

pg-formatter's Introduction

pg-formatter

NPM version Canonical Code Style Twitter Follow

A PostgreSQL SQL syntax beautifier.

Note:

This project is a thin wrapper of https://github.com/darold/pgFormatter. Execution of the module relies on Perl being available on the host system.

Usage

import {
  format
} from 'pg-formatter';

format(`SELECT foo FROM bar`);

Configuration

Configuration Format Default Description pgFormatter equivalent
anonymize boolean false Obscure all literals in queries, useful to hide confidential data before formatting. anonymize
commaBreak boolean false Add a newline after each comma in an insert statement. comma-break
functionCase string ("unchanged", "lowercase", "uppercase", "capitalize") unchanged Change the case of the function names. function-case
keywordCase string ("unchanged", "lowercase", "uppercase", "capitalize") unchanged Change the case of the reserved keyword. keyword-case
noRcFile boolean false Do not read ~/.pg_format automatically. no-rcfile
placeholder string (regex) N/A Regex to find code that must not be changed. placeholder
spaces number 4 Number of spaces to indent the code. spaces
stripComments boolean false Remove any comment from SQL code. nocomment
tabs boolean false Use tabs instead of spaces. When true, the spaces option is ignored. tabs

CLI Usage

$ npm install pg-formatter -g
$ pg-formatter --help
Formats SQL files

Options:
      --version         Show version number                            [boolean]
      --anonymize       Obscure all literals in queries, useful to hide
                        confidential data before formatting.
                                                      [boolean] [default: false]
      --comma-break     Add a newline after each comma in an insert statement.
                                                      [boolean] [default: false]
      --function-case   Change the case of the function names.
         [string] [choices: "unchanged", "lowercase", "uppercase", "capitalize"]
                                                          [default: "unchanged"]
  -i, --inplace         Override input file with formatted content.
                                                      [boolean] [default: false]
      --keyword-case    Change the case of the reserved keyword.
         [string] [choices: "unchanged", "lowercase", "uppercase", "capitalize"]
                                                          [default: "unchanged"]
      --no-rc-file      Do not read ~/.pg_format automatically.
                                                      [boolean] [default: false]
      --placeholder     Regex to find code that must not be changed.    [string]
      --spaces          Number of spaces to indent the code.
                                                           [number] [default: 4]
      --strip-comments  Remove any comment from SQL code.
                                                      [boolean] [default: false]
      --tabs            Use tabs instead of spaces. When true, the spaces option
                        is ignored.                   [boolean] [default: false]
      --help            Show help                                      [boolean]

pg-formatter's People

Contributors

frigus02 avatar gajus avatar jilvin avatar npdev453 avatar nponiros avatar richeyryan-geowox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

pg-formatter's Issues

Locale issues on Windows

I'm using the Strawberry Perl distro on Windows, along with Node 20.10.0. When I invoke pg-formatter out of the box, it does what it's supposed to, but then it also outputs:

perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
        LC_ALL = "C.UTF-8",
        (possibly more locale environment variables)
        LANG = (unset)
    are supported and installed on your system.
perl: warning: Falling back to the system default locale ("English_United States.1252").

I'm a newbie with Perl and haven't been able to find much info about locale handling on Windows. But after a lot of poking around, I tracked this down to:

pg-formatter/src/format.ts

Lines 121 to 123 in 6e1c8af

env: {
LC_ALL: 'C.UTF-8',
},

If I change the value of LC_ALL to C on line 122, then everything works fine with no warnings. (It also works if I remove lines 121-123 entirely.)

Is using C an appropriate fix on Windows? Or is there a better approach? In either case, can this be built into pg-formatter by checking process.platform?

[Idea] Prettier plugin

Hey @gajus ,

did you already consider putting this into a prettier plugin?

I really like your eslint plugin which provides formatting as an auto-fix (via this lib) for tagged template literals. However, for normal .sql a different solution is needed (e.g. calling the CLI manually).
Since there are pretty decent prettier integrations for most IDEs, it would be nice to have this as a prettier plugin.

I started using a very simple custom plugin like the following in my private projects:

Code (simple prettier plugin)
const format = require('pg-formatter').format;

// see: https://github.com/gajus/pg-formatter#configuration
const FORMAT_OPTIONS = {
functionCase: 'uppercase',
keywordCase: 'uppercase',
spaces: 2,
};

const languages = [
{
  name: 'SQL',
  parsers: ['postgresql'],
  extensions: ['.pgsql', '.sql'],
},
];

const parsers = {
postgresql: {
  parse: sql => ({ sql }),
  astFormat: 'postgresql',
},
};

const printers = {
postgresql: {
  print(path) {
    const sql = path.getValue().sql;
    return format(sql, FORMAT_OPTIONS);
  },
},
};

module.exports = {
languages,
parsers,
printers,
};

Maybe we can add a prettier plugin to format not only .sql files but tagged template literals as well?
The prettier API is somewhat limited (e.g. see prettier/prettier#12139 ) but I was thinking of overwriting the typescript/javascript parser and adding the formatter as post-processing plugin to the AST output. However, this is just a very rough idea and I have no PoC yet.

CLI interface broken - node execution context missing

Hey. Handy wrapper 👍.

For me (v2.0.2) the CLI interface cannot be called directly:

❯ npm install pg-formatter -g
❯ pg-formatter --help
/opt/homebrew/bin/pg-formatter: line 1: use strict: command not found
/opt/homebrew/bin/pg-formatter: line 2: syntax error near unexpected token `('
/opt/homebrew/bin/pg-formatter: line 2: `var __importDefault = (this && this.__importDefault) || function (mod) {'

Same for installing this as devDependency and trying to call it via npx pg-formatter

Workaround for now is: ❯ node node_modules/.bin/pg-formatter

The dist file is missing: #!/usr/bin/env node at the top

update to 4.4?

Currently, pg_format 4.1 seems to be bundled. could you update it to current?

Crashes (and potential code injection) if pwd contains spaces or special characters

https://github.com/gajus/pg-formatter/blob/master/src/format.js#L112 runs perl with an executablePath which is not properly quoted. If the working-directory name contains spaces or other special characters, they will be interpreted as shell syntax. In the normal case, someone made the mistake of checking out their project to a directory with spaces in a parent path, and this winds up crashing. (This happened to another developer on my team). In the worst case, admittedly an unlikely case given how this library would normally be used but definitely not impossible, this is running in a context where the parent path has an attacker-controlled directory name in it, and this injects arbitrary shell or perl code.

Reading configuration from rcfile (`.pg_format`)

Greetings @gajus !

Thank you for a great package, I started using it in one of my projects, it is quite handy.

I am wondering if reading config from .pg_format works, can't find the logic for it after briefly skimming the code.

So, what I was trying to do - adding a small config, like this:

no-extra-line=1

running pg_format with this config works, but pg-formatter seems to ignore it.

I also did not find -L | --no-extra-line param in CLI here.
I am happy to provide a patch to add this one, if that'd be the way to go.

Best,
Rust

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.