org.eigenbase.sql.pretty
Class SqlPrettyWriter

java.lang.Object
  extended by org.eigenbase.sql.pretty.SqlPrettyWriter
All Implemented Interfaces:
SqlWriter

public class SqlPrettyWriter
extends Object
implements SqlWriter

Pretty printer for SQL statements.

There are several options to control the format.

Option Description Default
SelectListItemsOnSeparateLines Whether each item in the select clause is on its own line false
CaseClausesOnNewLines Whether the WHEN, THEN and ELSE clauses of a CASE expression appear at the start of a new line. false
Indentation Number of spaces to indent 4
KeywordsLowerCase Whether to print keywords (SELECT, AS, etc.) in lower-case. false
ParenthesizeAllExprs Whether to enclose all expressions in parentheses, even if the operator has high enough precedence that the parentheses are not required.

For example, the parentheses are required in the expression (a + b) c because the '*' operator has higher precedence than the '+' operator, and so without the parentheses, the expression would be equivalent to a + (b * c). The fully-parenthesized expression, ((a + b) * c) is unambiguous even if you don't know the precedence of every operator.

QuoteAllIdentifiers Whether to quote all identifiers, even those which would be correct according to the rules of the SqlDialect if quotation marks were omitted. true
SelectListItemsOnSeparateLines Whether each item in the select clause is on its own line. false
SubqueryStyle Style for formatting sub-queries. Values are: Hyde, Black. Hyde
LineLength Set the desired maximum length for lines (to look nice in editors, printouts, etc.). 0

Since:
2005/8/24
Version:
$Id: //open/dev/farrago/src/org/eigenbase/sql/pretty/SqlPrettyWriter.java#17 $
Author:
Julian Hyde

Nested Class Summary
private static class SqlPrettyWriter.Bean
          Helper class which exposes the get/set methods of an object as properties.
protected  class SqlPrettyWriter.FrameImpl
          Implementation of SqlWriter.Frame.
 
Nested classes/interfaces inherited from interface org.eigenbase.sql.SqlWriter
SqlWriter.Frame, SqlWriter.FrameType, SqlWriter.FrameTypeEnum, SqlWriter.SubqueryStyle
 
Field Summary
protected  boolean alwaysUseParentheses
           
private  SqlPrettyWriter.Bean bean
           
private  boolean caseClausesOnNewLines
           
private  int charCount
           
private  boolean clauseStartsLine
           
private  int currentIndent
           
private static SqlPrettyWriter.Bean defaultBean
          Bean holding the default property values.
private  SqlDialect dialect
           
protected  SqlPrettyWriter.FrameImpl frame
           
private  int indentation
           
private  boolean keywordsLowerCase
           
private  int lineLength
           
private  Stack<SqlPrettyWriter.FrameImpl> listStack
           
protected static EigenbaseLogger logger
           
private  boolean needWhitespace
           
protected  String nextWhitespace
           
protected static String NL
           
protected  PrintWriter pw
           
private  boolean quoteAllIdentifiers
           
private  boolean selectListExtraIndentFlag
           
private  boolean selectListItemsOnSeparateLines
           
private static String[] spaces
           
private  SqlWriter.SubqueryStyle subqueryStyle
           
private  StringWriter sw
           
private  boolean updateSetListNewline
           
private  boolean whereListItemsOnSeparateLines
           
private  boolean windowDeclListNewline
           
private  boolean windowNewline
           
 
Constructor Summary
SqlPrettyWriter(SqlDialect dialect)
           
SqlPrettyWriter(SqlDialect dialect, boolean alwaysUseParentheses)
           
SqlPrettyWriter(SqlDialect dialect, boolean alwaysUseParentheses, PrintWriter pw)
           
 
Method Summary
protected  SqlPrettyWriter.FrameImpl createListFrame(SqlWriter.FrameType frameType, String keyword, String open, String close)
          Creates a list frame.
 void describe(PrintWriter pw, boolean omitDefaults)
          Prints the property settings of this pretty-writer to a writer.
 void endFunCall(SqlWriter.Frame frame)
          Ends a list which is a call to a function.
 void endList(SqlWriter.Frame frame)
          Ends a list.
 String format(SqlNode node)
           
