How to use f-Literal with PartiQL in AWS and boto3

2.6k Views Asked by At

I want to use PartiQL to query a DynamoDB table with boto3. I works perfectly, when I use it like this:

stmt = "SELECT * FROM Onlineshop WHERE PK= 'c#12345'"
resp = dynamodb.execute_statement(Statement= stmt)

But when I replace some values in the select statement with a f-literal it fails.

PK = 'c#12345'
table_name = 'Onlineshop'
stmt = f' "SELECT * FROM {table_name} WHERE PK= {PK}" '
resp = dynamodb.execute_statement(Statement= stmt)

What could be the reason?

Thank you in advance

W

2

There are 2 best solutions below

0
On BEST ANSWER

The originally-accepted answer suffers from a potential SQL injection problem so I've added this alternate answer. You should always pass parameters safely.

PK = "c#12345"

resp = dynamodb.execute_statement(
    Statement="SELECT * FROM Onlineshop WHERE PK=?",
    Parameters=[
        {
            "S": PK
        }
    ]
)

Arguably, you could inject the table name Onlineshop via f-string, as in the OP's original self-answer, but that's only safe if the table name was not provided by a user (or other external entity). I'd personally prefer to see the table name hard-coded.

0
On

well I found out how it works. Here the solution for anybody who wants to use this kind of query on dynamodb:

PKey = 'c#12345'
table_name = 'Onlineshop'
stmt = f"SELECT * FROM {table_name} WHERE PK= '{PKey}' "
resp = dynamodb.execute_statement(Statement= stmt)