Class SqlPrettyWriter

  • All Implemented Interfaces:
    SqlWriter

    public class SqlPrettyWriter
    extends java.lang.Object
    implements SqlWriter
    Pretty printer for SQL statements.

    There are several options to control the format.

    Formatting options
    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
    • Field Detail

      • DEFAULT_BEAN

        private static final SqlPrettyWriter.Bean DEFAULT_BEAN
        Bean holding the default property values.
      • NL

        protected static final java.lang.String NL
      • sw

        private final java.io.StringWriter sw
      • pw

        protected final java.io.PrintWriter pw
      • dynamicParameters

        private com.google.common.collect.ImmutableList.Builder<java.lang.Integer> dynamicParameters
      • needWhitespace

        private boolean needWhitespace
      • nextWhitespace

        protected java.lang.String nextWhitespace
      • alwaysUseParentheses

        protected boolean alwaysUseParentheses
      • keywordsLowerCase

        private boolean keywordsLowerCase
      • 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
      • 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,
                               java.io.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.
      • 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()
        Description copied from interface: SqlWriter
        Returns whether this writer should quote all identifiers, even those that do not contain mixed-case identifiers or punctuation.
        Specified by:
        isQuoteAllIdentifiers in interface SqlWriter
        Returns:
        whether to quote all identifiers
      • isClauseStartsLine

        public boolean isClauseStartsLine()
        Description copied from interface: SqlWriter
        Returns whether this writer should start each clause (e.g. GROUP BY) on a new line.
        Specified by:
        isClauseStartsLine in interface SqlWriter
        Returns:
        whether to start each clause on a new line
      • isSelectListItemsOnSeparateLines

        public boolean isSelectListItemsOnSeparateLines()
        Description copied from interface: SqlWriter
        Returns whether the items in the SELECT clause should each be on a separate line.
        Specified by:
        isSelectListItemsOnSeparateLines in interface SqlWriter
        Returns:
        whether to put each SELECT clause item on a new line
      • isWhereListItemsOnSeparateLines

        public boolean isWhereListItemsOnSeparateLines()
      • isSelectListExtraIndentFlag

        public boolean isSelectListExtraIndentFlag()
      • isKeywordsLowerCase

        public boolean isKeywordsLowerCase()
        Description copied from interface: SqlWriter
        Returns whether to output all keywords (e.g. SELECT, GROUP BY) in lower case.
        Specified by:
        isKeywordsLowerCase in interface SqlWriter
        Returns:
        whether to output SQL keywords in lower case
      • 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​(java.io.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​(java.util.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.
        • If set to "false":
           SELECT
               A as A
                   B as B
                   C as C
               D
           
        • If set to "true":
           SELECT
               A as A
               B as B
               C as C
               D
           
      • 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,
                                                            java.lang.String keyword,
                                                            java.lang.String open,
                                                            java.lang.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
      • startList

        protected SqlWriter.Frame startList​(SqlWriter.FrameType frameType,
                                            java.lang.String keyword,
                                            java.lang.String open,
                                            java.lang.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.
      • format

        public java.lang.String format​(SqlNode node)
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object
      • toSqlString

        public SqlString toSqlString()
        Description copied from interface: SqlWriter
        Returns the contents of this writer as a 'certified kocher' SQL string.
        Specified by:
        toSqlString in interface SqlWriter
        Returns:
        SQL string
      • getDialect

        public SqlDialect getDialect()
        Description copied from interface: SqlWriter
        Returns the dialect of SQL.
        Specified by:
        getDialect in interface SqlWriter
        Returns:
        SQL dialect
      • literal

        public void literal​(java.lang.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​(java.lang.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​(java.lang.String s)
      • needWhitespaceBefore

        private static boolean needWhitespaceBefore​(java.lang.String s)
      • needWhitespaceAfter

        private static boolean needWhitespaceAfter​(java.lang.String s)
      • whiteSpace

        protected void whiteSpace()
      • tooLong

        protected boolean tooLong​(java.lang.String s)
      • print

        public void print​(java.lang.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)
        Description copied from interface: SqlWriter
        Prints an integer.
        Specified by:
        print in interface SqlWriter
        Parameters:
        x - Integer
      • identifier

        public void identifier​(java.lang.String name,
                               boolean quoted)
        Description copied from interface: SqlWriter
        Prints an identifier, quoting as necessary.
        Specified by:
        identifier in interface SqlWriter
        Parameters:
        name - The identifier name
        quoted - Whether this identifier was quoted in the original sql statement, this may not be the only factor to decide whether this identifier should be quoted
      • dynamicParam

        public void dynamicParam​(int index)
        Description copied from interface: SqlWriter
        Prints a dynamic parameter (e.g. ? for default JDBC)
        Specified by:
        dynamicParam in interface SqlWriter
      • startList

        public SqlWriter.Frame startList​(SqlWriter.FrameType frameType,
                                         java.lang.String open,
                                         java.lang.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.
        close - String to close the list
      • sep

        public void sep​(java.lang.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​(java.lang.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)