private  SqlPrettyWriter.Bean getBean()
          Returns an object which encapsulates each property as a get/set method.
 SqlDialect getDialect()
           
 int getIndentation()
          Returns the offset for each level of indentation.
 int getLineLength()
           
 void identifier(String name)
          Prints an identifier, quoting as necessary.
(package private)  void indent(int indent)
           
 boolean inQuery()
          Returns whether we are currently in a query context (SELECT, INSERT, UNION, INTERSECT, EXCEPT, and the ORDER BY operator).
 boolean isAlwaysUseParentheses()
          Returns whether to enclose all expressions in parentheses, even if the operator has high enough precedence that the parentheses are not required.
 boolean isClauseStartsLine()
           
 boolean isKeywordsLowerCase()
           
 boolean isQuoteAllIdentifiers()
           
 boolean isSelectListExtraIndentFlag()
           
 boolean isSelectListItemsOnSeparateLines()
           
 boolean isWhereListItemsOnSeparateLines()
           
 void keyword(String s)
          Prints a sequence of keywords.
 void literal(String s)
          Prints a literal, exactly as provided.
private  void maybeWhitespace(String s)
           
private static boolean needWhitespaceAfter(String s)
           
private static boolean needWhitespaceBefore(String s)
           
 void newlineAndIndent()
          Prints a new line, and indents.
 void print(int x)
           
 void print(String s)
          Prints a string, preceded by whitespace if necessary.
 void reset()
          Resets this writer so that it can format another expression.
 void resetSettings()
          Resets all properties to their default values.
 void sep(String sep)
          Writes a list separator, unless the separator is "," and this is the first occurrence in the list.
 void sep(String sep, boolean printFirst)
          Writes a list separator.
 void setAlwaysUseParentheses(boolean b)
           
 void setCaseClausesOnNewLines(boolean caseClausesOnNewLines)
          Sets whether the WHEN, THEN and ELSE clauses of a CASE expression appear at the start of a new line.
 void setClauseStartsLine(boolean clauseStartsLine)
          Sets whether a clause (FROM, WHERE, GROUP BY, HAVING, WINDOW, ORDER BY) starts a new line.
 void setIndentation(int indentation)
          Sets the number of spaces indentation.
 void setKeywordsLowerCase(boolean b)
          Sets whether to print keywords (SELECT, AS, etc.) in lower-case.
 void setLineLength(int lineLength)
           
 void setNeedWhitespace(boolean needWhitespace)
          Sets whether whitespace is needed before the next token.
 void setQuoteAllIdentifiers(boolean b)
          Sets whether to quote all identifiers, even those which would be correct according to the rules of the SqlDialect if quotation marks were omitted.
 void setSelectListExtraIndentFlag(boolean b)
          Sets whether to use a fix for SELECT list indentations.
 void setSelectListItemsOnSeparateLines(boolean b)
          Sets whether each item in a SELECT list, GROUP BY list, or ORDER BY list is on its own line.
 void setSettings(Properties properties)
          Sets settings from a properties object.
 void setSubqueryStyle(SqlWriter.SubqueryStyle subqueryStyle)
          Sets the subquery style.
 void setWhereListItemsOnSeparateLines(boolean b)
          Sets whether to print a newline before each AND or OR (whichever is higher level) in WHERE clauses.
 void setWindowDeclListNewline(boolean windowDeclListNewline)
           
 void setWindowNewline(boolean windowNewline)
           
private static String spaces(int i)
          Returns a string of N spaces.
 SqlWriter.Frame startFunCall(String funName)
          Starts a list which is a call to a function.
 SqlWriter.Frame startList(SqlWriter.FrameTypeEnum frameType)
          Starts a list with no opening string.
 SqlWriter.Frame startList(SqlWriter.FrameType frameType, String open, String close)
          Starts a list.
