Custom formatters

You can plug-in your own formatter and get output in any desired format.

Principle

The whole SQL-DK is designed for streaming – it should hold in memory as few data as possible. Thus it iterates over the result set which comes from the database and passes immediately the cells and rows to the formatter which can flush them formatted to the output without longer hesitation.

The formatter receives events from SQL-DK core, not whole result set at once. There is list of events with hinted logical hierarchy and cardinality:

void writeStartBatch(); // 1
	void writeStartDatabase(DatabaseDefinition databaseDefinition); // 1-n
		void writeStartStatement(); // 1-n
			void writeQuery(String sql); // 0-1
			void writeParameters(List<? extends Parameter> parameters); // 0-1
			void writeStartResultSet(ColumnsHeader header); // 0-n
				void writeStartRow(); // 0-n
					void writeColumnValue(Object value); // 1-n
				void writeEndRow();
			void writeEndResultSet();
			void writeUpdatesResult(int updatedRowsCount); // 0-n
		void writeEndStatement();
	void writeEndDatabase();
void writeEndBatch();

Java

Formatters must implement the info.globalcode.sql.dk.formatting.Formatter interface. Extending abstract class info.globalcode.sql.dk.formatting.AbstractFormatter is recommended – it saves your keyboard because you will only override the methods for which you need some output. The AbstractFormatter also checks the integrity (that methods are called in correct order and context).

If you override some method from AbstractFormatter, you must call the super method:

@Override
public void writeStartResultSet() {
	super.writeStartResultSet(); // don't forget to call super methods
	printResultSeparator();
}

The formatter class must have constructor with one parameter of type FormatterContext like this:

public TabularFormatter(FormatterContext formatterContext) {
	super(formatterContext); // don't forget to call super constructor
	out = formatterContext.getOutputStream();
}

The formatted output should go to the out (formatterContext.getOutputStream()), never use System.out or System.err directly. Of course you can wrap this stream by some other one like this:

out = new ColorfulPrintWriter(formatterContext.getOutputStream());

Configuration

In order to install your formatter just add compiled class or JAR to the class path and add this piece of XML to your config file:

<formatter>
		<name>my-formatter</name>
		<class>com.example.MyWonderfulFormatter</class>
</formatter>

During runtime you will choose it by --formatter my-formatter option or by setting it as default in the configuration.

Best way to tune your class path is adding an array variable into your ~/.sql-dk/environment.sh:

PLUGINS=(
	"/path/to/first/formatter.jar"
	"/path/to/second/formatter.jar"
);

Powered by GNU/Linux. Created with XML Web generátor. Uses XML, XSLT, Java, Ant and other goodies.