Johan Wikman d115a54038 All changes 1.4.3...2.0.0
b709e29 Fix URL typo in release notes
01f203c Update release notes
c49810a Update COPYRIGHT
e327526 Add BSL version number to LICENSE.TXT
07e3a4e Remove superfluous COPURIGHT.md and LICENSE.md
54c3310 Replace Dynamic Data Routing Platform with Database Proxy
305d02f Remove *.cmake wildcard from .gitignore
b0b5208 Cleanup of spaces
aeca6d0 Extend maxscaled error messages
817d74c Document where the CDC users are stored
9a569db Update license
ff8697a MXS-716: Fix table level privilege detection
2071a8c Only check replies of slaves that are in use
f8dfa42 Fix possible hangs in CDC python scripts
fa1d99e Removed "filestem option" from example
009b549 Removed "filestem option" from example
8d515c2 Add example Kafka producer script for Python
64e976b Fix sporadic SSL authentication failures
5a655dc MXS-814: Check service/monitor permissions on all servers
2a7f596 Add note about galeramon priority to Galera tutorials
b90b5a6 Fixed SHOW SLAVE STATUS in binlog router
e22fe39 Changed couln size for SHOW SLAVE STATUS
ae97b18 Fix avrorouter build failure with older sqlite libraries
56ef8b7 Replace GPL license with BSL license in scripts and tests
552836f Initialize all fields when MySQL users are loaded from cache
bf42947 Update all licensing related files
b29db9d Remove optimize_wildcard parameter from use
5170844 Make readwritesplit diagnosting output more clear
262ffb1 Fix crash when a config parameter has no section
33ac9e6 Add note about LEAST_BEHIND_MASTER and server weights
e13e860 Fix a memory leak when backend authentication fails
75d00c2 MXS-801: Set the default value of strip_db_esc to true
bd5f2db MXS-800: Add a log message about the working directory
4b1dd8c Update MySQL Monitor documentation on detect_replication_lag
559bc99 Fix installation of license file
b057587 Change LICENSE to LICENSE.TXT
223fa43 Remove null characters from log messages
36fd05b Fix fatal signal handler log message
053dc8a Fix typos in documentation
371dc87 Fix Galera text in Master-Slave tutorial
30b6265 Disable adding of new objects at runtime
db92311 Update the documentation on configuration reloading
0923d40 Update Connector-C version
c4738b5 Add define for avro-conversion.ini
196e6ac Update license from GPL to BSL.
e612366 Correctly calculate the number of bytes read in dcb_read
93a2a03 Update rotate documentation in admin tutorial
c5eb854 MXS-585: Fix authentication handling regression
6330070 Fix schemarouter memory leak
aa5827e Fix CDC authentication memory leak
a5af4ad Fix avro memory leaks
627d73f Fix Avro scripts
0ff7556 Add build instructions to avrorouter documentation
734a1c8 Fix doxygen mainpage
e51ce09 Add licence text to avro scripts
4d27c14 Update Avro documentation and fix installation directories
a58a330 Fix readconnroute error message about router_options
22b138c MXS-772: Fix postinstall script
a9960b7 Fix function declaration in mysql_backend.c
cbe1704 Add missing newline
09d76ee Fix avro documentation default values
1d3f8f3 Added refresh users on START SLAVE
880db34 Make router configuration errors fatal
3bad5ca Update documentation and add logging to avrorouter
10f3384 Disable SSLv3
ca8d902 Fix rwsplit error reporting when master is lost
e816d65 Fix MaxScale Tutorial
deca3e1 Update MaxScale man page
f1735b7 Update release notes
9238714 qc: Change type of DEALLOCATE PREPARE
0b77c3b dbfwfilter: Do not require a trailing new line
1152ca9 Remove copyright message
a038a85 Remove debug assertion on ERANGE error in galeramon
12ab235 Fix comparison error for connections limit.
5de1a8f qc_sqlite: Correct string recognition
b63d754 Fix links in documentation contents
05d457e CDC protocol link fix
50676ef Fix monitor code formatting
218ba09 Remove MaxScale-and-SSL.md
0d6845b Add images to Avro documentation and tutorial
8dd2c9b Update MaxScale-2.0.0-Release-Notes.md
6d4b593 Change avrorouter default transaction grouping
4c629de Add notes about monitor changes to upgrading and release notes
267d0dc Update Binlogrouter.md
c624781 Update Replication-Proxy-Binlog-Router-Tutorial.md
f3261bc CDC users
1368797 Format authenticator and module headers
ab01749 Format filters
8b05d32 Format core and include files
f3974e5 Add GPL LICENSE to qc_mysqlembedded
bfec36a astyle rabbitmq_consumer/consumer.c
54b960a Check that the Avro directory is writable
3d4cd2e Fix cdc_users using the wrong path for service users cache
1e738dd Add CDC client program documentation
f6809fd Remove superfluous rabbitmw_consumer/LICENSE
6b5e667 Update license text in files
9bfcb46 Change CDC protocol documentation formatting
607f25c  REQUEST-DATA formatting
8175ab4 CDC protocol update
d5ca272 CDC protocol update
6c91764 Only check wsrep_local_index if node is joined
f12e2c2 Do not use SSL for monitors and services
6d2cd99 Fix TestAdminUsers
f4ae50d Apply astyle to server/core/test/*.c
7cc2824 Update build instructions
cf8e2b5 Update release notes
03c7a6c Remove wrong function prototypes
5a11eed Revert "Remove duplicate functions"
80ed488 Remove duplicate functions
bb0de8d Add info on SSL and throttling to release notes for 2.0.
0934aee Update MaxAdmin reference guide
2a3fe9b Update source URL in release notes
e575cf0 Merge branch 'MXS-177-develop' into develop
cc8c88d Change header for BSL
ecde266 Change header for BSL
890b208 Log a message when a script is executed
9c365df Added information on server side SSL to config guide.
aa3e002 Remove obsolete heading
79dd73a Make dprintAllSessions use dprintSession
1fc0db9 Align output of "show services"
1b9d301 Make monitorShowAll use monitorShow
983615e Adjust output of 'show modules'
436badd qc_sqlite: The module is now beta
a7cbbe5 Update Upgrade document
71ac13f Remove obsolete user/password from example
eb20ff8 Fix and clean up Avrorouter diagnostics code
31d4052 Change MaxScale to MariaDB MaxScale
e6e4858 Fix `source` parameter not working with `router_options`
d8de99a Update module version numbers
eb81add Merge remote-tracking branch 'origin/develop' into MXS-177-develop
daba563 Merge remote-tracking branch 'origin/MXS-651-develop-merge' into develop
678f417 Changes in response to reviews.
410fb81 Changes in response to reviews.
60135e5 Add initial release notes about Avrorouter
7400ecc qc_sqlite: Remove uninitialized read
536962c Update version number
018f044 Fix debug assertion in client command processing
51f0804 Prevent 'show monitor' from crashing with failed monitor
559347e Fix "Too many connections" message; add comments.
01d3929 Add printf format checking to dcb_printf
fbd49a6 dbfwfilter: Require complete parsing only when needed
1885863 Add information to release notes about readwritesplit changes
73b56a2 Update MaxScale section in release notes.
0a2f56f MaxAdmin: Remove debug information from 'show users'
3cf3279 MaxAdmin: Report SSL information as well
29c2b66 Always use SSL if server configured with SSL
7d6b335 dprintAllServers should use dprintServer
02a5246 qc_sqlite: Correctly detect parsing context
469419b compare: Add strict mode
8c5b3d3 compare: Allow the comparison of a single statement
4691514 Add Updgrade to 2.0 document
38b3ecb Expand the checks done before a monitor is stopped
8e2cfb9 Add backend name to authentication error message
9600a07 Fix MaxInfo crash
91c58b0 Removed log message for duplicate entry while adding an user
40392fe Fixed log message priority
0ec35b8 maxadmin: Allow the last user to be removed
5a0ebed maxadmin: Change name of user file
87aa8f1 maxadmin: Always allow root to connect
bf37751 Fix COM_QUIT packet detection
7c93ee4 Update avrorouter documentation and tutorial
95ce463 Fix wrong directory in avrorouter log message
cfe54c7 Update ChangeLog
d69562c Fix LOAD DATA LOCAL INFILE data size tracking
24e7cd6 MXS-584: added support for SET @@session.autocommit
d6f6f76 Fixes, correct too many connections message
efeb924 Update release notes for 2.0.0
8f71a87 qc_sqlite: Adjust error messages
b967d60 Remove copy of enum enum_server_command
822b7e3 Update package license
b58301a Update MaxScale License for overlooked files
c09ee47 Update MaxScale License
49f46fa Tidy up. Comment out config items not yet supported.
f5c3470 Updated and simplified the Building from Source document
98b98e2 Add note about master failure modes to documentation
e036f2c Update Limitations document
62219a5 Merge remote-tracking branch 'origin/drain-writeq' into develop
5caf667 Invoke DCB_REASON_DRAINED more frequently.
77b107b qc_sqlite: Add support for LOAD DATA INFILE
8e70f26 compare: Optionally print out the parse result
ad750e6 Merge remote-tracking branch 'origin/MXS-651-develop-merge' into develop
ef85779 Merge remote-tracking branch 'origin/develop' into MXS-651-develop-merge
ea9fdda MXS-477: Add LONGBLOB support for readconnroute
eae6d42 qc_sqlite: Remove superfluous columnname definition
8fe2b21 Add binlog source to avrorouter
b25cc37 qc_sqlite: Add missing destructors
8a749e7 qc_sqlite: Reduce number of keywords
5f4bb8b compare: Output query immediately
2456e52 dbfwfilter: Reject queries that cannot be parsed
5f1fbbd qc_sqlite: Extend SET grammar
b8d8418 dbfwfilter: Remove 'allow' from firewall filter rule
0bd2a44 MXS-741 When no events are read from binlog file, ...
a07c491 Remove duplicated function (merge error, probably)
b237008 Save conflict resolution, missed last time.
a0c0b40 Merge remote-tracking branch 'origin/develop' into MXS-651-develop
385d47d Change SSL logic, fix large read problem.
b93b5e0 Remove false debug assertion
b953b1f Turn off SSL read ahead.
e0d46a5 Fix error messages and remove commented code
49b4655 MXS-739: Fix invalid JSON in Maxinfo
0c30692 qc_sqlite: Handle GROUP_CONCAT arguments
54e48a1 qc_sqlite: Consider \ as an escape character in strings
713a5d6 qc_sqlite: Add test cases
20d1b51 qc_sqlite: Handle qualified names in CREATE VIEW
1019313 qc_sqlite: Make QUERY_TYPE_WRITE default for SHOW
059c14e qc_sqlite: Accept qualified function names in SELECT
db34989 qc_sqlite: Accept qualified function names
b93e2f1 qc_sqlite: Add limited support for GRAND and REVOKE
678672d qc_sqlite: Cleanup copying of database and table names
9b744b9 qc_sqlite: Update table and database names at the same time
db75e61 qc: Support getting the qualified table names
1f867f4 qc: Add join.test
9c7e02a qc_sqlite: Accept "...from NATURAL straight_join..."
93d1c31 qc_sqlite: Both " and ' can enclose a string literal
8055b21 qc_sqlite: Set more information based upon tokens
37e3663 qc_sqlite: Do not blindly add affected fields
50f1360 qc: Correctly collect affected fields
71c234e qc_sqlite: Recognize CREATE TABLE ... UNION
01803f1 qc_sqlite: Recognize {DEALLOCATE|DROP} PREPARE ...
6ecd4b3 qc_sqlite: Parse index hints
0bdab01 qc: Compare sets of tables
b908c8f Fix double freeing of internal DCBs
8903556 qc_sqlite: Recognize LEFT, INSERT and REPLACE
266e6c0 qc: Log all problems by default (compare program)
7b54cac qc_sqlite: Fix logging bug
9566e9f qc_sqlite: Plug a leak
b0a860d qc: Run compare a specified number of times
050d698 qc_sqlite: Simplified argument handling
97c56b8 qc: Allow arguments to be passed to the query classifier
09a46e0 qc_sqlite: Add argument log_unrecognized_statements
fd98153 qc: Allow arguments to be provided to the query classifier
313aa7e Fix Problems SSL assertion; non SSL connect to SSL
1d721e6 Fix DEB packaging errors
96bdc39 Fix RPM packaging failures on CentOS 7
6ba900d qc_sqlite: Recognize more SHOW commands
2869d0b qc_sqlite: Exclude support for sqlite's PRAGMA
0be68a3 qc_sqlite: Enhance SELECT syntax
28f3e1a Merge branch 'develop' into MXS-729
e18bd41 qc: Expose the result of the parsing
5896085 Add BUILD_AVRO to the CMake cache
daeb896 Remove changes to blr_master.c memory handling
d523821 Add comments
4eb9a66 Empty admin users file is now handled
52b46c6 qc: Update create.test
db09711 qc_sqlite: Ignore case when looking for test language keywords
f042a1d qc_sqlite: Extend CREATE TABLE syntax
177d2de qc_sqlite: Extend CREATE TABLE syntax
d3ca8e6 qc_sqlite: Add some support for HANDLER
86c6a96 qc_sqlite: Recognize RENAME TABLE
471594f qc_sqlite: Accept more table options at CREATE TABLE
3da6cde qc_sqlite: Remove unused keywords
bd89662 Fix crash on corrupted passwd file
b5d1764 MXS-733: Always print session states
043e2db Remove unused CMake variables
5604fe2 Restore missing line, fixes logic error.
66d15a5 Added log message warning for old users found
5be9fca Changes in response to review by Johan
899e0e2 Removed password parameter from admin_user_add and admin_remove_user
a2d9302 Merge branch 'develop' into MXS-729
bcaf82f Code review update
e61c716 Nagios plugin update with Maxadmin using UNIX socket only
d7150a2 qc_sqlite: Extend column syntax
3b78df0 qc_sqlite: Accept VALUE in addition to VALUES
85a705b qc_sqlite: Accept CHARSET in addition to CHARACTER SET
db9cec8 qc_sqlite: Accept qualified column  names in CREATE TABLE
a9cabb0 qc_sqlite: Extend SELECT syntax
f5e9878 qc_sqlite: Add set type
675cb93 qc_sqlite: Allow BINARY to turn into an identifier
b04a760 qc_sqlite: Accept DROP TABLES
1075d9c qc_sqlite: Allow qualified name with LIKE in CREATE
420ac56 qc_sqlite: Extend EXPLAIN grammar
727d626 Add missing error message to readwritesplit
f4fd09e Change templates and testing configurations to use sockets
1ef2e06 Add configurable default admin user
a723731 Remove wrong file
7c3b02b Maxadmin/maxscaled UNIX socket update
eed78d4 qc_sqlite: Pick out more information from select when CREATEing
267f091 qc_sqlite: Recognise DROP TEMPORARY TABLE
54fc29f qc_sqlite: Accept $ as a valid character in identifiers
afa2ec9 qc_sqlite: Allow keywords to be used in qualified name
db0427d MXS-729 code review update
a3b3000 Merge branch 'develop' into MXS-729
e73d66c qc_sqlite: Identify qualified identifiers
5bacade Trailing space fix
3bc9be3 MXS-729 socket=default support in maxscale.cnf
1a5c23c Code review update for MXS-729
d6665c7 qc_sqlite: Extend CREATE TABLE grammar
91725ce qc_sqlite: Dequote table and database names
cd7a022 qc: Add create test
1aa4e6b qc: Update test files
762b0c2 qc_mysqlembedded: Do not return "*" as table name
cd9968f qc_sqlite: Update delete.test
f16703d qc_sqlite: Add support for CALL
e3ca9b4 qc_mysqlembedded: Do not return an array of empty strings
5878a22 qc_sqlite: Support selects in DELETE
1cf0444 qc_sqlite: Fix bug in DELETE grammar
0bf39a1 qc_sqlite: Add support for CHECK TABLE
4a8feca qc_sqlite: Add helper for catenating SrcLists
ab299b3 qc_sqlite: Extend DELETE syntax
5778856 qc_sqlite: Extract database name as well
99901f1 qc_sqlite: Extend DELETE syntax
63396f8 qc_sqlite: Match "autocommit" caseinsensitively
e804dd3 qc_sqlite: Add support for LOCK/UNLOCK
c23e442 qc_sqlite: Extend DELETE syntax
5460e31 qc: Add delete test
ab392ad qc_sqlite: Free unused data
598c6f0 qc: Measure time of parsing
2fa3844 qc_sqlite: Put all changes being {%|#}ifdefs
1b43992 qc_sqlite: Modified update.test
1676ea4 qc_sqlite: LEFT|RIGHT are not required with JOIN
224ebd3 qc_sqlite: Extend UPDATE grammar
dbecca9 qc_sqlite: Extend UPDATE grammar
b6ca3b3 MaxAdmin security modification MXS-729
8fb47dd Remove copying of MariaDB embedded library files
22e1257 Normalize whitespace when canonicalizing queries
269cff2 MXS-697: Fix dbfwfilter logging for matched queries
6344f6f Ignore Apple .DS_Store files.
d606977 Improve comments in response to code review.
619aa13 Add configuration check flag to MaxScale
27c860b Drain write queue improvements.
33d4154 Read only one configuration file
d104c19 Format more core files
83fdead Format part of core source code
311d5de Format gateway.c and config.c with Astyle
8cbb48e Don't build maxavro library if BUILD_AVRO is not defined
32bb77a Merge branch 'MXS-483' into develop
db72c5d Format CDC/Avro related files
3c26e27 qc_sqlite: Use SrcList instead of Expr
f96ad6a Merge branch 'develop' into MXS-729
0728734 Fix query canonical form tests
e68262d Merge remote-tracking branch 'gpl-maxscale/master' into develop
65460dc Fix missing symbols from MySQLAuth
791c821 MaxAdmin listens on UNIX socket only and maxadmin can connect
89afed6 MXS-66: All configuration errors are fatal errors
d613053 Add more details to galeramon documentation
22f4f57 qc: Add support for multi UPDATE
0dba25a Added default port to blr_make_registration
9d8248c qc_sqlit: Plug leaks and access errors
057551a qc_sqlite: Fix to small an allocation
1f73820 qc_sqlite: Free memory allocated during parsing
93fefb9 qc: Enable compare to run the same test repeatedly
e52c578 qc_sqlite: Handle last_insert_id()
929e02a qc_sqlite: Extend UPDATE grammar
de3b9f7 qc_sqlite: Defines provided when running cmake and make
4d5c3b2 qc_sqlite: Add support for multiple-table DELETE FROM
36a4296 qc_mysqlembedded: Handle SQLCOM_DELETE_MULTI
41f613a Fix DCB and SESSION removal from free object pools
00f2ddd Move some common code used in only one protocol into protocol.
6fbd0b0 Format Go source with gofmt
abfbbcb Fix build failures and internal test suite
31de74a Merge branch 'develop' into MXS-483
20d461d Remove uniqueness constrain on oneshot tasks
6c09288 Add missing error message to converter task
0c2c389 Merge branch 'develop' into MXS-483
fa0accc Set freed memory to NULL after authentication failure
63f24e4 Install cdc_schema.go
5123c21 Fix ALTER TABLE parsing
004acc2 Merge branch 'develop' into MXS-483
f69a671 Remove array foreach macro use
a159cd9 qc_sqlite: Add support for SHOW DATABASES
31a2118 Make qc_mysqlembedded optional
27ef30e Changed the default query classifier
359010d Add -h flag as the alias for --host
bebc086 Fix minor bugs
c7ca253 qc_sqlite: Recognize START [TRANSACTION]
240f8bf qc_sqlite: Collect info from nested SELECTs
93ea393 qc_sqlite: Pass along the relative position of a token
cc960af qc_sqlite: Fix incorrect assigment
22a6fef Fix `gtid` avro index table
4c38bef qc_sqlite: STATUS is not a registered word
cace998 qc_sqlite: Include all fields of UPDATE
997b19c qc: Add update tests
7601b3f qc_sqlite: Parse "INSERT INTO t VALUES (), ();" correctly
ca426f1 qc_sqlite: Handle CREATE TRIGGER
f54f963 qc_sqlite: Allow INSERT without INTO
e4a1b6d Remove foreign keys from Avro index
e4501a2 Merge branch 'develop' into MXS-483
82b9585 Fix MMMon never assigning master status
a45a709 qc_mysqlembedded: Find the leaf name
2f3ca8f qc_mysqlembedded: Recognize SQLCOM_REPLACE
cc7ad83 qc_mysqlembedded: Pick up fields for INSERT SELECT as well
0e6b39e qc: Cleanup of select.test
9113f4f qc_sqlite: Pickup more fields from INSERT
4d58f98 Dummy query classifier
dfe824f Document `query_classifier` option
4aa329b MXS-718: Collect fields of INSERT
53818f2 Modify packet number for SSL backend connection
346f973 qc_sqlite: Accept qualified column names
8a83616 Fix in-memory SQLite table structure
6f2c884 Further backend SSL development
4444e92 qc_sqlite: Extend INSERT grammar
2aebcab qc_sqlite: Add support for TRUNCATE
1a6742e qc_sqlite: Accept DEFAULT as value in INSERT
07dec05 qc_sqlite: Crude classification made based on seen keywords
a90a579 Add missing function documentation
72bd0cf qc_sqlite: Change CREATE TABLE grammar
6e04bc8 qc: Add INSERT tests
3666bda qc_sqlite: Add SELECT test
d27e173 Add server/mysql-test/t/select.test to query_classifier
562d004 qc_sqlite: Cleanup error logging.
819cacb Merge branch 'develop' into MXS-483
0d3a789 Add warnings and comments to Avro row event processing
2fab570 Added support for SET autocommit=1
1aa83cf Code review fix
c999f0a Addition of SELECT USER()
8c723da Clean up avro_client.c and avro_file.c
eb21ee8 Clean up avro.c
946a284 Added Avro schema to table metadata processing
72f90be qc_sqlite: Add support for CREATE {FUNCTION|PROCEDURE} ...
4a4ab49 qc: Update line number also when skipping a block
ffddb2a qc_sqlite: Allow queries using INTERVAL
b8b03bd qc_sqlite: Add support for SELECT * FROM tbl2 = tbl1;
77a261a qc_sqlite: Add support for GROUP BY ... WITH ROLLUP
0ead41e cdc_schema now generates lowercase JSON
66e327a Classifier has to be specified explicitly
9074b91 Updated Avrorouter documentation
cf06c7a qc_sqlite: Some comments added.
f579eff Added simple Go based Avro schema generator
f448e90 MXS-419: Added ulimit calls to init scripts
b4ad257 Added FindAvro.cmake
56cc9b9 Added the last transaction script to installations
2d52da2 Added temporary avro-alpha package name
6ada071 Fixed cdc_users script
61f0206 Renaming and minor fixes to CDC Python scripts
9d77c32 Moved GTID table tracking to an in-memory database
8ae7cb0 MXS-704: Fixed `which` usage in post-install scripts
195e118 Readwritesplit sessions aren't created if master is down
2be91da Added affected tables to avro diagnostics
b185320 QUERY-LAST-TRANSACTION now returns proper table names
90860b5 Log stale master message only once
4859c60 Table name to GTID mapping
f77bd23 First steps to backend SSL, not yet working.
68b5bf0 qc_sqlite: Don't treat TRUE and FALSE as identifiers
fca8e59 qc_sqlite: Collect database names as well
6b0e04d qc_sqlite: Add support for SHOW CREATE VIEW
77f4b34 qc_mysqlembedded: Report more, rather than less
a73e033 qc_sqlite: Extend builtin functions
9d9650e qc_sqlite: SQL_BUFFER_RESULT must decay to an id
83fe99d qc_sqlite: Support INSERT IGNORE
9d1c9ca Added avrorouter limitations and tutorial
8dd094d qc_sqlite: Recognize builtin functions
2edc3d6 Moved write operations of the maxavro library to a different file
1364e54 Added more comments to the Avro RBR handling code
f711588 Added warnign about unsupported field types
df0d250 Added SQLite3 based indexing to avrorouter
0c55706 Added GTID event flag check in AVRO processing
bfe28dd qc_sqlite: Accept SET GLOBAL|SESSION ...
a8d2068 qc_mysqlembedded: Exlude code that won't compile on 5.5.42
16ea0b3 qc_sqlite: Add support for DROP FUNCTION
1c0f1fc qc: Report stats after comparison
02345b2 qc_sqlite: Recognize builtin readonly functions
c7a5e75 qc_sqlite: Recognize :=
0aa849d qc: Make compare undestand the delimiter command
fb0a877 qc_mysqlembedded: Examine Item::SUBSELECT_ITEMs
045cf8d qc: Add missing mtl commands
e5c6f45 qc_sqlite: Relax qc_get_type comparison
ac3b2df qc_sqlite: Add support for SHOW STATUS
73a34fb qc_sqlite: Add initial support for FLUSH
4ffbe79 qc_sqlite: Extend CREATE TABLE syntax
009af81 qc_sqlite: Add support for SHOW WARNINGS
001de97 qc: Ignore mysqltest constructs
128307d Merge branch 'release-1.4.3' into gpl-master
5e8a06a SET NAMES XXX added
3ca12ba MXS-685: MMMon clears server state before setting it
dc4d2b0 Further steps to connection limit, non-working.
ef70257 MXS-636: Master failures are no longer fatal errors
99f4c64 Updated QUERY-LAST-TRANSACTION format
d1ff157 Changed QUERY-LAST-TRANSACTION format to JSON
8b2f1ac Fixed formatting of the avrorouter
61543df Added QUERY-LAST-TRANSACTION command
c10d10b qc_sqlite: Add support for SHOW CREATE TABLE
106a38f qc_sqlite: Add support for DROP INDEX
2a85421 qc_sqlite: Extend what can be stated about a table
794cd1c qc_sqlite: Add support for MATCH ... AGAINST
dd7b747 qc_sqlite: Accept FULLTEXT and SPATIAL in CREATE TABLE
a13d6ce qc_sqlite: Add support for PREPARE and EXECUTE
0c5d29f qc_sqlite: Add support for ANALYZE
a6cd32b qc_sqlite: Extend SET syntax
5d47704 qc_sqlite: Pick out fields from UPDATE t SET i = ...
0e05735 qc: Understand --error in server test files
8535975 qc_sqlite: Extend CREATE VIEW syntax
b35e638 qc: Igore read type bit if write bit is on
818a814 qc_sqlite: Add support for SHOW VARIABLES
1aa877b qc_sqlite: Add initial support for DO
e92913a qc_sqlite: Add support for CREATE VIEW
d53a46d qc_sqlite: Recognize bit field literals b'1010'
1fb7977 Added GTID event timestmap into struct gtid_pos
8f95b10 Added new fields in AVRO diagnostics
cb4db54 Added tests with large SQL packets to modutil tests
e4dbd6b MXS-621: More fixes to log messages at startup
4f1e9ee qc: compare tester can now read server MySQL tests
cd8154b qc_sqlite: Allow CHARACTER SET to be specified for column
6f8d053 Added MariaDB 10.1 check for new flags in GTID event
71c471b qc_mysqlembedded: Fix type bits setting
26b00a7 qc_sqlite: Extend ALTER grammar
ea6057c qc_sqlite: Handle also pInto when dupping a struct select
2271559 qc_sqlite: Add support for SHOW TABLE STATUS
9caaf27 qc_sqlite: Add support for CREATE ... LIKE oldtable
cd19932 Merge tag '1.4.2' into master
9e9e4d8 Merge branch 'develop' of https://github.com/mariadb-corporation/maxscale-bsl into develop
267cb60 qc_mysqlembedded: Look into parenthesized comma expressions
77c6ca9 qc_sqlite: Recognize token "<=>"
5ca9a9f qc_sqlite: Allow comma expressions in where clause
b08e910 qc_sqlite: Add SELECT options
d11e581 qc_sqlite: Some recursion cleanup
d53d063 Add but don't invoke connection queue functionality.
6818104 Fix logic error in connections limiter
3c61605 qc_sqlite: Find more affected fields
9af8dfd Allow the classifiers to be specified on the command line
5d4a134 Activate call to protocol for max connections error message.
16638e7 Fix another mistake
234f9e6 Fix mistake
843a6fc Fix mistake.
2c6e9ad Fix errors in config.c; enable call to protocol on connection limit.
fd27849 Introduce configuration items for Maximum and Queued Service connections
60d198d Implement very simple connection limit.
84d8f0f Merge remote-tracking branch 'origin/develop' into MXS-177
8a58e63 Merge remote-tracking branch 'origin/develop' into develop
08487cd Add assertion to enforce number of free DCBs not being negative.
f73af2f Added MariaDB 10.1 check for new flags in GTID event
23898ec Fix wrong sprintf specifier, trailing white space.
ea6cfa3 readwritesplit: Cleaned up routeQuery
3858df0 Cleaned up select_connect_backend_servers
c38ee13 Added more buffer tests
48816df Added more modutils tests
537eac2 Added tests for modutil_get_complete_packets
22a6095 MXS-669: modutil_get_complete_packets no longer makes the buffer contiguous
51af97e qc_sqlite: Add support for CREATE INDEX
e50c573 qc_sqlite: Dig out fields for IN
f58c6df qc_sqlite: Dequote table name
319422b qc_sqlite: Accept ENUM as type for a column
5d6a45c qc_sqlite: Allow UNSIGNED to fallback to an id
16a5f20 qc_sqlite: Extend CREATE TABLE syntax
d6268da qc_sqlite: Accept RIGHT and FULL OUTER joins
2207415 qc_sqlite: Allow STRAIGHT_JOIN in SELECT
6fee546 qc_sqlite: Pick upp more table names
9de5f84 Remove trailing white space.
758f84d Improve comments and messages in dcb.c and session.c re recycle memory.
1c2de21 Merge remote-tracking branch 'origin/develop' into dcb-optimise
6614944 DCB code tidying. Fix missing spinlock release; remove redundant variables
ecd5e5c Remove extra code introduced by merge.
877127a Merge commit '3c0d3e5ab6ddde59da764ec904b517759074a31e' into develop
4275bbe Updated the Connector-C version to 2.2.3
c71042b Some tentative list management code; provide for counting service clients.
ad0c8a6 qc_sqlite: Allow empty insert statement
72e75e5 qc_sqlite: Add support for SELECT ... INTO
cc553fa qc_sqlite: MAXSCALE define can now be used everywhere
3305c6e qc_sqlite: Handle CASE in SELECT
702f62e qc_sqlite: Extend CREATE TABLE grammar
941c212 qc_sqlite: Add support for SHOW [INDEX|INDEXES|KEYS]
6a79136 qc_sqlite: Extend grammar for SHOW TABLES and SHOW COLUMNS
f175d2d qc_sqlite: Add SHOW COLUMNS support
6e47951 qc_sqlite: Add support for SHOW TABLES
bcfa0e7 qc_mysqlembedded: Return the actual name and not as-name
3e19f2e Fixed qlafilter build failure
810b24e MXS-675: Standardized qlafilter output
be92173 qc_sqlite: Exclude alias names from affected fields
9479280 qc_sqlite: Add support for explain EXTENDED
13b0e10 qc_sqlite: Add support for DELETE
a6ccfea qc_mysqlembedded: Look at all conditional items
b428041 qc_sqlite: Extend SELECT options
83f829f query_classifier: Correctly calculate the length of a GWBUF
2ddb24c query_classifier: Ensure that -- comments are handled
fa7a746 qc_sqlite: Allow STRAIGHT_JOIN in SELECTS
6f47819 FindLibUUID update
5ed897b Added FindLibUUID cmake file
16e02bb Added FindLibUUID cmake file
aff63e0 MXS-680: qc_mysqlembedded does not look into functions
8a0eeb4 query_classifier: Improve output of compare
6f08185 Query classifier can now convert enums to strings
124e2b9 MXS-679: Correctly collect fields of WHERE
353c97c transaction_safety default is off
896e37b qc_sqlite: Invert stop logic and be more verbose
7a44d4d qc_sqlite: Extend what is accepted in CREATE TABLE
4dbf499 qc_sqlite: Accept FIRST in ALTER TABLE
3f655c0 qc_sqlite: Update table and affected fields for INSERT
8e1e275 qc_sqlite: Make AS optional in CREATE statement
5f2084b qc_sqlite: Add support for ENGINE when creating a table
242f183 qc_sqlite: CREATE paramters handled in the correct place
8ed2e25 qc_sqlite: Trace only when needed
63d4531 qc_sqlite: Update affected fields also from functions
118cdc3 qc_sqlite: Allow multiple index names in USE|IGNORE INDEX
912da76 qc_sqlite: Add initial support for ...IGNORE INDEX...
0aa7de6 qc_sqlite: Log detailed message on error
3e3bf1a qc_sqlite: Extend create syntax.
c4a4572 qc_sqlite: Exclude quoted values
1621f49 Removed MYSQL_EMBEDDED_LIBRARIES
d3e324c UUID generation now comes from libuuid
e8fe678 qc_sqlite: Enable confitional compilation
a9522ba qc_sqlite: Handle X.Y selects
9bc9770 qc_sqlite: Use same stream when outputting padding
366257a qc_sqlite: Add support for UNSIGNED and ZEROFILL
d4d90ff qc_sqlite: Add support for DROP VIEW
d0519bd qc_sqlite: Extend DROP TABLE syntax
c1e4894 qc_sqlite: Add flag to compare for stopping at first error
9fd6344 MXS-674: Maxinfo generates invalid JSON
3c0d3e5 Fix stupid errors.
9d32b2d Include read queue in buffer provided by dcb_read; changes to match.
b690797 Fix double spinlock release in random_jkiss.
6a4328f Fix problems of memory not being freed in some error cases.
2112e56 Change DCB and Session handling to recycle memory; fix bug in random_jkiss.
3912f72 MXS-631, MXS-632: Cleaned up default value CMake files
383ccb8 Fixed build failure on MariaDB 5.5
a60bca5 Merge branch '1.2.1-binlog_router_trx' into develop
3c2a062 Fix to crashes in embedded library with MariaDB 10.0
d3fe938 MXS-662: Service protocol check no longer ignores bind address
c3da49b qc_sqlite: Update affected fields from everywhere
7a0fab8 qc_sqlite: Allow verbosity of compare test to be controlled
81d6822 qc_sqlite: Cleanup handling of select columns
13e5c59 qc_sqlite: Introduce custom allocation functions
026f27d qc_sqlite: Add support for "USE database"
99079df qc_sqlite: Ignore duplicates when comparing affected fields
ca45cd6 qc_sqlite: Add initial support for qc_get_database_names
75970b6 qc_sqlite: Add support for DROP TABLE.
b97e45d qc_sqlite: Move get_affected_fields() to other helpers
cb0fa96 qc_sqlite: Collect table names of INSERT
3a7c513 qc_mysqlembedded: Only look for created name if CREATE
308b0a4 qc_sqlite: Add support for gc_get_created_table_name.
0dc4af2 qc_sqlite: Add qc_has_clause() handling to update
e9f2d1d qc_sqlite: Update now also provides table names
c3192e4 qc_sqlite: Add initial support for get_table_names
c51eafd qc_sqlite: Add support for qc_has_clause
f318fb2 qc_mysqlembedded: Work around embedded lib bug
4ba2e11 qc_sqlite: Add initial support for qc_get_affected_fields
080dea5 qc_sqlite: Support is_read_query
3f94df1 Fixed compare.cc build failure
868a712 Updated freeing of buffer chains in readwritesplit
9bf7fca Formatted readwritesplit source code
de4da2b Add assertion to spinlock release to detect release of already released spinlock.
d30955a qc_sqlite: Handle the default case of affected fields.
5d02b3f qc_sqlite: Set operation when creating table
94a334d Add test for comparing qc-output
aa6f5d6 Allow a specific query classifier to be loaded explicitly
c799d37 Test both qc_mysqlembedded and qc_sqlite
f8d9aa1 qc_sqlite: Enable "set @user_var=@@system_var"
f190bdc qc_sqlite: Recognize /*!-comments
b694b55 Fixed binary Avro format streaming
c95fa86 qc_sqlite: Report correctly the type of set autocommit
9cb236c qc_sqlite: Add test case
77b4e62 Ensure classify test checks all types
962039e Change return type of qc_get_type
ae00df8 qc_sqlite: Add initial support for the SET statement.
88253c5 qc_sqlite: Rename functions
fa48043 Rework of MySQL backend protocol clean up to fix fault.
3851064 qc_sqlite: Correct recognition of system variables (@@xyz).
9d86f7f qc_sqlite: Detect user and system variables.
a683297 qc_sqlite: Recognize and accept system variables (@@xyz).
a4f64dd qc_sqlite: Add initial support for CREATE [TEMPORARY] TABLE
f834b4f MXS-661: Only COM_QUERY packets are parsed
30077c1 CMake policies set only for correct versions
a166f34 Suppress warning about unknown CMake target
1412730 Added more variables to launchable monitor scripts
358c194 MXS-656: Galera nodes with index 0 can be master again
842aec5 qc_sqlite: Add support for BEGIN, COMMIT, ROLLBACK
b9cad6d Add initial support for UPDATE.
95741cb Add initial support for insert.
3796158 Re-install sqlite whenever parse.y has changed
5bcd8cf Ensure that the query is the one passed
cf05533 Add support for obtaining the type of a query
400d8b4 Always log the outcome
45cf632 Fixed resource leaks and minor bugs
fa9e970 Printout the query when there is a mismatch.
263cb07 All classify to be used with any query classifier
ea381b9 Further cleanup of classify.c
23f6f30 Merge pull request #107 from godmodelabs/typo-dpkg
8c2a64e Fixed classify build failure
0c3070b Fixed binlog to Avro conversion bugs
b827ba9 MXS-653: Silence maxpasswd
30d981c MXS-654: Add test for checking maxpasswd
984039b Rearrange classify.c
837e46d Add log initialization
1cc7a6e Reformat query_classifier/test/classify.c
065a4e5 Merge branch 'develop' into develop-MXS-544-b-merge
ca27f13 Fixed binlog build failure
fb81be2 fixed typo dpgk <-> dpkg
1e88d5d Added python based CDC user creation script
040bbdd MXS-633: Monitor permission checks moved to modules
cde7595 Master-Slave clusters are now robust by default
158c776 Cleaned up core test suite
94c6e66 Fixed bugs resulting from merge
a491e11 Merge remote-tracking branch 'origin/MXS-544-b' into develop-MXS-544-b-merge
30f9f25 Cleaned up avro.c
6286f64 Merge branch 'release-1.4.1' into develop
00206ac MXS-194: Added support for more query types to dbfwfilter
267832b Fixed diagnostic output
a64b694 Fixed bugs in avrorouter
8faaba1 Fixed a bug in GTID seeking
a5fafb7 Fixed typos in avrorouter documentation
8080379 Added avrorouter documentation
fa07d8a Fixed dbfwfilter rule parser build failure
744ce0d Constraints are ignored in DDL statement processing
50808c6 Cleaned up avrorouter
47f6032 Merge branch '1.2.1-binlog_router_trx_lint' into develop
caa0956 Added missing dependencies to maxscale-core
92df61a Remove parallel make from travis coverity builds
fa2b2b4 Added more error logging to Avro record reading
9a98e8b Support for GTID requests and data bursts
c2a787b Small diagnostic fix
c4cee7e Added format output requested by client
50483c7 Cleaning up of Avro code
d485379 Added support for binary Avro protocol
c22cdbb Converted Avro GTID from string to integer representation
5795ca9 Added coverity notification email to .travis.yml
a06e44d Added coverity_scan to Travis
6b94384 Fixed memory leak in avro_schema.c
a11096c Support for db.table request for Avrorouter
4e5cbbf Fixed bugs in Avro record reading
a99e427 Fixed minor bugs in avrorouter
01db8ae Fixed errors with CREATE TABLE statements
f5f3d7a Diagnostic routine update
209324f Added missing include for log_manager.h
e62f764 Added sending of schemas and file rotation
8c8fcbb Added missing log_manager.h include
b13942d Changed printf calls in maxavro library to MXS_ERROR
1168962 More lint inspired changes, mainly in blr_master.c and blr_slave.c
ced8f2f Fixed directory checks in avrorouter
a8ae6be Minor fix to string processing
fbd2d95 Fixed typo in dbfwfilter's CMakeLists.txt
29c3cf4 Merge pull request #106 from mariadb-corporation/willfong-patch-1
854d4e9 Add password column name to example
2f956df Moved server state change logging to a common function
007121f Fixed truncated string values
782892b Fix lint errors and warnings for blr_file.c
4f99fc5 Added Avro testing script
2820980 Small fix to help clear lint problems in blr.c
3afeda4 Fixed errors and warnings located by lint
ecfff82 Fix most lint problems in blr.c
223689c Added ALTER TABLE support
80bc935 Fix final lint problems with mysql_common protocol functions.
e068310 Added preliminary alter table parsing
8c723f1 Lint monitor modules
fdb5620 Fix lint issues in authenticators.
84f0e04 Added function documentation and renamed files
365d9f5 Tidy up, mainly for lint
2ff3005 Added update rows event processing and event types to avro records
2ae0371 Fixed failing regex and improved data streaming
f19206a Renamed avrorouter header
aa7174b Moved relpacement and storage of ddl statements to a separate function
0c10be8 Improved client notification and added Avro block size managemet
91405a7 Cleaned up instance creation
dd97485 Removed useless vars
af64e9e Added CDC authentication with a db file
b73a118 Streamline and lint MySQL backend protocol.
65034ce Merge branch 'release-1.4.0' into develop
28f7e4e Added callback for AVRO client async data transmission
628c27a Added MAXAVRO_FILE struct to AVRO_CLIENT
32b3645 Fixed slavelag build failure
7b15542 Added default authentication method for CDC protocol
5f8e20f Renamed maxavro types and formatted files that use them
882cf84 Added more function documentation to maxavro library
9532f0b Fixed CDC protocol build failure
35a1d3a Added support for offsets in client requests
94577ac Fixed, formatted and refactored CDC protocol
da9bcad Use the maxavro library to read data from Avro files
3ececee Added low level error checking to maxavro library
01b0b8b Tidy and lint mysql_client.c
943f0a7 Added handling of Avro boolean data types to maxavro library
4c781f7 Cleaned up maxavro library and avrorouter
6b2e85d Renamed functions more consistently and cleaned up code
e07158a Moved query event handling to its own function
df7d4c0 Added avro_ prefix to rbr.c
fcbfceb Added seeking to a position in an Avro file
068243a CDC auth decoding
3584d54 Add checks to simplify downstream logic.
9b2c323 Removed useless fprintf
bd5cd52 Added missing authfunc setup
e4aff59 Added record value processing
5cc8615 Added value length functions
7921ecc Merge branch 'MXS-615' into MXS-483
4b09cca Added Travis status to readme.md
cca3a48 Simplify interface to max admin authentication.
4739838 Authenticator API update
233505f Maxavrocheck now accepts multiple files
3fdd137 Improved the Avro file handling
a6ba913 Merge from MXS-615
417d742 Added maxavrocheck
014f9cf Remove obsolete second parameter from authenticate function in authenticators.
ece7ece MaxAdmin authentication converted to a module. Fix quirk in SSL setup.
7c8b37e Moved contents of avro_schema.h into mxs_avro.h
d6660cf Improvements to type handling
71ed0cf Protocol API to have entry point for obtaining default authenticator name.
9d35de2 Fixed transaction tracking
5be02a2 Avrorouter internal state is now stored in the Avro file directory
9293464 Added new info to avro diagnostics
06e0e93 Protocol modules can still handle the authentication outside authenticator modules
6d7108b Added JSON output when Requesting an avro file
6188211 Added new CDC protocol state
c8af27f CDC authentication uses its own authenticator
6590f94 Factor out qc_get_qtype_str
b7880f1 Fix qc_sqlite CMakeLists.txt
bd4ff43 Fixed connector-c being updated and built after every make invokation
0d9e57b Fixed non-MariaDB connectors being used in builds
3d3b779 FIX BUG IN CLIENT DCB SHUTDOWN THAT CAN CAUSE CRASHES
e45ba33 Fixed Connector-C .cmake files
c130189 Fixed connector-c being updated and built after every make invokation
7f3cdf3 Fixed errors on binlog rotation
9d3c83a Remove qc_sqlite
15e8ba5 CDC protocol is now compliant with new protocol structure
4460869 Merge branch 'release-1.4.0' into MXS-483
ea40812 Cleaned up the binlog processing loop
cb646ca Add minimal select recognition to qc_sqlite
ac1a9c5 Fixed binlogrouter test
85dd227 Re-route sqlite's sqlite3Select.
7a2e6f3 Update CMakeLists.txt for qc_sqlite
7a751c3 Added timestamps to records and fixed minor bugs
f73bdde Avrorouter state storage to disk
fcf0488 Fixed Connector-C .cmake files
48b8e4e Merge branch 'MXS-615' into MXS-615-binlog-merge
7c8e19f Add missing dependencies for qc_sqlite
bb9b667 Improvements to type handling and binlog position tracking
dc66b74 Client UUID added
f12fce4 AVRO registration is now handled by avro router
575b809 Add skeleton sqlite-based query classifier.
d09d5fc Build sqlite
146d1f9 Fixed BLOB type handling and refined error messages
6e9e521 Added client user to diagnostics
4538bb8 Merge pull request #104 from rasmushoj/develop
7e18d95 Avro router diagnostics routine update
01e3f75 reverted changes in CMakeLists.txt
52f7c78 reverted changes in postinst.in
eaed577 Added sqlite 3110100
a58cdda Travis configuration for MaxScale. ...
38b452d MIGRATE FREE CLIENT DATA TO AUTH MODULE; BUG FIXES; TIDY UP
6e64506 Fixed minor bugs
aff2411 Enabled CDC protocol
f669100 Fixed NULL Avro value being assigned to a field which cannot be NULL
8f6b16a Added row event processing to avrorouter
2939fe0 Updated Avro schema management to use actual column names
9e3b0cb Removed use of RBR related functions in binlogrouter
d674903 Formatted avro files
fe028d1 DEVELOPMENT OF AUTHENTICATION AS MODULE - WILL NOT WORK YET
977aded Added authenticator modules to the build
a2b384f MOVE MYSQL AUTH CODE INTO AUTHENTICATOR MODULES DIRECTORY
a5d7484 PRELIMINARY CHANGES TO CREATE AUTHENTICATORS AS MODULES
66cf802 Merge remote-tracking branch 'origin/develop' into MXS-615
bca0a7d MINOR CHANGES TO SATISFY LINT
5a9e397 Added Avrorouter binlog file walking
fbc737f Fixed binlogrouter test
3c7c9d7 Added avrorouter main event handling loop
07ad81b Moved common binlogrouter code to a separate file
8c605ed Fixed avrorouter build failures
aa1ba05 Moved binlog definitions to a separate header and fixed build failures
eee7c55 Added create table statement detection
e52b27e Added AVRO_INSTANCE and AVRO_CLIENT
0830caa Change test for client DCB to use role being DCB_ROLE_CLIENT_HANDLER. ...
997bbca Change protocols to continue looping if an accept fails; ...
522e42d Make use of dcb_accept and dcb_listen in httpd and telnetd protocols.
4e692b0 Generalise dcb_listen to tailor log messages to different protocols. ...
52c431d Remove support for passing default port number when handling ...
afe5abc Fix bug in creation of SSL listener structure; fix bugs in ...
0bd6c77 Merge remote-tracking branch 'origin/MXS-544' into MXS-544-a ...
7598597 Add dcb_listen function to make a given DCB into a listener, ...
a275d89 Maxbinlogcheck avro version can detect proper end of file
9bb55a5 Moved row event and table map event handling to a separate file
b7d9e09 Add/improve comments, fix mistake with premature return.
c598770 First attempt at extracting general code into dcb_accept, ...
f20f28f Testing with maxbinlogcheck
b3c60b7 Added mysql_binlog files
0ff9971 Added MariaDB/MySQL binary data processing functions
124560c Merge branch '1.2.1-binlog_router_trx' into MXS-483
4deccff New router fro cdc client
2c11434 Fixed test compiler errors
c1f7d24 Obliged to merge remote-tracking branch 'origin/develop' ...
1775599 Merge remote-tracking branch 'origin/MXS-544' into Test-dev-544-merge
c5317da Small modifications in comments
11c0666 Code cleanup
64a5e9a Merge branch 'release-1.3.0' into MXS-483
2c11e89 First Implementation of CDC
2016-08-11 12:44:07 +03:00

1707 lines
55 KiB
C

/*
** 2009 Oct 23
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
******************************************************************************
*/
#include "fts3Int.h"
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
#include <string.h>
#include <assert.h>
/*
** Characters that may appear in the second argument to matchinfo().
*/
#define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
#define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
#define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
#define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
#define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
#define FTS3_MATCHINFO_LCS 's' /* nCol values */
#define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
#define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
#define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
/*
** The default value for the second argument to matchinfo().
*/
#define FTS3_MATCHINFO_DEFAULT "pcx"
/*
** Used as an fts3ExprIterate() context when loading phrase doclists to
** Fts3Expr.aDoclist[]/nDoclist.
*/
typedef struct LoadDoclistCtx LoadDoclistCtx;
struct LoadDoclistCtx {
Fts3Cursor *pCsr; /* FTS3 Cursor */
int nPhrase; /* Number of phrases seen so far */
int nToken; /* Number of tokens seen so far */
};
/*
** The following types are used as part of the implementation of the
** fts3BestSnippet() routine.
*/
typedef struct SnippetIter SnippetIter;
typedef struct SnippetPhrase SnippetPhrase;
typedef struct SnippetFragment SnippetFragment;
struct SnippetIter {
Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
int iCol; /* Extract snippet from this column */
int nSnippet; /* Requested snippet length (in tokens) */
int nPhrase; /* Number of phrases in query */
SnippetPhrase *aPhrase; /* Array of size nPhrase */
int iCurrent; /* First token of current snippet */
};
struct SnippetPhrase {
int nToken; /* Number of tokens in phrase */
char *pList; /* Pointer to start of phrase position list */
int iHead; /* Next value in position list */
char *pHead; /* Position list data following iHead */
int iTail; /* Next value in trailing position list */
char *pTail; /* Position list data following iTail */
};
struct SnippetFragment {
int iCol; /* Column snippet is extracted from */
int iPos; /* Index of first token in snippet */
u64 covered; /* Mask of query phrases covered */
u64 hlmask; /* Mask of snippet terms to highlight */
};
/*
** This type is used as an fts3ExprIterate() context object while
** accumulating the data returned by the matchinfo() function.
*/
typedef struct MatchInfo MatchInfo;
struct MatchInfo {
Fts3Cursor *pCursor; /* FTS3 Cursor */
int nCol; /* Number of columns in table */
int nPhrase; /* Number of matchable phrases in query */
sqlite3_int64 nDoc; /* Number of docs in database */
char flag;
u32 *aMatchinfo; /* Pre-allocated buffer */
};
/*
** An instance of this structure is used to manage a pair of buffers, each
** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
** for details.
*/
struct MatchinfoBuffer {
u8 aRef[3];
int nElem;
int bGlobal; /* Set if global data is loaded */
char *zMatchinfo;
u32 aMatchinfo[1];
};
/*
** The snippet() and offsets() functions both return text values. An instance
** of the following structure is used to accumulate those values while the
** functions are running. See fts3StringAppend() for details.
*/
typedef struct StrBuffer StrBuffer;
struct StrBuffer {
char *z; /* Pointer to buffer containing string */
int n; /* Length of z in bytes (excl. nul-term) */
int nAlloc; /* Allocated size of buffer z in bytes */
};
/*************************************************************************
** Start of MatchinfoBuffer code.
*/
/*
** Allocate a two-slot MatchinfoBuffer object.
*/
static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
MatchinfoBuffer *pRet;
int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
int nStr = (int)strlen(zMatchinfo);
pRet = sqlite3_malloc(nByte + nStr+1);
if( pRet ){
memset(pRet, 0, nByte);
pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
pRet->nElem = nElem;
pRet->zMatchinfo = ((char*)pRet) + nByte;
memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
pRet->aRef[0] = 1;
}
return pRet;
}
static void fts3MIBufferFree(void *p){
MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
assert( (u32*)p==&pBuf->aMatchinfo[1]
|| (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
);
if( (u32*)p==&pBuf->aMatchinfo[1] ){
pBuf->aRef[1] = 0;
}else{
pBuf->aRef[2] = 0;
}
if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
sqlite3_free(pBuf);
}
}
static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
void (*xRet)(void*) = 0;
u32 *aOut = 0;
if( p->aRef[1]==0 ){
p->aRef[1] = 1;
aOut = &p->aMatchinfo[1];
xRet = fts3MIBufferFree;
}
else if( p->aRef[2]==0 ){
p->aRef[2] = 1;
aOut = &p->aMatchinfo[p->nElem+2];
xRet = fts3MIBufferFree;
}else{
aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
if( aOut ){
xRet = sqlite3_free;
if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
}
}
*paOut = aOut;
return xRet;
}
static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
p->bGlobal = 1;
memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
}
/*
** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
*/
void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
if( p ){
assert( p->aRef[0]==1 );
p->aRef[0] = 0;
if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
sqlite3_free(p);
}
}
}
/*
** End of MatchinfoBuffer code.
*************************************************************************/
/*
** This function is used to help iterate through a position-list. A position
** list is a list of unique integers, sorted from smallest to largest. Each
** element of the list is represented by an FTS3 varint that takes the value
** of the difference between the current element and the previous one plus
** two. For example, to store the position-list:
**
** 4 9 113
**
** the three varints:
**
** 6 7 106
**
** are encoded.
**
** When this function is called, *pp points to the start of an element of
** the list. *piPos contains the value of the previous entry in the list.
** After it returns, *piPos contains the value of the next element of the
** list and *pp is advanced to the following varint.
*/
static void fts3GetDeltaPosition(char **pp, int *piPos){
int iVal;
*pp += fts3GetVarint32(*pp, &iVal);
*piPos += (iVal-2);
}
/*
** Helper function for fts3ExprIterate() (see below).
*/
static int fts3ExprIterate2(
Fts3Expr *pExpr, /* Expression to iterate phrases of */
int *piPhrase, /* Pointer to phrase counter */
int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
void *pCtx /* Second argument to pass to callback */
){
int rc; /* Return code */
int eType = pExpr->eType; /* Type of expression node pExpr */
if( eType!=FTSQUERY_PHRASE ){
assert( pExpr->pLeft && pExpr->pRight );
rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
}
}else{
rc = x(pExpr, *piPhrase, pCtx);
(*piPhrase)++;
}
return rc;
}
/*
** Iterate through all phrase nodes in an FTS3 query, except those that
** are part of a sub-tree that is the right-hand-side of a NOT operator.
** For each phrase node found, the supplied callback function is invoked.
**
** If the callback function returns anything other than SQLITE_OK,
** the iteration is abandoned and the error code returned immediately.
** Otherwise, SQLITE_OK is returned after a callback has been made for
** all eligible phrase nodes.
*/
static int fts3ExprIterate(
Fts3Expr *pExpr, /* Expression to iterate phrases of */
int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
void *pCtx /* Second argument to pass to callback */
){
int iPhrase = 0; /* Variable used as the phrase counter */
return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
}
/*
** This is an fts3ExprIterate() callback used while loading the doclists
** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
** fts3ExprLoadDoclists().
*/
static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
int rc = SQLITE_OK;
Fts3Phrase *pPhrase = pExpr->pPhrase;
LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
UNUSED_PARAMETER(iPhrase);
p->nPhrase++;
p->nToken += pPhrase->nToken;
return rc;
}
/*
** Load the doclists for each phrase in the query associated with FTS3 cursor
** pCsr.
**
** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
** phrases in the expression (all phrases except those directly or
** indirectly descended from the right-hand-side of a NOT operator). If
** pnToken is not NULL, then it is set to the number of tokens in all
** matchable phrases of the expression.
*/
static int fts3ExprLoadDoclists(
Fts3Cursor *pCsr, /* Fts3 cursor for current query */
int *pnPhrase, /* OUT: Number of phrases in query */
int *pnToken /* OUT: Number of tokens in query */
){
int rc; /* Return Code */
LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
sCtx.pCsr = pCsr;
rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
if( pnToken ) *pnToken = sCtx.nToken;
return rc;
}
static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
(*(int *)ctx)++;
pExpr->iPhrase = iPhrase;
return SQLITE_OK;
}
static int fts3ExprPhraseCount(Fts3Expr *pExpr){
int nPhrase = 0;
(void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
return nPhrase;
}
/*
** Advance the position list iterator specified by the first two
** arguments so that it points to the first element with a value greater
** than or equal to parameter iNext.
*/
static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
char *pIter = *ppIter;
if( pIter ){
int iIter = *piIter;
while( iIter<iNext ){
if( 0==(*pIter & 0xFE) ){
iIter = -1;
pIter = 0;
break;
}
fts3GetDeltaPosition(&pIter, &iIter);
}
*piIter = iIter;
*ppIter = pIter;
}
}
/*
** Advance the snippet iterator to the next candidate snippet.
*/
static int fts3SnippetNextCandidate(SnippetIter *pIter){
int i; /* Loop counter */
if( pIter->iCurrent<0 ){
/* The SnippetIter object has just been initialized. The first snippet
** candidate always starts at offset 0 (even if this candidate has a
** score of 0.0).
*/
pIter->iCurrent = 0;
/* Advance the 'head' iterator of each phrase to the first offset that
** is greater than or equal to (iNext+nSnippet).
*/
for(i=0; i<pIter->nPhrase; i++){
SnippetPhrase *pPhrase = &pIter->aPhrase[i];
fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
}
}else{
int iStart;
int iEnd = 0x7FFFFFFF;
for(i=0; i<pIter->nPhrase; i++){
SnippetPhrase *pPhrase = &pIter->aPhrase[i];
if( pPhrase->pHead && pPhrase->iHead<iEnd ){
iEnd = pPhrase->iHead;
}
}
if( iEnd==0x7FFFFFFF ){
return 1;
}
pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
for(i=0; i<pIter->nPhrase; i++){
SnippetPhrase *pPhrase = &pIter->aPhrase[i];
fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
}
}
return 0;
}
/*
** Retrieve information about the current candidate snippet of snippet
** iterator pIter.
*/
static void fts3SnippetDetails(
SnippetIter *pIter, /* Snippet iterator */
u64 mCovered, /* Bitmask of phrases already covered */
int *piToken, /* OUT: First token of proposed snippet */
int *piScore, /* OUT: "Score" for this snippet */
u64 *pmCover, /* OUT: Bitmask of phrases covered */
u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
){
int iStart = pIter->iCurrent; /* First token of snippet */
int iScore = 0; /* Score of this snippet */
int i; /* Loop counter */
u64 mCover = 0; /* Mask of phrases covered by this snippet */
u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
for(i=0; i<pIter->nPhrase; i++){
SnippetPhrase *pPhrase = &pIter->aPhrase[i];
if( pPhrase->pTail ){
char *pCsr = pPhrase->pTail;
int iCsr = pPhrase->iTail;
while( iCsr<(iStart+pIter->nSnippet) ){
int j;
u64 mPhrase = (u64)1 << i;
u64 mPos = (u64)1 << (iCsr - iStart);
assert( iCsr>=iStart );
if( (mCover|mCovered)&mPhrase ){
iScore++;
}else{
iScore += 1000;
}
mCover |= mPhrase;
for(j=0; j<pPhrase->nToken; j++){
mHighlight |= (mPos>>j);
}
if( 0==(*pCsr & 0x0FE) ) break;
fts3GetDeltaPosition(&pCsr, &iCsr);
}
}
}
/* Set the output variables before returning. */
*piToken = iStart;
*piScore = iScore;
*pmCover = mCover;
*pmHighlight = mHighlight;
}
/*
** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
** Each invocation populates an element of the SnippetIter.aPhrase[] array.
*/
static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
SnippetIter *p = (SnippetIter *)ctx;
SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
char *pCsr;
int rc;
pPhrase->nToken = pExpr->pPhrase->nToken;
rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
assert( rc==SQLITE_OK || pCsr==0 );
if( pCsr ){
int iFirst = 0;
pPhrase->pList = pCsr;
fts3GetDeltaPosition(&pCsr, &iFirst);
assert( iFirst>=0 );
pPhrase->pHead = pCsr;
pPhrase->pTail = pCsr;
pPhrase->iHead = iFirst;
pPhrase->iTail = iFirst;
}else{
assert( rc!=SQLITE_OK || (
pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
));
}
return rc;
}
/*
** Select the fragment of text consisting of nFragment contiguous tokens
** from column iCol that represent the "best" snippet. The best snippet
** is the snippet with the highest score, where scores are calculated
** by adding:
**
** (a) +1 point for each occurrence of a matchable phrase in the snippet.
**
** (b) +1000 points for the first occurrence of each matchable phrase in
** the snippet for which the corresponding mCovered bit is not set.
**
** The selected snippet parameters are stored in structure *pFragment before
** returning. The score of the selected snippet is stored in *piScore
** before returning.
*/
static int fts3BestSnippet(
int nSnippet, /* Desired snippet length */
Fts3Cursor *pCsr, /* Cursor to create snippet for */
int iCol, /* Index of column to create snippet from */
u64 mCovered, /* Mask of phrases already covered */
u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
SnippetFragment *pFragment, /* OUT: Best snippet found */
int *piScore /* OUT: Score of snippet pFragment */
){
int rc; /* Return Code */
int nList; /* Number of phrases in expression */
SnippetIter sIter; /* Iterates through snippet candidates */
int nByte; /* Number of bytes of space to allocate */
int iBestScore = -1; /* Best snippet score found so far */
int i; /* Loop counter */
memset(&sIter, 0, sizeof(sIter));
/* Iterate through the phrases in the expression to count them. The same
** callback makes sure the doclists are loaded for each phrase.
*/
rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
if( rc!=SQLITE_OK ){
return rc;
}
/* Now that it is known how many phrases there are, allocate and zero
** the required space using malloc().
*/
nByte = sizeof(SnippetPhrase) * nList;
sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
if( !sIter.aPhrase ){
return SQLITE_NOMEM;
}
memset(sIter.aPhrase, 0, nByte);
/* Initialize the contents of the SnippetIter object. Then iterate through
** the set of phrases in the expression to populate the aPhrase[] array.
*/
sIter.pCsr = pCsr;
sIter.iCol = iCol;
sIter.nSnippet = nSnippet;
sIter.nPhrase = nList;
sIter.iCurrent = -1;
rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
if( rc==SQLITE_OK ){
/* Set the *pmSeen output variable. */
for(i=0; i<nList; i++){
if( sIter.aPhrase[i].pHead ){
*pmSeen |= (u64)1 << i;
}
}
/* Loop through all candidate snippets. Store the best snippet in
** *pFragment. Store its associated 'score' in iBestScore.
*/
pFragment->iCol = iCol;
while( !fts3SnippetNextCandidate(&sIter) ){
int iPos;
int iScore;
u64 mCover;
u64 mHighlite;
fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
assert( iScore>=0 );
if( iScore>iBestScore ){
pFragment->iPos = iPos;
pFragment->hlmask = mHighlite;
pFragment->covered = mCover;
iBestScore = iScore;
}
}
*piScore = iBestScore;
}
sqlite3_free(sIter.aPhrase);
return rc;
}
/*
** Append a string to the string-buffer passed as the first argument.
**
** If nAppend is negative, then the length of the string zAppend is
** determined using strlen().
*/
static int fts3StringAppend(
StrBuffer *pStr, /* Buffer to append to */
const char *zAppend, /* Pointer to data to append to buffer */
int nAppend /* Size of zAppend in bytes (or -1) */
){
if( nAppend<0 ){
nAppend = (int)strlen(zAppend);
}
/* If there is insufficient space allocated at StrBuffer.z, use realloc()
** to grow the buffer until so that it is big enough to accomadate the
** appended data.
*/
if( pStr->n+nAppend+1>=pStr->nAlloc ){
int nAlloc = pStr->nAlloc+nAppend+100;
char *zNew = sqlite3_realloc(pStr->z, nAlloc);
if( !zNew ){
return SQLITE_NOMEM;
}
pStr->z = zNew;
pStr->nAlloc = nAlloc;
}
assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
/* Append the data to the string buffer. */
memcpy(&pStr->z[pStr->n], zAppend, nAppend);
pStr->n += nAppend;
pStr->z[pStr->n] = '\0';
return SQLITE_OK;
}
/*
** The fts3BestSnippet() function often selects snippets that end with a
** query term. That is, the final term of the snippet is always a term
** that requires highlighting. For example, if 'X' is a highlighted term
** and '.' is a non-highlighted term, BestSnippet() may select:
**
** ........X.....X
**
** This function "shifts" the beginning of the snippet forward in the
** document so that there are approximately the same number of
** non-highlighted terms to the right of the final highlighted term as there
** are to the left of the first highlighted term. For example, to this:
**
** ....X.....X....
**
** This is done as part of extracting the snippet text, not when selecting
** the snippet. Snippet selection is done based on doclists only, so there
** is no way for fts3BestSnippet() to know whether or not the document
** actually contains terms that follow the final highlighted term.
*/
static int fts3SnippetShift(
Fts3Table *pTab, /* FTS3 table snippet comes from */
int iLangid, /* Language id to use in tokenizing */
int nSnippet, /* Number of tokens desired for snippet */
const char *zDoc, /* Document text to extract snippet from */
int nDoc, /* Size of buffer zDoc in bytes */
int *piPos, /* IN/OUT: First token of snippet */
u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
){
u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
if( hlmask ){
int nLeft; /* Tokens to the left of first highlight */
int nRight; /* Tokens to the right of last highlight */
int nDesired; /* Ideal number of tokens to shift forward */
for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
nDesired = (nLeft-nRight)/2;
/* Ideally, the start of the snippet should be pushed forward in the
** document nDesired tokens. This block checks if there are actually
** nDesired tokens to the right of the snippet. If so, *piPos and
** *pHlMask are updated to shift the snippet nDesired tokens to the
** right. Otherwise, the snippet is shifted by the number of tokens
** available.
*/
if( nDesired>0 ){
int nShift; /* Number of tokens to shift snippet by */
int iCurrent = 0; /* Token counter */
int rc; /* Return Code */
sqlite3_tokenizer_module *pMod;
sqlite3_tokenizer_cursor *pC;
pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
/* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
** or more tokens in zDoc/nDoc.
*/
rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
if( rc!=SQLITE_OK ){
return rc;
}
while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
}
pMod->xClose(pC);
if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
assert( nShift<=nDesired );
if( nShift>0 ){
*piPos += nShift;
*pHlmask = hlmask >> nShift;
}
}
}
return SQLITE_OK;
}
/*
** Extract the snippet text for fragment pFragment from cursor pCsr and
** append it to string buffer pOut.
*/
static int fts3SnippetText(
Fts3Cursor *pCsr, /* FTS3 Cursor */
SnippetFragment *pFragment, /* Snippet to extract */
int iFragment, /* Fragment number */
int isLast, /* True for final fragment in snippet */
int nSnippet, /* Number of tokens in extracted snippet */
const char *zOpen, /* String inserted before highlighted term */
const char *zClose, /* String inserted after highlighted term */
const char *zEllipsis, /* String inserted between snippets */
StrBuffer *pOut /* Write output here */
){
Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
int rc; /* Return code */
const char *zDoc; /* Document text to extract snippet from */
int nDoc; /* Size of zDoc in bytes */
int iCurrent = 0; /* Current token number of document */
int iEnd = 0; /* Byte offset of end of current token */
int isShiftDone = 0; /* True after snippet is shifted */
int iPos = pFragment->iPos; /* First token of snippet */
u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
int iCol = pFragment->iCol+1; /* Query column to extract text from */
sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
if( zDoc==0 ){
if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
return SQLITE_NOMEM;
}
return SQLITE_OK;
}
nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
/* Open a token cursor on the document. */
pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
if( rc!=SQLITE_OK ){
return rc;
}
while( rc==SQLITE_OK ){
const char *ZDUMMY; /* Dummy argument used with tokenizer */
int DUMMY1 = -1; /* Dummy argument used with tokenizer */
int iBegin = 0; /* Offset in zDoc of start of token */
int iFin = 0; /* Offset in zDoc of end of token */
int isHighlight = 0; /* True for highlighted terms */
/* Variable DUMMY1 is initialized to a negative value above. Elsewhere
** in the FTS code the variable that the third argument to xNext points to
** is initialized to zero before the first (*but not necessarily
** subsequent*) call to xNext(). This is done for a particular application
** that needs to know whether or not the tokenizer is being used for
** snippet generation or for some other purpose.
**
** Extreme care is required when writing code to depend on this
** initialization. It is not a documented part of the tokenizer interface.
** If a tokenizer is used directly by any code outside of FTS, this
** convention might not be respected. */
rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
if( rc!=SQLITE_OK ){
if( rc==SQLITE_DONE ){
/* Special case - the last token of the snippet is also the last token
** of the column. Append any punctuation that occurred between the end
** of the previous token and the end of the document to the output.
** Then break out of the loop. */
rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
}
break;
}
if( iCurrent<iPos ){ continue; }
if( !isShiftDone ){
int n = nDoc - iBegin;
rc = fts3SnippetShift(
pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
);
isShiftDone = 1;
/* Now that the shift has been done, check if the initial "..." are
** required. They are required if (a) this is not the first fragment,
** or (b) this fragment does not begin at position 0 of its column.
*/
if( rc==SQLITE_OK ){
if( iPos>0 || iFragment>0 ){
rc = fts3StringAppend(pOut, zEllipsis, -1);
}else if( iBegin ){
rc = fts3StringAppend(pOut, zDoc, iBegin);
}
}
if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
}
if( iCurrent>=(iPos+nSnippet) ){
if( isLast ){
rc = fts3StringAppend(pOut, zEllipsis, -1);
}
break;
}
/* Set isHighlight to true if this term should be highlighted. */
isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
iEnd = iFin;
}
pMod->xClose(pC);
return rc;
}
/*
** This function is used to count the entries in a column-list (a
** delta-encoded list of term offsets within a single column of a single
** row). When this function is called, *ppCollist should point to the
** beginning of the first varint in the column-list (the varint that
** contains the position of the first matching term in the column data).
** Before returning, *ppCollist is set to point to the first byte after
** the last varint in the column-list (either the 0x00 signifying the end
** of the position-list, or the 0x01 that precedes the column number of
** the next column in the position-list).
**
** The number of elements in the column-list is returned.
*/
static int fts3ColumnlistCount(char **ppCollist){
char *pEnd = *ppCollist;
char c = 0;
int nEntry = 0;
/* A column-list is terminated by either a 0x01 or 0x00. */
while( 0xFE & (*pEnd | c) ){
c = *pEnd++ & 0x80;
if( !c ) nEntry++;
}
*ppCollist = pEnd;
return nEntry;
}
/*
** This function gathers 'y' or 'b' data for a single phrase.
*/
static void fts3ExprLHits(
Fts3Expr *pExpr, /* Phrase expression node */
MatchInfo *p /* Matchinfo context */
){
Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
int iStart;
Fts3Phrase *pPhrase = pExpr->pPhrase;
char *pIter = pPhrase->doclist.pList;
int iCol = 0;
assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
if( p->flag==FTS3_MATCHINFO_LHITS ){
iStart = pExpr->iPhrase * p->nCol;
}else{
iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
}
while( 1 ){
int nHit = fts3ColumnlistCount(&pIter);
if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
if( p->flag==FTS3_MATCHINFO_LHITS ){
p->aMatchinfo[iStart + iCol] = (u32)nHit;
}else if( nHit ){
p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
}
}
assert( *pIter==0x00 || *pIter==0x01 );
if( *pIter!=0x01 ) break;
pIter++;
pIter += fts3GetVarint32(pIter, &iCol);
}
}
/*
** Gather the results for matchinfo directives 'y' and 'b'.
*/
static void fts3ExprLHitGather(
Fts3Expr *pExpr,
MatchInfo *p
){
assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
if( pExpr->pLeft ){
fts3ExprLHitGather(pExpr->pLeft, p);
fts3ExprLHitGather(pExpr->pRight, p);
}else{
fts3ExprLHits(pExpr, p);
}
}
}
/*
** fts3ExprIterate() callback used to collect the "global" matchinfo stats
** for a single query.
**
** fts3ExprIterate() callback to load the 'global' elements of a
** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
** of the matchinfo array that are constant for all rows returned by the
** current query.
**
** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
** function populates Matchinfo.aMatchinfo[] as follows:
**
** for(iCol=0; iCol<nCol; iCol++){
** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
** }
**
** where X is the number of matches for phrase iPhrase is column iCol of all
** rows of the table. Y is the number of rows for which column iCol contains
** at least one instance of phrase iPhrase.
**
** If the phrase pExpr consists entirely of deferred tokens, then all X and
** Y values are set to nDoc, where nDoc is the number of documents in the
** file system. This is done because the full-text index doclist is required
** to calculate these values properly, and the full-text index doclist is
** not available for deferred tokens.
*/
static int fts3ExprGlobalHitsCb(
Fts3Expr *pExpr, /* Phrase expression node */
int iPhrase, /* Phrase number (numbered from zero) */
void *pCtx /* Pointer to MatchInfo structure */
){
MatchInfo *p = (MatchInfo *)pCtx;
return sqlite3Fts3EvalPhraseStats(
p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
);
}
/*
** fts3ExprIterate() callback used to collect the "local" part of the
** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
** array that are different for each row returned by the query.
*/
static int fts3ExprLocalHitsCb(
Fts3Expr *pExpr, /* Phrase expression node */
int iPhrase, /* Phrase number */
void *pCtx /* Pointer to MatchInfo structure */
){
int rc = SQLITE_OK;
MatchInfo *p = (MatchInfo *)pCtx;
int iStart = iPhrase * p->nCol * 3;
int i;
for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
char *pCsr;
rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
if( pCsr ){
p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
}else{
p->aMatchinfo[iStart+i*3] = 0;
}
}
return rc;
}
static int fts3MatchinfoCheck(
Fts3Table *pTab,
char cArg,
char **pzErr
){
if( (cArg==FTS3_MATCHINFO_NPHRASE)
|| (cArg==FTS3_MATCHINFO_NCOL)
|| (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
|| (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
|| (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
|| (cArg==FTS3_MATCHINFO_LCS)
|| (cArg==FTS3_MATCHINFO_HITS)
|| (cArg==FTS3_MATCHINFO_LHITS)
|| (cArg==FTS3_MATCHINFO_LHITS_BM)
){
return SQLITE_OK;
}
sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
return SQLITE_ERROR;
}
static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
int nVal; /* Number of integers output by cArg */
switch( cArg ){
case FTS3_MATCHINFO_NDOC:
case FTS3_MATCHINFO_NPHRASE:
case FTS3_MATCHINFO_NCOL:
nVal = 1;
break;
case FTS3_MATCHINFO_AVGLENGTH:
case FTS3_MATCHINFO_LENGTH:
case FTS3_MATCHINFO_LCS:
nVal = pInfo->nCol;
break;
case FTS3_MATCHINFO_LHITS:
nVal = pInfo->nCol * pInfo->nPhrase;
break;
case FTS3_MATCHINFO_LHITS_BM:
nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
break;
default:
assert( cArg==FTS3_MATCHINFO_HITS );
nVal = pInfo->nCol * pInfo->nPhrase * 3;
break;
}
return nVal;
}
static int fts3MatchinfoSelectDoctotal(
Fts3Table *pTab,
sqlite3_stmt **ppStmt,
sqlite3_int64 *pnDoc,
const char **paLen
){
sqlite3_stmt *pStmt;
const char *a;
sqlite3_int64 nDoc;
if( !*ppStmt ){
int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
if( rc!=SQLITE_OK ) return rc;
}
pStmt = *ppStmt;
assert( sqlite3_data_count(pStmt)==1 );
a = sqlite3_column_blob(pStmt, 0);
a += sqlite3Fts3GetVarint(a, &nDoc);
if( nDoc==0 ) return FTS_CORRUPT_VTAB;
*pnDoc = (u32)nDoc;
if( paLen ) *paLen = a;
return SQLITE_OK;
}
/*
** An instance of the following structure is used to store state while
** iterating through a multi-column position-list corresponding to the
** hits for a single phrase on a single row in order to calculate the
** values for a matchinfo() FTS3_MATCHINFO_LCS request.
*/
typedef struct LcsIterator LcsIterator;
struct LcsIterator {
Fts3Expr *pExpr; /* Pointer to phrase expression */
int iPosOffset; /* Tokens count up to end of this phrase */
char *pRead; /* Cursor used to iterate through aDoclist */
int iPos; /* Current position */
};
/*
** If LcsIterator.iCol is set to the following value, the iterator has
** finished iterating through all offsets for all columns.
*/
#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
static int fts3MatchinfoLcsCb(
Fts3Expr *pExpr, /* Phrase expression node */
int iPhrase, /* Phrase number (numbered from zero) */
void *pCtx /* Pointer to MatchInfo structure */
){
LcsIterator *aIter = (LcsIterator *)pCtx;
aIter[iPhrase].pExpr = pExpr;
return SQLITE_OK;
}
/*
** Advance the iterator passed as an argument to the next position. Return
** 1 if the iterator is at EOF or if it now points to the start of the
** position list for the next column.
*/
static int fts3LcsIteratorAdvance(LcsIterator *pIter){
char *pRead = pIter->pRead;
sqlite3_int64 iRead;
int rc = 0;
pRead += sqlite3Fts3GetVarint(pRead, &iRead);
if( iRead==0 || iRead==1 ){
pRead = 0;
rc = 1;
}else{
pIter->iPos += (int)(iRead-2);
}
pIter->pRead = pRead;
return rc;
}
/*
** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
**
** If the call is successful, the longest-common-substring lengths for each
** column are written into the first nCol elements of the pInfo->aMatchinfo[]
** array before returning. SQLITE_OK is returned in this case.
**
** Otherwise, if an error occurs, an SQLite error code is returned and the
** data written to the first nCol elements of pInfo->aMatchinfo[] is
** undefined.
*/
static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
LcsIterator *aIter;
int i;
int iCol;
int nToken = 0;
/* Allocate and populate the array of LcsIterator objects. The array
** contains one element for each matchable phrase in the query.
**/
aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
if( !aIter ) return SQLITE_NOMEM;
memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
(void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
for(i=0; i<pInfo->nPhrase; i++){
LcsIterator *pIter = &aIter[i];
nToken -= pIter->pExpr->pPhrase->nToken;
pIter->iPosOffset = nToken;
}
for(iCol=0; iCol<pInfo->nCol; iCol++){
int nLcs = 0; /* LCS value for this column */
int nLive = 0; /* Number of iterators in aIter not at EOF */
for(i=0; i<pInfo->nPhrase; i++){
int rc;
LcsIterator *pIt = &aIter[i];
rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
if( rc!=SQLITE_OK ) return rc;
if( pIt->pRead ){
pIt->iPos = pIt->iPosOffset;
fts3LcsIteratorAdvance(&aIter[i]);
nLive++;
}
}
while( nLive>0 ){
LcsIterator *pAdv = 0; /* The iterator to advance by one position */
int nThisLcs = 0; /* LCS for the current iterator positions */
for(i=0; i<pInfo->nPhrase; i++){
LcsIterator *pIter = &aIter[i];
if( pIter->pRead==0 ){
/* This iterator is already at EOF for this column. */
nThisLcs = 0;
}else{
if( pAdv==0 || pIter->iPos<pAdv->iPos ){
pAdv = pIter;
}
if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
nThisLcs++;
}else{
nThisLcs = 1;
}
if( nThisLcs>nLcs ) nLcs = nThisLcs;
}
}
if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
}
pInfo->aMatchinfo[iCol] = nLcs;
}
sqlite3_free(aIter);
return SQLITE_OK;
}
/*
** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
** be returned by the matchinfo() function. Argument zArg contains the
** format string passed as the second argument to matchinfo (or the
** default value "pcx" if no second argument was specified). The format
** string has already been validated and the pInfo->aMatchinfo[] array
** is guaranteed to be large enough for the output.
**
** If bGlobal is true, then populate all fields of the matchinfo() output.
** If it is false, then assume that those fields that do not change between
** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
** have already been populated.
**
** Return SQLITE_OK if successful, or an SQLite error code if an error
** occurs. If a value other than SQLITE_OK is returned, the state the
** pInfo->aMatchinfo[] buffer is left in is undefined.
*/
static int fts3MatchinfoValues(
Fts3Cursor *pCsr, /* FTS3 cursor object */
int bGlobal, /* True to grab the global stats */
MatchInfo *pInfo, /* Matchinfo context object */
const char *zArg /* Matchinfo format string */
){
int rc = SQLITE_OK;
int i;
Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
sqlite3_stmt *pSelect = 0;
for(i=0; rc==SQLITE_OK && zArg[i]; i++){
pInfo->flag = zArg[i];
switch( zArg[i] ){
case FTS3_MATCHINFO_NPHRASE:
if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
break;
case FTS3_MATCHINFO_NCOL:
if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
break;
case FTS3_MATCHINFO_NDOC:
if( bGlobal ){
sqlite3_int64 nDoc = 0;
rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
pInfo->aMatchinfo[0] = (u32)nDoc;
}
break;
case FTS3_MATCHINFO_AVGLENGTH:
if( bGlobal ){
sqlite3_int64 nDoc; /* Number of rows in table */
const char *a; /* Aggregate column length array */
rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
if( rc==SQLITE_OK ){
int iCol;
for(iCol=0; iCol<pInfo->nCol; iCol++){
u32 iVal;
sqlite3_int64 nToken;
a += sqlite3Fts3GetVarint(a, &nToken);
iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
pInfo->aMatchinfo[iCol] = iVal;
}
}
}
break;
case FTS3_MATCHINFO_LENGTH: {
sqlite3_stmt *pSelectDocsize = 0;
rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
if( rc==SQLITE_OK ){
int iCol;
const char *a = sqlite3_column_blob(pSelectDocsize, 0);
for(iCol=0; iCol<pInfo->nCol; iCol++){
sqlite3_int64 nToken;
a += sqlite3Fts3GetVarint(a, &nToken);
pInfo->aMatchinfo[iCol] = (u32)nToken;
}
}
sqlite3_reset(pSelectDocsize);
break;
}
case FTS3_MATCHINFO_LCS:
rc = fts3ExprLoadDoclists(pCsr, 0, 0);
if( rc==SQLITE_OK ){
rc = fts3MatchinfoLcs(pCsr, pInfo);
}
break;
case FTS3_MATCHINFO_LHITS_BM:
case FTS3_MATCHINFO_LHITS: {
int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
memset(pInfo->aMatchinfo, 0, nZero);
fts3ExprLHitGather(pCsr->pExpr, pInfo);
break;
}
default: {
Fts3Expr *pExpr;
assert( zArg[i]==FTS3_MATCHINFO_HITS );
pExpr = pCsr->pExpr;
rc = fts3ExprLoadDoclists(pCsr, 0, 0);
if( rc!=SQLITE_OK ) break;
if( bGlobal ){
if( pCsr->pDeferred ){
rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
if( rc!=SQLITE_OK ) break;
}
rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
sqlite3Fts3EvalTestDeferred(pCsr, &rc);
if( rc!=SQLITE_OK ) break;
}
(void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
break;
}
}
pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
}
sqlite3_reset(pSelect);
return rc;
}
/*
** Populate pCsr->aMatchinfo[] with data for the current row. The
** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
*/
static void fts3GetMatchinfo(
sqlite3_context *pCtx, /* Return results here */
Fts3Cursor *pCsr, /* FTS3 Cursor object */
const char *zArg /* Second argument to matchinfo() function */
){
MatchInfo sInfo;
Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
int rc = SQLITE_OK;
int bGlobal = 0; /* Collect 'global' stats as well as local */
u32 *aOut = 0;
void (*xDestroyOut)(void*) = 0;
memset(&sInfo, 0, sizeof(MatchInfo));
sInfo.pCursor = pCsr;
sInfo.nCol = pTab->nColumn;
/* If there is cached matchinfo() data, but the format string for the
** cache does not match the format string for this request, discard
** the cached data. */
if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
pCsr->pMIBuffer = 0;
}
/* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
** matchinfo function has been called for this query. In this case
** allocate the array used to accumulate the matchinfo data and
** initialize those elements that are constant for every row.
*/
if( pCsr->pMIBuffer==0 ){
int nMatchinfo = 0; /* Number of u32 elements in match-info */
int i; /* Used to iterate through zArg */
/* Determine the number of phrases in the query */
pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
sInfo.nPhrase = pCsr->nPhrase;
/* Determine the number of integers in the buffer returned by this call. */
for(i=0; zArg[i]; i++){
char *zErr = 0;
if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
sqlite3_result_error(pCtx, zErr, -1);
sqlite3_free(zErr);
return;
}
nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
}
/* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
pCsr->isMatchinfoNeeded = 1;
bGlobal = 1;
}
if( rc==SQLITE_OK ){
xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
if( xDestroyOut==0 ){
rc = SQLITE_NOMEM;
}
}
if( rc==SQLITE_OK ){
sInfo.aMatchinfo = aOut;
sInfo.nPhrase = pCsr->nPhrase;
rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
if( bGlobal ){
fts3MIBufferSetGlobal(pCsr->pMIBuffer);
}
}
if( rc!=SQLITE_OK ){
sqlite3_result_error_code(pCtx, rc);
if( xDestroyOut ) xDestroyOut(aOut);
}else{
int n = pCsr->pMIBuffer->nElem * sizeof(u32);
sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
}
}
/*
** Implementation of snippet() function.
*/
void sqlite3Fts3Snippet(
sqlite3_context *pCtx, /* SQLite function call context */
Fts3Cursor *pCsr, /* Cursor object */
const char *zStart, /* Snippet start text - "<b>" */
const char *zEnd, /* Snippet end text - "</b>" */
const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
int iCol, /* Extract snippet from this column */
int nToken /* Approximate number of tokens in snippet */
){
Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
int rc = SQLITE_OK;
int i;
StrBuffer res = {0, 0, 0};
/* The returned text includes up to four fragments of text extracted from
** the data in the current row. The first iteration of the for(...) loop
** below attempts to locate a single fragment of text nToken tokens in
** size that contains at least one instance of all phrases in the query
** expression that appear in the current row. If such a fragment of text
** cannot be found, the second iteration of the loop attempts to locate
** a pair of fragments, and so on.
*/
int nSnippet = 0; /* Number of fragments in this snippet */
SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
int nFToken = -1; /* Number of tokens in each fragment */
if( !pCsr->pExpr ){
sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
return;
}
for(nSnippet=1; 1; nSnippet++){
int iSnip; /* Loop counter 0..nSnippet-1 */
u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
if( nToken>=0 ){
nFToken = (nToken+nSnippet-1) / nSnippet;
}else{
nFToken = -1 * nToken;
}
for(iSnip=0; iSnip<nSnippet; iSnip++){
int iBestScore = -1; /* Best score of columns checked so far */
int iRead; /* Used to iterate through columns */
SnippetFragment *pFragment = &aSnippet[iSnip];
memset(pFragment, 0, sizeof(*pFragment));
/* Loop through all columns of the table being considered for snippets.
** If the iCol argument to this function was negative, this means all
** columns of the FTS3 table. Otherwise, only column iCol is considered.
*/
for(iRead=0; iRead<pTab->nColumn; iRead++){
SnippetFragment sF = {0, 0, 0, 0};
int iS = 0;
if( iCol>=0 && iRead!=iCol ) continue;
/* Find the best snippet of nFToken tokens in column iRead. */
rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
if( rc!=SQLITE_OK ){
goto snippet_out;
}
if( iS>iBestScore ){
*pFragment = sF;
iBestScore = iS;
}
}
mCovered |= pFragment->covered;
}
/* If all query phrases seen by fts3BestSnippet() are present in at least
** one of the nSnippet snippet fragments, break out of the loop.
*/
assert( (mCovered&mSeen)==mCovered );
if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
}
assert( nFToken>0 );
for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
rc = fts3SnippetText(pCsr, &aSnippet[i],
i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
);
}
snippet_out:
sqlite3Fts3SegmentsClose(pTab);
if( rc!=SQLITE_OK ){
sqlite3_result_error_code(pCtx, rc);
sqlite3_free(res.z);
}else{
sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
}
}
typedef struct TermOffset TermOffset;
typedef struct TermOffsetCtx TermOffsetCtx;
struct TermOffset {
char *pList; /* Position-list */
int iPos; /* Position just read from pList */
int iOff; /* Offset of this term from read positions */
};
struct TermOffsetCtx {
Fts3Cursor *pCsr;
int iCol; /* Column of table to populate aTerm for */
int iTerm;
sqlite3_int64 iDocid;
TermOffset *aTerm;
};
/*
** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
*/
static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
TermOffsetCtx *p = (TermOffsetCtx *)ctx;
int nTerm; /* Number of tokens in phrase */
int iTerm; /* For looping through nTerm phrase terms */
char *pList; /* Pointer to position list for phrase */
int iPos = 0; /* First position in position-list */
int rc;
UNUSED_PARAMETER(iPhrase);
rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
nTerm = pExpr->pPhrase->nToken;
if( pList ){
fts3GetDeltaPosition(&pList, &iPos);
assert( iPos>=0 );
}
for(iTerm=0; iTerm<nTerm; iTerm++){
TermOffset *pT = &p->aTerm[p->iTerm++];
pT->iOff = nTerm-iTerm-1;
pT->pList = pList;
pT->iPos = iPos;
}
return rc;
}
/*
** Implementation of offsets() function.
*/
void sqlite3Fts3Offsets(
sqlite3_context *pCtx, /* SQLite function call context */
Fts3Cursor *pCsr /* Cursor object */
){
Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
int rc; /* Return Code */
int nToken; /* Number of tokens in query */
int iCol; /* Column currently being processed */
StrBuffer res = {0, 0, 0}; /* Result string */
TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
if( !pCsr->pExpr ){
sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
return;
}
memset(&sCtx, 0, sizeof(sCtx));
assert( pCsr->isRequireSeek==0 );
/* Count the number of terms in the query */
rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
if( rc!=SQLITE_OK ) goto offsets_out;
/* Allocate the array of TermOffset iterators. */
sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
if( 0==sCtx.aTerm ){
rc = SQLITE_NOMEM;
goto offsets_out;
}
sCtx.iDocid = pCsr->iPrevId;
sCtx.pCsr = pCsr;
/* Loop through the table columns, appending offset information to
** string-buffer res for each column.
*/
for(iCol=0; iCol<pTab->nColumn; iCol++){
sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
const char *ZDUMMY; /* Dummy argument used with xNext() */
int NDUMMY = 0; /* Dummy argument used with xNext() */
int iStart = 0;
int iEnd = 0;
int iCurrent = 0;
const char *zDoc;
int nDoc;
/* Initialize the contents of sCtx.aTerm[] for column iCol. There is
** no way that this operation can fail, so the return code from
** fts3ExprIterate() can be discarded.
*/
sCtx.iCol = iCol;
sCtx.iTerm = 0;
(void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
/* Retreive the text stored in column iCol. If an SQL NULL is stored
** in column iCol, jump immediately to the next iteration of the loop.
** If an OOM occurs while retrieving the data (this can happen if SQLite
** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
** to the caller.
*/
zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
if( zDoc==0 ){
if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
continue;
}
rc = SQLITE_NOMEM;
goto offsets_out;
}
/* Initialize a tokenizer iterator to iterate through column iCol. */
rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
zDoc, nDoc, &pC
);
if( rc!=SQLITE_OK ) goto offsets_out;
rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
while( rc==SQLITE_OK ){
int i; /* Used to loop through terms */
int iMinPos = 0x7FFFFFFF; /* Position of next token */
TermOffset *pTerm = 0; /* TermOffset associated with next token */
for(i=0; i<nToken; i++){
TermOffset *pT = &sCtx.aTerm[i];
if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
iMinPos = pT->iPos-pT->iOff;
pTerm = pT;
}
}
if( !pTerm ){
/* All offsets for this column have been gathered. */
rc = SQLITE_DONE;
}else{
assert( iCurrent<=iMinPos );
if( 0==(0xFE&*pTerm->pList) ){
pTerm->pList = 0;
}else{
fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
}
while( rc==SQLITE_OK && iCurrent<iMinPos ){
rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
}
if( rc==SQLITE_OK ){
char aBuffer[64];
sqlite3_snprintf(sizeof(aBuffer), aBuffer,
"%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
);
rc = fts3StringAppend(&res, aBuffer, -1);
}else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
rc = FTS_CORRUPT_VTAB;
}
}
}
if( rc==SQLITE_DONE ){
rc = SQLITE_OK;
}
pMod->xClose(pC);
if( rc!=SQLITE_OK ) goto offsets_out;
}
offsets_out:
sqlite3_free(sCtx.aTerm);
assert( rc!=SQLITE_DONE );
sqlite3Fts3SegmentsClose(pTab);
if( rc!=SQLITE_OK ){
sqlite3_result_error_code(pCtx, rc);
sqlite3_free(res.z);
}else{
sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
}
return;
}
/*
** Implementation of matchinfo() function.
*/
void sqlite3Fts3Matchinfo(
sqlite3_context *pContext, /* Function call context */
Fts3Cursor *pCsr, /* FTS3 table cursor */
const char *zArg /* Second arg to matchinfo() function */
){
Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
const char *zFormat;
if( zArg ){
zFormat = zArg;
}else{
zFormat = FTS3_MATCHINFO_DEFAULT;
}
if( !pCsr->pExpr ){
sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
return;
}else{
/* Retrieve matchinfo() data. */
fts3GetMatchinfo(pContext, pCsr, zFormat);
sqlite3Fts3SegmentsClose(pTab);
}
}
#endif