01: /*
02: * TextFormatter.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.gui.editor;
13:
14: import java.util.Set;
15: import workbench.gui.sql.EditorPanel;
16: import workbench.log.LogMgr;
17: import workbench.resource.Settings;
18: import workbench.sql.DelimiterDefinition;
19: import workbench.sql.ScriptParser;
20: import workbench.sql.formatter.SqlFormatter;
21: import workbench.util.StringUtil;
22:
23: /**
24: *
25: * @author support@sql-workbench.net
26: */
27: public class TextFormatter {
28:
29: public TextFormatter() {
30: }
31:
32: public void formatSql(EditorPanel editor,
33: DelimiterDefinition alternateDelimiter, Set dbFunctions,
34: Set dbDatatypes, String lineComment) {
35: String sql = editor.getSelectedStatement();
36: ScriptParser parser = new ScriptParser();
37: parser.setAlternateDelimiter(alternateDelimiter);
38: parser.setReturnStartingWhitespace(true);
39: parser.setAlternateLineComment(lineComment);
40: parser.setScript(sql);
41:
42: String delimit = parser.getDelimiterString();
43:
44: int count = parser.getSize();
45: if (count < 1)
46: return;
47:
48: StringBuilder newSql = new StringBuilder(sql.length() + 100);
49:
50: String end = Settings.getInstance()
51: .getInternalEditorLineEnding();
52:
53: for (int i = 0; i < count; i++) {
54: String command = parser.getCommand(i);
55:
56: // no need to format "empty" strings
57: if (StringUtil.isEmptyString(command)
58: || StringUtil.isWhitespace(command)) {
59: newSql.append(command);
60: continue;
61: }
62:
63: SqlFormatter f = new SqlFormatter(command, Settings
64: .getInstance().getFormatterMaxSubselectLength());
65: f.setDBFunctions(dbFunctions);
66: f.setDbDataTypes(dbDatatypes);
67: int cols = Settings.getInstance()
68: .getFormatterMaxColumnsInSelect();
69: f.setMaxColumnsPerSelect(cols);
70:
71: try {
72: String formattedSql = f.getFormattedSql().toString();
73: newSql.append(formattedSql);
74: if (!command.trim().endsWith(delimit)) {
75: newSql.append(delimit);
76: }
77: } catch (Exception e) {
78: LogMgr.logError("EditorPanel.reformatSql()",
79: "Error when formatting SQL", e);
80: }
81: }
82:
83: if (newSql.length() == 0)
84: return;
85:
86: if (editor.isTextSelected()) {
87: editor.setSelectedText(newSql.toString());
88: } else {
89: editor.setText(newSql.toString());
90: }
91: }
92: }
|