java/sql-dk/src/main/java/info/globalcode/sql/dk/formatting/AbstractFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Tue, 30 Apr 2019 19:49:17 +0200
branchv_0
changeset 248 7f81cfa150d0
parent 238 4a1864c3e867
child 250 aae5009bd0af
permissions -rw-r--r--
transform the record formatter into the recfile formatter
still a human-readable format and very similar
but also machine-readable – can be processed in GNU Recutils and Relational pipes
     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  * <ol>
    29  * <li>ensures integrity – if methods are called in correct order and context</li>
    30  * <li>provides default implmentations of methods that does not produce any output for given
    31  * events</li>
    32  * </ol>
    33  *
    34  * @author Ing. František Kučera (frantovo.cz)
    35  */
    36 public abstract class AbstractFormatter implements Formatter {
    37 
    38 	private Stack<State> state = new Stack<>();
    39 	private FormatterContext formatterContext;
    40 	private ColumnsHeader currentColumnsHeader;
    41 	private String currentQuery;
    42 	private int currentColumnsCount;
    43 	private int currentRowCount;
    44 	private int resultSetCount;
    45 
    46 	public AbstractFormatter(FormatterContext formatterContext) {
    47 		this.formatterContext = formatterContext;
    48 		state.push(State.ROOT);
    49 	}
    50 
    51 	protected String getCurrentRelationName() {
    52 		if (getFormatterContext().getRelationNames() == null || getFormatterContext().getRelationNames().size() < resultSetCount) {
    53 			return "r" + resultSetCount;
    54 		} else {
    55 			return getFormatterContext().getRelationNames().get(resultSetCount - 1);
    56 		}
    57 	}
    58 
    59 	/*
    60 	 * root
    61 	 * .batch
    62 	 * ..database
    63 	 * ...statement
    64 	 * ....@query
    65 	 * ....@parameters
    66 	 * ....resultSet
    67 	 * .....row
    68 	 * ......@columnValue
    69 	 * ....@updatesResult
    70 	 */
    71 	protected enum State {
    72 
    73 		ROOT,
    74 		BATCH,
    75 		DATABASE,
    76 		STATEMENT,
    77 		RESULT_SET,
    78 		ROW
    79 	}
    80 
    81 	/**
    82 	 * Go down in hierarchy.
    83 	 * Pushes new state and verifies the old one.
    84 	 *
    85 	 * @param current the new state – currently entering
    86 	 * @param expected expected previous states (any of them is valid)
    87 	 * @return previous state
    88 	 * @throws IllegalStateException if previous state was not one from expected
    89 	 */
    90 	private State pushState(State current, EnumSet expected) {
    91 		State previous = state.peek();
    92 
    93 		if (expected.contains(previous)) {
    94 			state.push(current);
    95 			return previous;
    96 		} else {
    97 			throw new IllegalStateException("Formatter was in wrong state: " + previous + " when it should be in one of: " + expected);
    98 		}
    99 	}
   100 
   101 	protected State peekState(EnumSet expected) {
   102 		State current = state.peek();
   103 
   104 		if (expected.contains(current)) {
   105 			return current;
   106 		} else {
   107 			throw new IllegalStateException("Formatter is in wrong state: " + current + " when it should be in one of: " + expected);
   108 		}
   109 
   110 	}
   111 
   112 	/**
   113 	 * Go up in hierarchy.
   114 	 * Pops the superior state/branch.
   115 	 *
   116 	 * @param expected expected superior state
   117 	 * @return the superior state
   118 	 * @throws IllegalStateException if superior state was not one from expected or if there is no
   119 	 * more superior state (we are at root level)
   120 	 */
   121 	private State popState(EnumSet expected) {
   122 		try {
   123 			state.pop();
   124 			State superior = state.peek();
   125 			if (expected.contains(superior)) {
   126 				return superior;
   127 			} else {
   128 				throw new IllegalStateException("Formatter had wrong superior state: " + superior + " when it should be in one of: " + expected);
   129 			}
   130 		} catch (EmptyStackException e) {
   131 			throw new IllegalStateException("Formatter was already at root level – there is nothing above that.", e);
   132 		}
   133 	}
   134 
   135 	@Override
   136 	public void writeStartBatch() {
   137 		pushState(State.BATCH, EnumSet.of(State.ROOT));
   138 		resultSetCount = 0;
   139 	}
   140 
   141 	@Override
   142 	public void writeEndBatch() {
   143 		popState(EnumSet.of(State.ROOT));
   144 	}
   145 
   146 	@Override
   147 	public void writeStartDatabase(DatabaseDefinition databaseDefinition) {
   148 		pushState(State.DATABASE, EnumSet.of(State.BATCH));
   149 	}
   150 
   151 	@Override
   152 	public void writeEndDatabase() {
   153 		popState(EnumSet.of(State.BATCH));
   154 	}
   155 
   156 	@Override
   157 	public void writeStartStatement() {
   158 		pushState(State.STATEMENT, EnumSet.of(State.DATABASE));
   159 	}
   160 
   161 	@Override
   162 	public void writeEndStatement() {
   163 		popState(EnumSet.of(State.DATABASE));
   164 	}
   165 
   166 	@Override
   167 	public void writeStartResultSet(ColumnsHeader header) {
   168 		pushState(State.RESULT_SET, EnumSet.of(State.STATEMENT));
   169 		resultSetCount++;
   170 		currentRowCount = 0;
   171 		currentColumnsHeader = header;
   172 	}
   173 
   174 	@Override
   175 	public void writeEndResultSet() {
   176 		popState(EnumSet.of(State.STATEMENT));
   177 		currentColumnsHeader = null;
   178 	}
   179 
   180 	@Override
   181 	public void writeQuery(String sql) {
   182 		peekState(EnumSet.of(State.STATEMENT));
   183 
   184 		if (currentColumnsHeader == null) {
   185 			currentQuery = sql;
   186 		} else {
   187 			throw new IllegalStateException("Query string '" + sql + "' must be set before columns header – was already set: " + currentColumnsHeader);
   188 		}
   189 	}
   190 
   191 	@Override
   192 	public void writeParameters(List<? extends Parameter> parameters) {
   193 		peekState(EnumSet.of(State.STATEMENT));
   194 
   195 		if (currentColumnsHeader != null) {
   196 			throw new IllegalStateException("Parameters '" + parameters + "' must be set before columns header – was already set: " + currentColumnsHeader);
   197 		}
   198 
   199 		if (currentQuery == null && parameters != null) {
   200 			throw new IllegalStateException("Parameters '" + parameters + "' must be set after query – was not yet set.");
   201 		}
   202 	}
   203 
   204 	@Override
   205 	public void writeStartRow() {
   206 		pushState(State.ROW, EnumSet.of(State.RESULT_SET));
   207 		currentColumnsCount = 0;
   208 		currentRowCount++;
   209 	}
   210 
   211 	@Override
   212 	public void writeEndRow() {
   213 		popState(EnumSet.of(State.RESULT_SET));
   214 	}
   215 
   216 	@Override
   217 	public void writeColumnValue(Object value) {
   218 		peekState(EnumSet.of(State.ROW));
   219 		currentColumnsCount++;
   220 
   221 		int declaredCount = currentColumnsHeader.getColumnCount();
   222 		if (currentColumnsCount > declaredCount) {
   223 			throw new IllegalStateException("Current columns count is " + currentColumnsCount + " which is more than declared " + declaredCount + " in header.");
   224 		}
   225 	}
   226 
   227 	@Override
   228 	public void writeUpdatesResult(int updatedRowsCount) {
   229 		peekState(EnumSet.of(State.STATEMENT));
   230 	}
   231 
   232 	@Override
   233 	public void close() throws FormatterException {
   234 	}
   235 
   236 	public FormatterContext getFormatterContext() {
   237 		return formatterContext;
   238 	}
   239 
   240 	protected ColumnsHeader getCurrentColumnsHeader() {
   241 		return currentColumnsHeader;
   242 	}
   243 
   244 	/**
   245 	 * @return column number, 1 = first
   246 	 */
   247 	protected int getCurrentColumnsCount() {
   248 		return currentColumnsCount;
   249 	}
   250 
   251 	protected boolean isCurrentColumnFirst() {
   252 		return currentColumnsCount == 1;
   253 	}
   254 
   255 	protected boolean isCurrentColumnLast() {
   256 		return currentColumnsCount == currentColumnsHeader.getColumnCount();
   257 	}
   258 
   259 	/**
   260 	 * @return row number, 1 = first
   261 	 */
   262 	protected int getCurrentRowCount() {
   263 		return currentRowCount;
   264 	}
   265 }