protected  SqlWriter.Frame startList(SqlWriter.FrameType frameType, String keyword, String open, String close)
          Starts a list.
 SqlWriter.Frame startList(String open, String close)
          Starts a list.
protected  boolean tooLong(String s)
           
 String toString()
           
protected  void whiteSpace()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

logger

protected static final EigenbaseLogger logger

defaultBean

private static final SqlPrettyWriter.Bean defaultBean
Bean holding the default property values.


NL

protected static final String NL

spaces

private static final String[] spaces

dialect

private final SqlDialect dialect

sw

private final StringWriter sw

pw

protected final PrintWriter pw

listStack

private final Stack<SqlPrettyWriter.FrameImpl> listStack

frame

protected SqlPrettyWriter.FrameImpl frame

needWhitespace

private boolean needWhitespace

nextWhitespace

protected String nextWhitespace

alwaysUseParentheses

protected boolean alwaysUseParentheses

keywordsLowerCase

private boolean keywordsLowerCase

bean

private SqlPrettyWriter.Bean bean

quoteAllIdentifiers

private boolean quoteAllIdentifiers

indentation

private int indentation

clauseStartsLine

private boolean clauseStartsLine

selectListItemsOnSeparateLines

private boolean selectListItemsOnSeparateLines

selectListExtraIndentFlag

private boolean selectListExtraIndentFlag

currentIndent

private int currentIndent

windowDeclListNewline

private boolean windowDeclListNewline

updateSetListNewline

private boolean updateSetListNewline

windowNewline

private boolean windowNewline

subqueryStyle

private SqlWriter.SubqueryStyle subqueryStyle

whereListItemsOnSeparateLines

private boolean whereListItemsOnSeparateLines

caseClausesOnNewLines

private boolean caseClausesOnNewLines

lineLength

private int lineLength

charCount

private int charCount
Constructor Detail

SqlPrettyWriter

public SqlPrettyWriter(SqlDialect dialect,
                       boolean alwaysUseParentheses,
                       PrintWriter pw)

SqlPrettyWriter

public SqlPrettyWriter(SqlDialect dialect,
                       boolean alwaysUseParentheses)

SqlPrettyWriter

public SqlPrettyWriter(SqlDialect dialect)
Method Detail

setCaseClausesOnNewLines

public void setCaseClausesOnNewLines(boolean caseClausesOnNewLines)
Sets whether the WHEN, THEN and ELSE clauses of a CASE expression appear at the start of a new line. The default is false.


setSubqueryStyle

public void setSubqueryStyle(SqlWriter.SubqueryStyle subqueryStyle)
Sets the subquery style. Default is SqlWriter.SubqueryStyle.Hyde.


setWindowNewline

public void setWindowNewline(boolean windowNewline)

setWindowDeclListNewline

public void setWindowDeclListNewline(boolean windowDeclListNewline)

getIndentation

public int getIndentation()
Description copied from interface: SqlWriter
Returns the offset for each level of indentation. Default 4.

Specified by:
getIndentation in interface SqlWriter

isAlwaysUseParentheses

public boolean isAlwaysUseParentheses()
Description copied from interface: SqlWriter
Returns whether to enclose all expressions in parentheses, even if the operator has high enough precedence that the parentheses are not required.

For example, the parentheses are required in the expression (a + b) * c because the '*' operator has higher precedence than the '+' operator, and so without the parentheses, the expression would be equivalent to a + (b * c). The fully-parenthesized expression, ((a + b) * c) is unambiguous even if you don't know the precedence of every operator.

Specified by:
isAlwaysUseParentheses in interface SqlWriter

inQuery

public boolean inQuery()
Description copied from interface: SqlWriter
Returns whether we are currently in a query context (SELECT, INSERT, UNION, INTERSECT, EXCEPT, and the ORDER BY operator).

Specified by:
inQuery in interface SqlWriter

isQuoteAllIdentifiers

