Skip to content

Postgresql: parsing errors are not propagated to the postgres layer (it was "Postgresql string escaping") #677

Closed

Description

@docbacardi

ArcadeDB Version: 22.11.1

JDK Version: openjdk version "11.0.17" 2022-10-18

OS: Ubuntu 22.04.1 LTS

Expected behavior

I'm trying to escape a single quote in a string enclosed in single quotes using the Postgres interface.
Which MAGIC in SELECT 'abc MAGIC def' will produce the output abc ' def?

chicken@asteroid:~$ psql --host=localhost testdatabase root
Password for user root: 
psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1), server 10.5)
Type "help" for help.

testdatabase=> SELECT 'abc MAGIC def';
 'abc MAGIC def' 
-----------------
 abc ' def
(1 row)

It would be great to get something universal not limited to single quotes.

Actual behavior

The straight forward approach \' throws an error.
Postgres has escape strings (E'abc \' def') : https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-BACKSLASH-TABLE . Especially the hexadecimal byte values (\xhh) would be useful to escape anything.

Steps to reproduce

Connect to ArcadeDB with the psql client and run SELECT 'abc \' def':

chicken@asteroid:~$ psql --host=localhost testdatabase root
Password for user root: 
psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1), server 10.5)
Type "help" for help.

testdatabase=> SELECT 'abc \' def';
ERROR:  Syntax error on executing query: Encountered " <IDENTIFIER> "def "" at line 1, column 16.
Was expecting one of:
    <EOF> 
    <LIMIT> ...
    <SKIP2> ...
    <OFFSET> ...
    <TIMEOUT> ...
    <AS> ...
    <LET> ...
    <UNWIND> ...
    ";" ...
    "," ...
...

