Skip to content

FullText support syntax incorrect for MySQL #14051

Closed

Description

@mschipperheyn

Issue Creation Checklist

[x ] I have read the contribution guidelines

Bug Description

Since Sequelize 6.5.0, there is FullText support, but it is based on Postgres which uses a completely different syntax from MySQL.
We used a hack before to get this working on MySQL, but, with the new version, that hack doesn't work anymore.

What do you expect to happen?

Before 6.5.0 work around

We use a searchText column for all our models with a FULLTEXT index applied.

What we want to add to the query:

Sequelize.literal(`MATCH (`Faq`.`searchText`) AGAINST(\'"test label" test* label*\' IN BOOLEAN MODE)`)

The reason we add both "test" and test* is that we want to ensure "as you type" hit, but will get a preference for an exact match.

What is actually happening?

After the 6.5.0 upgrade, we use

    searchText: {
        [Op.match]: '"test label" test* label*',
    },

and this gets generated

`Faq`.`searchText` @@ \'\\"test\\" test* \\"label\\" label*\'

which gets rejected by MySQL

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@@ '\\"test\\" test* \\"label\\" label*')' at line 1

Additional context

Environment

  • Sequelize version: 6.13.0
  • Node.js version: 16.13.1
  • If TypeScript related: TypeScript version: 4.5.4

