Skip to content

Commit

Permalink
use psycopg sql utils to avoid sql injection
Browse files Browse the repository at this point in the history
  • Loading branch information
bitner committed Jul 22, 2024
1 parent 31536e7 commit 59efd37
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions space2stats_api/app/utils/db_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@


def get_summaries(fields, h3_ids):
h3_ids_str = ", ".join(f"'{h3_id}'" for h3_id in h3_ids)
sql_query = f"""
SELECT hex_id, {', '.join(fields)}
FROM {DB_TABLE_NAME}
WHERE hex_id IN ({h3_ids_str})
"""
colnames = ['hex_id'] + fields
cols = [pg.sql.Identifier(c) for c in colnames]
sql_query = pg.sql.SQL(
"""
SELECT {0}
FROM {1}
WHERE hex_id = ANY (%s)
"""
).format(
pg.sql.SQL(', ').join(cols),
pg.sql.Identifier(DB_TABLE_NAME)
)
try:
conn = pg.connect(
host=DB_HOST,
Expand All @@ -25,7 +31,7 @@ def get_summaries(fields, h3_ids):
password=DB_PASSWORD,
)
cur = conn.cursor()
cur.execute(sql_query)
cur.execute(sql_query, [h3_ids,])
rows = cur.fetchall()
colnames = [desc[0] for desc in cur.description]
cur.close()
Expand All @@ -37,10 +43,10 @@ def get_summaries(fields, h3_ids):


def get_available_fields():
sql_query = f"""
sql_query = """
SELECT column_name
FROM information_schema.columns
WHERE table_name = '{DB_TABLE_NAME}'
WHERE table_name = %s
"""
try:
conn = pg.connect(
Expand All @@ -51,7 +57,7 @@ def get_available_fields():
password=DB_PASSWORD,
)
cur = conn.cursor()
cur.execute(sql_query)
cur.execute(sql_query, [DB_TABLE_NAME,])
columns = [row[0] for row in cur.fetchall() if row[0] != "hex_id"]
cur.close()
conn.close()
Expand Down

0 comments on commit 59efd37

Please sign in to comment.