java/sql-dk/src/info/globalcode/sql/dk/formatting/AbstractFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Mon, 23 Dec 2013 16:29:51 +0100
branchv_0
changeset 42 6fdaa4db3943
parent 41 514df5061f59
child 88 102ba0fcb07f
permissions -rw-r--r--
DatabaseConnection implements AutoCloseable
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    10  * This program is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  * GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License
    16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 package info.globalcode.sql.dk.formatting;
    19 
    20 import info.globalcode.sql.dk.Parameter;
    21 import info.globalcode.sql.dk.configuration.DatabaseDefinition;
    22 import java.util.EmptyStackException;
    23 import java.util.EnumSet;
    24 import java.util.List;
    25 import java.util.Stack;
    26 
    27 /**
    28  *
    29  * @author Ing. František Kučera (frantovo.cz)
    30  */
    31 public abstract class AbstractFormatter implements Formatter {
    32 
    33 	private Stack<State> state = new Stack<>();
    34 	private FormatterContext formatterContext;
    35 	private ColumnsHeader currentColumnsHeader;
    36 	private String currentQuery;
    37 	private int currentColumnsCount;
    38 	private int currentRowCount;
    39 
    40 	public AbstractFormatter(FormatterContext formatterContext) {
    41 		this.formatterContext = formatterContext;
    42 		state.push(State.ROOT);
    43 	}
    44 
    45 	/*
    46 	 * root
    47 	 * .database
    48 	 * ..resultSet
    49 	 * ...@query
    50 	 * ...@parameters
    51 	 * ...@columnsHeader
    52 	 * ...row
    53 	 * ....@columnValue
    54 	 * ..updatesResult
    55 	 * ...@query
    56 	 * ...@parameters
    57 	 * ...@updatedRowsCount
    58 	 */
    59 	protected enum State {
    60 
    61 		ROOT,
    62 		DATABASE,
    63 		RESULT_SET,
    64 		ROW,
    65 		UPDATES_RESULT
    66 	}
    67 
    68 	/**
    69 	 * Go down in hierarchy.
    70 	 * Pushes new state and verifies the old one.
    71 	 *
    72 	 * @param current the new state – currently entering
    73 	 * @param expected expected previous states (any of them is valid)
    74 	 * @return previous state
    75 	 * @throws IllegalStateException if previous state was not one from expected
    76 	 */
    77 	private State pushState(State current, EnumSet expected) {
    78 		State previous = state.peek();
    79 
    80 		if (expected.contains(previous)) {
    81 			state.push(current);
    82 			return previous;
    83 		} else {
    84 			throw new IllegalStateException("Formatter was in wrong state: " + previous + " when it should be in one of: " + expected);
    85 		}
    86 	}
    87 
    88 	protected State peekState(EnumSet expected) {
    89 		State current = state.peek();
    90 
    91 		if (expected.contains(current)) {
    92 			return current;
    93 		} else {
    94 			throw new IllegalStateException("Formatter is in wrong state: " + current + " when it should be in one of: " + expected);
    95 		}
    96 
    97 	}
    98 
    99 	/**
   100 	 * Go up in hierarchy.
   101 	 * Pops the superior state/branch.
   102 	 *
   103 	 * @param expected expected superior state
   104 	 * @return the superior state
   105 	 * @throws IllegalStateException if superior state was not one from expected or if there is no
   106 	 * more superior state (we are at root level)
   107 	 */
   108 	private State popState(EnumSet expected) {
   109 		try {
   110 			state.pop();
   111 			State superior = state.peek();
   112 			if (expected.contains(superior)) {
   113 				return superior;
   114 			} else {
   115 				throw new IllegalStateException("Formatter had wrong superior state: " + superior + " when it should be in one of: " + expected);
   116 			}
   117 		} catch (EmptyStackException e) {
   118 			throw new IllegalStateException("Formatter was already at root level – there is nothing above that.", e);
   119 		}
   120 	}
   121 
   122 	@Override
   123 	public void writeStartDatabase(DatabaseDefinition databaseDefinition) {
   124 		pushState(State.DATABASE, EnumSet.of(State.ROOT));
   125 	}
   126 
   127 	@Override
   128 	public void writeEndDatabase() {
   129 		popState(EnumSet.of(State.ROOT));
   130 	}
   131 
   132 	@Override
   133 	public void writeStartResultSet() {
   134 		pushState(State.RESULT_SET, EnumSet.of(State.DATABASE));
   135 		currentRowCount = 0;
   136 	}
   137 
   138 	@Override
   139 	public void writeEndResultSet() {
   140 		popState(EnumSet.of(State.DATABASE));
   141 		currentColumnsHeader = null;
   142 	}
   143 
   144 	@Override
   145 	public void writeQuery(String sql) {
   146 		peekState(EnumSet.of(State.RESULT_SET, State.UPDATES_RESULT));
   147 
   148 		if (currentColumnsHeader == null) {
   149 			currentQuery = sql;
   150 		} else {
   151 			throw new IllegalStateException("Query string '" + sql + "' must be set before columns header – was already set: " + currentColumnsHeader);
   152 		}
   153 	}
   154 
   155 	@Override
   156 	public void writeParameters(List<? extends Parameter> parameters) {
   157 		peekState(EnumSet.of(State.RESULT_SET, State.UPDATES_RESULT));
   158 
   159 		if (currentColumnsHeader != null) {
   160 			throw new IllegalStateException("Parameters '" + parameters + "' must be set before columns header – was already set: " + currentColumnsHeader);
   161 		}
   162 
   163 		if (currentQuery == null) {
   164 			throw new IllegalStateException("Parameters '" + parameters + "' must be set after query – was not yet set.");
   165 		}
   166 	}
   167 
   168 	@Override
   169 	public void writeColumnsHeader(ColumnsHeader header) {
   170 		peekState(EnumSet.of(State.RESULT_SET));
   171 
   172 		if (currentColumnsHeader == null) {
   173 			currentColumnsHeader = header;
   174 		} else {
   175 			throw new IllegalStateException("Columns header can be set only once per result set – was already set: " + currentColumnsHeader);
   176 		}
   177 	}
   178 
   179 	@Override
   180 	public void writeStartRow() {
   181 		pushState(State.ROW, EnumSet.of(State.RESULT_SET));
   182 		currentColumnsCount = 0;
   183 		currentRowCount++;
   184 	}
   185 
   186 	@Override
   187 	public void writeEndRow() {
   188 		popState(EnumSet.of(State.RESULT_SET));
   189 	}
   190 
   191 	@Override
   192 	public void writeColumnValue(Object value) {
   193 		peekState(EnumSet.of(State.ROW));
   194 		currentColumnsCount++;
   195 
   196 		int declaredCount = currentColumnsHeader.getColumnCount();
   197 		if (currentColumnsCount > declaredCount) {
   198 			throw new IllegalStateException("Current columns count is " + currentColumnsCount + " which is more than declared " + declaredCount + " in header.");
   199 		}
   200 	}
   201 
   202 	/**
   203 	 * @param value from ResultSet
   204 	 * @return String representation of given value
   205 	 */
   206 	protected String toString(Object value) {
   207 		/**
   208 		 * TODO: basic formatting: boolean, null, date, numbers…
   209 		 */
   210 		return String.valueOf(value);
   211 	}
   212 
   213 	@Override
   214 	public void writeStartUpdatesResult() {
   215 		pushState(State.UPDATES_RESULT, EnumSet.of(State.DATABASE));
   216 	}
   217 
   218 	@Override
   219 	public void writeEndUpdatesResult() {
   220 		popState(EnumSet.of(State.DATABASE));
   221 		currentColumnsHeader = null;
   222 	}
   223 
   224 	@Override
   225 	public void writeUpdatedRowsCount(int updatedRowsCount) {
   226 		peekState(EnumSet.of(State.UPDATES_RESULT));
   227 	}
   228 
   229 	public FormatterContext getFormatterContext() {
   230 		return formatterContext;
   231 	}
   232 
   233 	protected ColumnsHeader getCurrentColumnsHeader() {
   234 		return currentColumnsHeader;
   235 	}
   236 
   237 	/**
   238 	 * @return column number, 1 = first
   239 	 */
   240 	protected int getCurrentColumnsCount() {
   241 		return currentColumnsCount;
   242 	}
   243 
   244 	protected boolean isCurrentColumnFirst() {
   245 		return currentColumnsCount == 1;
   246 	}
   247 
   248 	protected boolean isCurrentColumnLast() {
   249 		return currentColumnsCount == currentColumnsHeader.getColumnCount();
   250 	}
   251 
   252 	/**
   253 	 * @return row number, 1 = first
   254 	 */
   255 	protected int getCurrentRowCount() {
   256 		return currentRowCount;
   257 	}
   258 	/**
   259 	 * TODO: write SQLWarning
   260 	 */
   261 }