Bug Report Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • [x ] I think this problem happens only for the following dialect(s): MySQL
  • I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • [x ] No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. WikiRik commented on Feb 4, 2022

    @WikiRik
    Member

    So if I understand correctly you want the match operator to work for MySQL as well? Since I think that using Sequelize.literal() should still work in the latest version

  2. added
    dialect: mysql
    type: feature
    on Feb 4, 2022
  3. mschipperheyn commented on Feb 8, 2022

    @mschipperheyn
    Author

    Actually no. On 16.15.1, I get an error:

    Error: Invalid value Literal {
      val: 'MATCH (`Faq`.`searchText`) AGAINST(\'"faq" faq*\' IN BOOLEAN MODE)'
    }
        at Object.escape (/Users/mschipperheyn/eclipse-workspace/divorcio-facil/node_modules/sequelize/dist/lib/sql-string.js:52:11)
        at MySQLQueryGenerator.escape (/Users/mschipperheyn/eclipse-workspace/divorcio-facil/node_modules/sequelize/dist/lib/dialects/abstract/query-generator.js:709:22)
        at MySQLQueryGenerator.whereItemQuery (/Users/mschipperheyn/eclipse-workspace/divorcio-facil/node_modules/sequelize/dist/lib/dialects/abstract/query-generator.js:1733:102)
    
    

    Unfortunately, 6.4.0 where it still works is a bit of a nightmare in terms of typescript related issues. So, I guess I'm between a. rock and a hard place. Let me see how hard it would be to create a PR to just resolve this feature.

  4. mschipperheyn commented on Feb 14, 2022

    @mschipperheyn
    Author
  5. WikiRik commented on Feb 16, 2022

    @WikiRik
    Member

    Thanks for the ping. Unfortunately, I haven't had the time yet to look into this. Feel free to see if you can create a PR for this

  6. ephys commented on Feb 25, 2022

    @ephys
    Member

    Supporting literal in Op.match is something I plan on doing with #14022 and #14020

  7. mschipperheyn commented on Feb 28, 2022

    @mschipperheyn
    Author

    @ephys let me know if I can be of assistance

  8. ephys commented on Feb 28, 2022

    @ephys
    Member

    @mschipperheyn thanks :)
    If you're willing, I'm looking for reviews on this PR #14022

    Specifically the file test/unit/sql/where.test.ts is the new suite of unit tests that tries to cover everything related to converting WhereOptions to a SQL string for the different dialects.

    Good thing you pinged me, too, because I forgot to test Op.match in MySQL

    Once this PR is merged, I'll start fixing every failing unit test in #14020

    A few disclaimers:

    import { Op, literal } from 'sequelize';
    
    User.findAll({
      where: {
        firstName: { [Op.match]: literal(`'abc' IN NATURAL LANGUAGE MODE`) }
      },
    });
    // WHERE MATCH('first_name') AGAINST ('abc' IN NATURAL LANGUAGE MODE)
    
    // VS
    
    import { sql, attr } from 'sequelize';
    
    User.findAll({
      where: sql`MATCH (${attr('firstName')}) AGAINST ('abc' IN NATURAL LANGUAGE MODE)`,
    });
    // WHERE MATCH('first_name') AGAINST ('abc' IN NATURAL LANGUAGE MODE)

    I think it may be better to do the second one as we'd be unable to properly support MATCH with the first approach

  9. mschipperheyn commented on Mar 2, 2022

    @mschipperheyn
    Author

    I'll have a look when I wake up

  10. mschipperheyn commented on Mar 5, 2022

    @mschipperheyn
    Author

    Yeah, I think the second approach would be better. IT allows for more flexibility, but it should be easy to mix it in with other "regular" attribute filters

  11. ephys commented on Mar 7, 2022

    @ephys
    Member

    Well doing something like

    User.findAll({
      where: {
        firstName:  sql`MATCH (${attr('firstName')}) AGAINST ('abc' IN NATURAL LANGUAGE MODE)`
      },
    });

    would not make sense, you can't compare an attribute to a literal ; we don't know where the attribute should go. If you want to combine it with other clauses, simply use or or and:

    User.findAll({
      where: and(
        sql`MATCH (${attr('firstName')}) AGAINST ('abc' IN NATURAL LANGUAGE MODE)`,
        { id: 14 },
      ),
    });

    This also means this is already possible today. The sql & attr features would make it better but you can just do this today:

    import { literal, and } from 'sequelize';
    
    User.findAll({
      where: and(
        literal("MATCH (`first_name`) AGAINST ('abc' IN NATURAL LANGUAGE MODE)"),
        { id: 14 },
      ),
    });

    The only thing we need to do (for this issue) is make sequelize throw with a clear error message when Op.match is used with the mysql dialect

  12. mschipperheyn commented on Mar 7, 2022

    @mschipperheyn
    Author

    @ephys Just to be clear:

    User.findAll({
      where: and(
        literal("MATCH (`first_name`) AGAINST ('abc' IN NATURAL LANGUAGE MODE)"),
        { id: 14 },
      ),
    });
    

    is no longer possible since after 6.4.0. It throws Invalid value Literal
    It also throws on ephys/fix-and-or-typing

  13. ephys commented on Mar 7, 2022

    @ephys
    Member

    I've just tried it with mysql (db) 8.0, sequelize 6.14.0, mysql2 2.3.3 and it worked.

    The following code:

      await Foo.findAll({
        logging: console.log,
        where: and(
          literal('MATCH (`time`) AGAINST (\'abc\' IN NATURAL LANGUAGE MODE)'),
          { time: '14' },
        ),
      });
    

    resulted in

    SELECT `id`, `time` FROM `Foos` AS `Foo` WHERE (MATCH (`time`) AGAINST ('abc' IN NATURAL LANGUAGE MODE) AND `Foo`.`time` = '14');

    I also have a passing test in that PR for it (although not inside and()):

    testSql(literal('raw sql'), {
      default: 'raw sql',
    });

    The only test that fails (for now) is this one https://github.com/sequelize/sequelize/pull/14022/files#diff-086a401f6323d954b7175bb6ba259f1bc895a24ee599ab2e9c4350b93e980d09R463, but it's not what you want as it would insert an extra = operator:

    testSql.skip({ intAttr1: literal('literal') }, {
      default: '[intAttr1] = literal',
    });
  14. mschipperheyn commented on Mar 9, 2022

    @mschipperheyn
    Author

    I've tried various versions of sequelize versions after 6.4.0, including 6.14.0, 6.16.1 and the PR branch. All of them throw errors with my previously working Match code. So let me post here the code I'm using. Perhaps we have some error of alignment.
    I almost always use findAndCountAll by the way

    await Foo.findAndCountAll({
        offset: 0,
        limit: 10,
        order: [ [ 'updatedAt', 'DESC'] ],
        where: {
            [Op.and]: [
                 literal('MATCH (`Foo`.`searchText`) AGAINST(\'"marc" marc*\' IN BOOLEAN MODE)')
            ]
        }
    })
    

    I tried it with the Op.and(...whereArray) style as well with the same result.

  15. ephys commented on Mar 10, 2022

    @ephys
    Member

    Still very strange, I couldn't reproduce the error with your code snippet either

    I ran the following SSCCE locally:

    class User extends Model {}
    
    User.init({
      firstName: DataTypes.STRING,
    }, {
      sequelize,
      modelName: 'User',
    });
    
    User.addHook('afterSync', async () => {
      await sequelize.query('ALTER TABLE `Users` ADD FULLTEXT(`firstName`);');
    });
    
    await sequelize.sync({ force: true });
    
    await User.findAndCountAll({
      offset: 0,
      limit: 10,
      order: [['updatedAt', 'DESC']],
      where: {
        [Op.and]: [
          literal('MATCH (`User`.`firstName`) AGAINST(\'"marc" marc*\' IN BOOLEAN MODE)'),
        ],
      },
    });

    and it gave me the output I was expecting:

    [Sequelize] Executed (default): DROP TABLE IF EXISTS `Users`; [Elapsed time: 289 ms] 
    
    [Sequelize] Executed (default): DROP TABLE IF EXISTS `Users`; [Elapsed time: 14 ms] 
    
    [Sequelize] Executed (default): CREATE TABLE IF NOT EXISTS `Users` (`id` INTEGER NOT NULL auto_increment , `firstName` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB; [Elapsed time: 152 ms] 
    
    [Sequelize] Executed (default): SHOW INDEX FROM `Users` FROM `sequelize_test` [Elapsed time: 9 ms] 
    
    [Sequelize] Executed (default): ALTER TABLE `Users` ADD FULLTEXT(`firstName`); [Elapsed time: 834 ms] 
    
    [Sequelize] Executed (default): SELECT count(*) AS `count` FROM `Users` AS `User` WHERE (MATCH (`User`.`firstName`) AGAINST('"marc" marc*' IN BOOLEAN MODE)); [Elapsed time: 2 ms] 
    
    [Sequelize] Executed (default): SELECT `id`, `firstName`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE (MATCH (`User`.`firstName`) AGAINST('"marc" marc*' IN BOOLEAN MODE)) ORDER BY `User`.`updatedAt` DESC LIMIT 0, 10; [Elapsed time: 3 ms] 
    

    It would really help me if you could create one that reproduces the problem (https://github.com/sequelize/sequelize-sscce)

  16. self-assigned this
    on Mar 10, 2022
  17. mschipperheyn commented on Mar 10, 2022

    @mschipperheyn
    Author

    Ok, I will have a go at a reproduction. First of all I will do a fresh install and see if there isn't some kind of lingering issue there somehow. Oh wait a minute. We are using sequelize-typescript as an abstraction layer. That must be it somehow.

  18. mschipperheyn commented on Apr 1, 2022

    @mschipperheyn
    Author

    This occurred because Sequelize exported from sequelize-typescript was used instead of Sequelize exported from sequelize itself.

  19. ephys commented on Apr 1, 2022

    @ephys
    Member

    thanks for letting us know :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

dialect: mysqltype: feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions