0

I want to make an advanced search form, with search by syntax. I've already found a github repository with an implementation very similar to what I want, but I can't understand the implementation so I can't adapt it to my needs. The search I'm trying to accomplish is the one that scryfall uses to search mtg cards. Here is a list of tests in python for a better idea of what I mean:

'c:bm' => '((id IN (SELECT card_id FROM card_color WHERE color_id = 3)) AND (id IN (SELECT card_id FROM card_color GROUP BY card_id HAVING COUNT(card_id) > 1)))'
'c:u OR (c:g AND NOT tou>3)' => "(id IN (SELECT card_id FROM card_color WHERE color_id = 2)) OR ((id IN (SELECT card_id FROM card_color WHERE color_id = 5)) AND NOT (toughness IS NOT NULL AND toughness <> '' AND CAST(toughness AS REAL) > 3))"

I can't find any resources explaining how this is done. What I need is an overview of how it's done so I could do it myself. There's an answer with code here but I wouldn't be able to write that myself. I need to understand it so I could adapt the code that I've found for my needs.

  • Is your language Python? If so, you should add this as a tag. What about the implementation you linked don't you understand? I would suggest studying up on lexical analysis to get a better understanding of parsing queries. – Cameron Tinker Jul 06 '20 at 19:05
  • 1
    I still don't know if I'm going to do it in Python or PHP. I can't totally understand the implementation. Ok I'll take a look at lexical analysis. –  Jul 06 '20 at 19:07
  • Why would you want to parse it? Just submit is to the DBMS, it has the appropiate parser for the particular implementation. – wildplasser Jul 06 '20 at 19:48
  • 1
    I don't think you understood the examples. I want to ask, for example, for 'c:b', that means color black, and with that I have to produce the SQL to select black cards. –  Jul 06 '20 at 20:26

1 Answers1

1

Don't worry about the SQL part of the problem yet. I suspect that generating the SQL condition will be fairly straightforward once you have a parse tree for the search-query.

So your immediate problem is to parse the search-queries. Assuming there isn't already an available parser for this specific language, you basically have two alternatives:

  1. Use a library/tool to generate a parser. (Lots of options for this, especially in Python. Find one with good tutorials.)
  2. Write a parser yourself. (There's certainly no lack of resources explaining various ways to do this. You might find a recursive-descent parser easiest to understand, and I think it would work for your search-queries.)

In either case, I suggest you start by writing a grammar for the search-query language.

Michael Dyck
  • 2,153
  • 1
  • 14
  • 18