Debian Codegraph @

src/main/org/h2/fulltext/FullText.java

raw
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.io.Reader;
10 import java.io.StreamTokenizer;
11 import java.sql.Clob;
12 import java.sql.Connection;
13 import java.sql.DatabaseMetaData;
14 import java.sql.PreparedStatement;
15 import java.sql.ResultSet;
16 import java.sql.SQLException;
17 import java.sql.Statement;
18 import java.sql.Types;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.Set;
24 import java.util.StringTokenizer;
25 import java.util.UUID;
26
27 import org.h2.api.Trigger;
28 import org.h2.command.Parser;
29 import org.h2.engine.SessionLocal;
30 import org.h2.expression.Expression;
31 import org.h2.expression.ExpressionColumn;
32 import org.h2.expression.ValueExpression;
33 import org.h2.expression.condition.Comparison;
34 import org.h2.expression.condition.ConditionAndOr;
35 import org.h2.jdbc.JdbcConnection;
36 import org.h2.message.DbException;
37 import org.h2.tools.SimpleResultSet;
38 import org.h2.util.IOUtils;
39 import org.h2.util.StringUtils;
40 import org.h2.util.Utils;
41
42 /**
43 * This class implements the native full text search.
44 * Most methods can be called using SQL statements as well.
45 */
46 public class FullText {
47
48 /**
49 * A column name of the result set returned by the searchData method.
50 */
51 private static final String FIELD_SCHEMA = "SCHEMA";
52
53 /**
54 * A column name of the result set returned by the searchData method.
55 */
56 private static final String FIELD_TABLE = "TABLE";
57
58 /**
59 * A column name of the result set returned by the searchData method.
60 */
61 private static final String FIELD_COLUMNS = "COLUMNS";
62
63 /**
64 * A column name of the result set returned by the searchData method.
65 */
66 private static final String FIELD_KEYS = "KEYS";
67
68 /**
69 * The hit score.
70 */
71 private static final String FIELD_SCORE = "SCORE";
72
73 private static final String TRIGGER_PREFIX = "FT_";
74 private static final String SCHEMA = "FT";
75 private static final String SELECT_MAP_BY_WORD_ID =
76 "SELECT ROWID FROM " + SCHEMA + ".MAP WHERE WORDID=?";
77 private static final String SELECT_ROW_BY_ID =
78 "SELECT `KEY`, INDEXID FROM " + SCHEMA + ".ROWS WHERE ID=?";
79
80 /**
81 * The column name of the result set returned by the search method.
82 */
83 private static final String FIELD_QUERY = "QUERY";
84
85 /**
86 * Initializes full text search functionality for this database. This adds
87 * the following Java functions to the database:
88 * <ul>
89 * <li>FT_CREATE_INDEX(schemaNameString, tableNameString,
90 * columnListString)</li>
91 * <li>FT_SEARCH(queryString, limitInt, offsetInt): result set</li>
92 * <li>FT_REINDEX()</li>
93 * <li>FT_DROP_ALL()</li>
94 * </ul>
95 * It also adds a schema FT to the database where bookkeeping information
96 * is stored. This function may be called from a Java application, or by
97 * using the SQL statements:
98 *
99 * <pre>
100 * CREATE ALIAS IF NOT EXISTS FT_INIT FOR
101 * &quot;org.h2.fulltext.FullText.init&quot;;
102 * CALL FT_INIT();
103 * </pre>
104 *
105 * @param conn the connection
106 * @throws SQLException on failure
107 */
108 public static void init(Connection conn) throws SQLException {
109 Statement stat = conn.createStatement();
110 stat.execute("CREATE SCHEMA IF NOT EXISTS " + SCHEMA);
111 stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
112 ".INDEXES(ID INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " +
113 "SCHEMA VARCHAR, `TABLE` VARCHAR, COLUMNS VARCHAR, " +
114 "UNIQUE(SCHEMA, `TABLE`))");
115 stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
116 ".WORDS(ID INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, " +
117 "NAME VARCHAR, UNIQUE(NAME))");
118 stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
119 ".ROWS(ID BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, HASH INT, INDEXID INT, " +
120 "`KEY` VARCHAR, UNIQUE(HASH, INDEXID, `KEY`))");
121 stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
122 ".MAP(ROWID INT, WORDID INT, PRIMARY KEY(WORDID, ROWID))");
123 stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
124 ".IGNORELIST(LIST VARCHAR)");
125 stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
126 ".SETTINGS(`KEY` VARCHAR PRIMARY KEY, `VALUE` VARCHAR)");
127 String className = FullText.class.getName();
128 stat.execute("CREATE ALIAS IF NOT EXISTS FT_CREATE_INDEX FOR '" + className + ".createIndex'");
129 stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_INDEX FOR '" + className + ".dropIndex'");
130 stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH FOR '" + className + ".search'");
131 stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH_DATA FOR '" + className + ".searchData'");
132 stat.execute("CREATE ALIAS IF NOT EXISTS FT_REINDEX FOR '" + className + ".reindex'");
133 stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_ALL FOR '" + className + ".dropAll'");
134 FullTextSettings setting = FullTextSettings.getInstance(conn);
135 ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA +
136 ".IGNORELIST");
137 while (rs.next()) {
138 String commaSeparatedList = rs.getString(1);
139 setIgnoreList(setting, commaSeparatedList);
140 }
141 rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".SETTINGS");
142 while (rs.next()) {
143 String key = rs.getString(1);
144 if ("whitespaceChars".equals(key)) {
145 String value = rs.getString(2);
146 setting.setWhitespaceChars(value);
147 }
148 }
149 rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".WORDS");
150 while (rs.next()) {
151 String word = rs.getString("NAME");
152 int id = rs.getInt("ID");
153 word = setting.convertWord(word);
154 if (word != null) {
155 setting.addWord(word, id);
156 }
157 }
158 setting.setInitialized(true);
159 }
160
161 /**
162 * Create a new full text index for a table and column list. Each table may
163 * only have one index at any time.
164 *
165 * @param conn the connection
166 * @param schema the schema name of the table (case sensitive)
167 * @param table the table name (case sensitive)
168 * @param columnList the column list (null for all columns)
169 * @throws SQLException on failure
170 */
171 public static void createIndex(Connection conn, String schema,
172 String table, String columnList) throws SQLException {
173 init(conn);
174 PreparedStatement prep = conn.prepareStatement("INSERT INTO " + SCHEMA
175 + ".INDEXES(SCHEMA, `TABLE`, COLUMNS) VALUES(?, ?, ?)");
176 prep.setString(1, schema);
177 prep.setString(2, table);
178 prep.setString(3, columnList);
179 prep.execute();
180 createTrigger(conn, schema, table);
181 indexExistingRows(conn, schema, table);
182 }
183
184 /**
185 * Re-creates the full text index for this database. Calling this method is
186 * usually not needed, as the index is kept up-to-date automatically.
187 *
188 * @param conn the connection
189 * @throws SQLException on failure
190 */
191 public static void reindex(Connection conn) throws SQLException {
192 init(conn);
193 removeAllTriggers(conn, TRIGGER_PREFIX);
194 FullTextSettings setting = FullTextSettings.getInstance(conn);
195 setting.clearWordList();
196 Statement stat = conn.createStatement();
197 stat.execute("TRUNCATE TABLE " + SCHEMA + ".WORDS");
198 stat.execute("TRUNCATE TABLE " + SCHEMA + ".ROWS");
199 stat.execute("TRUNCATE TABLE " + SCHEMA + ".MAP");
200 ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".INDEXES");
201 while (rs.next()) {
202 String schema = rs.getString("SCHEMA");
203 String table = rs.getString("TABLE");
204 createTrigger(conn, schema, table);
205 indexExistingRows(conn, schema, table);
206 }
207 }
208
209 /**
210 * Drop an existing full text index for a table. This method returns
211 * silently if no index for this table exists.
212 *
213 * @param conn the connection
214 * @param schema the schema name of the table (case sensitive)
215 * @param table the table name (case sensitive)
216 * @throws SQLException on failure
217 */
218 public static void dropIndex(Connection conn, String schema, String table)
219 throws SQLException {
220 init(conn);
221 PreparedStatement prep = conn.prepareStatement("SELECT ID FROM " + SCHEMA
222 + ".INDEXES WHERE SCHEMA=? AND `TABLE`=?");
223 prep.setString(1, schema);
224 prep.setString(2, table);
225 ResultSet rs = prep.executeQuery();
226 if (!rs.next()) {
227 return;
228 }
229 int indexId = rs.getInt(1);
230 prep = conn.prepareStatement("DELETE FROM " + SCHEMA
231 + ".INDEXES WHERE ID=?");
232 prep.setInt(1, indexId);
233 prep.execute();
234 createOrDropTrigger(conn, schema, table, false);
235 prep = conn.prepareStatement("DELETE FROM " + SCHEMA +
236 ".ROWS WHERE INDEXID=? AND ROWNUM<10000");
237 while (true) {
238 prep.setInt(1, indexId);
239 int deleted = prep.executeUpdate();
240 if (deleted == 0) {
241 break;
242 }
243 }
244 prep = conn.prepareStatement("DELETE FROM " + SCHEMA + ".MAP " +
245 "WHERE NOT EXISTS (SELECT * FROM " + SCHEMA +
246 ".ROWS R WHERE R.ID=ROWID) AND ROWID<10000");
247 while (true) {
248 int deleted = prep.executeUpdate();
249 if (deleted == 0) {
250 break;
251 }
252 }
253 }
254
255 /**
256 * Drops all full text indexes from the database.
257 *
258 * @param conn the connection
259 * @throws SQLException on failure
260 */
261 public static void dropAll(Connection conn) throws SQLException {
262 init(conn);
263 Statement stat = conn.createStatement();
264 stat.execute("DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE");
265 removeAllTriggers(conn, TRIGGER_PREFIX);
266 FullTextSettings setting = FullTextSettings.getInstance(conn);
267 setting.removeAllIndexes();
268 setting.clearIgnored();
269 setting.clearWordList();
270 }
271
272 /**
273 * Searches from the full text index for this database.
274 * The returned result set has the following column:
275 * <ul><li>QUERY (varchar): the query to use to get the data.
276 * The query does not include 'SELECT * FROM '. Example:
277 * PUBLIC.TEST WHERE ID = 1
278 * </li><li>SCORE (float) the relevance score. This value is always 1.0
279 * for the native fulltext search.
280 * </li></ul>
281 *
282 * @param conn the connection
283 * @param text the search query
284 * @param limit the maximum number of rows or 0 for no limit
285 * @param offset the offset or 0 for no offset
286 * @return the result set
287 * @throws SQLException on failure
288 */
289 public static ResultSet search(Connection conn, String text, int limit,
290 int offset) throws SQLException {
291 try {
292 return search(conn, text, limit, offset, false);
293 } catch (DbException e) {
294 throw DbException.toSQLException(e);
295 }
296 }
297
298 /**
299 * Searches from the full text index for this database. The result contains
300 * the primary key data as an array. The returned result set has the
301 * following columns:
302 * <ul>
303 * <li>SCHEMA (varchar): the schema name. Example: PUBLIC </li>
304 * <li>TABLE (varchar): the table name. Example: TEST </li>
305 * <li>COLUMNS (array of varchar): comma separated list of quoted column
306 * names. The column names are quoted if necessary. Example: (ID) </li>
307 * <li>KEYS (array of values): comma separated list of values. Example: (1)
308 * </li>
309 * <li>SCORE (float) the relevance score. This value is always 1.0
310 * for the native fulltext search.
311 * </li>
312 * </ul>
313 *
314 * @param conn the connection
315 * @param text the search query
316 * @param limit the maximum number of rows or 0 for no limit
317 * @param offset the offset or 0 for no offset
318 * @return the result set
319 * @throws SQLException on failure
320 */
321 public static ResultSet searchData(Connection conn, String text, int limit,
322 int offset) throws SQLException {
323 try {
324 return search(conn, text, limit, offset, true);
325 } catch (DbException e) {
326 throw DbException.toSQLException(e);
327 }
328 }
329
330 /**
331 * Change the ignore list. The ignore list is a comma separated list of
332 * common words that must not be indexed. The default ignore list is empty.
333 * If indexes already exist at the time this list is changed, reindex must
334 * be called.
335 *
336 * @param conn the connection
337 * @param commaSeparatedList the list
338 * @throws SQLException on failure
339 */
340 public static void setIgnoreList(Connection conn, String commaSeparatedList)
341 throws SQLException {
342 try {
343 init(conn);
344 FullTextSettings setting = FullTextSettings.getInstance(conn);
345 setIgnoreList(setting, commaSeparatedList);
346 Statement stat = conn.createStatement();
347 stat.execute("TRUNCATE TABLE " + SCHEMA + ".IGNORELIST");
348 PreparedStatement prep = conn.prepareStatement("INSERT INTO " +
349 SCHEMA + ".IGNORELIST VALUES(?)");
350 prep.setString(1, commaSeparatedList);
351 prep.execute();
352 } catch (DbException e) {
353 throw DbException.toSQLException(e);
354 }
355 }
356
357 /**
358 * Change the whitespace characters. The whitespace characters are used to
359 * separate words. If indexes already exist at the time this list is
360 * changed, reindex must be called.
361 *
362 * @param conn the connection
363 * @param whitespaceChars the list of characters
364 * @throws SQLException on failure
365 */
366 public static void setWhitespaceChars(Connection conn,
367 String whitespaceChars) throws SQLException {
368 try {
369 init(conn);
370 FullTextSettings setting = FullTextSettings.getInstance(conn);
371 setting.setWhitespaceChars(whitespaceChars);
372 PreparedStatement prep = conn.prepareStatement("MERGE INTO " +
373 SCHEMA + ".SETTINGS VALUES(?, ?)");
374 prep.setString(1, "whitespaceChars");
375 prep.setString(2, whitespaceChars);
376 prep.execute();
377 } catch (DbException e) {
378 throw DbException.toSQLException(e);
379 }
380 }
381
382 /**
383 * INTERNAL.
384 * Convert the object to a string.
385 *
386 * @param data the object
387 * @param type the SQL type
388 * @return the string
389 * @throws SQLException on failure
390 */
391 protected static String asString(Object data, int type) throws SQLException {
392 if (data == null) {
393 return "NULL";
394 }
395 switch (type) {
396 case Types.BIT:
397 case Types.BOOLEAN:
398 case Types.INTEGER:
399 case Types.BIGINT:
400 case Types.DECIMAL:
401 case Types.DOUBLE:
402 case Types.FLOAT:
403 case Types.NUMERIC:
404 case Types.REAL:
405 case Types.SMALLINT:
406 case Types.TINYINT:
407 case Types.DATE:
408 case Types.TIME:
409 case Types.TIMESTAMP:
410 case Types.LONGVARCHAR:
411 case Types.CHAR:
412 case Types.VARCHAR:
413 return data.toString();
414 case Types.CLOB:
415 try {
416 if (data instanceof Clob) {
417 data = ((Clob) data).getCharacterStream();
418 }
419 return IOUtils.readStringAndClose((Reader) data, -1);
420 } catch (IOException e) {
421 throw DbException.toSQLException(e);
422 }
423 case Types.VARBINARY:
424 case Types.LONGVARBINARY:
425 case Types.BINARY:
426 case Types.JAVA_OBJECT:
427 case Types.OTHER:
428 case Types.BLOB:
429 case Types.STRUCT:
430 case Types.REF:
431 case Types.NULL:
432 case Types.ARRAY:
433 case Types.DATALINK:
434 case Types.DISTINCT:
435 throw throwException("Unsupported column data type: " + type);
436 default:
437 return "";
438 }
439 }
440
441 /**
442 * Create an empty search result and initialize the columns.
443 *
444 * @param data true if the result set should contain the primary key data as
445 * an array.
446 * @return the empty result set
447 */
448 protected static SimpleResultSet createResultSet(boolean data) {
449 SimpleResultSet result = new SimpleResultSet();
450 if (data) {
451 result.addColumn(FullText.FIELD_SCHEMA, Types.VARCHAR, 0, 0);
452 result.addColumn(FullText.FIELD_TABLE, Types.VARCHAR, 0, 0);
453 result.addColumn(FullText.FIELD_COLUMNS, Types.ARRAY, "VARCHAR ARRAY", 0, 0);
454 result.addColumn(FullText.FIELD_KEYS, Types.ARRAY, "VARCHAR ARRAY", 0, 0);
455 } else {
456 result.addColumn(FullText.FIELD_QUERY, Types.VARCHAR, 0, 0);
457 }
458 result.addColumn(FullText.FIELD_SCORE, Types.FLOAT, 0, 0);
459 return result;
460 }
461
462 /**
463 * Parse a primary key condition into the primary key columns.
464 *
465 * @param conn the database connection
466 * @param key the primary key condition as a string
467 * @return an array containing the column name list and the data list
468 */
469 protected static String[][] parseKey(Connection conn, String key) {
470 ArrayList<String> columns = Utils.newSmallArrayList();
471 ArrayList<String> data = Utils.newSmallArrayList();
472 JdbcConnection c = (JdbcConnection) conn;
473 SessionLocal session = (SessionLocal) c.getSession();
474 Parser p = new Parser(session);
475 Expression expr = p.parseExpression(key);
476 addColumnData(session, columns, data, expr);
477 String[] col = columns.toArray(new String[0]);
478 String[] dat = data.toArray(new String[0]);
479 String[][] columnData = { col, dat };
480 return columnData;
481 }
482
483 /**
484 * INTERNAL.
485 * Convert an object to a String as used in a SQL statement.
486 *
487 * @param data the object
488 * @param type the SQL type
489 * @return the SQL String
490 * @throws SQLException on failure
491 */
492 protected static String quoteSQL(Object data, int type) throws SQLException {
493 if (data == null) {
494 return "NULL";
495 }
496 switch (type) {
497 case Types.BIT:
498 case Types.BOOLEAN:
499 case Types.INTEGER:
500 case Types.BIGINT:
501 case Types.DECIMAL:
502 case Types.DOUBLE:
503 case Types.FLOAT:
504 case Types.NUMERIC:
505 case Types.REAL:
506 case Types.SMALLINT:
507 case Types.TINYINT:
508 return data.toString();
509 case Types.DATE:
510 case Types.TIME:
511 case Types.TIMESTAMP:
512 case Types.LONGVARCHAR:
513 case Types.CHAR:
514 case Types.VARCHAR:
515 return quoteString(data.toString());
516 case Types.VARBINARY:
517 case Types.LONGVARBINARY:
518 case Types.BINARY:
519 if (data instanceof UUID) {
520 return "'" + data + "'";
521 }
522 byte[] bytes = (byte[]) data;
523 StringBuilder builder = new StringBuilder(bytes.length * 2 + 2).append('\'');
524 StringUtils.convertBytesToHex(builder, bytes).append('\'');
525 return builder.toString();
526 case Types.CLOB:
527 case Types.JAVA_OBJECT:
528 case Types.OTHER:
529 case Types.BLOB:
530 case Types.STRUCT:
531 case Types.REF:
532 case Types.NULL:
533 case Types.ARRAY:
534 case Types.DATALINK:
535 case Types.DISTINCT:
536 throw throwException("Unsupported key data type: " + type);
537 default:
538 return "";
539 }
540 }
541
542 /**
543 * Remove all triggers that start with the given prefix.
544 *
545 * @param conn the database connection
546 * @param prefix the prefix
547 * @throws SQLException on failure
548 */
549 protected static void removeAllTriggers(Connection conn, String prefix)
550 throws SQLException {
551 Statement stat = conn.createStatement();
552 ResultSet rs = stat.executeQuery(
553 "SELECT DISTINCT TRIGGER_SCHEMA, TRIGGER_NAME FROM INFORMATION_SCHEMA.TRIGGERS");
554 Statement stat2 = conn.createStatement();
555 while (rs.next()) {
556 String schema = rs.getString("TRIGGER_SCHEMA");
557 String name = rs.getString("TRIGGER_NAME");
558 if (name.startsWith(prefix)) {
559 name = StringUtils.quoteIdentifier(schema) + "." +
560 StringUtils.quoteIdentifier(name);
561 stat2.execute("DROP TRIGGER " + name);
562 }
563 }
564 }
565
566 /**
567 * Set the column indices of a set of keys.
568 *
569 * @param index the column indices (will be modified)
570 * @param keys the key list
571 * @param columns the column list
572 * @throws SQLException on failure
573 */
574 protected static void setColumns(int[] index, ArrayList<String> keys,
575 ArrayList<String> columns) throws SQLException {
576 for (int i = 0, keySize = keys.size(); i < keySize; i++) {
577 String key = keys.get(i);
578 int found = -1;
579 int columnsSize = columns.size();
580 for (int j = 0; found == -1 && j < columnsSize; j++) {
581 String column = columns.get(j);
582 if (column.equals(key)) {
583 found = j;
584 }
585 }
586 if (found < 0) {
587 throw throwException("Column not found: " + key);
588 }
589 index[i] = found;
590 }
591 }
592
593 /**
594 * Do the search.
595 *
596 * @param conn the database connection
597 * @param text the query
598 * @param limit the limit
599 * @param offset the offset
600 * @param data whether the raw data should be returned
601 * @return the result set
602 * @throws SQLException on failure
603 */
604 protected static ResultSet search(Connection conn, String text, int limit,
605 int offset, boolean data) throws SQLException {
606 SimpleResultSet result = createResultSet(data);
607 if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
608 // this is just to query the result set columns
609 return result;
610 }
611 if (text == null || StringUtils.isWhitespaceOrEmpty(text)) {
612 return result;
613 }
614 FullTextSettings setting = FullTextSettings.getInstance(conn);
615 if (!setting.isInitialized()) {
616 init(conn);
617 }
618 Set<String> words = new HashSet<>();
619 addWords(setting, words, text);
620 Set<Integer> rIds = null, lastRowIds;
621
622 PreparedStatement prepSelectMapByWordId = setting.prepare(conn,
623 SELECT_MAP_BY_WORD_ID);
624 for (String word : words) {
625 lastRowIds = rIds;
626 rIds = new HashSet<>();
627 Integer wId = setting.getWordId(word);
628 if (wId == null) {
629 continue;
630 }
631 prepSelectMapByWordId.setInt(1, wId);
632 ResultSet rs = prepSelectMapByWordId.executeQuery();
633 while (rs.next()) {
634 Integer rId = rs.getInt(1);
635 if (lastRowIds == null || lastRowIds.contains(rId)) {
636 rIds.add(rId);
637 }
638 }
639 }
640 if (rIds == null || rIds.isEmpty()) {
641 return result;
642 }
643 PreparedStatement prepSelectRowById = setting.prepare(conn, SELECT_ROW_BY_ID);
644 int rowCount = 0;
645 for (int rowId : rIds) {
646 prepSelectRowById.setInt(1, rowId);
647 ResultSet rs = prepSelectRowById.executeQuery();
648 if (!rs.next()) {
649 continue;
650 }
651 if (offset > 0) {
652 offset--;
653 } else {
654 String key = rs.getString(1);
655 int indexId = rs.getInt(2);
656 IndexInfo index = setting.getIndexInfo(indexId);
657 if (data) {
658 String[][] columnData = parseKey(conn, key);
659 result.addRow(
660 index.schema,
661 index.table,
662 columnData[0],
663 columnData[1],
664 1.0);
665 } else {
666 String query = StringUtils.quoteIdentifier(index.schema) +
667 "." + StringUtils.quoteIdentifier(index.table) +
668 " WHERE " + key;
669 result.addRow(query, 1.0);
670 }
671 rowCount++;
672 if (limit > 0 && rowCount >= limit) {
673 break;
674 }
675 }
676 }
677 return result;
678 }
679
680 private static void addColumnData(SessionLocal session, ArrayList<String> columns, ArrayList<String> data,
681 Expression expr) {
682 if (expr instanceof ConditionAndOr) {
683 ConditionAndOr and = (ConditionAndOr) expr;
684 addColumnData(session, columns, data, and.getSubexpression(0));
685 addColumnData(session, columns, data, and.getSubexpression(1));
686 } else {
687 Comparison comp = (Comparison) expr;
688 ExpressionColumn ec = (ExpressionColumn) comp.getSubexpression(0);
689 String columnName = ec.getColumnName(session, -1);
690 columns.add(columnName);
691 if (expr.getSubexpressionCount() == 1) {
692 data.add(null);
693 } else {
694 ValueExpression ev = (ValueExpression) comp.getSubexpression(1);
695 data.add(ev.getValue(null).getString());
696 }
697 }
698 }
699
700 /**
701 * Add all words in the given text to the hash set.
702 *
703 * @param setting the fulltext settings
704 * @param set the hash set
705 * @param reader the reader
706 */
707 protected static void addWords(FullTextSettings setting,
708 Set<String> set, Reader reader) {
709 StreamTokenizer tokenizer = new StreamTokenizer(reader);
710 tokenizer.resetSyntax();
711 tokenizer.wordChars(' ' + 1, 255);
712 char[] whitespaceChars = setting.getWhitespaceChars().toCharArray();
713 for (char ch : whitespaceChars) {
714 tokenizer.whitespaceChars(ch, ch);
715 }
716 try {
717 while (true) {
718 int token = tokenizer.nextToken();
719 if (token == StreamTokenizer.TT_EOF) {
720 break;
721 } else if (token == StreamTokenizer.TT_WORD) {
722 String word = tokenizer.sval;
723 word = setting.convertWord(word);
724 if (word != null) {
725 set.add(word);
726 }
727 }
728 }
729 } catch (IOException e) {
730 throw DbException.convertIOException(e, "Tokenizer error");
731 }
732 }
733
734 /**
735 * Add all words in the given text to the hash set.
736 *
737 * @param setting the fulltext settings
738 * @param set the hash set
739 * @param text the text
740 */
741 protected static void addWords(FullTextSettings setting,
742 Set<String> set, String text) {
743 String whitespaceChars = setting.getWhitespaceChars();
744 StringTokenizer tokenizer = new StringTokenizer(text, whitespaceChars);
745 while (tokenizer.hasMoreTokens()) {
746 String word = tokenizer.nextToken();
747 word = setting.convertWord(word);
748 if (word != null) {
749 set.add(word);
750 }
751 }
752 }
753
754 /**
755 * Create the trigger.
756 *
757 * @param conn the database connection
758 * @param schema the schema name
759 * @param table the table name
760 * @throws SQLException on failure
761 */
762 private static void createTrigger(Connection conn, String schema,
763 String table) throws SQLException {
764 createOrDropTrigger(conn, schema, table, true);
765 }
766
767 private static void createOrDropTrigger(Connection conn,
768 String schema, String table, boolean create) throws SQLException {
769 try (Statement stat = conn.createStatement()) {
770 String trigger = StringUtils.quoteIdentifier(schema) + "."
771 + StringUtils.quoteIdentifier(TRIGGER_PREFIX + table);
772 stat.execute("DROP TRIGGER IF EXISTS " + trigger);
773 if (create) {
774 StringBuilder buff = new StringBuilder(
775 "CREATE TRIGGER IF NOT EXISTS ");
776 // unless multithread, trigger needs to be called on rollback as well,
777 // because we use the init connection do to changes in the index
778 // (not the user connection)
779 buff.append(trigger).
780 append(" AFTER INSERT, UPDATE, DELETE");
781 buff.append(" ON ");
782 StringUtils.quoteIdentifier(buff, schema).
783 append('.');
784 StringUtils.quoteIdentifier(buff, table).
785 append(" FOR EACH ROW CALL \"").
786 append(FullText.FullTextTrigger.class.getName()).
787 append('"');
788 stat.execute(buff.toString());
789 }
790 }
791 }
792
793 /**
794 * Add the existing data to the index.
795 *
796 * @param conn the database connection
797 * @param schema the schema name
798 * @param table the table name
799 * @throws SQLException on failure
800 */
801 private static void indexExistingRows(Connection conn, String schema,
802 String table) throws SQLException {
803 FullText.FullTextTrigger existing = new FullText.FullTextTrigger();
804 existing.init(conn, schema, null, table, false, Trigger.INSERT);
805 String sql = "SELECT * FROM " + StringUtils.quoteIdentifier(schema)
806 + "." + StringUtils.quoteIdentifier(table);
807 ResultSet rs = conn.createStatement().executeQuery(sql);
808 int columnCount = rs.getMetaData().getColumnCount();
809 while (rs.next()) {
810 Object[] row = new Object[columnCount];
811 for (int i = 0; i < columnCount; i++) {
812 row[i] = rs.getObject(i + 1);
813 }
814 existing.fire(conn, null, row);
815 }
816 }
817
818 private static String quoteString(String data) {
819 if (data.indexOf('\'') < 0) {
820 return "'" + data + "'";
821 }
822 int len = data.length();
823 StringBuilder buff = new StringBuilder(len + 2);
824 buff.append('\'');
825 for (int i = 0; i < len; i++) {
826 char ch = data.charAt(i);
827 if (ch == '\'') {
828 buff.append(ch);
829 }
830 buff.append(ch);
831 }
832 buff.append('\'');
833 return buff.toString();
834 }
835
836 private static void setIgnoreList(FullTextSettings setting,
837 String commaSeparatedList) {
838 String[] list = StringUtils.arraySplit(commaSeparatedList, ',', true);
839 setting.addIgnored(Arrays.asList(list));
840 }
841
842 /**
843 * Check if a the indexed columns of a row probably have changed. It may
844 * return true even if the change was minimal (for example from 0.0 to
845 * 0.00).
846 *
847 * @param oldRow the old row
848 * @param newRow the new row
849 * @param indexColumns the indexed columns
850 * @return true if the indexed columns don't match
851 */
852 protected static boolean hasChanged(Object[] oldRow, Object[] newRow,
853 int[] indexColumns) {
854 for (int c : indexColumns) {
855 Object o = oldRow[c], n = newRow[c];
856 if (o == null) {
857 if (n != null) {
858 return true;
859 }
860 } else if (!o.equals(n)) {
861 return true;
862 }
863 }
864 return false;
865 }
866
867 /**
868 * Trigger updates the index when a inserting, updating, or deleting a row.
869 */
870 public static final class FullTextTrigger implements Trigger {
871 private FullTextSettings setting;
872 private IndexInfo index;
873 private int[] columnTypes;
874
875 private static final int INSERT_WORD = 0;
876 private static final int INSERT_ROW = 1;
877 private static final int INSERT_MAP = 2;
878 private static final int DELETE_ROW = 3;
879 private static final int DELETE_MAP = 4;
880 private static final int SELECT_ROW = 5;
881
882 private static final String[] SQL = {
883 "MERGE INTO " + SCHEMA + ".WORDS(NAME) KEY(NAME) VALUES(?)",
884 "INSERT INTO " + SCHEMA + ".ROWS(HASH, INDEXID, `KEY`) VALUES(?, ?, ?)",
885 "INSERT INTO " + SCHEMA + ".MAP(ROWID, WORDID) VALUES(?, ?)",
886 "DELETE FROM " + SCHEMA + ".ROWS WHERE HASH=? AND INDEXID=? AND `KEY`=?",
887 "DELETE FROM " + SCHEMA + ".MAP WHERE ROWID=? AND WORDID=?",
888 "SELECT ID FROM " + SCHEMA + ".ROWS WHERE HASH=? AND INDEXID=? AND `KEY`=?"
889 };
890
891 /**
892 * INTERNAL
893 * @see Trigger#init(Connection, String, String, String, boolean, int)
894 */
895 @Override
896 public void init(Connection conn, String schemaName, String triggerName,
897 String tableName, boolean before, int type) throws SQLException {
898 setting = FullTextSettings.getInstance(conn);
899 if (!setting.isInitialized()) {
900 FullText.init(conn);
901 }
902 ArrayList<String> keyList = Utils.newSmallArrayList();
903 DatabaseMetaData meta = conn.getMetaData();
904 ResultSet rs = meta.getColumns(null,
905 StringUtils.escapeMetaDataPattern(schemaName),
906 StringUtils.escapeMetaDataPattern(tableName),
907 null);
908 ArrayList<String> columnList = Utils.newSmallArrayList();
909 while (rs.next()) {
910 columnList.add(rs.getString("COLUMN_NAME"));
911 }
912 columnTypes = new int[columnList.size()];
913 index = new IndexInfo();
914 index.schema = schemaName;
915 index.table = tableName;
916 index.columns = columnList.toArray(new String[0]);
917 rs = meta.getColumns(null,
918 StringUtils.escapeMetaDataPattern(schemaName),
919 StringUtils.escapeMetaDataPattern(tableName),
920 null);
921 for (int i = 0; rs.next(); i++) {
922 columnTypes[i] = rs.getInt("DATA_TYPE");
923 }
924 if (keyList.isEmpty()) {
925 rs = meta.getPrimaryKeys(null,
926 StringUtils.escapeMetaDataPattern(schemaName),
927 tableName);
928 while (rs.next()) {
929 keyList.add(rs.getString("COLUMN_NAME"));
930 }
931 }
932 if (keyList.isEmpty()) {
933 throw throwException("No primary key for table " + tableName);
934 }
935 ArrayList<String> indexList = Utils.newSmallArrayList();
936 PreparedStatement prep = conn.prepareStatement(
937 "SELECT ID, COLUMNS FROM " + SCHEMA + ".INDEXES" +
938 " WHERE SCHEMA=? AND `TABLE`=?");
939 prep.setString(1, schemaName);
940 prep.setString(2, tableName);
941 rs = prep.executeQuery();
942 if (rs.next()) {
943 index.id = rs.getInt(1);
944 String columns = rs.getString(2);
945 if (columns != null) {
946 Collections.addAll(indexList, StringUtils.arraySplit(columns, ',', true));
947 }
948 }
949 if (indexList.isEmpty()) {
950 indexList.addAll(columnList);
951 }
952 index.keys = new int[keyList.size()];
953 setColumns(index.keys, keyList, columnList);
954 index.indexColumns = new int[indexList.size()];
955 setColumns(index.indexColumns, indexList, columnList);
956 setting.addIndexInfo(index);
957 }
958
959 /**
960 * INTERNAL
961 * @see Trigger#fire(Connection, Object[], Object[])
962 */
963 @Override
964 public void fire(Connection conn, Object[] oldRow, Object[] newRow)
965 throws SQLException {
966 if (oldRow != null) {
967 if (newRow != null) {
968 // update
969 if (hasChanged(oldRow, newRow, index.indexColumns)) {
970 delete(conn, oldRow);
971 insert(conn, newRow);
972 }
973 } else {
974 // delete
975 delete(conn, oldRow);
976 }
977 } else if (newRow != null) {
978 // insert
979 insert(conn, newRow);
980 }
981 }
982
983 /**
984 * INTERNAL
985 */
986 @Override
987 public void close() {
988 setting.removeIndexInfo(index);
989 }
990
991 /**
992 * INTERNAL
993 */
994 @Override
995 public void remove() {
996 setting.removeIndexInfo(index);
997 }
998
999 /**
1000 * Add a row to the index.
1001 *
1002 * @param conn to use
1003 * @param row the row
1004 * @throws SQLException on failure
1005 */
1006 private void insert(Connection conn, Object[] row) throws SQLException {
1007 PreparedStatement prepInsertRow = null;
1008 PreparedStatement prepInsertMap = null;
1009 try {
1010 String key = getKey(row);
1011 int hash = key.hashCode();
1012 prepInsertRow = getStatement(conn, INSERT_ROW);
1013 prepInsertRow.setInt(1, hash);
1014 prepInsertRow.setInt(2, index.id);
1015 prepInsertRow.setString(3, key);
1016 prepInsertRow.execute();
1017 ResultSet rs = prepInsertRow.getGeneratedKeys();
1018 rs.next();
1019 int rowId = rs.getInt(1);
1020
1021 prepInsertMap = getStatement(conn, INSERT_MAP);
1022 prepInsertMap.setInt(1, rowId);
1023 int[] wordIds = getWordIds(conn, row);
1024 for (int id : wordIds) {
1025 prepInsertMap.setInt(2, id);
1026 prepInsertMap.execute();
1027 }
1028 } finally {
1029 IOUtils.closeSilently(prepInsertRow);
1030 IOUtils.closeSilently(prepInsertMap);
1031 }
1032 }
1033
1034 /**
1035 * Delete a row from the index.
1036 *
1037 * @param conn to use
1038 * @param row the row
1039 * @throws SQLException on failure
1040 */
1041 private void delete(Connection conn, Object[] row) throws SQLException {
1042 PreparedStatement prepSelectRow = null;
1043 PreparedStatement prepDeleteMap = null;
1044 PreparedStatement prepDeleteRow = null;
1045 try {
1046 String key = getKey(row);
1047 int hash = key.hashCode();
1048 prepSelectRow = getStatement(conn, SELECT_ROW);
1049 prepSelectRow.setInt(1, hash);
1050 prepSelectRow.setInt(2, index.id);
1051 prepSelectRow.setString(3, key);
1052 ResultSet rs = prepSelectRow.executeQuery();
1053 prepDeleteMap = getStatement(conn, DELETE_MAP);
1054 prepDeleteRow = getStatement(conn, DELETE_ROW);
1055 if (rs.next()) {
1056 int rowId = rs.getInt(1);
1057 prepDeleteMap.setInt(1, rowId);
1058 int[] wordIds = getWordIds(conn, row);
1059 for (int id : wordIds) {
1060 prepDeleteMap.setInt(2, id);
1061 prepDeleteMap.executeUpdate();
1062 }
1063 prepDeleteRow.setInt(1, hash);
1064 prepDeleteRow.setInt(2, index.id);
1065 prepDeleteRow.setString(3, key);
1066 prepDeleteRow.executeUpdate();
1067 }
1068 } finally {
1069 IOUtils.closeSilently(prepSelectRow);
1070 IOUtils.closeSilently(prepDeleteMap);
1071 IOUtils.closeSilently(prepDeleteRow);
1072 }
1073 }
1074
1075 private int[] getWordIds(Connection conn, Object[] row) throws SQLException {
1076 HashSet<String> words = new HashSet<>();
1077 for (int idx : index.indexColumns) {
1078 int type = columnTypes[idx];
1079 Object data = row[idx];
1080 if (type == Types.CLOB && data != null) {
1081 Reader reader;
1082 if (data instanceof Reader) {
1083 reader = (Reader) data;
1084 } else {
1085 reader = ((Clob) data).getCharacterStream();
1086 }
1087 addWords(setting, words, reader);
1088 } else {
1089 String string = asString(data, type);
1090 addWords(setting, words, string);
1091 }
1092 }
1093 PreparedStatement prepInsertWord = null;
1094 try {
1095 prepInsertWord = getStatement(conn, INSERT_WORD);
1096 int[] wordIds = new int[words.size()];
1097 int i = 0;
1098 for (String word : words) {
1099 int wordId;
1100 Integer wId;
1101 while((wId = setting.getWordId(word)) == null) {
1102 prepInsertWord.setString(1, word);
1103 prepInsertWord.execute();
1104 ResultSet rs = prepInsertWord.getGeneratedKeys();
1105 if (rs.next()) {
1106 wordId = rs.getInt(1);
1107 if (wordId != 0) {
1108 setting.addWord(word, wordId);
1109 wId = wordId;
1110 break;
1111 }
1112 }
1113 }
1114 wordIds[i++] = wId;
1115 }
1116 Arrays.sort(wordIds);
1117 return wordIds;
1118 } finally {
1119 IOUtils.closeSilently(prepInsertWord);
1120 }
1121 }
1122
1123 private String getKey(Object[] row) throws SQLException {
1124 StringBuilder builder = new StringBuilder();
1125 int[] keys = index.keys;
1126 for (int i = 0, l = keys.length; i < l; i++) {
1127 if (i > 0) {
1128 builder.append(" AND ");
1129 }
1130 int columnIndex = keys[i];
1131 StringUtils.quoteIdentifier(builder, index.columns[columnIndex]);
1132 Object o = row[columnIndex];
1133 if (o == null) {
1134 builder.append(" IS NULL");
1135 } else {
1136 builder.append('=').append(quoteSQL(o, columnTypes[columnIndex]));
1137 }
1138 }
1139 return builder.toString();
1140 }
1141
1142 private static PreparedStatement getStatement(Connection conn, int index) throws SQLException {
1143 return conn.prepareStatement(SQL[index], Statement.RETURN_GENERATED_KEYS);
1144 }
1145
1146 }
1147
1148 /**
1149 * INTERNAL
1150 * Close all fulltext settings, freeing up memory.
1151 */
1152 public static void closeAll() {
1153 FullTextSettings.closeAll();
1154 }
1155
1156 /**
1157 * Throw a SQLException with the given message.
1158 *
1159 * @param message the message
1160 * @return never returns normally
1161 * @throws SQLException the exception
1162 */
1163 protected static SQLException throwException(String message)
1164 throws SQLException {
1165 throw new SQLException(message, "FULLTEXT");
1166 }
1167 }