/
InterbaseDdlBuilder.java
381 lines (337 loc) · 16.1 KB
/
InterbaseDdlBuilder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package org.jumpmind.db.platform.interbase;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.sql.Types;
import java.util.Iterator;
import java.util.List;
import org.jumpmind.db.alter.AddColumnChange;
import org.jumpmind.db.alter.AddPrimaryKeyChange;
import org.jumpmind.db.alter.CopyColumnValueChange;
import org.jumpmind.db.alter.RemoveColumnChange;
import org.jumpmind.db.alter.TableChange;
import org.jumpmind.db.model.Column;
import org.jumpmind.db.model.ColumnTypes;
import org.jumpmind.db.model.Database;
import org.jumpmind.db.model.IIndex;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.platform.AbstractDdlBuilder;
import org.jumpmind.db.platform.DatabaseNamesConstants;
import org.jumpmind.db.platform.PlatformUtils;
/*
* The SQL Builder for the Interbase database.
*/
public class InterbaseDdlBuilder extends AbstractDdlBuilder {
public static int SWITCH_TO_LONGVARCHAR_SIZE = 4096;
public InterbaseDdlBuilder() {
super(DatabaseNamesConstants.INTERBASE);
databaseInfo.setMaxIdentifierLength(31);
databaseInfo.setCommentPrefix("/*");
databaseInfo.setCommentSuffix("*/");
databaseInfo.setSystemForeignKeyIndicesAlwaysNonUnique(true);
// BINARY and VARBINARY are also handled by the
// InterbaseBuilder.getSqlType method
databaseInfo.addNativeTypeMapping(Types.ARRAY, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.BIGINT, "NUMERIC(18,0)");
// Theoretically we could use (VAR)CHAR CHARACTER SET OCTETS but the
// JDBC driver is not
// able to handle that properly (the byte[]/BinaryStream accessors do
// not work)
databaseInfo.addNativeTypeMapping(Types.BINARY, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.BIT, "SMALLINT", Types.SMALLINT);
databaseInfo.addNativeTypeMapping(Types.BLOB, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.CLOB, "BLOB SUB_TYPE TEXT");
databaseInfo.addNativeTypeMapping(Types.DISTINCT, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.DOUBLE, "DOUBLE PRECISION");
databaseInfo.addNativeTypeMapping(Types.FLOAT, "DOUBLE PRECISION", Types.DOUBLE);
databaseInfo.addNativeTypeMapping(Types.JAVA_OBJECT, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.LONGVARBINARY, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.LONGVARCHAR, "VARCHAR("
+ SWITCH_TO_LONGVARCHAR_SIZE + ")", Types.VARCHAR);
databaseInfo.addNativeTypeMapping(Types.NULL, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.OTHER, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.REAL, "FLOAT");
databaseInfo.addNativeTypeMapping(Types.REF, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.STRUCT, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping(Types.TINYINT, "SMALLINT", Types.SMALLINT);
databaseInfo.addNativeTypeMapping(Types.VARBINARY, "BLOB", Types.LONGVARBINARY);
databaseInfo.addNativeTypeMapping("BOOLEAN", "SMALLINT", "SMALLINT");
databaseInfo.addNativeTypeMapping("DATALINK", "BLOB", "LONGVARBINARY");
databaseInfo.addNativeTypeMapping(ColumnTypes.NVARCHAR, "VARCHAR", Types.VARCHAR);
databaseInfo.addNativeTypeMapping(ColumnTypes.LONGNVARCHAR, "VARCHAR", Types.VARCHAR);
databaseInfo.addNativeTypeMapping(ColumnTypes.NCHAR, "CHAR", Types.CHAR);
databaseInfo.setDefaultSize(Types.CHAR, 254);
databaseInfo.setDefaultSize(Types.VARCHAR, 254);
databaseInfo.setHasSize(Types.BINARY, false);
databaseInfo.setHasSize(Types.VARBINARY, false);
databaseInfo.setNonBlankCharColumnSpacePadded(false);
databaseInfo.setBlankCharColumnSpacePadded(false);
databaseInfo.setCharColumnSpaceTrimmed(false);
databaseInfo.setEmptyStringNulled(false);
}
@Override
protected void createTable(Table table, StringBuilder ddl, boolean temporary, boolean recreate) {
super.createTable(table, ddl, temporary, recreate);
if (!temporary) {
// creating generator and trigger for auto-increment
Column[] columns = table.getAutoIncrementColumns();
for (int idx = 0; idx < columns.length; idx++) {
writeAutoIncrementCreateStmts(table, columns[idx], ddl);
}
}
}
@Override
protected String getNativeDefaultValue(Column column) {
if ((column.getMappedTypeCode() == Types.BIT)
|| (PlatformUtils.supportsJava14JdbcTypes() && (column.getMappedTypeCode() == PlatformUtils
.determineBooleanTypeCode()))) {
return getDefaultValueHelper().convert(column.getDefaultValue(),
column.getMappedTypeCode(), Types.SMALLINT).toString();
} else {
return super.getNativeDefaultValue(column);
}
}
@Override
protected void dropTable(Table table, StringBuilder ddl, boolean temporary, boolean recreate) {
if (!temporary && !recreate) {
// dropping generators for auto-increment
Column[] columns = table.getAutoIncrementColumns();
for (int idx = 0; idx < columns.length; idx++) {
writeAutoIncrementDropStmts(table, columns[idx], ddl);
}
}
super.dropTable(table, ddl, temporary, recreate);
}
@Override
public void writeExternalIndexDropStmt(Table table, IIndex index, StringBuilder ddl) {
// Index names in Interbase are unique to a schema and hence we do not
// need the ON <tablename> clause
ddl.append("DROP INDEX ");
printIdentifier(getIndexName(index), ddl);
printEndOfStatement(ddl);
}
/*
* Writes the creation statements to make the given column an auto-increment
* column.
*/
private void writeAutoIncrementCreateStmts(Table table, Column column, StringBuilder ddl) {
ddl.append("CREATE GENERATOR ");
printIdentifier(getGeneratorName(table, column), ddl);
printEndOfStatement(ddl);
ddl.append("CREATE TRIGGER ");
printIdentifier(getTriggerName(table, column), ddl);
ddl.append(" FOR ");
ddl.append(getFullyQualifiedTableNameShorten(table));
println(" ACTIVE BEFORE INSERT POSITION 0 AS", ddl);
ddl.append("BEGIN IF (NEW.");
printIdentifier(getColumnName(column), ddl);
ddl.append(" IS NULL) THEN NEW.");
printIdentifier(getColumnName(column), ddl);
ddl.append(" = GEN_ID(");
printIdentifier(getGeneratorName(table, column), ddl);
ddl.append(", 1); END");
printEndOfStatement(ddl);
}
/*
* Writes the statements to drop the auto-increment status for the given
* column.
*/
private void writeAutoIncrementDropStmts(Table table, Column column, StringBuilder ddl) {
ddl.append("DROP TRIGGER ");
printIdentifier(getTriggerName(table, column), ddl);
printEndOfStatement(ddl);
ddl.append("DROP GENERATOR ");
printIdentifier(getGeneratorName(table, column), ddl);
printEndOfStatement(ddl);
}
/*
* Determines the name of the trigger for an auto-increment column.
*
* @param table The table
*
* @param column The auto-increment column
*
* @return The trigger name
*/
protected String getTriggerName(Table table, Column column) {
String secondPart = column.getName();
// make sure a backup table gets a different name than the original
if (table.getName().endsWith("_")) {
secondPart += "_";
}
return getConstraintName("TRG", table, secondPart, null);
}
/*
* Determines the name of the generator for an auto-increment column.
*
* @param table The table
*
* @param column The auto-increment column
*
* @return The generator name
*/
protected String getGeneratorName(Table table, Column column) {
String secondPart = column.getName();
// make sure a backup table gets a different name than the original
if (table.getName().endsWith("_")) {
secondPart += "_";
}
return getConstraintName("GEN", table, secondPart, null);
}
@Override
protected void writeColumnAutoIncrementStmt(Table table, Column column, StringBuilder ddl) {
// we're using a generator
}
@Override
public String getSelectLastIdentityValues(Table table) {
Column[] columns = table.getAutoIncrementColumns();
if (columns.length == 0) {
return null;
} else {
StringBuffer result = new StringBuffer();
result.append("SELECT ");
for (int idx = 0; idx < columns.length; idx++) {
result.append("GEN_ID(");
result.append(getDelimitedIdentifier(getGeneratorName(table, columns[idx])));
result.append(", 0)");
}
result.append(" FROM RDB$DATABASE");
return result.toString();
}
}
public String fixLastIdentityValues(Table table) {
Column[] columns = table.getAutoIncrementColumns();
if (columns.length == 0) {
return null;
} else {
StringBuffer result = new StringBuffer();
result.append("SELECT ");
for (int idx = 0; idx < columns.length; idx++) {
result.append("GEN_ID(");
result.append(getDelimitedIdentifier(getGeneratorName(table, columns[idx])));
result.append(", (SELECT MAX(").append(columns[idx].getName()).append(")+1 FROM ");
result.append(table.getName()).append("))");
}
result.append(" FROM RDB$DATABASE");
return result.toString();
}
}
@Override
protected void processTableStructureChanges(Database currentModel, Database desiredModel,
Table sourceTable, Table targetTable, List<TableChange> changes, StringBuilder ddl) {
// TODO: Dropping of primary keys is currently not supported because we
// cannot
// determine the pk constraint names and drop them in one go
// (We could used a stored procedure if Interbase would allow them to
// use DDL)
// This will be easier once named primary keys are supported
boolean pkColumnAdded = false;
for (Iterator<TableChange> changeIt = changes.iterator(); changeIt.hasNext();) {
TableChange change = changeIt.next();
if (change instanceof AddColumnChange) {
AddColumnChange addColumnChange = (AddColumnChange) change;
// TODO: we cannot add columns to the primary key this way
// because we would have to drop the pk first and then
// add a new one afterwards which is not supported yet
if (addColumnChange.getNewColumn().isPrimaryKey()) {
pkColumnAdded = true;
} else {
processChange(currentModel, desiredModel, addColumnChange, ddl);
changeIt.remove();
}
} else if (change instanceof RemoveColumnChange) {
RemoveColumnChange removeColumnChange = (RemoveColumnChange) change;
// TODO: we cannot drop primary key columns this way
// because we would have to drop the pk first and then
// add a new one afterwards which is not supported yet
if (!removeColumnChange.getColumn().isPrimaryKey()) {
processChange(currentModel, desiredModel, removeColumnChange, ddl);
changeIt.remove();
}
} else if (change instanceof CopyColumnValueChange) {
CopyColumnValueChange copyColumnChange = (CopyColumnValueChange)change;
processChange(currentModel, desiredModel, copyColumnChange, ddl);
changeIt.remove();
}
}
for (Iterator<TableChange> changeIt = changes.iterator(); changeIt.hasNext();) {
TableChange change = changeIt.next();
// we can only add a primary key if all columns are present in the
// table
// i.e. none was added during this alteration
if ((change instanceof AddPrimaryKeyChange) && !pkColumnAdded) {
processChange(currentModel, desiredModel, (AddPrimaryKeyChange) change, ddl);
changeIt.remove();
}
}
}
/*
* Processes the addition of a column to a table.
*/
protected void processChange(Database currentModel, Database desiredModel,
AddColumnChange change, StringBuilder ddl) {
ddl.append("ALTER TABLE ");
ddl.append(getFullyQualifiedTableNameShorten(change.getChangedTable()));
printIndent(ddl);
ddl.append("ADD ");
writeColumn(change.getChangedTable(), change.getNewColumn(), ddl);
printEndOfStatement(ddl);
Table curTable = currentModel.findTable(change.getChangedTable().getName(),
delimitedIdentifierModeOn);
if (!change.isAtEnd()) {
Column prevColumn = change.getPreviousColumn();
if (prevColumn != null) {
// we need the corresponding column object from the current
// table
prevColumn = curTable.findColumn(prevColumn.getName(), delimitedIdentifierModeOn);
}
// Even though Interbase can only add columns, we can move them
// later on
ddl.append("ALTER TABLE ");
ddl.append(getFullyQualifiedTableNameShorten(change.getChangedTable()));
printIndent(ddl);
ddl.append("ALTER ");
printIdentifier(getColumnName(change.getNewColumn()), ddl);
ddl.append(" POSITION ");
// column positions start at 1 in Interbase
ddl.append(prevColumn == null ? "1" : String.valueOf(curTable
.getColumnIndex(prevColumn) + 1));
printEndOfStatement(ddl);
}
if (change.getNewColumn().isAutoIncrement()) {
writeAutoIncrementCreateStmts(curTable, change.getNewColumn(), ddl);
}
change.apply(currentModel, delimitedIdentifierModeOn);
}
/*
* Processes the removal of a column from a table.
*/
protected void processChange(Database currentModel, Database desiredModel,
RemoveColumnChange change, StringBuilder ddl) {
if (change.getColumn().isAutoIncrement()) {
writeAutoIncrementDropStmts(change.getChangedTable(), change.getColumn(), ddl);
}
ddl.append("ALTER TABLE ");
ddl.append(getFullyQualifiedTableNameShorten(change.getChangedTable()));
printIndent(ddl);
ddl.append("DROP ");
printIdentifier(getColumnName(change.getColumn()), ddl);
printEndOfStatement(ddl);
change.apply(currentModel, delimitedIdentifierModeOn);
}
}