hogimn / SqlFormatter

SQL Formatter: A C# and .NET Core (also .NET Standard) Implementation Inspired by the Open-Source Java Project

Home Page:https://github.com/vertical-blank/sql-formatter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

dotnet package

SQL Formatter

This repository contains the C# port of the popular Java SQL formatter

This does not support:

  • Stored procedures.
  • Changing of the delimiter type to something else than ;.

Examples

You can easily use SQL.Formatter.SqlFormatter :

SqlFormatter.Format("SELECT * FROM table1")

This will output:

SELECT
  *
FROM
  table1

You can also pass FormatConfig object built by builder:

SqlFormatter.Format("SELECT * FROM tbl",
  FormatConfig.Builder()
    .Indent("    ") // Defaults to two spaces
    .Uppercase(true) // Defaults to false (not safe to use when SQL dialect has case-sensitive identifiers)
    .LinesBetweenQueries(2) // Defaults to 1
    .MaxColumnLength(100) // Defaults to 50
    .Params(new List<string>{"a", "b", "c"}) // Dictionary or List. See Placeholders replacement.
    .Build());
);

Dialect

You can pass dialect SQL.Formatter.Language.Dialect or String to SqlFormatter.Of :

SqlFormatter
    .Of(Dialect.N1ql)  // Recommended
     //.Of("n1ql")      // String can be passed
    .Format("SELECT *");

SQL formatter supports the following dialects:

Extend formatters

Formatters can be extended as below :

SqlFormatter
    .Of(Dialect.MySql)
    .Extend(cfg => cfg.PlusOperators("=>"))
    .Format("SELECT * FROM table WHERE A => 4")

Then it results in:

SELECT
  *
FROM
  table
WHERE
  A => 4

Placeholders replacement

You can pass List or Dictionary to Format :

// Named placeholders
Dictionary<string, string> namedParams = new Dictionary<string, string>();
namedParams.Add("foo", "'bar'");
SqlFormatter.Of(Dialect.TSql).Format("SELECT * FROM tbl WHERE foo = @foo", namedParams);

// Indexed placeholders
SqlFormatter.Format("SELECT * FROM tbl WHERE foo = ?", new List<string> {"'bar'"});

Both result in:

SELECT
  *
FROM
  tbl
WHERE
  foo = 'bar'

About

SQL Formatter: A C# and .NET Core (also .NET Standard) Implementation Inspired by the Open-Source Java Project

https://github.com/vertical-blank/sql-formatter

License:MIT License


Languages

Language:C# 98.6%Language:HTML 0.7%Language:CSS 0.6%Language:JavaScript 0.1%