public boolean isQuoteAllIdentifiers()
Specified by:
isQuoteAllIdentifiers in interface SqlWriter

isClauseStartsLine

public boolean isClauseStartsLine()
Specified by:
isClauseStartsLine in interface SqlWriter

isSelectListItemsOnSeparateLines

public boolean isSelectListItemsOnSeparateLines()
Specified by:
isSelectListItemsOnSeparateLines in interface SqlWriter

isWhereListItemsOnSeparateLines

public boolean isWhereListItemsOnSeparateLines()

isSelectListExtraIndentFlag

public boolean isSelectListExtraIndentFlag()

isKeywordsLowerCase

public boolean isKeywordsLowerCase()
Specified by:
isKeywordsLowerCase in interface SqlWriter

getLineLength

public int getLineLength()

resetSettings

public void resetSettings()
Description copied from interface: SqlWriter
Resets all properties to their default values.

Specified by:
resetSettings in interface SqlWriter

reset

public void reset()
Description copied from interface: SqlWriter
Resets this writer so that it can format another expression. Does not affect formatting preferences (see SqlWriter.resetSettings()

Specified by:
reset in interface SqlWriter

getBean

private SqlPrettyWriter.Bean getBean()
Returns an object which encapsulates each property as a get/set method.


setIndentation

public void setIndentation(int indentation)
Sets the number of spaces indentation.

See Also:
getIndentation()

describe

public void describe(PrintWriter pw,
                     boolean omitDefaults)
Prints the property settings of this pretty-writer to a writer.

Parameters:
pw - Writer
omitDefaults - Whether to omit properties whose value is the same as the default

setSettings

public void setSettings(Properties properties)
Sets settings from a properties object.


setClauseStartsLine

public void setClauseStartsLine(boolean clauseStartsLine)
Sets whether a clause (FROM, WHERE, GROUP BY, HAVING, WINDOW, ORDER BY) starts a new line. Default is true. SELECT is always at the start of a line.


setSelectListItemsOnSeparateLines

public void setSelectListItemsOnSeparateLines(boolean b)
Sets whether each item in a SELECT list, GROUP BY list, or ORDER BY list is on its own line. Default false.


setSelectListExtraIndentFlag

public void setSelectListExtraIndentFlag(boolean b)
Sets whether to use a fix for SELECT list indentations.


setKeywordsLowerCase

public void setKeywordsLowerCase(boolean b)
Sets whether to print keywords (SELECT, AS, etc.) in lower-case. The default is false: keywords are printed in upper-case.


setWhereListItemsOnSeparateLines

public void setWhereListItemsOnSeparateLines(boolean b)
Sets whether to print a newline before each AND or OR (whichever is higher level) in WHERE clauses. NOTE: Ignored when alwaysUseParentheses is set to true.


setAlwaysUseParentheses

public void setAlwaysUseParentheses(boolean b)

newlineAndIndent

public void newlineAndIndent()
Description copied from interface: SqlWriter
Prints a new line, and indents.

Specified by:
newlineAndIndent in interface SqlWriter

indent

void indent(int indent)

setQuoteAllIdentifiers

public void setQuoteAllIdentifiers(boolean b)
Sets whether to quote all identifiers, even those which would be correct according to the rules of the SqlDialect if quotation marks were omitted.

Default true.


createListFrame

protected SqlPrettyWriter.FrameImpl createListFrame(SqlWriter.FrameType frameType,
                                                    String keyword,
                                                    String open,
                                                    String close)
Creates a list frame.

Derived classes should override this method to specify the indentation of the list.

Parameters:
frameType - What type of list
keyword - The keyword to be printed at the start of the list
open - The string to print at the start of the list
close - The string to print at the end of the list
Returns:
A frame

spaces

private static String spaces(int i)
Returns a string of N spaces.


startList

protected SqlWriter.Frame startList(SqlWriter.FrameType frameType,
                                    String keyword,
                                    String open,
                                    String close)
Starts a list.

Parameters:
frameType - Type of list. For example, a SELECT list will be governed according to SELECT-list formatting preferences.
open - String to print at the start of the list; typically "(" or the empty string.
close - String to print at the end of the list.

endList

public void endList(SqlWriter.Frame frame)
Description copied from interface: SqlWriter
Ends a list.

Specified by:
endList in interface SqlWriter
Parameters:
frame - The frame which was created by SqlWriter.startList(java.lang.String, java.lang.String).

format

public String format(SqlNode node)

toString

public String toString()
Overrides:
toString in class Object

getDialect

public SqlDialect getDialect()
Specified by:
getDialect in interface SqlWriter

literal

public void literal(String s)
Description copied from interface: SqlWriter
Prints a literal, exactly as provided. Does not attempt to indent or convert to upper or lower case. Does not add quotation marks. Adds preceding whitespace if necessary.

Specified by:
literal in interface SqlWriter

keyword

public void keyword(String s)
Description copied from interface: SqlWriter
Prints a sequence of keywords. Must not start or end with space, but may contain a space. For example, keyword("SELECT"), keyword("CHARACTER SET").

Specified by:
keyword in interface SqlWriter

maybeWhitespace

private void maybeWhitespace(String s)

needWhitespaceBefore

private static boolean needWhitespaceBefore(String s)

needWhitespaceAfter

private static boolean needWhitespaceAfter(String s)

whiteSpace

protected void whiteSpace()

tooLong

protected boolean tooLong(String s)

print

public void print(String s)
Description copied from interface: SqlWriter
Prints a string, preceded by whitespace if necessary.

Specified by:
print in interface SqlWriter

print

public void print(int x)
Specified by:
print in interface SqlWriter

identifier

public void identifier(String name)
Description copied from interface: SqlWriter
Prints an identifier, quoting as necessary.

Specified by:
identifier in interface SqlWriter

startFunCall

public SqlWriter.Frame startFunCall(String funName)
Description copied from interface: SqlWriter
Starts a list which is a call to a function.

Specified by:
startFunCall in interface SqlWriter
See Also:
SqlWriter.endFunCall(Frame)

endFunCall

public void endFunCall(SqlWriter.Frame frame)
Description copied from interface: SqlWriter
Ends a list which is a call to a function.

Specified by:
endFunCall in interface SqlWriter
See Also:
SqlWriter.startFunCall(String)

startList

public SqlWriter.Frame startList(String open,
                                 String close)
Description copied from interface: SqlWriter
Starts a list.

Specified by:
startList in interface SqlWriter

startList

public SqlWriter.Frame startList(SqlWriter.FrameTypeEnum frameType)
Description copied from interface: SqlWriter
Starts a list with no opening string.

Specified by:
startList in interface SqlWriter
Parameters:
frameType - Type of list. For example, a SELECT list will be

startList

public SqlWriter.Frame startList(SqlWriter.FrameType frameType,
                                 String open,
                                 String close)
Description copied from interface: SqlWriter
Starts a list.

Specified by:
startList in interface SqlWriter
Parameters:
frameType - Type of list. For example, a SELECT list will be governed according to SELECT-list formatting preferences.
open - String to start the list; typically "(" or the empty string.

sep

public void sep(String sep)
Description copied from interface: SqlWriter
Writes a list separator, unless the separator is "," and this is the first occurrence in the list.

Specified by:
sep in interface SqlWriter
Parameters:
sep - List separator, typically ",".

sep

public void sep(String sep,
                boolean printFirst)
Description copied from interface: SqlWriter
Writes a list separator.

Specified by:
sep in interface SqlWriter
Parameters:
sep - List separator, typically ","
printFirst - Whether to print the first occurrence of the separator

setNeedWhitespace

public void setNeedWhitespace(boolean needWhitespace)
Description copied from interface: SqlWriter
Sets whether whitespace is needed before the next token.

Specified by:
setNeedWhitespace in interface SqlWriter

setLineLength

public void setLineLength(int lineLength)