12

i have a textarea in my project where users can save SQL queries but one of the requirements is to check if this query is valid or not

EXAMPLE

if user entered something like :

SELECT ** FROM EMP 

this should return false and an error message just saying invalid it doesn't have to give any reasons

mainly the queries will be just select statement

NOTICE i DON'T want to use any server side at this point

Question

Does any one knows a javascript / jquery library or plugin that have this functionality or any thing similar

i have Google this and it didn't show any thing

Thanks

Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
  • Did you Google 'javascript sql parser'? I just found this: https://github.com/forward/sql-parser – Laurence Nov 01 '12 at 01:46
  • 2
    Does the parser need to know about your database? i.e. Which tables/views you have? – Lee Taylor Nov 01 '12 at 02:19
  • It would be far better to let the database engine figure this out for you. I wonder if there is a way to do a dry run of a query... see if the query compiles but not execute it... – Brad Nov 01 '12 at 02:20
  • No it doesn't have too ... i don't think javascript can do this – Mina Gabriel Nov 01 '12 at 02:51

1 Answers1

5

Here is an example fiddle using the JS SQL Parser:

http://jsfiddle.net/Hb6az/

The parser will throw an error if it hits something unexpected, so you have to wrap your checking code in a try {} catch(error) {} block.

Laurence
  • 1,673
  • 11
  • 16
  • 3
    Note from the description: "Currently it is only capable of parsing fairly basic SELECT queries" – Michael Mior Nov 01 '12 at 02:33
  • it looks good but as @MichaelMior said it parse basic SELECT queries see http://jsfiddle.net/minagabriel/Hb6az/1/ – Mina Gabriel Nov 01 '12 at 02:52
  • Try it from your local machine, it looks like jsFiddle is having trouble with the external resource and SQLParser is not getting defined. – Laurence Nov 01 '12 at 12:08
  • @Laurence - I tried installing JS SQL Parser from localhost WAMP server. I couldn't find working. Is there a better way to make it work? – ronquiq Apr 26 '21 at 16:08
  • @ronquiq I have not used this in a very long time but it was an NPM package, you'd need to install it with `npm` or `yarn` – Laurence Apr 30 '21 at 20:48