Activity

  1. gramian commented on Dec 16, 2022

    @gramian
    Collaborator

    I can confirm this issue also for the studio and the query endpoint. I would guess the issue lies in this block: https://github.com/ArcadeData/arcadedb/blob/main/engine/src/main/grammar/SQLGrammar.jjt#L425 , which could maybe solved by: https://stackoverflow.com/a/24163497 ?

  2. gramian commented on Dec 16, 2022

    @gramian
    Collaborator

    @lvca even easier: character literals are escaped correctly already, so copy-pasting the escaping expression from a few lines above, gives for string literals:

      < STRING_LITERAL:
        (
          "\""
          ( (~["\n","\r","\""])
          | ("\\"
            ( ["n","t","b","r","f","\\","'","\"","/"]
            | ["0"-"7"] ( ["0"-"7"] )?
            | ["0"-"3"] ["0"-"7"] ["0"-"7"]
            )
            )
          )*
          "\""
        )
        |
        (
          "'"
          ( (~["\n","\r","\""])
          | ("\\"
            ( ["n","t","b","r","f","\\","'","\"","/"]
            | ["0"-"7"] ( ["0"-"7"] )?
            | ["0"-"3"] ["0"-"7"] ["0"-"7"]
            )
            )
          )*
          "'"
        )
      >
    

    which should fix this issue when applied to the above position in the grammar.

  3. lvca commented on Dec 17, 2022

    @lvca
    Member

    I'm testing your first solution with:

    < STRING_LITERAL:
        "\""
        (
             "\\" ~[]     //any escaped character
        |                 //or
            ~["\"","\\"]  //any character except quote or backslash
        )*
        "\""
      >
    

    And see if covers all the cases.

  4. lvca commented on Dec 17, 2022

    @lvca
    Member

    Ok, tested both solutions and many tests broken. We have to dig more into this.

  5. gramian commented on Dec 17, 2022

    @gramian
    Collaborator

    @lvca You are right, I didn't have the chance to test yet. This form should do better with the tests:

      < STRING_LITERAL:
        (
          "\""
          ( (~["\n","\r","\"","\\"])
          | ("\\"
              ( ["n","t","b","r","f","\\","\"","/","%","?"])
            )
          )*
          "\""
        )
        |
        (
          "'"
          ( (~["\n","\r","'","\\"])
          | ("\\"
              ( ["n","t","b","r","f","\\","'","/","%","?"])
            )
          )*
          "'"
        )
      >
    
  6. lvca commented on Dec 18, 2022

    @lvca
    Member

    @docbacardi could you please confirm that the latest snapshot from the main branch works? (clone main branch and run mvn clean install -DskipTests and then you can find your new distro under package/target)

  7. gramian commented on Dec 18, 2022

    @gramian
    Collaborator

    @docbacardi BTW there is no hexadecimal encoding, but unicode encoding, for example SELECT "\u1234", if that helps.

  8. docbacardi commented on Dec 18, 2022

    @docbacardi
    ContributorAuthor

    It works, thank you very much. Your speed is impressive!

    Using unicode instead of hex is fine for me. The parser seems to have a problem with malformed unicode values though. Using less than 4 digits throws an exception.

    This is the command:

    testdatabase=> SELECT 'abc \u030 def';
    server closed the connection unexpectedly
    	This probably means the server terminated abnormally
    	before or while processing the request.
    The connection to the server was lost. Attempting reset: Succeeded.
    psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1), server 10.5)
    

    It throws the following exception:

    Exception in thread "ArcadeDB-postgres//127.0.0.1" java.lang.Error: Invalid escape character at line 1 column 14
    	at com.arcadedb.query.sql.parser.JavaCharStream.readChar(JavaCharStream.java:316)
    	at com.arcadedb.query.sql.parser.SqlParserTokenManager.jjMoveNfa_0(SqlParserTokenManager.java:5393)
    	at com.arcadedb.query.sql.parser.SqlParserTokenManager.jjMoveStringLiteralDfa0_0(SqlParserTokenManager.java:124)
    	at com.arcadedb.query.sql.parser.SqlParserTokenManager.getNextToken(SqlParserTokenManager.java:5579)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_scan_token(SqlParser.java:26397)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_302(SqlParser.java:25001)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_136(SqlParser.java:24990)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_505(SqlParser.java:24911)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_402(SqlParser.java:24889)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_268(SqlParser.java:22109)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_122(SqlParser.java:22078)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_342(SqlParser.java:21915)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_166(SqlParser.java:21894)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3R_92(SqlParser.java:21286)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_3_33(SqlParser.java:21148)
    	at com.arcadedb.query.sql.parser.SqlParser.jj_2_33(SqlParser.java:16933)
    	at com.arcadedb.query.sql.parser.SqlParser.StatementInternal(SqlParser.java:956)
    	at com.arcadedb.query.sql.parser.SqlParser.Statement(SqlParser.java:878)
    	at com.arcadedb.query.sql.parser.SqlParser.parse(SqlParser.java:236)
    	at com.arcadedb.query.sql.parser.StatementCache.parse(StatementCache.java:110)
    	at com.arcadedb.query.sql.parser.StatementCache.get(StatementCache.java:70)
    	at com.arcadedb.query.sql.executor.SQLEngine.parse(SQLEngine.java:97)
    	at com.arcadedb.query.sql.SQLQueryEngine.command(SQLQueryEngine.java:84)
    	at com.arcadedb.database.EmbeddedDatabase.command(EmbeddedDatabase.java:1223)
    	at com.arcadedb.server.ServerDatabase.command(ServerDatabase.java:405)
    	at com.arcadedb.postgres.PostgresNetworkExecutor.queryCommand(PostgresNetworkExecutor.java:359)
    	at com.arcadedb.postgres.PostgresNetworkExecutor.lambda$run$4(PostgresNetworkExecutor.java:157)
    	at com.arcadedb.postgres.PostgresNetworkExecutor.readMessage(PostgresNetworkExecutor.java:974)
    	at com.arcadedb.postgres.PostgresNetworkExecutor.run(PostgresNetworkExecutor.java:140)
    Caused by: java.io.IOException
    	at com.arcadedb.query.sql.parser.JavaCharStream.hexval(JavaCharStream.java:79)
    	at com.arcadedb.query.sql.parser.JavaCharStream.readChar(JavaCharStream.java:312)
    	... 28 more
    
  9. lvca commented on Dec 18, 2022

    @lvca
    Member

    I think I found the point in the SQL parser that is reading always 4 chars for Unicode:

    buffer[bufpos] = c = (char) (hexval(c) << 12 | hexval(ReadByte()) << 8 | hexval(ReadByte()) << 4 | hexval(ReadByte()));

    This piece of code was inherited from OrientDB.

    Not sure if unicode must be 4 chars or less, I'm going to check some docs online. In case we could just read characters until a space is found.

  10. lvca commented on Dec 18, 2022

    @lvca
    Member

    Ok, seems the minimum is 4 digits. 3 digits unicode is not valid and should be filled by a zero:

    "The Unicode Standard defines a codespace,[57] a set of numerical values ranging from 0 through 10FFFF16,[58] called code points[59] and denoted as U+0000 through U+10FFFF ("U+"[60] followed by the code point value in hexadecimal, which is prepended with leading zeros to a minimum of four digits;"

    (source: https://en.wikipedia.org/wiki/Unicode)

    So unless I'm wrong here we're going to leave things as they are.

  11. docbacardi commented on Dec 19, 2022

    @docbacardi
    ContributorAuthor

    I'm sorry, my last post was misleading. What a terrible bug report.
    I fully agree that unicode numbers should have 4 digits. What I'm missing is a clear error message on the client side. Right now there is no response at all or a connection loss:

    chicken@asteroid:~/arcadedb/arcadedb-22.12.1-SNAPSHOT$ psql --host=localhost testdatabase root
    Password for user root: 
    psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1), server 10.5)
    Type "help" for help.
    
    testdatabase=> SELECT 'abc \u030 def';
    testdatabase=> SELECT 'abc \u30 def';
    server closed the connection unexpectedly
    	This probably means the server terminated abnormally
    	before or while processing the request.
    The connection to the server was lost. Attempting reset: Succeeded.
    psql (14.5 (Ubuntu 14.5-0ubuntu0.22.04.1), server 10.5)
    testdatabase=> 
    

    Here is an example for a clear error message:

    testdatabase=> SEWECT x FROM y;
    ERROR:  Syntax error on executing query: Encountered " <IDENTIFIER> "SEWECT "" at line 1, column 1.
    Was expecting one of:
        <LET> ...
        <EXPLAIN> ...
    

    But maybe I should not mix issues and open a new one for this.

  12. lvca commented on Dec 19, 2022

    @lvca
    Member

    100% agree, the sql error should be propagated to the client!

  13. self-assigned this
    on Dec 19, 2022
  14. added this to the 22.12.1 milestone on Dec 19, 2022
  15. changed the title [-]Postgresql string escaping[/-] [+]Postgresql: parsing errors are not propagated to the postgres layer (it was "Postgresql string escaping")[/+] on Dec 19, 2022
  16. lvca commented on Dec 21, 2022

    @lvca
    Member

    Thanks @docbacardi for the fix!

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions