Search code examples
pythonpython-3.xdictionaryexasol

How to remove quotes from dictionary value string dynamically


I have a dictionary like: d = {'table': 'db_schema.foo', 'column': 'bar'}. I want to pass this dictionary after removing quotes from all values. So I want to get {'table': db_schema.foo, 'column': bar} dynamically.

Details:

I am trying to pass run a dynamic query into exasol after connecting. I am using pyexasol here and trying execute() . I am trying to execute simple query like:

SELECT * 
FROM db_schema.foo
WHERE bar >= 0

If I provide dictionary d then the query that's get executed is:

SELECT * 
FROM 'db_schema.foo'
WHERE 'bar' >= 0

and results in error. So I want to remove quote from all values. I have tried {k:v.strip("\'") for k, v in d.items()} etc. but not successful yet.

Requested Code:

foo_query = '''select *
                from {app_table}
                where {col} >= '2020-01-01'
                limit 10;'''
foo_param={'app_table': 'src.application',
             'col': 'createdat'}
foo_results = exasol.runQueryExaParams(query=foo_query, query_param=foo_param)
foo_results1 = exasol.runQueryExaParams(query=foo_query, query_param={k:v.strip("\'") for k, v in foo_param.items()})

where exasol is a class built on pyexasol with just connection parameters. Relevant method from class there is:

    def runQueryExaParams(self, query, query_param):
        self.conn = pyexasol.connect(
            dsn=self.__dsn, user=self.__user, password=self.__password, encryption=True)
        res = self.conn.export_to_pandas(query, query_param)
        self.conn.close()
        res.columns = res.columns.str.lower()
        return res

In both cases I am getting same error:

pyexasol.exceptions.ExaQueryError: 
(
    message     =>  syntax error, unexpected simple_string_literal [line 3, column 22] (Session: )
    dsn         =>  
    user        =>  
    schema      =>  
    code        =>  42000
    session_id  =>  
    query       =>  EXPORT (
select *
                from 'src.application'
                where 'createdat' >= '2020-01-01'
                limit 10
) INTO CSV
AT 'https://1.2.3.4' FILE '000.csv'
WITH COLUMN NAMES
)

Solution

  • As I said in my comment, you need to read SQL FORMATTING.

    With that said, you need to change your code to be something like this:

    query = '''
        SELECT *
        FROM {app_table!q}
        WHERE {col!i} >= '2020-01-01'
        LIMIT 10;
    '''
    
    query_param = {
        'app_table': ('src', 'application'),
        'col': 'createdat'
    }
    
    results = exasol.runQueryExaParams(
        query=query,
        query_param=query_param
    )
    

    As the documentation indicates, the code above will result in a query like this:

    SELECT *
    FROM "src"."application"
    WHERE createdat >= '2020-01-01'
    LIMIT 10;
    

    I hope it helps.