| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.table; |
| 7 |
|
| 8 |
import java.sql.DatabaseMetaData; |
| 9 |
import java.sql.PreparedStatement; |
| 10 |
import java.sql.ResultSet; |
| 11 |
import java.sql.ResultSetMetaData; |
| 12 |
import java.sql.SQLException; |
| 13 |
import java.sql.Statement; |
| 14 |
import java.sql.Types; |
| 15 |
import java.util.ArrayList; |
| 16 |
import java.util.HashMap; |
| 17 |
import java.util.List; |
| 18 |
import java.util.Objects; |
| 19 |
|
| 20 |
import org.h2.api.ErrorCode; |
| 21 |
import org.h2.command.Prepared; |
| 22 |
import org.h2.engine.NullsDistinct; |
| 23 |
import org.h2.engine.SessionLocal; |
| 24 |
import org.h2.index.Index; |
| 25 |
import org.h2.index.IndexType; |
| 26 |
import org.h2.index.LinkedIndex; |
| 27 |
import org.h2.jdbc.JdbcConnection; |
| 28 |
import org.h2.jdbc.JdbcResultSet; |
| 29 |
import org.h2.message.DbException; |
| 30 |
import org.h2.result.LocalResult; |
| 31 |
import org.h2.result.ResultInterface; |
| 32 |
import org.h2.result.Row; |
| 33 |
import org.h2.schema.Schema; |
| 34 |
import org.h2.util.JdbcUtils; |
| 35 |
import org.h2.util.StringUtils; |
| 36 |
import org.h2.util.Utils; |
| 37 |
import org.h2.value.DataType; |
| 38 |
import org.h2.value.TypeInfo; |
| 39 |
import org.h2.value.Value; |
| 40 |
import org.h2.value.ValueDate; |
| 41 |
import org.h2.value.ValueTime; |
| 42 |
import org.h2.value.ValueTimestamp; |
| 43 |
|
| 44 |
/** |
| 45 |
* A linked table contains connection information for a table accessible by |
| 46 |
* JDBC. The table may be stored in a different database. |
| 47 |
*/ |
| 48 |
public class TableLink extends Table { |
| 49 |
|
| 50 |
private static final int MAX_RETRY = 2; |
| 51 |
|
| 52 |
private static final long ROW_COUNT_APPROXIMATION = 100_000; |
| 53 |
|
| 54 |
private final String originalSchema; |
| 55 |
private String driver, url, user, password, originalTable, qualifiedTableName; |
| 56 |
private TableLinkConnection conn; |
| 57 |
private HashMap<String, PreparedStatement> preparedMap = new HashMap<>(); |
| 58 |
private final ArrayList<Index> indexes = Utils.newSmallArrayList(); |
| 59 |
private final boolean emitUpdates; |
| 60 |
private LinkedIndex linkedIndex; |
| 61 |
private DbException connectException; |
| 62 |
private boolean storesLowerCase; |
| 63 |
private boolean storesMixedCase; |
| 64 |
private boolean storesMixedCaseQuoted; |
| 65 |
private boolean supportsMixedCaseIdentifiers; |
| 66 |
private String identifierQuoteString; |
| 67 |
private boolean globalTemporary; |
| 68 |
private boolean readOnly; |
| 69 |
private final boolean targetsMySql; |
| 70 |
private int fetchSize = 0; |
| 71 |
private boolean autocommit =true; |
| 72 |
|
| 73 |
public TableLink(Schema schema, int id, String name, String driver, |
| 74 |
String url, String user, String password, String originalSchema, |
| 75 |
String originalTable, boolean emitUpdates, boolean force) { |
| 76 |
super(schema, id, name, false, true); |
| 77 |
this.driver = driver; |
| 78 |
this.url = url; |
| 79 |
this.user = user; |
| 80 |
this.password = password; |
| 81 |
this.originalSchema = originalSchema; |
| 82 |
this.originalTable = originalTable; |
| 83 |
this.emitUpdates = emitUpdates; |
| 84 |
this.targetsMySql = isMySqlUrl(this.url); |
| 85 |
try { |
| 86 |
connect(); |
| 87 |
} catch (DbException e) { |
| 88 |
if (!force) { |
| 89 |
throw e; |
| 90 |
} |
| 91 |
Column[] cols = { }; |
| 92 |
setColumns(cols); |
| 93 |
linkedIndex = new LinkedIndex(this, id, IndexColumn.wrap(cols), 0, IndexType.createNonUnique(false)); |
| 94 |
indexes.add(linkedIndex); |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
private void connect() { |
| 99 |
connectException = null; |
| 100 |
for (int retry = 0;; retry++) { |
| 101 |
try { |
| 102 |
conn = database.getLinkConnection(driver, url, user, password); |
| 103 |
conn.setAutoCommit(autocommit); |
| 104 |
synchronized (conn) { |
| 105 |
try { |
| 106 |
readMetaData(); |
| 107 |
return; |
| 108 |
} catch (Exception e) { |
| 109 |
// could be SQLException or RuntimeException |
| 110 |
conn.close(true); |
| 111 |
conn = null; |
| 112 |
throw DbException.convert(e); |
| 113 |
} |
| 114 |
} |
| 115 |
} catch (DbException e) { |
| 116 |
if (retry >= MAX_RETRY) { |
| 117 |
connectException = e; |
| 118 |
throw e; |
| 119 |
} |
| 120 |
} |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
private void readMetaData() throws SQLException { |
| 125 |
DatabaseMetaData meta = conn.getConnection().getMetaData(); |
| 126 |
storesLowerCase = meta.storesLowerCaseIdentifiers(); |
| 127 |
storesMixedCase = meta.storesMixedCaseIdentifiers(); |
| 128 |
storesMixedCaseQuoted = meta.storesMixedCaseQuotedIdentifiers(); |
| 129 |
supportsMixedCaseIdentifiers = meta.supportsMixedCaseIdentifiers(); |
| 130 |
identifierQuoteString = meta.getIdentifierQuoteString(); |
| 131 |
ArrayList<Column> columnList = Utils.newSmallArrayList(); |
| 132 |
HashMap<String, Column> columnMap = new HashMap<>(); |
| 133 |
String schema = null; |
| 134 |
boolean isQuery = originalTable.startsWith("("); |
| 135 |
if (!isQuery) { |
| 136 |
try (ResultSet rs = meta.getTables(null, originalSchema, originalTable, null)) { |
| 137 |
if (rs.next() && rs.next()) { |
| 138 |
throw DbException.get(ErrorCode.SCHEMA_NAME_MUST_MATCH, originalTable); |
| 139 |
} |
| 140 |
} |
| 141 |
try (ResultSet rs = meta.getColumns(null, originalSchema, originalTable, null)) { |
| 142 |
int i = 0; |
| 143 |
String catalog = null; |
| 144 |
while (rs.next()) { |
| 145 |
String thisCatalog = rs.getString("TABLE_CAT"); |
| 146 |
if (catalog == null) { |
| 147 |
catalog = thisCatalog; |
| 148 |
} |
| 149 |
String thisSchema = rs.getString("TABLE_SCHEM"); |
| 150 |
if (schema == null) { |
| 151 |
schema = thisSchema; |
| 152 |
} |
| 153 |
if (!Objects.equals(catalog, thisCatalog) || |
| 154 |
!Objects.equals(schema, thisSchema)) { |
| 155 |
// if the table exists in multiple schemas or tables, |
| 156 |
// use the alternative solution |
| 157 |
columnMap.clear(); |
| 158 |
columnList.clear(); |
| 159 |
break; |
| 160 |
} |
| 161 |
String n = rs.getString("COLUMN_NAME"); |
| 162 |
n = convertColumnName(n); |
| 163 |
int sqlType = rs.getInt("DATA_TYPE"); |
| 164 |
String sqlTypeName = rs.getString("TYPE_NAME"); |
| 165 |
long precision = rs.getInt("COLUMN_SIZE"); |
| 166 |
precision = convertPrecision(sqlType, precision); |
| 167 |
int scale = rs.getInt("DECIMAL_DIGITS"); |
| 168 |
scale = convertScale(sqlType, scale); |
| 169 |
int type = DataType.convertSQLTypeToValueType(sqlType, sqlTypeName); |
| 170 |
Column col = new Column(n, TypeInfo.getTypeInfo(type, precision, scale, null), this, i++); |
| 171 |
columnList.add(col); |
| 172 |
columnMap.put(n, col); |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
if (originalTable.indexOf('.') < 0 && !StringUtils.isNullOrEmpty(schema)) { |
| 177 |
qualifiedTableName = schema + '.' + originalTable; |
| 178 |
} else { |
| 179 |
qualifiedTableName = originalTable; |
| 180 |
} |
| 181 |
// check if the table is accessible |
| 182 |
|
| 183 |
try (Statement stat = conn.getConnection().createStatement(); |
| 184 |
ResultSet rs = stat.executeQuery("SELECT * FROM " + qualifiedTableName + " T WHERE 1=0")) { |
| 185 |
if (rs instanceof JdbcResultSet) { |
| 186 |
ResultInterface result = ((JdbcResultSet) rs).getResult(); |
| 187 |
columnList.clear(); |
| 188 |
columnMap.clear(); |
| 189 |
for (int i = 0, l = result.getVisibleColumnCount(); i < l;) { |
| 190 |
String n = result.getColumnName(i); |
| 191 |
Column col = new Column(n, result.getColumnType(i), this, ++i); |
| 192 |
columnList.add(col); |
| 193 |
columnMap.put(n, col); |
| 194 |
} |
| 195 |
} else if (columnList.isEmpty()) { |
| 196 |
// alternative solution |
| 197 |
ResultSetMetaData rsMeta = rs.getMetaData(); |
| 198 |
for (int i = 0, l = rsMeta.getColumnCount(); i < l;) { |
| 199 |
String n = rsMeta.getColumnName(i + 1); |
| 200 |
n = convertColumnName(n); |
| 201 |
int sqlType = rsMeta.getColumnType(i + 1); |
| 202 |
long precision = rsMeta.getPrecision(i + 1); |
| 203 |
precision = convertPrecision(sqlType, precision); |
| 204 |
int scale = rsMeta.getScale(i + 1); |
| 205 |
scale = convertScale(sqlType, scale); |
| 206 |
int type = DataType.getValueTypeFromResultSet(rsMeta, i + 1); |
| 207 |
Column col = new Column(n, TypeInfo.getTypeInfo(type, precision, scale, null), this, i++); |
| 208 |
columnList.add(col); |
| 209 |
columnMap.put(n, col); |
| 210 |
} |
| 211 |
} |
| 212 |
} catch (Exception e) { |
| 213 |
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, e, |
| 214 |
originalTable + '(' + e + ')'); |
| 215 |
} |
| 216 |
Column[] cols = columnList.toArray(new Column[0]); |
| 217 |
setColumns(cols); |
| 218 |
int id = getId(); |
| 219 |
linkedIndex = new LinkedIndex(this, id, IndexColumn.wrap(cols), 0, IndexType.createNonUnique(false)); |
| 220 |
indexes.add(linkedIndex); |
| 221 |
if (!isQuery) { |
| 222 |
readIndexes(meta, columnMap); |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
private void readIndexes(DatabaseMetaData meta, HashMap<String, Column> columnMap) { |
| 227 |
String pkName = null; |
| 228 |
try (ResultSet rs = meta.getPrimaryKeys(null, originalSchema, originalTable)) { |
| 229 |
if (rs.next()) { |
| 230 |
pkName = readPrimaryKey(rs, columnMap); |
| 231 |
} |
| 232 |
} catch (Exception e) { |
| 233 |
// Some ODBC bridge drivers don't support it: |
| 234 |
// some combinations of "DataDirect SequeLink(R) for JDBC" |
| 235 |
// https://www.progress.com/odbc/sequelink |
| 236 |
} |
| 237 |
try (ResultSet rs = meta.getIndexInfo(null, originalSchema, originalTable, false, true)) { |
| 238 |
readIndexes(rs, columnMap, pkName); |
| 239 |
} catch (Exception e) { |
| 240 |
// Oracle throws an exception if the table is not found or is a |
| 241 |
// SYNONYM |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
private String readPrimaryKey(ResultSet rs, HashMap<String, Column> columnMap) throws SQLException { |
| 246 |
String pkName = null; |
| 247 |
// the problem is, the rows are not sorted by KEY_SEQ |
| 248 |
ArrayList<Column> list = Utils.newSmallArrayList(); |
| 249 |
do { |
| 250 |
int idx = rs.getInt("KEY_SEQ"); |
| 251 |
if (StringUtils.isNullOrEmpty(pkName)) { |
| 252 |
pkName = rs.getString("PK_NAME"); |
| 253 |
} |
| 254 |
while (list.size() < idx) { |
| 255 |
list.add(null); |
| 256 |
} |
| 257 |
String col = rs.getString("COLUMN_NAME"); |
| 258 |
col = convertColumnName(col); |
| 259 |
Column column = columnMap.get(col); |
| 260 |
if (idx == 0) { |
| 261 |
// workaround for a bug in the SQLite JDBC driver |
| 262 |
list.add(column); |
| 263 |
} else { |
| 264 |
list.set(idx - 1, column); |
| 265 |
} |
| 266 |
} while (rs.next()); |
| 267 |
addIndex(list, list.size(), IndexType.createPrimaryKey(false, false)); |
| 268 |
return pkName; |
| 269 |
} |
| 270 |
|
| 271 |
private void readIndexes(ResultSet rs, HashMap<String, Column> columnMap, String pkName) throws SQLException { |
| 272 |
String indexName = null; |
| 273 |
ArrayList<Column> list = Utils.newSmallArrayList(); |
| 274 |
int uniqueColumnCount = 0; |
| 275 |
IndexType indexType = null; |
| 276 |
while (rs.next()) { |
| 277 |
if (rs.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic) { |
| 278 |
// ignore index statistics |
| 279 |
continue; |
| 280 |
} |
| 281 |
String newIndex = rs.getString("INDEX_NAME"); |
| 282 |
if (pkName != null && pkName.equals(newIndex)) { |
| 283 |
continue; |
| 284 |
} |
| 285 |
if (indexName != null && !indexName.equals(newIndex)) { |
| 286 |
addIndex(list, uniqueColumnCount, indexType); |
| 287 |
uniqueColumnCount = 0; |
| 288 |
indexName = null; |
| 289 |
} |
| 290 |
if (indexName == null) { |
| 291 |
indexName = newIndex; |
| 292 |
list.clear(); |
| 293 |
} |
| 294 |
if (!rs.getBoolean("NON_UNIQUE")) { |
| 295 |
uniqueColumnCount++; |
| 296 |
} |
| 297 |
indexType = uniqueColumnCount > 0 |
| 298 |
? IndexType.createUnique(false, false, uniqueColumnCount, /* TODO */ NullsDistinct.NOT_DISTINCT) |
| 299 |
: IndexType.createNonUnique(false); |
| 300 |
String col = rs.getString("COLUMN_NAME"); |
| 301 |
col = convertColumnName(col); |
| 302 |
Column column = columnMap.get(col); |
| 303 |
list.add(column); |
| 304 |
} |
| 305 |
if (indexName != null) { |
| 306 |
addIndex(list, uniqueColumnCount, indexType); |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
private static long convertPrecision(int sqlType, long precision) { |
| 311 |
// workaround for an Oracle problem: |
| 312 |
// for DATE columns, the reported precision is 7 |
| 313 |
// for DECIMAL columns, the reported precision is 0 |
| 314 |
switch (sqlType) { |
| 315 |
case Types.DECIMAL: |
| 316 |
case Types.NUMERIC: |
| 317 |
if (precision == 0) { |
| 318 |
precision = 65535; |
| 319 |
} |
| 320 |
break; |
| 321 |
case Types.DATE: |
| 322 |
precision = Math.max(ValueDate.PRECISION, precision); |
| 323 |
break; |
| 324 |
case Types.TIMESTAMP: |
| 325 |
precision = Math.max(ValueTimestamp.MAXIMUM_PRECISION, precision); |
| 326 |
break; |
| 327 |
case Types.TIME: |
| 328 |
precision = Math.max(ValueTime.MAXIMUM_PRECISION, precision); |
| 329 |
break; |
| 330 |
} |
| 331 |
return precision; |
| 332 |
} |
| 333 |
|
| 334 |
private static int convertScale(int sqlType, int scale) { |
| 335 |
// workaround for an Oracle problem: |
| 336 |
// for DECIMAL columns, the reported precision is -127 |
| 337 |
switch (sqlType) { |
| 338 |
case Types.DECIMAL: |
| 339 |
case Types.NUMERIC: |
| 340 |
if (scale < 0) { |
| 341 |
scale = 32767; |
| 342 |
} |
| 343 |
break; |
| 344 |
} |
| 345 |
return scale; |
| 346 |
} |
| 347 |
|
| 348 |
private String convertColumnName(String columnName) { |
| 349 |
if(targetsMySql) { |
| 350 |
// MySQL column names are not case-sensitive on any platform |
| 351 |
columnName = StringUtils.toUpperEnglish(columnName); |
| 352 |
} else if ((storesMixedCase || storesLowerCase) && |
| 353 |
columnName.equals(StringUtils.toLowerEnglish(columnName))) { |
| 354 |
columnName = StringUtils.toUpperEnglish(columnName); |
| 355 |
} else if (storesMixedCase && !supportsMixedCaseIdentifiers) { |
| 356 |
// TeraData |
| 357 |
columnName = StringUtils.toUpperEnglish(columnName); |
| 358 |
} else if (storesMixedCase && storesMixedCaseQuoted) { |
| 359 |
// MS SQL Server (identifiers are case insensitive even if quoted) |
| 360 |
columnName = StringUtils.toUpperEnglish(columnName); |
| 361 |
} |
| 362 |
return columnName; |
| 363 |
} |
| 364 |
|
| 365 |
private void addIndex(List<Column> list, int uniqueColumnCount, IndexType indexType) { |
| 366 |
// bind the index to the leading recognized columns in the index |
| 367 |
// (null columns might come from a function-based index) |
| 368 |
int firstNull = list.indexOf(null); |
| 369 |
if (firstNull == 0) { |
| 370 |
trace.info("Omitting linked index - no recognized columns."); |
| 371 |
return; |
| 372 |
} else if (firstNull > 0) { |
| 373 |
trace.info("Unrecognized columns in linked index. " + |
| 374 |
"Registering the index against the leading {0} " + |
| 375 |
"recognized columns of {1} total columns.", firstNull, list.size()); |
| 376 |
list = list.subList(0, firstNull); |
| 377 |
} |
| 378 |
Column[] cols = list.toArray(new Column[0]); |
| 379 |
Index index = new LinkedIndex(this, 0, IndexColumn.wrap(cols), uniqueColumnCount, indexType); |
| 380 |
indexes.add(index); |
| 381 |
} |
| 382 |
|
| 383 |
@Override |
| 384 |
public String getDropSQL() { |
| 385 |
StringBuilder builder = new StringBuilder("DROP TABLE IF EXISTS "); |
| 386 |
return getSQL(builder, DEFAULT_SQL_FLAGS).toString(); |
| 387 |
} |
| 388 |
|
| 389 |
@Override |
| 390 |
public String getCreateSQL() { |
| 391 |
StringBuilder buff = new StringBuilder("CREATE FORCE "); |
| 392 |
if (isTemporary()) { |
| 393 |
if (globalTemporary) { |
| 394 |
buff.append("GLOBAL "); |
| 395 |
} else { |
| 396 |
buff.append("LOCAL "); |
| 397 |
} |
| 398 |
buff.append("TEMPORARY "); |
| 399 |
} |
| 400 |
buff.append("LINKED TABLE "); |
| 401 |
getSQL(buff, DEFAULT_SQL_FLAGS); |
| 402 |
if (comment != null) { |
| 403 |
buff.append(" COMMENT "); |
| 404 |
StringUtils.quoteStringSQL(buff, comment); |
| 405 |
} |
| 406 |
buff.append('('); |
| 407 |
StringUtils.quoteStringSQL(buff, driver).append(", "); |
| 408 |
StringUtils.quoteStringSQL(buff, url).append(", "); |
| 409 |
StringUtils.quoteStringSQL(buff, user).append(", "); |
| 410 |
StringUtils.quoteStringSQL(buff, password).append(", "); |
| 411 |
StringUtils.quoteStringSQL(buff, originalTable).append(')'); |
| 412 |
if (emitUpdates) { |
| 413 |
buff.append(" EMIT UPDATES"); |
| 414 |
} |
| 415 |
if (readOnly) { |
| 416 |
buff.append(" READONLY"); |
| 417 |
} |
| 418 |
if (fetchSize != 0) { |
| 419 |
buff.append(" FETCH_SIZE ").append(fetchSize); |
| 420 |
} |
| 421 |
if(!autocommit) { |
| 422 |
buff.append(" AUTOCOMMIT OFF"); |
| 423 |
} |
| 424 |
buff.append(" /*").append(DbException.HIDE_SQL).append("*/"); |
| 425 |
return buff.toString(); |
| 426 |
} |
| 427 |
|
| 428 |
@Override |
| 429 |
public Index addIndex(SessionLocal session, String indexName, int indexId, IndexColumn[] cols, |
| 430 |
int uniqueColumnCount, IndexType indexType, boolean create, String indexComment) { |
| 431 |
throw DbException.getUnsupportedException("LINK"); |
| 432 |
} |
| 433 |
|
| 434 |
@Override |
| 435 |
public Index getScanIndex(SessionLocal session) { |
| 436 |
return linkedIndex; |
| 437 |
} |
| 438 |
|
| 439 |
@Override |
| 440 |
public boolean isInsertable() { |
| 441 |
return !readOnly; |
| 442 |
} |
| 443 |
|
| 444 |
private void checkReadOnly() { |
| 445 |
if (readOnly) { |
| 446 |
throw DbException.get(ErrorCode.DATABASE_IS_READ_ONLY); |
| 447 |
} |
| 448 |
} |
| 449 |
|
| 450 |
@Override |
| 451 |
public void removeRow(SessionLocal session, Row row) { |
| 452 |
checkReadOnly(); |
| 453 |
getScanIndex(session).remove(session, row); |
| 454 |
} |
| 455 |
|
| 456 |
@Override |
| 457 |
public void addRow(SessionLocal session, Row row) { |
| 458 |
checkReadOnly(); |
| 459 |
getScanIndex(session).add(session, row); |
| 460 |
} |
| 461 |
|
| 462 |
@Override |
| 463 |
public void close(SessionLocal session) { |
| 464 |
if (conn != null) { |
| 465 |
try { |
| 466 |
conn.close(false); |
| 467 |
} finally { |
| 468 |
conn = null; |
| 469 |
} |
| 470 |
} |
| 471 |
} |
| 472 |
|
| 473 |
@Override |
| 474 |
public synchronized long getRowCount(SessionLocal session) { |
| 475 |
//The T alias is used to support the PostgreSQL syntax |
| 476 |
String sql = "SELECT COUNT(*) FROM " + qualifiedTableName + " T"; |
| 477 |
try { |
| 478 |
PreparedStatement prep = execute(sql, null, false, session); |
| 479 |
ResultSet rs = prep.getResultSet(); |
| 480 |
rs.next(); |
| 481 |
long count = rs.getLong(1); |
| 482 |
rs.close(); |
| 483 |
reusePreparedStatement(prep, sql); |
| 484 |
return count; |
| 485 |
} catch (Exception e) { |
| 486 |
throw wrapException(sql, e); |
| 487 |
} |
| 488 |
} |
| 489 |
|
| 490 |
/** |
| 491 |
* Wrap a SQL exception that occurred while accessing a linked table. |
| 492 |
* |
| 493 |
* @param sql the SQL statement |
| 494 |
* @param ex the exception from the remote database |
| 495 |
* @return the wrapped exception |
| 496 |
*/ |
| 497 |
public static DbException wrapException(String sql, Exception ex) { |
| 498 |
SQLException e = DbException.toSQLException(ex); |
| 499 |
return DbException.get(ErrorCode.ERROR_ACCESSING_LINKED_TABLE_2, |
| 500 |
e, sql, e.toString()); |
| 501 |
} |
| 502 |
|
| 503 |
public String getQualifiedTable() { |
| 504 |
return qualifiedTableName; |
| 505 |
} |
| 506 |
|
| 507 |
/** |
| 508 |
* Execute a SQL statement using the given parameters. Prepared |
| 509 |
* statements are kept in a hash map to avoid re-creating them. |
| 510 |
* |
| 511 |
* @param sql the SQL statement |
| 512 |
* @param params the parameters or null |
| 513 |
* @param reusePrepared if the prepared statement can be re-used immediately |
| 514 |
* @param session the session |
| 515 |
* @return the prepared statement, or null if it is re-used |
| 516 |
*/ |
| 517 |
public PreparedStatement execute(String sql, ArrayList<Value> params, boolean reusePrepared, // |
| 518 |
SessionLocal session) { |
| 519 |
if (conn == null) { |
| 520 |
throw connectException; |
| 521 |
} |
| 522 |
for (int retry = 0;; retry++) { |
| 523 |
try { |
| 524 |
synchronized (conn) { |
| 525 |
PreparedStatement prep = preparedMap.remove(sql); |
| 526 |
if (prep == null) { |
| 527 |
prep = conn.getConnection().prepareStatement(sql); |
| 528 |
if (fetchSize != 0) { |
| 529 |
prep.setFetchSize(fetchSize); |
| 530 |
} |
| 531 |
} |
| 532 |
if (trace.isDebugEnabled()) { |
| 533 |
StringBuilder builder = new StringBuilder(getName()).append(":\n").append(sql); |
| 534 |
if (params != null && !params.isEmpty()) { |
| 535 |
builder.append(" {"); |
| 536 |
for (int i = 0, l = params.size(); i < l;) { |
| 537 |
Value v = params.get(i); |
| 538 |
if (i > 0) { |
| 539 |
builder.append(", "); |
| 540 |
} |
| 541 |
builder.append(++i).append(": "); |
| 542 |
v.getSQL(builder, DEFAULT_SQL_FLAGS); |
| 543 |
} |
| 544 |
builder.append('}'); |
| 545 |
} |
| 546 |
builder.append(';'); |
| 547 |
trace.debug(builder.toString()); |
| 548 |
} |
| 549 |
if (params != null) { |
| 550 |
JdbcConnection ownConnection = session.createConnection(false); |
| 551 |
for (int i = 0, size = params.size(); i < size; i++) { |
| 552 |
Value v = params.get(i); |
| 553 |
JdbcUtils.set(prep, i + 1, v, ownConnection); |
| 554 |
} |
| 555 |
} |
| 556 |
prep.execute(); |
| 557 |
if (reusePrepared) { |
| 558 |
reusePreparedStatement(prep, sql); |
| 559 |
return null; |
| 560 |
} |
| 561 |
return prep; |
| 562 |
} |
| 563 |
} catch (SQLException e) { |
| 564 |
if (retry >= MAX_RETRY) { |
| 565 |
throw DbException.convert(e); |
| 566 |
} |
| 567 |
conn.close(true); |
| 568 |
connect(); |
| 569 |
} |
| 570 |
} |
| 571 |
} |
| 572 |
|
| 573 |
@Override |
| 574 |
public void checkSupportAlter() { |
| 575 |
throw DbException.getUnsupportedException("LINK"); |
| 576 |
} |
| 577 |
|
| 578 |
@Override |
| 579 |
public long truncate(SessionLocal session) { |
| 580 |
throw DbException.getUnsupportedException("LINK"); |
| 581 |
} |
| 582 |
|
| 583 |
@Override |
| 584 |
public boolean canGetRowCount(SessionLocal session) { |
| 585 |
return true; |
| 586 |
} |
| 587 |
|
| 588 |
@Override |
| 589 |
public boolean canDrop() { |
| 590 |
return true; |
| 591 |
} |
| 592 |
|
| 593 |
@Override |
| 594 |
public TableType getTableType() { |
| 595 |
return TableType.TABLE_LINK; |
| 596 |
} |
| 597 |
|
| 598 |
@Override |
| 599 |
public void removeChildrenAndResources(SessionLocal session) { |
| 600 |
super.removeChildrenAndResources(session); |
| 601 |
close(session); |
| 602 |
database.removeMeta(session, getId()); |
| 603 |
driver = null; |
| 604 |
url = user = password = originalTable = null; |
| 605 |
preparedMap = null; |
| 606 |
invalidate(); |
| 607 |
} |
| 608 |
|
| 609 |
public boolean isOracle() { |
| 610 |
return url.startsWith("jdbc:oracle:"); |
| 611 |
} |
| 612 |
|
| 613 |
private static boolean isMySqlUrl(String url) { |
| 614 |
return url.startsWith("jdbc:mysql:") |
| 615 |
|| url.startsWith("jdbc:mariadb:"); |
| 616 |
} |
| 617 |
|
| 618 |
@Override |
| 619 |
public ArrayList<Index> getIndexes() { |
| 620 |
return indexes; |
| 621 |
} |
| 622 |
|
| 623 |
@Override |
| 624 |
public long getMaxDataModificationId() { |
| 625 |
// data may have been modified externally |
| 626 |
return Long.MAX_VALUE; |
| 627 |
} |
| 628 |
|
| 629 |
@Override |
| 630 |
public void updateRows(Prepared prepared, SessionLocal session, LocalResult rows) { |
| 631 |
checkReadOnly(); |
| 632 |
if (emitUpdates) { |
| 633 |
while (rows.next()) { |
| 634 |
prepared.checkCanceled(); |
| 635 |
Row oldRow = rows.currentRowForTable(); |
| 636 |
rows.next(); |
| 637 |
Row newRow = rows.currentRowForTable(); |
| 638 |
linkedIndex.update(oldRow, newRow, session); |
| 639 |
} |
| 640 |
} else { |
| 641 |
super.updateRows(prepared, session, rows); |
| 642 |
} |
| 643 |
} |
| 644 |
|
| 645 |
public void setGlobalTemporary(boolean globalTemporary) { |
| 646 |
this.globalTemporary = globalTemporary; |
| 647 |
} |
| 648 |
|
| 649 |
public void setReadOnly(boolean readOnly) { |
| 650 |
this.readOnly = readOnly; |
| 651 |
} |
| 652 |
|
| 653 |
@Override |
| 654 |
public long getRowCountApproximation(SessionLocal session) { |
| 655 |
return ROW_COUNT_APPROXIMATION; |
| 656 |
} |
| 657 |
|
| 658 |
/** |
| 659 |
* Add this prepared statement to the list of cached statements. |
| 660 |
* |
| 661 |
* @param prep the prepared statement |
| 662 |
* @param sql the SQL statement |
| 663 |
*/ |
| 664 |
public void reusePreparedStatement(PreparedStatement prep, String sql) { |
| 665 |
synchronized (conn) { |
| 666 |
preparedMap.put(sql, prep); |
| 667 |
} |
| 668 |
} |
| 669 |
|
| 670 |
@Override |
| 671 |
public boolean isDeterministic() { |
| 672 |
return false; |
| 673 |
} |
| 674 |
|
| 675 |
/** |
| 676 |
* Linked tables don't know if they are readonly. This overwrites |
| 677 |
* the default handling. |
| 678 |
*/ |
| 679 |
@Override |
| 680 |
public void checkWritingAllowed() { |
| 681 |
// only the target database can verify this |
| 682 |
} |
| 683 |
|
| 684 |
@Override |
| 685 |
public void convertInsertRow(SessionLocal session, Row row, Boolean overridingSystem) { |
| 686 |
convertRow(session, row); |
| 687 |
} |
| 688 |
|
| 689 |
@Override |
| 690 |
public void convertUpdateRow(SessionLocal session, Row row, boolean fromTrigger) { |
| 691 |
convertRow(session, row); |
| 692 |
} |
| 693 |
|
| 694 |
private void convertRow(SessionLocal session, Row row) { |
| 695 |
for (int i = 0; i < columns.length; i++) { |
| 696 |
Value value = row.getValue(i); |
| 697 |
if (value != null) { |
| 698 |
// null means use the default value |
| 699 |
Column column = columns[i]; |
| 700 |
Value v2 = column.validateConvertUpdateSequence(session, value, row); |
| 701 |
if (v2 != value) { |
| 702 |
row.setValue(i, v2); |
| 703 |
} |
| 704 |
} |
| 705 |
} |
| 706 |
} |
| 707 |
|
| 708 |
/** |
| 709 |
* Specify the number of rows fetched by the linked table command |
| 710 |
* |
| 711 |
* @param fetchSize to set |
| 712 |
*/ |
| 713 |
public void setFetchSize(int fetchSize) { |
| 714 |
this.fetchSize = fetchSize; |
| 715 |
} |
| 716 |
|
| 717 |
/** |
| 718 |
* Specify if the autocommit mode is activated or not |
| 719 |
* |
| 720 |
* @param mode to set |
| 721 |
*/ |
| 722 |
public void setAutoCommit(boolean mode) { |
| 723 |
this.autocommit= mode; |
| 724 |
} |
| 725 |
|
| 726 |
/** |
| 727 |
* The autocommit mode |
| 728 |
* @return true if autocommit is on |
| 729 |
*/ |
| 730 |
public boolean getAutocommit(){ |
| 731 |
return autocommit; |
| 732 |
} |
| 733 |
|
| 734 |
/** |
| 735 |
* The number of rows to fetch |
| 736 |
* default is 0 |
| 737 |
* |
| 738 |
* @return number of rows to fetch |
| 739 |
*/ |
| 740 |
public int getFetchSize() { |
| 741 |
return fetchSize; |
| 742 |
} |
| 743 |
|
| 744 |
/** |
| 745 |
* Returns the identifier quote string or space. |
| 746 |
* |
| 747 |
* @return the identifier quote string or space |
| 748 |
*/ |
| 749 |
public String getIdentifierQuoteString() { |
| 750 |
return identifierQuoteString; |
| 751 |
} |
| 752 |
|
| 753 |
} |