Skip to content

maxrichie5/go-sqlfmt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-sqlfmt

An SQL formatter written in Go.

This project is https://github.com/Snowflake-Labs/snowsql-formatter ported from javascript into Go with some enhancements, like being able to colorize the output.

There is support for Standard SQL, Couchbase N1QL, IBM DB2 and Oracle PL/SQL dialects.

Install

Get the latest version from NPM:

go get -u github.com/maxrichie5/go-sqlfmt

Usage

Basic Usage

package main

import (
    "fmt"
    "github.com/maxrichie5/go-sqlfmt/sqlfmt"
)

func main() {
    query := `SELECT * FROM foo WHERE goo = 'taco'`
    fmt.Println(sqlfmt.Format(query))
}

This will output:

SELECT
  *
FROM
  foo
WHERE
  goo = 'taco'

Config

You can use the Config to specify some formatting options:

sqlfmt.Format(query, sqlfmt.NewDefaultConfig().WithLang(sqlfmt.N1QL))

Currently just four SQL dialects are supported:

Config options available are:

  • Language (SQL Dialect)
  • Indentation
  • Lines between queries
  • Make reserved words uppercase
  • Add parameters
  • Add coloring config
  • Add tokenizing config

Colored Output

You can also format with color:

fmt.Println(sqlfmt.PrettyFormat(query))

Or use PrettyPrint to have it print for you:

sqlfmt.PrettyPrint(query)

You can even use a custom coloring config (if you supply a color config, you don't need to use the Pretty functions):

clr := sqlfmt.NewDefaultColorConfig()
clr.ReservedWordFormatOptions = []sqlfmt.ANSIFormatOption{
    sqlfmt.ColorBrightGreen, sqlfmt.FormatUnderline,
}
sqlfmt.Format(query, sqlfmt.NewDefaultConfig().WithColorConfig(clr))

Placeholders replacement

Named Placeholders

query := "SELECT * FROM tbl WHERE foo = @foo"
sqlfmt.Format(query, sqlfmt.NewDefaultConfig().WithParams(
    sqlfmt.NewMapParams(map[string]string{
        "foo": "'bar'",
    }),
))

Indexed Placeholders

query := "SELECT * FROM tbl WHERE foo = ?"
sqlfmt.Format(query, sqlfmt.NewDefaultConfig().WithParams(
    sqlfmt.NewListParams([]string{"'bar'"}),
))

Both result in:

SELECT
  *
FROM
  tbl
WHERE
  foo = 'bar'

Tokenizer customization

If for some reason you want things to be tokenized differently, that can be adjusted too.

stdCfg := sqlfmt.NewStandardSQLTokenizerConfig()
stdCfg.ReservedTopLevelWords = append(stdCfg.ReservedTopLevelWords, "BONUS")
sqlfmt.Format(query, sqlfmt.NewDefaultConfig().WithTokenizerConfig(stdCfg))

Contributing

Create a branch and open a pull request!

Next Steps

  • Add a snowsql dialect
  • Add support for SnowSQL specific keywords and constructs

License

MIT

About

An SQL formatter written in Go.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages