| 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.fulltext; |
| 7 |
|
| 8 |
import java.io.IOException; |
| 9 |
import java.nio.file.Paths; |
| 10 |
import java.sql.Connection; |
| 11 |
import java.sql.DatabaseMetaData; |
| 12 |
import java.sql.PreparedStatement; |
| 13 |
import java.sql.ResultSet; |
| 14 |
import java.sql.SQLException; |
| 15 |
import java.sql.Statement; |
| 16 |
import java.util.ArrayList; |
| 17 |
import java.util.Collections; |
| 18 |
import java.util.HashMap; |
| 19 |
|
| 20 |
import org.apache.lucene.analysis.Analyzer; |
| 21 |
import org.apache.lucene.analysis.standard.StandardAnalyzer; |
| 22 |
import org.apache.lucene.document.DateTools; |
| 23 |
import org.apache.lucene.document.Document; |
| 24 |
import org.apache.lucene.document.Field; |
| 25 |
import org.apache.lucene.document.FieldType; |
| 26 |
import org.apache.lucene.document.TextField; |
| 27 |
import org.apache.lucene.index.DirectoryReader; |
| 28 |
import org.apache.lucene.index.IndexFormatTooOldException; |
| 29 |
import org.apache.lucene.index.IndexReader; |
| 30 |
import org.apache.lucene.index.IndexWriter; |
| 31 |
import org.apache.lucene.index.IndexWriterConfig; |
| 32 |
import org.apache.lucene.index.Term; |
| 33 |
import org.apache.lucene.queryparser.flexible.standard.StandardQueryParser; |
| 34 |
import org.apache.lucene.search.IndexSearcher; |
| 35 |
import org.apache.lucene.search.Query; |
| 36 |
import org.apache.lucene.search.ScoreDoc; |
| 37 |
import org.apache.lucene.search.TopDocs; |
| 38 |
import org.apache.lucene.store.ByteBuffersDirectory; |
| 39 |
import org.apache.lucene.store.Directory; |
| 40 |
import org.apache.lucene.store.FSDirectory; |
| 41 |
import org.h2.api.Trigger; |
| 42 |
import org.h2.command.Parser; |
| 43 |
import org.h2.engine.SessionLocal; |
| 44 |
import org.h2.expression.ExpressionColumn; |
| 45 |
import org.h2.jdbc.JdbcConnection; |
| 46 |
import org.h2.store.fs.FileUtils; |
| 47 |
import org.h2.tools.SimpleResultSet; |
| 48 |
import org.h2.util.StringUtils; |
| 49 |
import org.h2.util.Utils; |
| 50 |
|
| 51 |
/** |
| 52 |
* This class implements the full text search based on Apache Lucene. |
| 53 |
* Most methods can be called using SQL statements as well. |
| 54 |
*/ |
| 55 |
public class FullTextLucene extends FullText { |
| 56 |
|
| 57 |
/** |
| 58 |
* Whether the text content should be stored in the Lucene index. |
| 59 |
*/ |
| 60 |
protected static final boolean STORE_DOCUMENT_TEXT_IN_INDEX = |
| 61 |
Utils.getProperty("h2.storeDocumentTextInIndex", false); |
| 62 |
|
| 63 |
private static final HashMap<String, IndexAccess> INDEX_ACCESS = new HashMap<>(); |
| 64 |
private static final String TRIGGER_PREFIX = "FTL_"; |
| 65 |
private static final String SCHEMA = "FTL"; |
| 66 |
private static final String LUCENE_FIELD_DATA = "_DATA"; |
| 67 |
private static final String LUCENE_FIELD_QUERY = "_QUERY"; |
| 68 |
private static final String LUCENE_FIELD_MODIFIED = "_modified"; |
| 69 |
private static final String LUCENE_FIELD_COLUMN_PREFIX = "_"; |
| 70 |
|
| 71 |
/** |
| 72 |
* The prefix for a in-memory path. This prefix is only used internally |
| 73 |
* within this class and not related to the database URL. |
| 74 |
*/ |
| 75 |
private static final String IN_MEMORY_PREFIX = "mem:"; |
| 76 |
|
| 77 |
/** |
| 78 |
* Initializes full text search functionality for this database. This adds |
| 79 |
* the following Java functions to the database: |
| 80 |
* <ul> |
| 81 |
* <li>FTL_CREATE_INDEX(schemaNameString, tableNameString, |
| 82 |
* columnListString)</li> |
| 83 |
* <li>FTL_SEARCH(queryString, limitInt, offsetInt): result set</li> |
| 84 |
* <li>FTL_REINDEX()</li> |
| 85 |
* <li>FTL_DROP_ALL()</li> |
| 86 |
* </ul> |
| 87 |
* It also adds a schema FTL to the database where bookkeeping information |
| 88 |
* is stored. This function may be called from a Java application, or by |
| 89 |
* using the SQL statements: |
| 90 |
* |
| 91 |
* <pre> |
| 92 |
* CREATE ALIAS IF NOT EXISTS FTL_INIT FOR |
| 93 |
* "org.h2.fulltext.FullTextLucene.init"; |
| 94 |
* CALL FTL_INIT(); |
| 95 |
* </pre> |
| 96 |
* |
| 97 |
* @param conn the connection |
| 98 |
* @throws SQLException on failure |
| 99 |
*/ |
| 100 |
public static void init(Connection conn) throws SQLException { |
| 101 |
try (Statement stat = conn.createStatement()) { |
| 102 |
stat.execute("CREATE SCHEMA IF NOT EXISTS " + SCHEMA); |
| 103 |
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA + |
| 104 |
".INDEXES(SCHEMA VARCHAR, `TABLE` VARCHAR, " + |
| 105 |
"COLUMNS VARCHAR, PRIMARY KEY(SCHEMA, `TABLE`))"); |
| 106 |
String className = FullTextLucene.class.getName(); |
| 107 |
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_CREATE_INDEX FOR '" + className + ".createIndex'"); |
| 108 |
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_DROP_INDEX FOR '" + className + ".dropIndex'"); |
| 109 |
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_SEARCH FOR '" + className + ".search'"); |
| 110 |
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_SEARCH_DATA FOR '" + className + ".searchData'"); |
| 111 |
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_REINDEX FOR '" + className + ".reindex'"); |
| 112 |
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_DROP_ALL FOR '" + className + ".dropAll'"); |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
/** |
| 117 |
* Create a new full text index for a table and column list. Each table may |
| 118 |
* only have one index at any time. |
| 119 |
* |
| 120 |
* @param conn the connection |
| 121 |
* @param schema the schema name of the table (case sensitive) |
| 122 |
* @param table the table name (case sensitive) |
| 123 |
* @param columnList the column list (null for all columns) |
| 124 |
* @throws SQLException on failure |
| 125 |
*/ |
| 126 |
public static void createIndex(Connection conn, String schema, |
| 127 |
String table, String columnList) throws SQLException { |
| 128 |
init(conn); |
| 129 |
PreparedStatement prep = conn.prepareStatement("INSERT INTO " + SCHEMA |
| 130 |
+ ".INDEXES(SCHEMA, `TABLE`, COLUMNS) VALUES(?, ?, ?)"); |
| 131 |
prep.setString(1, schema); |
| 132 |
prep.setString(2, table); |
| 133 |
prep.setString(3, columnList); |
| 134 |
prep.execute(); |
| 135 |
createTrigger(conn, schema, table); |
| 136 |
indexExistingRows(conn, schema, table); |
| 137 |
} |
| 138 |
|
| 139 |
/** |
| 140 |
* Drop an existing full text index for a table. This method returns |
| 141 |
* silently if no index for this table exists. |
| 142 |
* |
| 143 |
* @param conn the connection |
| 144 |
* @param schema the schema name of the table (case sensitive) |
| 145 |
* @param table the table name (case sensitive) |
| 146 |
* @throws SQLException on failure |
| 147 |
*/ |
| 148 |
public static void dropIndex(Connection conn, String schema, String table) |
| 149 |
throws SQLException { |
| 150 |
init(conn); |
| 151 |
|
| 152 |
PreparedStatement prep = conn.prepareStatement("DELETE FROM " + SCHEMA |
| 153 |
+ ".INDEXES WHERE SCHEMA=? AND `TABLE`=?"); |
| 154 |
prep.setString(1, schema); |
| 155 |
prep.setString(2, table); |
| 156 |
int rowCount = prep.executeUpdate(); |
| 157 |
if (rowCount != 0) { |
| 158 |
reindex(conn); |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
/** |
| 163 |
* Re-creates the full text index for this database. Calling this method is |
| 164 |
* usually not needed, as the index is kept up-to-date automatically. |
| 165 |
* |
| 166 |
* @param conn the connection |
| 167 |
* @throws SQLException on failure |
| 168 |
*/ |
| 169 |
public static void reindex(Connection conn) throws SQLException { |
| 170 |
init(conn); |
| 171 |
removeAllTriggers(conn, TRIGGER_PREFIX); |
| 172 |
removeIndexFiles(conn); |
| 173 |
Statement stat = conn.createStatement(); |
| 174 |
ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".INDEXES"); |
| 175 |
while (rs.next()) { |
| 176 |
String schema = rs.getString("SCHEMA"); |
| 177 |
String table = rs.getString("TABLE"); |
| 178 |
createTrigger(conn, schema, table); |
| 179 |
indexExistingRows(conn, schema, table); |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
/** |
| 184 |
* Drops all full text indexes from the database. |
| 185 |
* |
| 186 |
* @param conn the connection |
| 187 |
* @throws SQLException on failure |
| 188 |
*/ |
| 189 |
public static void dropAll(Connection conn) throws SQLException { |
| 190 |
Statement stat = conn.createStatement(); |
| 191 |
stat.execute("DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE"); |
| 192 |
removeAllTriggers(conn, TRIGGER_PREFIX); |
| 193 |
removeIndexFiles(conn); |
| 194 |
} |
| 195 |
|
| 196 |
/** |
| 197 |
* Searches from the full text index for this database. |
| 198 |
* The returned result set has the following column: |
| 199 |
* <ul><li>QUERY (varchar): the query to use to get the data. |
| 200 |
* The query does not include 'SELECT * FROM '. Example: |
| 201 |
* PUBLIC.TEST WHERE ID = 1 |
| 202 |
* </li><li>SCORE (float) the relevance score as returned by Lucene. |
| 203 |
* </li></ul> |
| 204 |
* |
| 205 |
* @param conn the connection |
| 206 |
* @param text the search query |
| 207 |
* @param limit the maximum number of rows or 0 for no limit |
| 208 |
* @param offset the offset or 0 for no offset |
| 209 |
* @return the result set |
| 210 |
* @throws SQLException on failure |
| 211 |
*/ |
| 212 |
public static ResultSet search(Connection conn, String text, int limit, |
| 213 |
int offset) throws SQLException { |
| 214 |
return search(conn, text, limit, offset, false); |
| 215 |
} |
| 216 |
|
| 217 |
/** |
| 218 |
* Searches from the full text index for this database. The result contains |
| 219 |
* the primary key data as an array. The returned result set has the |
| 220 |
* following columns: |
| 221 |
* <ul> |
| 222 |
* <li>SCHEMA (varchar): the schema name. Example: PUBLIC</li> |
| 223 |
* <li>TABLE (varchar): the table name. Example: TEST</li> |
| 224 |
* <li>COLUMNS (array of varchar): comma separated list of quoted column |
| 225 |
* names. The column names are quoted if necessary. Example: (ID)</li> |
| 226 |
* <li>KEYS (array of values): comma separated list of values. |
| 227 |
* Example: (1)</li> |
| 228 |
* <li>SCORE (float) the relevance score as returned by Lucene.</li> |
| 229 |
* </ul> |
| 230 |
* |
| 231 |
* @param conn the connection |
| 232 |
* @param text the search query |
| 233 |
* @param limit the maximum number of rows or 0 for no limit |
| 234 |
* @param offset the offset or 0 for no offset |
| 235 |
* @return the result set |
| 236 |
* @throws SQLException on failure |
| 237 |
*/ |
| 238 |
public static ResultSet searchData(Connection conn, String text, int limit, |
| 239 |
int offset) throws SQLException { |
| 240 |
return search(conn, text, limit, offset, true); |
| 241 |
} |
| 242 |
|
| 243 |
/** |
| 244 |
* Convert an exception to a fulltext exception. |
| 245 |
* |
| 246 |
* @param e the original exception |
| 247 |
* @return the converted SQL exception |
| 248 |
*/ |
| 249 |
protected static SQLException convertException(Exception e) { |
| 250 |
return new SQLException("Error while indexing document", "FULLTEXT", e); |
| 251 |
} |
| 252 |
|
| 253 |
/** |
| 254 |
* Create the trigger. |
| 255 |
* |
| 256 |
* @param conn the database connection |
| 257 |
* @param schema the schema name |
| 258 |
* @param table the table name |
| 259 |
* @throws SQLException on failure |
| 260 |
*/ |
| 261 |
private static void createTrigger(Connection conn, String schema, |
| 262 |
String table) throws SQLException { |
| 263 |
createOrDropTrigger(conn, schema, table, true); |
| 264 |
} |
| 265 |
|
| 266 |
private static void createOrDropTrigger(Connection conn, |
| 267 |
String schema, String table, boolean create) throws SQLException { |
| 268 |
Statement stat = conn.createStatement(); |
| 269 |
String trigger = StringUtils.quoteIdentifier(schema) + "." + |
| 270 |
StringUtils.quoteIdentifier(TRIGGER_PREFIX + table); |
| 271 |
stat.execute("DROP TRIGGER IF EXISTS " + trigger); |
| 272 |
if (create) { |
| 273 |
StringBuilder builder = new StringBuilder( |
| 274 |
"CREATE TRIGGER IF NOT EXISTS "); |
| 275 |
// the trigger is also called on rollback because transaction |
| 276 |
// rollback will not undo the changes in the Lucene index |
| 277 |
builder.append(trigger). |
| 278 |
append(" AFTER INSERT, UPDATE, DELETE, ROLLBACK ON "); |
| 279 |
StringUtils.quoteIdentifier(builder, schema). |
| 280 |
append('.'); |
| 281 |
StringUtils.quoteIdentifier(builder, table). |
| 282 |
append(" FOR EACH ROW CALL \""). |
| 283 |
append(FullTextLucene.FullTextTrigger.class.getName()). |
| 284 |
append('\"'); |
| 285 |
stat.execute(builder.toString()); |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
/** |
| 290 |
* Get the index writer/searcher wrapper for the given connection. |
| 291 |
* |
| 292 |
* @param conn the connection |
| 293 |
* @return the index access wrapper |
| 294 |
* @throws SQLException on failure |
| 295 |
*/ |
| 296 |
protected static IndexAccess getIndexAccess(Connection conn) |
| 297 |
throws SQLException { |
| 298 |
String path = getIndexPath(conn); |
| 299 |
synchronized (INDEX_ACCESS) { |
| 300 |
IndexAccess access = INDEX_ACCESS.get(path); |
| 301 |
while (access == null) { |
| 302 |
try { |
| 303 |
Directory indexDir = path.startsWith(IN_MEMORY_PREFIX) ? |
| 304 |
new ByteBuffersDirectory() : FSDirectory.open(Paths.get(path)); |
| 305 |
Analyzer analyzer = new StandardAnalyzer(); |
| 306 |
IndexWriterConfig conf = new IndexWriterConfig(analyzer); |
| 307 |
conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); |
| 308 |
IndexWriter writer = new IndexWriter(indexDir, conf); |
| 309 |
//see https://cwiki.apache.org/confluence/display/lucene/NearRealtimeSearch |
| 310 |
access = new IndexAccess(writer); |
| 311 |
} catch (IndexFormatTooOldException e) { |
| 312 |
reindex(conn); |
| 313 |
continue; |
| 314 |
} catch (IOException e) { |
| 315 |
throw convertException(e); |
| 316 |
} |
| 317 |
INDEX_ACCESS.put(path, access); |
| 318 |
break; |
| 319 |
} |
| 320 |
return access; |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
/** |
| 325 |
* Get the path of the Lucene index for this database. |
| 326 |
* |
| 327 |
* @param conn the database connection |
| 328 |
* @return the path |
| 329 |
* @throws SQLException on failure |
| 330 |
*/ |
| 331 |
protected static String getIndexPath(Connection conn) throws SQLException { |
| 332 |
Statement stat = conn.createStatement(); |
| 333 |
ResultSet rs = stat.executeQuery("CALL DATABASE_PATH()"); |
| 334 |
rs.next(); |
| 335 |
String path = rs.getString(1); |
| 336 |
if (path == null) { |
| 337 |
return IN_MEMORY_PREFIX + conn.getCatalog(); |
| 338 |
} |
| 339 |
int index = path.lastIndexOf(':'); |
| 340 |
// position 1 means a windows drive letter is used, ignore that |
| 341 |
if (index > 1) { |
| 342 |
path = path.substring(index + 1); |
| 343 |
} |
| 344 |
rs.close(); |
| 345 |
return path; |
| 346 |
} |
| 347 |
|
| 348 |
/** |
| 349 |
* Add the existing data to the index. |
| 350 |
* |
| 351 |
* @param conn the database connection |
| 352 |
* @param schema the schema name |
| 353 |
* @param table the table name |
| 354 |
* @throws SQLException on failure |
| 355 |
*/ |
| 356 |
private static void indexExistingRows(Connection conn, String schema, |
| 357 |
String table) throws SQLException { |
| 358 |
FullTextLucene.FullTextTrigger existing = new FullTextLucene.FullTextTrigger(); |
| 359 |
existing.init(conn, schema, null, table, false, Trigger.INSERT); |
| 360 |
String sql = "SELECT * FROM " + StringUtils.quoteIdentifier(schema) |
| 361 |
+ "." + StringUtils.quoteIdentifier(table); |
| 362 |
ResultSet rs = conn.createStatement().executeQuery(sql); |
| 363 |
int columnCount = rs.getMetaData().getColumnCount(); |
| 364 |
while (rs.next()) { |
| 365 |
Object[] row = new Object[columnCount]; |
| 366 |
for (int i = 0; i < columnCount; i++) { |
| 367 |
row[i] = rs.getObject(i + 1); |
| 368 |
} |
| 369 |
existing.insert(row, false); |
| 370 |
} |
| 371 |
existing.commitIndex(); |
| 372 |
} |
| 373 |
|
| 374 |
private static void removeIndexFiles(Connection conn) throws SQLException { |
| 375 |
String path = getIndexPath(conn); |
| 376 |
removeIndexAccess(path); |
| 377 |
if (!path.startsWith(IN_MEMORY_PREFIX)) { |
| 378 |
FileUtils.deleteRecursive(path, false); |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
/** |
| 383 |
* Close the index writer and searcher and remove them from the index access |
| 384 |
* set. |
| 385 |
* |
| 386 |
* @param indexPath the index path |
| 387 |
* @throws SQLException on failure |
| 388 |
*/ |
| 389 |
protected static void removeIndexAccess(String indexPath) |
| 390 |
throws SQLException { |
| 391 |
synchronized (INDEX_ACCESS) { |
| 392 |
try { |
| 393 |
IndexAccess access = INDEX_ACCESS.remove(indexPath); |
| 394 |
if(access != null) { |
| 395 |
access.close(); |
| 396 |
} |
| 397 |
} catch (Exception e) { |
| 398 |
throw convertException(e); |
| 399 |
} |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
/** |
| 404 |
* Do the search. |
| 405 |
* |
| 406 |
* @param conn the database connection |
| 407 |
* @param text the query |
| 408 |
* @param limit the limit |
| 409 |
* @param offset the offset |
| 410 |
* @param data whether the raw data should be returned |
| 411 |
* @return the result set |
| 412 |
* @throws SQLException on failure |
| 413 |
*/ |
| 414 |
protected static ResultSet search(Connection conn, String text, |
| 415 |
int limit, int offset, boolean data) throws SQLException { |
| 416 |
SimpleResultSet result = createResultSet(data); |
| 417 |
if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) { |
| 418 |
// this is just to query the result set columns |
| 419 |
return result; |
| 420 |
} |
| 421 |
if (text == null || StringUtils.isWhitespaceOrEmpty(text)) { |
| 422 |
return result; |
| 423 |
} |
| 424 |
try { |
| 425 |
IndexAccess access = getIndexAccess(conn); |
| 426 |
// take a reference as the searcher may change |
| 427 |
IndexSearcher searcher = access.getSearcher(); |
| 428 |
try { |
| 429 |
// reuse the same analyzer; it's thread-safe; |
| 430 |
// also allows subclasses to control the analyzer used. |
| 431 |
Analyzer analyzer = access.writer.getAnalyzer(); |
| 432 |
StandardQueryParser parser = new StandardQueryParser(analyzer); |
| 433 |
Query query = parser.parse(text, LUCENE_FIELD_DATA); |
| 434 |
// Lucene insists on a hard limit and will not provide |
| 435 |
// a total hits value. Take at least 100 which is |
| 436 |
// an optimal limit for Lucene as any more |
| 437 |
// will trigger writing results to disk. |
| 438 |
int maxResults = (limit == 0 ? 100 : limit) + offset; |
| 439 |
TopDocs docs = searcher.search(query, maxResults); |
| 440 |
long totalHits = docs.totalHits.value; |
| 441 |
if (limit == 0) { |
| 442 |
// in this context it's safe to cast |
| 443 |
limit = (int) totalHits; |
| 444 |
} |
| 445 |
for (int i = 0, len = docs.scoreDocs.length; i < limit |
| 446 |
&& i + offset < totalHits |
| 447 |
&& i + offset < len; i++) { |
| 448 |
ScoreDoc sd = docs.scoreDocs[i + offset]; |
| 449 |
Document doc = searcher.doc(sd.doc); |
| 450 |
float score = sd.score; |
| 451 |
String q = doc.get(LUCENE_FIELD_QUERY); |
| 452 |
if (data) { |
| 453 |
int idx = q.indexOf(" WHERE "); |
| 454 |
JdbcConnection c = (JdbcConnection) conn; |
| 455 |
SessionLocal session = (SessionLocal) c.getSession(); |
| 456 |
Parser p = new Parser(session); |
| 457 |
String tab = q.substring(0, idx); |
| 458 |
ExpressionColumn expr = (ExpressionColumn) p |
| 459 |
.parseExpression(tab); |
| 460 |
String schemaName = expr.getOriginalTableAliasName(); |
| 461 |
String tableName = expr.getColumnName(session, -1); |
| 462 |
q = q.substring(idx + " WHERE ".length()); |
| 463 |
String[][] columnData = parseKey(conn, q); |
| 464 |
result.addRow(schemaName, tableName, columnData[0], |
| 465 |
columnData[1], score); |
| 466 |
} else { |
| 467 |
result.addRow(q, score); |
| 468 |
} |
| 469 |
} |
| 470 |
} finally { |
| 471 |
access.returnSearcher(searcher); |
| 472 |
} |
| 473 |
} catch (Exception e) { |
| 474 |
throw convertException(e); |
| 475 |
} |
| 476 |
return result; |
| 477 |
} |
| 478 |
|
| 479 |
/** |
| 480 |
* Trigger updates the index when a inserting, updating, or deleting a row. |
| 481 |
*/ |
| 482 |
public static final class FullTextTrigger implements Trigger { |
| 483 |
|
| 484 |
private String schema; |
| 485 |
private String table; |
| 486 |
private int[] keys; |
| 487 |
private int[] indexColumns; |
| 488 |
private String[] columns; |
| 489 |
private int[] columnTypes; |
| 490 |
private String indexPath; |
| 491 |
private IndexAccess indexAccess; |
| 492 |
|
| 493 |
private final FieldType DOC_ID_FIELD_TYPE; |
| 494 |
|
| 495 |
public FullTextTrigger() { |
| 496 |
DOC_ID_FIELD_TYPE = new FieldType(TextField.TYPE_STORED); |
| 497 |
DOC_ID_FIELD_TYPE.setTokenized(false); |
| 498 |
DOC_ID_FIELD_TYPE.freeze(); |
| 499 |
} |
| 500 |
|
| 501 |
/** |
| 502 |
* INTERNAL |
| 503 |
* @see Trigger#init(Connection, String, String, String, boolean, int) |
| 504 |
*/ |
| 505 |
@Override |
| 506 |
public void init(Connection conn, String schemaName, String triggerName, |
| 507 |
String tableName, boolean before, int type) throws SQLException { |
| 508 |
this.schema = schemaName; |
| 509 |
this.table = tableName; |
| 510 |
this.indexPath = getIndexPath(conn); |
| 511 |
this.indexAccess = getIndexAccess(conn); |
| 512 |
ArrayList<String> keyList = Utils.newSmallArrayList(); |
| 513 |
DatabaseMetaData meta = conn.getMetaData(); |
| 514 |
ResultSet rs = meta.getColumns(null, |
| 515 |
StringUtils.escapeMetaDataPattern(schemaName), |
| 516 |
StringUtils.escapeMetaDataPattern(tableName), |
| 517 |
null); |
| 518 |
ArrayList<String> columnList = Utils.newSmallArrayList(); |
| 519 |
while (rs.next()) { |
| 520 |
columnList.add(rs.getString("COLUMN_NAME")); |
| 521 |
} |
| 522 |
columnTypes = new int[columnList.size()]; |
| 523 |
columns = columnList.toArray(new String[0]); |
| 524 |
rs = meta.getColumns(null, |
| 525 |
StringUtils.escapeMetaDataPattern(schemaName), |
| 526 |
StringUtils.escapeMetaDataPattern(tableName), |
| 527 |
null); |
| 528 |
for (int i = 0; rs.next(); i++) { |
| 529 |
columnTypes[i] = rs.getInt("DATA_TYPE"); |
| 530 |
} |
| 531 |
if (keyList.isEmpty()) { |
| 532 |
rs = meta.getPrimaryKeys(null, |
| 533 |
StringUtils.escapeMetaDataPattern(schemaName), |
| 534 |
tableName); |
| 535 |
while (rs.next()) { |
| 536 |
keyList.add(rs.getString("COLUMN_NAME")); |
| 537 |
} |
| 538 |
} |
| 539 |
if (keyList.isEmpty()) { |
| 540 |
throw throwException("No primary key for table " + tableName); |
| 541 |
} |
| 542 |
ArrayList<String> indexList = Utils.newSmallArrayList(); |
| 543 |
PreparedStatement prep = conn.prepareStatement( |
| 544 |
"SELECT COLUMNS FROM " + SCHEMA |
| 545 |
+ ".INDEXES WHERE SCHEMA=? AND `TABLE`=?"); |
| 546 |
prep.setString(1, schemaName); |
| 547 |
prep.setString(2, tableName); |
| 548 |
rs = prep.executeQuery(); |
| 549 |
if (rs.next()) { |
| 550 |
String cols = rs.getString(1); |
| 551 |
if (cols != null) { |
| 552 |
Collections.addAll(indexList, |
| 553 |
StringUtils.arraySplit(cols, ',', true)); |
| 554 |
} |
| 555 |
} |
| 556 |
if (indexList.isEmpty()) { |
| 557 |
indexList.addAll(columnList); |
| 558 |
} |
| 559 |
keys = new int[keyList.size()]; |
| 560 |
setColumns(keys, keyList, columnList); |
| 561 |
indexColumns = new int[indexList.size()]; |
| 562 |
setColumns(indexColumns, indexList, columnList); |
| 563 |
} |
| 564 |
|
| 565 |
/** |
| 566 |
* INTERNAL |
| 567 |
* @see Trigger#fire(Connection, Object[], Object[]) |
| 568 |
*/ |
| 569 |
@Override |
| 570 |
public void fire(Connection conn, Object[] oldRow, Object[] newRow) |
| 571 |
throws SQLException { |
| 572 |
if (oldRow != null) { |
| 573 |
if (newRow != null) { |
| 574 |
// update |
| 575 |
if (hasChanged(oldRow, newRow, indexColumns)) { |
| 576 |
delete(oldRow, false); |
| 577 |
insert(newRow, true); |
| 578 |
} |
| 579 |
} else { |
| 580 |
// delete |
| 581 |
delete(oldRow, true); |
| 582 |
} |
| 583 |
} else if (newRow != null) { |
| 584 |
// insert |
| 585 |
insert(newRow, true); |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
/** |
| 590 |
* INTERNAL |
| 591 |
*/ |
| 592 |
@Override |
| 593 |
public void close() throws SQLException { |
| 594 |
removeIndexAccess(indexPath); |
| 595 |
} |
| 596 |
|
| 597 |
/** |
| 598 |
* Commit all changes to the Lucene index. |
| 599 |
* @throws SQLException on failure |
| 600 |
*/ |
| 601 |
void commitIndex() throws SQLException { |
| 602 |
try { |
| 603 |
indexAccess.commit(); |
| 604 |
} catch (IOException e) { |
| 605 |
throw convertException(e); |
| 606 |
} |
| 607 |
} |
| 608 |
|
| 609 |
/** |
| 610 |
* Add a row to the index. |
| 611 |
* |
| 612 |
* @param row the row |
| 613 |
* @param commitIndex whether to commit the changes to the Lucene index |
| 614 |
* @throws SQLException on failure |
| 615 |
*/ |
| 616 |
void insert(Object[] row, boolean commitIndex) throws SQLException { |
| 617 |
String query = getQuery(row); |
| 618 |
Document doc = new Document(); |
| 619 |
doc.add(new Field(LUCENE_FIELD_QUERY, query, DOC_ID_FIELD_TYPE)); |
| 620 |
long time = System.currentTimeMillis(); |
| 621 |
doc.add(new Field(LUCENE_FIELD_MODIFIED, |
| 622 |
DateTools.timeToString(time, DateTools.Resolution.SECOND), |
| 623 |
TextField.TYPE_STORED)); |
| 624 |
StringBuilder builder = new StringBuilder(); |
| 625 |
for (int i = 0, length = indexColumns.length; i < length; i++) { |
| 626 |
int index = indexColumns[i]; |
| 627 |
String columnName = columns[index]; |
| 628 |
String data = asString(row[index], columnTypes[index]); |
| 629 |
// column names that start with _ |
| 630 |
// must be escaped to avoid conflicts |
| 631 |
// with internal field names (_DATA, _QUERY, _modified) |
| 632 |
if (columnName.startsWith(LUCENE_FIELD_COLUMN_PREFIX)) { |
| 633 |
columnName = LUCENE_FIELD_COLUMN_PREFIX + columnName; |
| 634 |
} |
| 635 |
doc.add(new Field(columnName, data, TextField.TYPE_NOT_STORED)); |
| 636 |
if (i > 0) { |
| 637 |
builder.append(' '); |
| 638 |
} |
| 639 |
builder.append(data); |
| 640 |
} |
| 641 |
FieldType dataFieldType = STORE_DOCUMENT_TEXT_IN_INDEX ? |
| 642 |
TextField.TYPE_STORED : TextField.TYPE_NOT_STORED; |
| 643 |
doc.add(new Field(LUCENE_FIELD_DATA, builder.toString(), dataFieldType)); |
| 644 |
try { |
| 645 |
indexAccess.writer.addDocument(doc); |
| 646 |
if (commitIndex) { |
| 647 |
commitIndex(); |
| 648 |
} |
| 649 |
} catch (IOException e) { |
| 650 |
throw convertException(e); |
| 651 |
} |
| 652 |
} |
| 653 |
|
| 654 |
/** |
| 655 |
* Delete a row from the index. |
| 656 |
* |
| 657 |
* @param row the row |
| 658 |
* @param commitIndex whether to commit the changes to the Lucene index |
| 659 |
* @throws SQLException on failure |
| 660 |
*/ |
| 661 |
private void delete(Object[] row, boolean commitIndex) throws SQLException { |
| 662 |
String query = getQuery(row); |
| 663 |
try { |
| 664 |
Term term = new Term(LUCENE_FIELD_QUERY, query); |
| 665 |
indexAccess.writer.deleteDocuments(term); |
| 666 |
if (commitIndex) { |
| 667 |
commitIndex(); |
| 668 |
} |
| 669 |
} catch (IOException e) { |
| 670 |
throw convertException(e); |
| 671 |
} |
| 672 |
} |
| 673 |
|
| 674 |
private String getQuery(Object[] row) throws SQLException { |
| 675 |
StringBuilder builder = new StringBuilder(); |
| 676 |
if (schema != null) { |
| 677 |
StringUtils.quoteIdentifier(builder, schema).append('.'); |
| 678 |
} |
| 679 |
StringUtils.quoteIdentifier(builder, table).append(" WHERE "); |
| 680 |
for (int i = 0, length = keys.length; i < length; i++) { |
| 681 |
if (i > 0) { |
| 682 |
builder.append(" AND "); |
| 683 |
} |
| 684 |
int columnIndex = keys[i]; |
| 685 |
StringUtils.quoteIdentifier(builder, columns[columnIndex]); |
| 686 |
Object o = row[columnIndex]; |
| 687 |
if (o == null) { |
| 688 |
builder.append(" IS NULL"); |
| 689 |
} else { |
| 690 |
builder.append('=').append(FullText.quoteSQL(o, columnTypes[columnIndex])); |
| 691 |
} |
| 692 |
} |
| 693 |
return builder.toString(); |
| 694 |
} |
| 695 |
} |
| 696 |
|
| 697 |
/** |
| 698 |
* A wrapper for the Lucene writer and searcher. |
| 699 |
*/ |
| 700 |
private static final class IndexAccess { |
| 701 |
|
| 702 |
/** |
| 703 |
* The index writer. |
| 704 |
*/ |
| 705 |
final IndexWriter writer; |
| 706 |
|
| 707 |
/** |
| 708 |
* The index searcher. |
| 709 |
*/ |
| 710 |
private IndexSearcher searcher; |
| 711 |
|
| 712 |
IndexAccess(IndexWriter writer) throws IOException { |
| 713 |
this.writer = writer; |
| 714 |
initializeSearcher(); |
| 715 |
} |
| 716 |
|
| 717 |
/** |
| 718 |
* Start using the searcher. |
| 719 |
* |
| 720 |
* @return the searcher |
| 721 |
* @throws IOException on failure |
| 722 |
*/ |
| 723 |
synchronized IndexSearcher getSearcher() throws IOException { |
| 724 |
if (!searcher.getIndexReader().tryIncRef()) { |
| 725 |
initializeSearcher(); |
| 726 |
} |
| 727 |
return searcher; |
| 728 |
} |
| 729 |
|
| 730 |
private void initializeSearcher() throws IOException { |
| 731 |
IndexReader reader = DirectoryReader.open(writer); |
| 732 |
searcher = new IndexSearcher(reader); |
| 733 |
} |
| 734 |
|
| 735 |
/** |
| 736 |
* Stop using the searcher. |
| 737 |
* |
| 738 |
* @param searcher the searcher |
| 739 |
* @throws IOException on failure |
| 740 |
*/ |
| 741 |
synchronized void returnSearcher(IndexSearcher searcher) throws IOException { |
| 742 |
searcher.getIndexReader().decRef(); |
| 743 |
} |
| 744 |
|
| 745 |
/** |
| 746 |
* Commit the changes. |
| 747 |
* @throws IOException on failure |
| 748 |
*/ |
| 749 |
public synchronized void commit() throws IOException { |
| 750 |
writer.commit(); |
| 751 |
returnSearcher(searcher); |
| 752 |
searcher = new IndexSearcher(DirectoryReader.open(writer)); |
| 753 |
} |
| 754 |
|
| 755 |
/** |
| 756 |
* Close the index. |
| 757 |
* @throws IOException on failure |
| 758 |
*/ |
| 759 |
public synchronized void close() throws IOException { |
| 760 |
searcher = null; |
| 761 |
writer.close(); |
| 762 |
} |
| 763 |
} |
| 764 |
} |