Search code examples
pythonpostgresqlasyncpg

Insert text in braces with asyncpg


I have a follow table:

CREATE TABLE raw_data (
    id bigserial NOT NULL,
    datetime varchar NOT NULL DEFAULT now(),
    param_id int4 NOT NULL,
    raw_data varchar NOT NULL)

I'm trying to insert the data with braces with asyncpg:

app['bd_conn'] = await asyncpg.create_pool(host=os.environ.get('DB_HOST'),
                                           database=os.environ.get('DB_NAME'),
                                           user=os.environ.get('DB_USER'),
                                           password=os.environ.get('DB_PASS'),
                                           max_size=5,
                                           min_size=1)
db_engine = app['bd_conn']
raw_data = "{H}"
param = "1000"
async with db_engine.acquire() as conn:
    stmt = f"""
            insert into raw_data (param, raw_data)
            values ({param}, {raw_data})
            """
    await conn.fetch(stmt)

and because of the braces in raw_data, I get an error

syntax error at or near "{"

how can I fix this error? It is necessary to pass braces


Solution

  • your query is vulnerable to SQL injections -> security issue. it's not good to hardcode parameters. instead, do this:

    param = 1000  # an integer
    raw_data = "{H}"  # a string
    
    stmt = """
           insert into raw_data (param_id, raw_data)
           values ($1, $2)
           """
    await conn.execute(stmt, param, raw_data)