func_name
stringlengths 2
53
| func_src_before
stringlengths 63
114k
| func_src_after
stringlengths 86
114k
| line_changes
dict | char_changes
dict | commit_link
stringlengths 66
117
| file_name
stringlengths 5
72
| vul_type
stringclasses 9
values |
---|---|---|---|---|---|---|---|
set_language | def set_language(self, lang):
"""
Update language of user in the User object and in the database
:param lang: string with language tag like "en-US"
:return: None
"""
log.debug('Updating info about user %s language '
'in memory & database...', self)
self.language = lang
query = ("UPDATE users "
f"SET language='{self.language}' "
f"WHERE chat_id='{self.chat_id}'")
try:
db.add(query)
except DatabaseError:
log.error("Can't add new language of %s to the database", self)
else:
log.debug('Language updated.') | def set_language(self, lang):
"""
Update language of user in the User object and in the database
:param lang: string with language tag like "en-US"
:return: None
"""
log.debug('Updating info about user %s language '
'in memory & database...', self)
self.language = lang
query = ("UPDATE users "
f"SET language=%s "
f"WHERE chat_id=%s")
parameters = self.language, self.chat_id
try:
db.add(query, parameters)
except DatabaseError:
log.error("Can't add new language of %s to the database", self)
else:
log.debug('Language updated.') | {
"deleted": [
{
"line_no": 13,
"char_start": 383,
"char_end": 435,
"line": " f\"SET language='{self.language}' \"\n"
},
{
"line_no": 14,
"char_start": 435,
"char_end": 487,
"line": " f\"WHERE chat_id='{self.chat_id}'\")\n"
},
{
"line_no": 17,
"char_start": 501,
"char_end": 527,
"line": " db.add(query)\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 383,
"char_end": 420,
"line": " f\"SET language=%s \"\n"
},
{
"line_no": 14,
"char_start": 420,
"char_end": 458,
"line": " f\"WHERE chat_id=%s\")\n"
},
{
"line_no": 16,
"char_start": 459,
"char_end": 508,
"line": " parameters = self.language, self.chat_id\n"
},
{
"line_no": 18,
"char_start": 521,
"char_end": 559,
"line": " db.add(query, parameters)\n"
}
]
} | {
"deleted": [
{
"char_start": 415,
"char_end": 417,
"chars": "'{"
},
{
"char_start": 418,
"char_end": 432,
"chars": "elf.language}'"
},
{
"char_start": 468,
"char_end": 470,
"chars": "'{"
},
{
"char_start": 482,
"char_end": 487,
"chars": "}'\")\n"
}
],
"added": [
{
"char_start": 415,
"char_end": 416,
"chars": "%"
},
{
"char_start": 453,
"char_end": 495,
"chars": "%s\")\n\n parameters = self.language, "
},
{
"char_start": 545,
"char_end": 557,
"chars": ", parameters"
}
]
} | github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a | photogpsbot/users.py | cwe-089 |
tid_num_to_tag_nums | def tid_num_to_tag_nums(self, tid_num):
''' Returns list of the associated tag_nums to the given tid_num. '''
q = "SELECT tag FROM tid_tag WHERE tid = '" + str(tid_num) + "'"
self.query(q)
return [i[0] for i in self.c.fetchall()] | def tid_num_to_tag_nums(self, tid_num):
''' Returns list of the associated tag_nums to the given tid_num. '''
q = "SELECT tag FROM tid_tag WHERE tid = ?"
self.query(q, tid_num)
return [i[0] for i in self.c.fetchall()] | {
"deleted": [
{
"line_no": 4,
"char_start": 123,
"char_end": 196,
"line": " q = \"SELECT tag FROM tid_tag WHERE tid = '\" + str(tid_num) + \"'\"\n"
},
{
"line_no": 5,
"char_start": 196,
"char_end": 218,
"line": " self.query(q)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 123,
"char_end": 175,
"line": " q = \"SELECT tag FROM tid_tag WHERE tid = ?\"\n"
},
{
"line_no": 5,
"char_start": 175,
"char_end": 206,
"line": " self.query(q, tid_num)\n"
}
]
} | {
"deleted": [
{
"char_start": 172,
"char_end": 194,
"chars": "'\" + str(tid_num) + \"'"
}
],
"added": [
{
"char_start": 172,
"char_end": 173,
"chars": "?"
},
{
"char_start": 195,
"char_end": 204,
"chars": ", tid_num"
}
]
} | github.com/pukkapies/urop2019/commit/3ca2e2c291d2d5fe262d20a8e0520bdfb622432b | modules/query_lastfm.py | cwe-089 |
summary | @app.route('/summary', methods=['GET'])
def summary():
if 'username' in session:
conn = mysql.connect()
cursor = conn.cursor()
#select the maximum score from the results table
cursor.execute("SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount='" + session['username'] + "'");
courseConcentration = cursor.fetchone()
return render_template('summary.html', courseConcentration = courseConcentration[0])
return redirect(url_for('login')) | @app.route('/summary', methods=['GET'])
def summary():
if 'username' in session:
conn = mysql.connect()
cursor = conn.cursor()
#select the maximum score from the results table
cursor.execute("SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount=%s", (session['username']));
courseConcentration = cursor.fetchone()
return render_template('summary.html', courseConcentration = courseConcentration[0])
return redirect(url_for('login')) | {
"deleted": [
{
"line_no": 9,
"char_start": 185,
"char_end": 397,
"line": "\t\tcursor.execute(\"SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount='\" + session['username'] + \"'\");\n"
}
],
"added": [
{
"line_no": 9,
"char_start": 185,
"char_end": 393,
"line": "\t\tcursor.execute(\"SELECT courseConcentration FROM results WHERE total = (SELECT MAX(total) FROM (SELECT * FROM results WHERE courseId > 4) Temp) and courseId > 4 and emailAccount=%s\", (session['username']));\n"
}
]
} | {
"deleted": [
{
"char_start": 364,
"char_end": 365,
"chars": "'"
},
{
"char_start": 367,
"char_end": 369,
"chars": "+ "
},
{
"char_start": 388,
"char_end": 394,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 364,
"char_end": 366,
"chars": "%s"
},
{
"char_start": 367,
"char_end": 368,
"chars": ","
},
{
"char_start": 369,
"char_end": 370,
"chars": "("
},
{
"char_start": 389,
"char_end": 390,
"chars": ")"
}
]
} | github.com/CaitlinKennedy/Tech-Track/commit/20ef2d4010f9497b8221524edd0c706e2c6a4147 | src/tech_track.py | cwe-089 |
add_post | def add_post(content):
"""Add a post to the 'database' with the current timestamp."""
conn = psycopg2.connect("dbname=forum")
cursor = conn.cursor()
cursor.execute("insert into posts values ('%s')" % content)
conn.commit()
conn.close() | def add_post(content):
"""Add a post to the 'database' with the current timestamp."""
conn = psycopg2.connect("dbname=forum")
cursor = conn.cursor()
one_post = content
cursor.execute("insert into posts values (%s)", (one_post,))
conn.commit()
conn.close() | {
"deleted": [
{
"line_no": 5,
"char_start": 155,
"char_end": 217,
"line": " cursor.execute(\"insert into posts values ('%s')\" % content)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 155,
"char_end": 176,
"line": " one_post = content\n"
},
{
"line_no": 6,
"char_start": 176,
"char_end": 239,
"line": " cursor.execute(\"insert into posts values (%s)\", (one_post,))\n"
}
]
} | {
"deleted": [
{
"char_start": 199,
"char_end": 200,
"chars": "'"
},
{
"char_start": 202,
"char_end": 203,
"chars": "'"
},
{
"char_start": 205,
"char_end": 207,
"chars": " %"
},
{
"char_start": 208,
"char_end": 209,
"chars": "c"
},
{
"char_start": 211,
"char_end": 212,
"chars": "t"
},
{
"char_start": 213,
"char_end": 214,
"chars": "n"
}
],
"added": [
{
"char_start": 157,
"char_end": 178,
"chars": "one_post = content\n "
},
{
"char_start": 224,
"char_end": 225,
"chars": ","
},
{
"char_start": 226,
"char_end": 227,
"chars": "("
},
{
"char_start": 230,
"char_end": 234,
"chars": "_pos"
},
{
"char_start": 235,
"char_end": 237,
"chars": ",)"
}
]
} | github.com/paulc1600/DB-API-Forum/commit/069700fb4beec79182fff3c556e9cccce3230d6f | forumdb.py | cwe-089 |
delete_playlist | def delete_playlist(id, db):
db.execute("DELETE FROM playlist where id={id};".format(id=id)) | def delete_playlist(id, db):
db.execute("DELETE FROM playlist where id=%s;", (id,)) | {
"deleted": [
{
"line_no": 2,
"char_start": 29,
"char_end": 96,
"line": " db.execute(\"DELETE FROM playlist where id={id};\".format(id=id))\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 29,
"char_end": 87,
"line": " db.execute(\"DELETE FROM playlist where id=%s;\", (id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 75,
"char_end": 79,
"chars": "{id}"
},
{
"char_start": 81,
"char_end": 88,
"chars": ".format"
},
{
"char_start": 91,
"char_end": 94,
"chars": "=id"
}
],
"added": [
{
"char_start": 75,
"char_end": 77,
"chars": "%s"
},
{
"char_start": 79,
"char_end": 81,
"chars": ", "
},
{
"char_start": 84,
"char_end": 85,
"chars": ","
}
]
} | github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6 | playlist/playlist_repository.py | cwe-089 |
writeToDb | def writeToDb(self, url):
try:
self.cursor.execute("INSERT INTO queue (url, visited) VALUES ('{}', '0');".format(url))
self.db.commit()
except Exception as e:
print(e) | def writeToDb(self, url):
try:
self.cursor.execute("INSERT INTO queue (url, visited) VALUES (?, '0');", url)
self.db.commit()
except Exception as e:
print(e) | {
"deleted": [
{
"line_no": 3,
"char_start": 43,
"char_end": 143,
"line": " self.cursor.execute(\"INSERT INTO queue (url, visited) VALUES ('{}', '0');\".format(url))\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 43,
"char_end": 133,
"line": " self.cursor.execute(\"INSERT INTO queue (url, visited) VALUES (?, '0');\", url)\n"
}
]
} | {
"deleted": [
{
"char_start": 117,
"char_end": 121,
"chars": "'{}'"
},
{
"char_start": 129,
"char_end": 137,
"chars": ".format("
},
{
"char_start": 140,
"char_end": 141,
"chars": ")"
}
],
"added": [
{
"char_start": 117,
"char_end": 118,
"chars": "?"
},
{
"char_start": 126,
"char_end": 128,
"chars": ", "
}
]
} | github.com/jappe999/WebScraper/commit/46a4e0843aa44d903293637afad53dfcbc37b480 | beta/database.py | cwe-089 |
send_message | @frappe.whitelist(allow_guest=True)
def send_message(subject="Website Query", message="", sender="", status="Open"):
from frappe.www.contact import send_message as website_send_message
lead = customer = None
website_send_message(subject, message, sender)
customer = frappe.db.sql("""select distinct dl.link_name from `tabDynamic Link` dl
left join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'
and c.email_id='{email_id}'""".format(email_id=sender))
if not customer:
lead = frappe.db.get_value('Lead', dict(email_id=sender))
if not lead:
new_lead = frappe.get_doc(dict(
doctype='Lead',
email_id = sender,
lead_name = sender.split('@')[0].title()
)).insert(ignore_permissions=True)
opportunity = frappe.get_doc(dict(
doctype ='Opportunity',
enquiry_from = 'Customer' if customer else 'Lead',
status = 'Open',
title = subject,
contact_email = sender,
to_discuss = message
))
if customer:
opportunity.customer = customer[0][0]
elif lead:
opportunity.lead = lead
else:
opportunity.lead = new_lead.name
opportunity.insert(ignore_permissions=True)
comm = frappe.get_doc({
"doctype":"Communication",
"subject": subject,
"content": message,
"sender": sender,
"sent_or_received": "Received",
'reference_doctype': 'Opportunity',
'reference_name': opportunity.name
})
comm.insert(ignore_permissions=True)
return "okay" | @frappe.whitelist(allow_guest=True)
def send_message(subject="Website Query", message="", sender="", status="Open"):
from frappe.www.contact import send_message as website_send_message
lead = customer = None
website_send_message(subject, message, sender)
customer = frappe.db.sql("""select distinct dl.link_name from `tabDynamic Link` dl
left join `tabContact` c on dl.parent=c.name where dl.link_doctype='Customer'
and c.email_id = %s""", sender)
if not customer:
lead = frappe.db.get_value('Lead', dict(email_id=sender))
if not lead:
new_lead = frappe.get_doc(dict(
doctype='Lead',
email_id = sender,
lead_name = sender.split('@')[0].title()
)).insert(ignore_permissions=True)
opportunity = frappe.get_doc(dict(
doctype ='Opportunity',
enquiry_from = 'Customer' if customer else 'Lead',
status = 'Open',
title = subject,
contact_email = sender,
to_discuss = message
))
if customer:
opportunity.customer = customer[0][0]
elif lead:
opportunity.lead = lead
else:
opportunity.lead = new_lead.name
opportunity.insert(ignore_permissions=True)
comm = frappe.get_doc({
"doctype":"Communication",
"subject": subject,
"content": message,
"sender": sender,
"sent_or_received": "Received",
'reference_doctype': 'Opportunity',
'reference_name': opportunity.name
})
comm.insert(ignore_permissions=True)
return "okay" | {
"deleted": [
{
"line_no": 10,
"char_start": 424,
"char_end": 482,
"line": "\t\tand c.email_id='{email_id}'\"\"\".format(email_id=sender))\n"
}
],
"added": [
{
"line_no": 10,
"char_start": 424,
"char_end": 458,
"line": "\t\tand c.email_id = %s\"\"\", sender)\n"
}
]
} | {
"deleted": [
{
"char_start": 441,
"char_end": 453,
"chars": "'{email_id}'"
},
{
"char_start": 456,
"char_end": 473,
"chars": ".format(email_id="
},
{
"char_start": 479,
"char_end": 480,
"chars": ")"
}
],
"added": [
{
"char_start": 440,
"char_end": 441,
"chars": " "
},
{
"char_start": 442,
"char_end": 445,
"chars": " %s"
},
{
"char_start": 448,
"char_end": 450,
"chars": ", "
}
]
} | github.com/libracore/erpnext/commit/9acb885e60f77cd4e9ea8c98bdc39c18abcac731 | erpnext/templates/utils.py | cwe-089 |
delete | @jwt_required
def delete(self, email):
""" Deletes admin with the corresponding email """
return database_utilities.execute_query(f"""delete from admins where email = '{email}'""") | @jwt_required
def delete(self, email):
""" Deletes admin with the corresponding email """
return database_utilities.execute_query(f"""delete from admins where email = %s""", (email, )) | {
"deleted": [
{
"line_no": 4,
"char_start": 106,
"char_end": 204,
"line": " return database_utilities.execute_query(f\"\"\"delete from admins where email = '{email}'\"\"\")\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 106,
"char_end": 208,
"line": " return database_utilities.execute_query(f\"\"\"delete from admins where email = %s\"\"\", (email, ))"
}
]
} | {
"deleted": [
{
"char_start": 191,
"char_end": 193,
"chars": "'{"
},
{
"char_start": 198,
"char_end": 203,
"chars": "}'\"\"\""
}
],
"added": [
{
"char_start": 191,
"char_end": 199,
"chars": "%s\"\"\", ("
},
{
"char_start": 204,
"char_end": 207,
"chars": ", )"
}
]
} | github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485 | apis/admins.py | cwe-089 |
delete_playlists_videos | def delete_playlists_videos(playlist_id, db):
db.execute("DELETE FROM video where playlist_id={playlist_id};".format(
playlist_id=playlist_id)) | def delete_playlists_videos(playlist_id, db):
db.execute("DELETE FROM video where playlist_id=%s;", (playlist_id,)) | {
"deleted": [
{
"line_no": 2,
"char_start": 46,
"char_end": 122,
"line": " db.execute(\"DELETE FROM video where playlist_id={playlist_id};\".format(\n"
},
{
"line_no": 3,
"char_start": 122,
"char_end": 155,
"line": " playlist_id=playlist_id))\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 46,
"char_end": 119,
"line": " db.execute(\"DELETE FROM video where playlist_id=%s;\", (playlist_id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 98,
"char_end": 105,
"chars": "{playli"
},
{
"char_start": 106,
"char_end": 111,
"chars": "t_id}"
},
{
"char_start": 113,
"char_end": 127,
"chars": ".format(\n "
},
{
"char_start": 128,
"char_end": 142,
"chars": " playlist_id="
}
],
"added": [
{
"char_start": 98,
"char_end": 99,
"chars": "%"
},
{
"char_start": 102,
"char_end": 104,
"chars": ", "
},
{
"char_start": 116,
"char_end": 117,
"chars": ","
}
]
} | github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6 | video/video_repository.py | cwe-089 |
upsert_mapped_projects | @staticmethod
def upsert_mapped_projects(user_id: int, project_id: int):
""" Adds projects to mapped_projects if it doesn't exist """
sql = "select * from users where id = {0} and projects_mapped @> '{{{1}}}'".format(user_id, project_id)
result = db.engine.execute(sql)
if result.rowcount > 0:
return # User has previously mapped this project so return
sql = '''update users
set projects_mapped = array_append(projects_mapped, {0})
where id = {1}'''.format(project_id, user_id)
db.engine.execute(sql) | @staticmethod
def upsert_mapped_projects(user_id: int, project_id: int):
""" Adds projects to mapped_projects if it doesn't exist """
sql = "select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'"
result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id)
if result.rowcount > 0:
return # User has previously mapped this project so return
sql = '''update users
set projects_mapped = array_append(projects_mapped, :project_id)
where id = :user_id'''
db.engine.execute(text(sql), project_id=project_id, user_id=user_id) | {
"deleted": [
{
"line_no": 4,
"char_start": 150,
"char_end": 262,
"line": " sql = \"select * from users where id = {0} and projects_mapped @> '{{{1}}}'\".format(user_id, project_id)\n"
},
{
"line_no": 5,
"char_start": 262,
"char_end": 302,
"line": " result = db.engine.execute(sql)\n"
},
{
"line_no": 11,
"char_start": 438,
"char_end": 515,
"line": " set projects_mapped = array_append(projects_mapped, {0})\n"
},
{
"line_no": 12,
"char_start": 515,
"char_end": 579,
"line": " where id = {1}'''.format(project_id, user_id)\n"
},
{
"line_no": 14,
"char_start": 580,
"char_end": 610,
"line": " db.engine.execute(sql)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 150,
"char_end": 247,
"line": " sql = \"select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'\"\n"
},
{
"line_no": 5,
"char_start": 247,
"char_end": 333,
"line": " result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id)\n"
},
{
"line_no": 11,
"char_start": 469,
"char_end": 554,
"line": " set projects_mapped = array_append(projects_mapped, :project_id)\n"
},
{
"line_no": 12,
"char_start": 554,
"char_end": 595,
"line": " where id = :user_id'''\n"
},
{
"line_no": 14,
"char_start": 596,
"char_end": 672,
"line": " db.engine.execute(text(sql), project_id=project_id, user_id=user_id)\n"
}
]
} | {
"deleted": [
{
"char_start": 196,
"char_end": 199,
"chars": "{0}"
},
{
"char_start": 226,
"char_end": 250,
"chars": "{1}}}'\".format(user_id, "
},
{
"char_start": 260,
"char_end": 261,
"chars": ")"
},
{
"char_start": 510,
"char_end": 513,
"chars": "{0}"
},
{
"char_start": 544,
"char_end": 570,
"chars": "{1}'''.format(project_id, "
},
{
"char_start": 577,
"char_end": 578,
"chars": ")"
}
],
"added": [
{
"char_start": 196,
"char_end": 204,
"chars": ":user_id"
},
{
"char_start": 231,
"char_end": 232,
"chars": ":"
},
{
"char_start": 242,
"char_end": 246,
"chars": "}}'\""
},
{
"char_start": 282,
"char_end": 287,
"chars": "text("
},
{
"char_start": 290,
"char_end": 331,
"chars": "), user_id=user_id, project_id=project_id"
},
{
"char_start": 541,
"char_end": 552,
"chars": ":project_id"
},
{
"char_start": 583,
"char_end": 584,
"chars": ":"
},
{
"char_start": 591,
"char_end": 594,
"chars": "'''"
},
{
"char_start": 622,
"char_end": 627,
"chars": "text("
},
{
"char_start": 631,
"char_end": 672,
"chars": ", project_id=project_id, user_id=user_id)"
}
]
} | github.com/hotosm/tasking-manager/commit/dee040a2d22b3c4d5e38e2dbf8c6b651ad4c241a | server/models/postgis/user.py | cwe-089 |
get_first_ranked_month | def get_first_ranked_month(db, scene, player):
sql = "select date from ranks where scene='{}' and player='{}' order by date limit 1;".format(scene, player)
res = db.exec(sql)
date = res[0][0]
return date | def get_first_ranked_month(db, scene, player):
sql = "select date from ranks where scene='{scene}' and player='{player}' order by date limit 1;"
args = {'scene': scene, 'player': player}
res = db.exec(sql, args)
date = res[0][0]
return date | {
"deleted": [
{
"line_no": 2,
"char_start": 47,
"char_end": 160,
"line": " sql = \"select date from ranks where scene='{}' and player='{}' order by date limit 1;\".format(scene, player)\n"
},
{
"line_no": 3,
"char_start": 160,
"char_end": 183,
"line": " res = db.exec(sql)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 47,
"char_end": 149,
"line": " sql = \"select date from ranks where scene='{scene}' and player='{player}' order by date limit 1;\"\n"
},
{
"line_no": 3,
"char_start": 149,
"char_end": 195,
"line": " args = {'scene': scene, 'player': player}\n"
},
{
"line_no": 4,
"char_start": 195,
"char_end": 224,
"line": " res = db.exec(sql, args)\n"
}
]
} | {
"deleted": [
{
"char_start": 137,
"char_end": 140,
"chars": ".fo"
},
{
"char_start": 141,
"char_end": 145,
"chars": "mat("
},
{
"char_start": 158,
"char_end": 159,
"chars": ")"
}
],
"added": [
{
"char_start": 95,
"char_end": 100,
"chars": "scene"
},
{
"char_start": 116,
"char_end": 122,
"chars": "player"
},
{
"char_start": 148,
"char_end": 153,
"chars": "\n "
},
{
"char_start": 154,
"char_end": 170,
"chars": "rgs = {'scene': "
},
{
"char_start": 177,
"char_end": 178,
"chars": "'"
},
{
"char_start": 184,
"char_end": 194,
"chars": "': player}"
},
{
"char_start": 216,
"char_end": 222,
"chars": ", args"
}
]
} | github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63 | bracket_utils.py | cwe-089 |
openPoll | @hook.command(adminonly=True)
def openPoll(question, reply=None, db=None):
"""Creates a new poll."""
if not db_ready: db_init(db)
try:
active = db.execute("SELECT pollID FROM polls WHERE active = 1").fetchone()[0]
if active:
reply("There already is an open poll.")
return
except:
db.execute("INSERT INTO polls (question, active) VALUES ('{}', 1)".format(question))
reply("Opened new poll: {}".format(question))
#reply("Poll opened!")
return | @hook.command(adminonly=True)
def openPoll(question, reply=None, db=None):
"""Creates a new poll."""
if not db_ready: db_init(db)
try:
active = db.execute("SELECT pollID FROM polls WHERE active = 1").fetchone()[0]
if active:
reply("There already is an open poll.")
return
except:
db.execute("INSERT INTO polls (question, active) VALUES (?, 1)", (question,))
reply("Opened new poll: {}".format(question))
#reply("Poll opened!")
return | {
"deleted": [
{
"line_no": 11,
"char_start": 337,
"char_end": 430,
"line": " db.execute(\"INSERT INTO polls (question, active) VALUES ('{}', 1)\".format(question))\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 337,
"char_end": 423,
"line": " db.execute(\"INSERT INTO polls (question, active) VALUES (?, 1)\", (question,))\n"
}
]
} | {
"deleted": [
{
"char_start": 402,
"char_end": 406,
"chars": "'{}'"
},
{
"char_start": 411,
"char_end": 418,
"chars": ".format"
}
],
"added": [
{
"char_start": 402,
"char_end": 403,
"chars": "?"
},
{
"char_start": 408,
"char_end": 410,
"chars": ", "
},
{
"char_start": 419,
"char_end": 420,
"chars": ","
}
]
} | github.com/FrozenPigs/Taigabot/commit/ea9b83a66ae1f0f38a1895f3e8dfa2833d77e3a6 | plugins/poll.py | cwe-089 |
__init__.view_grocery_list | def view_grocery_list():
print("grocery== list")
groceryListFrame = Frame(self)
groceryListFrame.rowconfigure(0, weight=1)
groceryListFrame.columnconfigure(0, weight=1)
groceryListFrame.rowconfigure(1, weight=3)
groceryListFrame.columnconfigure(1, weight=3)
groceryListFrame.pack()
menu.pack_forget()
groceryButton.pack_forget()
label.configure(text="Grocery List")
i = 0
database_file = "meal_planner.db"
item_array = []
with sqlite3.connect(database_file) as conn:
cursor = conn.cursor()
tableName = "ingredients_" + str(weekNumber)
selection = cursor.execute("""SELECT * FROM """ + tableName)
for result in [selection]:
for row in result.fetchall():
print(row)
for ingredient in row:
print(ingredient)
item_array.append(str(ingredient).split())
i = i +1
Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky="w")
j = 0
for item in item_array:
print(item)
returnButton = Button(menuFrame, text = "Return to Menu", highlightbackground="#e7e7e7", command=lambda: [groceryListFrame.pack_forget(),
menu.pack(), returnButton.pack_forget(), label.configure(text="Meal Planer"),
groceryButton.pack(side=RIGHT)])
returnButton.pack(side=RIGHT) | def view_grocery_list():
print("grocery== list")
groceryListFrame = Frame(self)
groceryListFrame.rowconfigure(0, weight=1)
groceryListFrame.columnconfigure(0, weight=1)
groceryListFrame.rowconfigure(1, weight=3)
groceryListFrame.columnconfigure(1, weight=3)
groceryListFrame.pack()
menu.pack_forget()
groceryButton.pack_forget()
label.configure(text="Grocery List")
i = 0
database_file = "meal_planner.db"
item_array = []
with sqlite3.connect(database_file) as conn:
cursor = conn.cursor()
tableName = "ingredients_" + str(weekNumber)
selection = cursor.execute("""SELECT * FROM ?;""", (tableName, ))
for result in [selection]:
for row in result.fetchall():
print(row)
for ingredient in row:
print(ingredient)
item_array.append(str(ingredient).split())
i = i +1
Label(groceryListFrame, text=ingredient, font=MEDIUM_FONT, justify=LEFT).grid(row=i, column=0, sticky="w")
j = 0
for item in item_array:
print(item)
returnButton = Button(menuFrame, text = "Return to Menu", highlightbackground="#e7e7e7", command=lambda: [groceryListFrame.pack_forget(),
menu.pack(), returnButton.pack_forget(), label.configure(text="Meal Planer"),
groceryButton.pack(side=RIGHT)])
returnButton.pack(side=RIGHT) | {
"deleted": [
{
"line_no": 20,
"char_start": 745,
"char_end": 822,
"line": " selection = cursor.execute(\"\"\"SELECT * FROM \"\"\" + tableName)\n"
}
],
"added": [
{
"line_no": 20,
"char_start": 745,
"char_end": 827,
"line": " selection = cursor.execute(\"\"\"SELECT * FROM ?;\"\"\", (tableName, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 809,
"char_end": 811,
"chars": "+ "
}
],
"added": [
{
"char_start": 805,
"char_end": 807,
"chars": "?;"
},
{
"char_start": 810,
"char_end": 811,
"chars": ","
},
{
"char_start": 812,
"char_end": 813,
"chars": "("
},
{
"char_start": 822,
"char_end": 825,
"chars": ", )"
}
]
} | github.com/trishamoyer/RecipePlanner-Python/commit/44d2ce370715d9344fad34b3b749322ab095a925 | mealPlan.py | cwe-089 |
view_page_record | @app.route('/<page_name>/history/record')
def view_page_record(page_name):
content_id = request.args.get('id')
query = db.query("select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = '%s'" % content_id)
page_record = query.namedresult()[0]
return render_template(
'page_record.html',
page_name = page_name,
page_record = page_record
) | @app.route('/<page_name>/history/record')
def view_page_record(page_name):
content_id = request.args.get('id')
query = db.query("select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = $1", content_id)
page_record = query.namedresult()[0]
return render_template(
'page_record.html',
page_name = page_name,
page_record = page_record
) | {
"deleted": [
{
"line_no": 4,
"char_start": 115,
"char_end": 292,
"line": " query = db.query(\"select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = '%s'\" % content_id)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 115,
"char_end": 289,
"line": " query = db.query(\"select page_content.content, page_content.timestamp from page, page_content where page.id = page_content.page_id and page_content.id = $1\", content_id)\n"
}
]
} | {
"deleted": [
{
"char_start": 272,
"char_end": 276,
"chars": "'%s'"
},
{
"char_start": 277,
"char_end": 279,
"chars": " %"
}
],
"added": [
{
"char_start": 272,
"char_end": 274,
"chars": "$1"
},
{
"char_start": 275,
"char_end": 276,
"chars": ","
}
]
} | github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b | server.py | cwe-089 |
update_inverter | def update_inverter(self, inverter_serial, ts, status, etoday, etotal):
query = '''
UPDATE Inverters
SET
TimeStamp='%s',
Status='%s',
eToday='%s',
eTotal='%s'
WHERE Serial='%s';
''' % (ts, status, etoday, etotal, inverter_serial)
self.c.execute(query) | def update_inverter(self, inverter_serial, ts, status, etoday, etotal):
query = '''
UPDATE Inverters
SET
TimeStamp=?,
Status=?,
eToday=?,
eTotal=?
WHERE Serial=?;
'''
self.c.execute(query, (ts, status, etoday, etotal, inverter_serial)) | {
"deleted": [
{
"line_no": 5,
"char_start": 146,
"char_end": 179,
"line": " TimeStamp='%s', \n"
},
{
"line_no": 6,
"char_start": 179,
"char_end": 209,
"line": " Status='%s', \n"
},
{
"line_no": 7,
"char_start": 209,
"char_end": 238,
"line": " eToday='%s',\n"
},
{
"line_no": 8,
"char_start": 238,
"char_end": 266,
"line": " eTotal='%s'\n"
},
{
"line_no": 9,
"char_start": 266,
"char_end": 297,
"line": " WHERE Serial='%s';\n"
},
{
"line_no": 10,
"char_start": 297,
"char_end": 357,
"line": " ''' % (ts, status, etoday, etotal, inverter_serial)\n"
},
{
"line_no": 11,
"char_start": 357,
"char_end": 386,
"line": " self.c.execute(query)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 146,
"char_end": 176,
"line": " TimeStamp=?, \n"
},
{
"line_no": 6,
"char_start": 176,
"char_end": 203,
"line": " Status=?, \n"
},
{
"line_no": 7,
"char_start": 203,
"char_end": 229,
"line": " eToday=?,\n"
},
{
"line_no": 8,
"char_start": 229,
"char_end": 254,
"line": " eTotal=?\n"
},
{
"line_no": 9,
"char_start": 254,
"char_end": 282,
"line": " WHERE Serial=?;\n"
},
{
"line_no": 10,
"char_start": 282,
"char_end": 294,
"line": " '''\n"
},
{
"line_no": 11,
"char_start": 294,
"char_end": 370,
"line": " self.c.execute(query, (ts, status, etoday, etotal, inverter_serial))\n"
}
]
} | {
"deleted": [
{
"char_start": 172,
"char_end": 176,
"chars": "'%s'"
},
{
"char_start": 202,
"char_end": 206,
"chars": "'%s'"
},
{
"char_start": 232,
"char_end": 236,
"chars": "'%s'"
},
{
"char_start": 261,
"char_end": 265,
"chars": "'%s'"
},
{
"char_start": 291,
"char_end": 295,
"chars": "'%s'"
},
{
"char_start": 309,
"char_end": 310,
"chars": "%"
},
{
"char_start": 356,
"char_end": 385,
"chars": "\n self.c.execute(query"
}
],
"added": [
{
"char_start": 172,
"char_end": 173,
"chars": "?"
},
{
"char_start": 199,
"char_end": 200,
"chars": "?"
},
{
"char_start": 226,
"char_end": 227,
"chars": "?"
},
{
"char_start": 252,
"char_end": 253,
"chars": "?"
},
{
"char_start": 279,
"char_end": 280,
"chars": "?"
},
{
"char_start": 293,
"char_end": 300,
"chars": "\n "
},
{
"char_start": 301,
"char_end": 323,
"chars": " self.c.execute(query,"
}
]
} | github.com/philipptrenz/s0-bridge/commit/269b48caa05377b7c58c3e6d1622a4429cb5ba65 | util/database.py | cwe-089 |
insert | def insert(key, value):
connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD'])
cur = connection.cursor()
try:
cur.execute("insert into reply_map values('{}', '{}')".format(key, value))
connection.commit()
except:
pass | def insert(key, value):
connection = psycopg2.connect(host=config['HOST'], port=config['PORT'], database=config['NAME'], user=config['USER'], password=config['PASSWORD'])
cur = connection.cursor()
try:
cur.execute("insert into reply_map values(?, ?)", (key, value))
connection.commit()
except:
pass | {
"deleted": [
{
"line_no": 5,
"char_start": 214,
"char_end": 297,
"line": " cur.execute(\"insert into reply_map values('{}', '{}')\".format(key, value))\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 214,
"char_end": 286,
"line": " cur.execute(\"insert into reply_map values(?, ?)\", (key, value))\n"
}
]
} | {
"deleted": [
{
"char_start": 264,
"char_end": 268,
"chars": "'{}'"
},
{
"char_start": 270,
"char_end": 274,
"chars": "'{}'"
},
{
"char_start": 276,
"char_end": 283,
"chars": ".format"
}
],
"added": [
{
"char_start": 264,
"char_end": 265,
"chars": "?"
},
{
"char_start": 267,
"char_end": 268,
"chars": "?"
},
{
"char_start": 270,
"char_end": 272,
"chars": ", "
}
]
} | github.com/tadaren/reply_bot/commit/5aeafa7e9597a766992af9ff8189e1f050b6579b | db.py | cwe-089 |
save_failure_transaction | def save_failure_transaction(self, user_id, project_id, money):
self.cursor.execute("insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, %s, now(), 'failed' )" % (project_id, user_id, money))
self.db.commit() | def save_failure_transaction(self, user_id, project_id, money):
self.cursor.execute("insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, "
"%s, now(), 'failed' )", (project_id, user_id, money))
self.db.commit() | {
"deleted": [
{
"line_no": 2,
"char_start": 68,
"char_end": 239,
"line": " self.cursor.execute(\"insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, %s, now(), 'failed' )\" % (project_id, user_id, money))\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 68,
"char_end": 186,
"line": " self.cursor.execute(\"insert into transactions (project_id,user_id, money, timestamp, state) values (%s, %s, \"\n"
},
{
"line_no": 3,
"char_start": 186,
"char_end": 269,
"line": " \"%s, now(), 'failed' )\", (project_id, user_id, money))\n"
}
]
} | {
"deleted": [
{
"char_start": 206,
"char_end": 208,
"chars": " %"
}
],
"added": [
{
"char_start": 184,
"char_end": 215,
"chars": "\"\n \""
},
{
"char_start": 237,
"char_end": 238,
"chars": ","
}
]
} | github.com/JLucka/kickstarter-dev/commit/e2ffa062697e060fdfbd2eccbb89a8c53a569e0b | backend/transactions/TransactionConnector.py | cwe-089 |
test_process_as_form | @unpack
def test_process_as_form(self, job_number, dcn_key, was_prev_matched,
was_prev_closed, was_prev_tracked):
email_obj = {
'sender' : "Alex Roy <[email protected]>",
'subject' : "DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`",
'date' : "Tue, 7 May 2019 17:34:17 +0000",
'content' : (
f"job_number={job_number}&title=TEST_ENTRY&city=Ottawa&"
f"address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&"
f"contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&"
f"quality=2&cc_email=&link_to_cert={dcn_key}\r\n"
)
}
# set-up new entries in db, if necessary
fake_dilfo_insert = """
INSERT INTO df_dilfo (job_number, receiver_email, closed)
VALUES ({}, '[email protected]', {})
"""
fake_match_insert = """
INSERT INTO df_matched (job_number, verifier, ground_truth)
VALUES ({}, '[email protected]', {})
"""
with create_connection() as conn:
if was_prev_closed or was_prev_tracked:
conn.cursor().execute(fake_dilfo_insert.format(job_number, was_prev_closed))
if was_prev_matched:
if was_prev_closed:
conn.cursor().execute(fake_match_insert.format(job_number, 1))
else:
conn.cursor().execute(fake_match_insert.format(job_number, 0))
with create_connection() as conn:
df_dilfo_pre = pd.read_sql(f"SELECT * FROM df_dilfo WHERE job_number={job_number}", conn)
df_matched_pre = pd.read_sql(f"SELECT * FROM df_matched WHERE job_number={job_number}", conn)
process_as_form(email_obj)
# make assertions about db now that reply has been processed
with create_connection() as conn:
df_dilfo_post = pd.read_sql(f"SELECT * FROM df_dilfo WHERE job_number={job_number}", conn)
df_matched_post = pd.read_sql(f"SELECT * FROM df_matched WHERE job_number={job_number}", conn)
self.assertEqual(len(df_dilfo_post), 1)
self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key))
self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key))
self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post))
self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns))
self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns)) | @unpack
def test_process_as_form(self, job_number, dcn_key, was_prev_matched,
was_prev_closed, was_prev_tracked):
email_obj = {
'sender' : "Alex Roy <[email protected]>",
'subject' : "DO NOT MODIFY MESSAGE BELOW - JUST HIT `SEND`",
'date' : "Tue, 7 May 2019 17:34:17 +0000",
'content' : (
f"job_number={job_number}&title=TEST_ENTRY&city=Ottawa&"
f"address=2562+Del+Zotto+Ave.%2C+Ottawa%2C+Ontario&"
f"contractor=GCN&engineer=Goodkey&owner=Douglas+Stalker&"
f"quality=2&cc_email=&link_to_cert={dcn_key}\r\n"
)
}
# set-up new entries in db, if necessary
fake_dilfo_insert = """
INSERT INTO df_dilfo (job_number, receiver_email, closed)
VALUES (?, '[email protected]', ?)
"""
fake_match_insert = """
INSERT INTO df_matched (job_number, verifier, ground_truth)
VALUES (?, '[email protected]', ?)
"""
with create_connection() as conn:
if was_prev_closed or was_prev_tracked:
conn.cursor().execute(fake_dilfo_insert, [job_number, was_prev_closed])
if was_prev_matched:
if was_prev_closed:
conn.cursor().execute(fake_match_insert, [job_number, 1])
else:
conn.cursor().execute(fake_match_insert, [job_number, 0])
with create_connection() as conn:
df_dilfo_pre = pd.read_sql("SELECT * FROM df_dilfo WHERE job_number=?", conn, params=[job_number])
df_matched_pre = pd.read_sql("SELECT * FROM df_matched WHERE job_number=?", conn, params=[job_number])
process_as_form(email_obj)
# make assertions about db now that reply has been processed
with create_connection() as conn:
df_dilfo_post = pd.read_sql("SELECT * FROM df_dilfo WHERE job_number=?", conn, params=[job_number])
df_matched_post = pd.read_sql("SELECT * FROM df_matched WHERE job_number=?", conn, params=[job_number])
self.assertEqual(len(df_dilfo_post), 1)
self.assertEqual(bool(df_dilfo_post.iloc[0].closed), bool(was_prev_closed or dcn_key))
self.assertEqual(any(df_matched_post.ground_truth), bool(was_prev_closed or dcn_key))
self.assertEqual(len(df_matched_pre) + bool(dcn_key and not(was_prev_closed)), len(df_matched_post))
self.assertEqual(list(df_matched_pre.columns), list(df_matched_post.columns))
self.assertEqual(list(df_dilfo_pre.columns), list(df_dilfo_post.columns)) | {
"deleted": [
{
"line_no": 18,
"char_start": 823,
"char_end": 876,
"line": " VALUES ({}, '[email protected]', {})\n"
},
{
"line_no": 22,
"char_start": 992,
"char_end": 1045,
"line": " VALUES ({}, '[email protected]', {})\n"
},
{
"line_no": 26,
"char_start": 1151,
"char_end": 1244,
"line": " conn.cursor().execute(fake_dilfo_insert.format(job_number, was_prev_closed))\n"
},
{
"line_no": 29,
"char_start": 1313,
"char_end": 1396,
"line": " conn.cursor().execute(fake_match_insert.format(job_number, 1))\n"
},
{
"line_no": 31,
"char_start": 1418,
"char_end": 1501,
"line": " conn.cursor().execute(fake_match_insert.format(job_number, 0))\n"
},
{
"line_no": 33,
"char_start": 1543,
"char_end": 1645,
"line": " df_dilfo_pre = pd.read_sql(f\"SELECT * FROM df_dilfo WHERE job_number={job_number}\", conn)\n"
},
{
"line_no": 34,
"char_start": 1645,
"char_end": 1751,
"line": " df_matched_pre = pd.read_sql(f\"SELECT * FROM df_matched WHERE job_number={job_number}\", conn)\n"
},
{
"line_no": 38,
"char_start": 1897,
"char_end": 2000,
"line": " df_dilfo_post = pd.read_sql(f\"SELECT * FROM df_dilfo WHERE job_number={job_number}\", conn)\n"
},
{
"line_no": 39,
"char_start": 2000,
"char_end": 2107,
"line": " df_matched_post = pd.read_sql(f\"SELECT * FROM df_matched WHERE job_number={job_number}\", conn)\n"
}
],
"added": [
{
"line_no": 18,
"char_start": 823,
"char_end": 874,
"line": " VALUES (?, '[email protected]', ?)\n"
},
{
"line_no": 22,
"char_start": 990,
"char_end": 1041,
"line": " VALUES (?, '[email protected]', ?)\n"
},
{
"line_no": 26,
"char_start": 1147,
"char_end": 1235,
"line": " conn.cursor().execute(fake_dilfo_insert, [job_number, was_prev_closed])\n"
},
{
"line_no": 29,
"char_start": 1304,
"char_end": 1382,
"line": " conn.cursor().execute(fake_match_insert, [job_number, 1])\n"
},
{
"line_no": 31,
"char_start": 1404,
"char_end": 1482,
"line": " conn.cursor().execute(fake_match_insert, [job_number, 0])\n"
},
{
"line_no": 33,
"char_start": 1524,
"char_end": 1635,
"line": " df_dilfo_pre = pd.read_sql(\"SELECT * FROM df_dilfo WHERE job_number=?\", conn, params=[job_number])\n"
},
{
"line_no": 34,
"char_start": 1635,
"char_end": 1750,
"line": " df_matched_pre = pd.read_sql(\"SELECT * FROM df_matched WHERE job_number=?\", conn, params=[job_number])\n"
},
{
"line_no": 38,
"char_start": 1896,
"char_end": 2008,
"line": " df_dilfo_post = pd.read_sql(\"SELECT * FROM df_dilfo WHERE job_number=?\", conn, params=[job_number])\n"
},
{
"line_no": 39,
"char_start": 2008,
"char_end": 2124,
"line": " df_matched_post = pd.read_sql(\"SELECT * FROM df_matched WHERE job_number=?\", conn, params=[job_number])\n"
}
]
} | {
"deleted": [
{
"char_start": 843,
"char_end": 845,
"chars": "{}"
},
{
"char_start": 872,
"char_end": 874,
"chars": "{}"
},
{
"char_start": 1012,
"char_end": 1014,
"chars": "{}"
},
{
"char_start": 1041,
"char_end": 1043,
"chars": "{}"
},
{
"char_start": 1206,
"char_end": 1214,
"chars": ".format("
},
{
"char_start": 1241,
"char_end": 1242,
"chars": ")"
},
{
"char_start": 1372,
"char_end": 1380,
"chars": ".format("
},
{
"char_start": 1393,
"char_end": 1394,
"chars": ")"
},
{
"char_start": 1477,
"char_end": 1485,
"chars": ".format("
},
{
"char_start": 1498,
"char_end": 1499,
"chars": ")"
},
{
"char_start": 1582,
"char_end": 1583,
"chars": "f"
},
{
"char_start": 1624,
"char_end": 1625,
"chars": "{"
},
{
"char_start": 1635,
"char_end": 1643,
"chars": "}\", conn"
},
{
"char_start": 1686,
"char_end": 1687,
"chars": "f"
},
{
"char_start": 1730,
"char_end": 1731,
"chars": "{"
},
{
"char_start": 1741,
"char_end": 1749,
"chars": "}\", conn"
},
{
"char_start": 1937,
"char_end": 1938,
"chars": "f"
},
{
"char_start": 1979,
"char_end": 1980,
"chars": "{"
},
{
"char_start": 1990,
"char_end": 1998,
"chars": "}\", conn"
},
{
"char_start": 2042,
"char_end": 2043,
"chars": "f"
},
{
"char_start": 2086,
"char_end": 2087,
"chars": "{"
},
{
"char_start": 2097,
"char_end": 2105,
"chars": "}\", conn"
}
],
"added": [
{
"char_start": 843,
"char_end": 844,
"chars": "?"
},
{
"char_start": 871,
"char_end": 872,
"chars": "?"
},
{
"char_start": 1010,
"char_end": 1011,
"chars": "?"
},
{
"char_start": 1038,
"char_end": 1039,
"chars": "?"
},
{
"char_start": 1202,
"char_end": 1205,
"chars": ", ["
},
{
"char_start": 1232,
"char_end": 1233,
"chars": "]"
},
{
"char_start": 1363,
"char_end": 1366,
"chars": ", ["
},
{
"char_start": 1379,
"char_end": 1380,
"chars": "]"
},
{
"char_start": 1463,
"char_end": 1466,
"chars": ", ["
},
{
"char_start": 1479,
"char_end": 1480,
"chars": "]"
},
{
"char_start": 1604,
"char_end": 1622,
"chars": "?\", conn, params=["
},
{
"char_start": 1632,
"char_end": 1633,
"chars": "]"
},
{
"char_start": 1719,
"char_end": 1737,
"chars": "?\", conn, params=["
},
{
"char_start": 1747,
"char_end": 1748,
"chars": "]"
},
{
"char_start": 1977,
"char_end": 1995,
"chars": "?\", conn, params=["
},
{
"char_start": 2005,
"char_end": 2006,
"chars": "]"
},
{
"char_start": 2093,
"char_end": 2111,
"chars": "?\", conn, params=["
},
{
"char_start": 2121,
"char_end": 2122,
"chars": "]"
}
]
} | github.com/confirmationbias616/certificate_checker/commit/9e890b9613b627e3a5995d0e4a594c8e0831e2ce | tests.py | cwe-089 |
render_page_name | @app.route('/<page_name>')
def render_page_name(page_name):
query = db.query("select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1" % page_name)
wiki_page = query.namedresult()
has_content = False
page_is_taken = False
if len(wiki_page) < 1:
content = ""
else:
page_is_taken = True
content = wiki_page[0].content
if len(content) > 0:
has_content = True
else:
pass
content = markdown.markdown(wiki_linkify(content))
return render_template(
'pageholder.html',
page_is_taken = page_is_taken,
page_name = page_name,
markdown = markdown,
wiki_linkify = wiki_linkify,
has_content = has_content,
content = content
) | @app.route('/<page_name>')
def render_page_name(page_name):
query = db.query("select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1", page_name)
wiki_page = query.namedresult()
has_content = False
page_is_taken = False
if len(wiki_page) < 1:
content = ""
else:
page_is_taken = True
content = wiki_page[0].content
if len(content) > 0:
has_content = True
else:
pass
content = markdown.markdown(wiki_linkify(content))
return render_template(
'pageholder.html',
page_is_taken = page_is_taken,
page_name = page_name,
markdown = markdown,
wiki_linkify = wiki_linkify,
has_content = has_content,
content = content
) | {
"deleted": [
{
"line_no": 3,
"char_start": 60,
"char_end": 300,
"line": " query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1\" % page_name)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 60,
"char_end": 297,
"line": " query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1\", page_name)\n"
}
]
} | {
"deleted": [
{
"char_start": 243,
"char_end": 247,
"chars": "'%s'"
},
{
"char_start": 286,
"char_end": 288,
"chars": " %"
}
],
"added": [
{
"char_start": 243,
"char_end": 245,
"chars": "$1"
},
{
"char_start": 284,
"char_end": 285,
"chars": ","
}
]
} | github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b | server.py | cwe-089 |
tid_to_tid_num | def tid_to_tid_num(self, tid):
''' Returns tid_num, given tid. '''
q = "SELECT rowid FROM tids WHERE tid = '" + tid + "'"
self.query(q)
return self.c.fetchone()[0] | def tid_to_tid_num(self, tid):
''' Returns tid_num, given tid. '''
q = "SELECT rowid FROM tids WHERE tid = ?"
self.query(q, tid)
return self.c.fetchone()[0] | {
"deleted": [
{
"line_no": 4,
"char_start": 80,
"char_end": 143,
"line": " q = \"SELECT rowid FROM tids WHERE tid = '\" + tid + \"'\"\n"
},
{
"line_no": 5,
"char_start": 143,
"char_end": 165,
"line": " self.query(q)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 80,
"char_end": 131,
"line": " q = \"SELECT rowid FROM tids WHERE tid = ?\"\n"
},
{
"line_no": 5,
"char_start": 131,
"char_end": 158,
"line": " self.query(q, tid)\n"
}
]
} | {
"deleted": [
{
"char_start": 128,
"char_end": 141,
"chars": "'\" + tid + \"'"
}
],
"added": [
{
"char_start": 128,
"char_end": 129,
"chars": "?"
},
{
"char_start": 151,
"char_end": 156,
"chars": ", tid"
}
]
} | github.com/pukkapies/urop2019/commit/3ca2e2c291d2d5fe262d20a8e0520bdfb622432b | modules/query_lastfm.py | cwe-089 |
get_old_sourcebyinstitution_number | def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution):
"""
Get all the old sourcebyinstitution number from the SQLite database.
"""
query = """
SELECT
titles
FROM
history
WHERE
sourcebyinstitution = "%s"
ORDER BY
titles DESC
LIMIT 1
""" % sourcebyinstitution
sqlite.execute(query)
for record in sqlite:
old_sourcebyinstitution_number = record[0]
return old_sourcebyinstitution_number | def get_old_sourcebyinstitution_number(conn, sqlite, sourcebyinstitution):
"""
Get all the old sourcebyinstitution number from the SQLite database.
"""
query = """
SELECT
titles
FROM
history
WHERE
sourcebyinstitution = ?
ORDER BY
titles DESC
LIMIT 1
"""
sqlite.execute(query, (sourcebyinstitution,))
for record in sqlite:
old_sourcebyinstitution_number = record[0]
return old_sourcebyinstitution_number | {
"deleted": [
{
"line_no": 11,
"char_start": 261,
"char_end": 300,
"line": " sourcebyinstitution = \"%s\"\n"
},
{
"line_no": 15,
"char_start": 357,
"char_end": 387,
"line": " \"\"\" % sourcebyinstitution\n"
},
{
"line_no": 17,
"char_start": 388,
"char_end": 414,
"line": " sqlite.execute(query)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 261,
"char_end": 297,
"line": " sourcebyinstitution = ?\n"
},
{
"line_no": 15,
"char_start": 354,
"char_end": 362,
"line": " \"\"\"\n"
},
{
"line_no": 17,
"char_start": 363,
"char_end": 413,
"line": " sqlite.execute(query, (sourcebyinstitution,))\n"
}
]
} | {
"deleted": [
{
"char_start": 295,
"char_end": 299,
"chars": "\"%s\""
},
{
"char_start": 364,
"char_end": 386,
"chars": " % sourcebyinstitution"
}
],
"added": [
{
"char_start": 295,
"char_end": 296,
"chars": "?"
},
{
"char_start": 387,
"char_end": 411,
"chars": ", (sourcebyinstitution,)"
}
]
} | github.com/miku/siskin/commit/7fa398d2fea72bf2e8b4808f75df4b3d35ae959a | bin/solrcheckup.py | cwe-089 |
top_karma | def top_karma(bot, trigger):
"""
Show karma status for the top n number of IRC users.
"""
try:
top_limit = int(trigger.group(2).strip())
except ValueError:
top_limit = 5
query = "SELECT slug, value FROM nick_values NATURAL JOIN nicknames \
WHERE key = 'karma' ORDER BY value DESC LIMIT %d"
karmalist = bot.db.execute(query % top_limit).fetchall()
for user in karmalist:
bot.say("%s == %s" % (user[0], user[1])) | def top_karma(bot, trigger):
"""
Show karma status for the top n number of IRC users.
"""
try:
top_limit = int(trigger.group(2).strip())
except ValueError:
top_limit = 5
query = "SELECT slug, value FROM nick_values NATURAL JOIN nicknames \
WHERE key = 'karma' ORDER BY value DESC LIMIT ?"
karmalist = bot.db.execute(query, str(top_limit)).fetchall()
for user in karmalist:
bot.say("%s == %s" % (user[0], user[1])) | {
"deleted": [
{
"line_no": 11,
"char_start": 281,
"char_end": 339,
"line": " WHERE key = 'karma' ORDER BY value DESC LIMIT %d\"\n"
},
{
"line_no": 12,
"char_start": 339,
"char_end": 400,
"line": " karmalist = bot.db.execute(query % top_limit).fetchall()\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 281,
"char_end": 338,
"line": " WHERE key = 'karma' ORDER BY value DESC LIMIT ?\"\n"
},
{
"line_no": 12,
"char_start": 338,
"char_end": 403,
"line": " karmalist = bot.db.execute(query, str(top_limit)).fetchall()\n"
}
]
} | {
"deleted": [
{
"char_start": 335,
"char_end": 337,
"chars": "%d"
},
{
"char_start": 376,
"char_end": 378,
"chars": "% "
}
],
"added": [
{
"char_start": 335,
"char_end": 336,
"chars": "?"
},
{
"char_start": 374,
"char_end": 375,
"chars": ","
},
{
"char_start": 376,
"char_end": 380,
"chars": "str("
},
{
"char_start": 389,
"char_end": 390,
"chars": ")"
}
]
} | github.com/OpCode1300/sopel-karma/commit/e4d49f7b3d88f8874c7862392f3f4c2065a25695 | sopel_modules/karma/karma.py | cwe-089 |
retrieve_playlist_by_id | def retrieve_playlist_by_id(id, db):
db.execute(
"SELECT id, name, video_position from playlist WHERE id={id};".format(id=id))
row = db.fetchone()
return row | def retrieve_playlist_by_id(id, db):
db.execute(
"SELECT id, name, video_position from playlist WHERE id=%s;", (id,))
row = db.fetchone()
return row | {
"deleted": [
{
"line_no": 3,
"char_start": 53,
"char_end": 139,
"line": " \"SELECT id, name, video_position from playlist WHERE id={id};\".format(id=id))\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 53,
"char_end": 130,
"line": " \"SELECT id, name, video_position from playlist WHERE id=%s;\", (id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 117,
"char_end": 121,
"chars": "{id}"
},
{
"char_start": 123,
"char_end": 130,
"chars": ".format"
},
{
"char_start": 133,
"char_end": 136,
"chars": "=id"
}
],
"added": [
{
"char_start": 117,
"char_end": 119,
"chars": "%s"
},
{
"char_start": 121,
"char_end": 123,
"chars": ", "
},
{
"char_start": 126,
"char_end": 127,
"chars": ","
}
]
} | github.com/Madmous/playlist/commit/666e52c5f0b8c1f4296e84471637033d9542a7a6 | playlist/playlist_repository.py | cwe-089 |
get_task | @bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value)
def get_task(message):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = '" + str(message.chat.id) + "'")
name = conn.fetchone()
settings.close()
if name == None:
bot.send_message(message.chat.id, "You should login before get tasks.")
else:
bases.update.update_user(name[1], name[0], name[2])
bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1]))
set_state(message.chat.id, config.States.S_START.value) | @bot.message_handler(func = lambda message: get_current_state(message.chat.id) == config.States.S_GET_TASK.value)
def get_task(message):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = ?", (str(message.chat.id),))
name = conn.fetchone()
settings.close()
if name == None:
bot.send_message(message.chat.id, "You should login before get tasks.")
else:
bases.update.update_user(name[1], name[0], name[2])
bot.send_message(message.chat.id, bases.problem.get_unsolved_problem(message.text, name[1]))
set_state(message.chat.id, config.States.S_START.value) | {
"deleted": [
{
"line_no": 5,
"char_start": 266,
"char_end": 353,
"line": " conn.execute(\"select * from users where chat_id = '\" + str(message.chat.id) + \"'\")\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 266,
"char_end": 349,
"line": " conn.execute(\"select * from users where chat_id = ?\", (str(message.chat.id),))\n"
}
]
} | {
"deleted": [
{
"char_start": 320,
"char_end": 321,
"chars": "'"
},
{
"char_start": 322,
"char_end": 324,
"chars": " +"
},
{
"char_start": 345,
"char_end": 351,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 320,
"char_end": 321,
"chars": "?"
},
{
"char_start": 322,
"char_end": 323,
"chars": ","
},
{
"char_start": 324,
"char_end": 325,
"chars": "("
},
{
"char_start": 345,
"char_end": 347,
"chars": ",)"
}
]
} | github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90 | bot.py | cwe-089 |
stats | @bot.message_handler(commands=['stats'])
def stats(message):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = '" + str(message.chat.id) + "'")
name = conn.fetchone()
settings.close()
if name != None:
bases.update.update_user(name[1], name[0], name[2])
bases.problem.create_text_stats(name[1])
img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
bot.send_photo(message.chat.id, img)
img.close()
if bases.problem.create_stats_picture(name[1]):
bot.send_message(message.chat.id, "Sorry, you haven't solved tasks.")
return 0
img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
bot.send_photo(message.chat.id, img)
img.close()
else:
bot.send_message(message.chat.id, "You should login before getting statistic.") | @bot.message_handler(commands=['stats'])
def stats(message):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = ?", (str(message.chat.id),))
name = conn.fetchone()
settings.close()
if name != None:
bases.update.update_user(name[1], name[0], name[2])
bases.problem.create_text_stats(name[1])
img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
bot.send_photo(message.chat.id, img)
img.close()
if bases.problem.create_stats_picture(name[1]):
bot.send_message(message.chat.id, "Sorry, you haven't solved tasks.")
return 0
img = open(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\users\\" + name[1] + ".png", "rb")
bot.send_photo(message.chat.id, img)
img.close()
else:
bot.send_message(message.chat.id, "You should login before getting statistic.") | {
"deleted": [
{
"line_no": 5,
"char_start": 190,
"char_end": 277,
"line": " conn.execute(\"select * from users where chat_id = '\" + str(message.chat.id) + \"'\")\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 190,
"char_end": 273,
"line": " conn.execute(\"select * from users where chat_id = ?\", (str(message.chat.id),))\n"
}
]
} | {
"deleted": [
{
"char_start": 244,
"char_end": 245,
"chars": "'"
},
{
"char_start": 246,
"char_end": 248,
"chars": " +"
},
{
"char_start": 269,
"char_end": 275,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 244,
"char_end": 245,
"chars": "?"
},
{
"char_start": 246,
"char_end": 247,
"chars": ","
},
{
"char_start": 248,
"char_end": 249,
"chars": "("
},
{
"char_start": 269,
"char_end": 271,
"chars": ",)"
}
]
} | github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90 | bot.py | cwe-089 |
delete | @jwt_required
def delete(self, user_id):
""" Deletes user with the corresponding user_id """
return database_utilities.execute_query(f"""delete from users where user_id = '{user_id}'""") | @jwt_required
def delete(self, user_id):
""" Deletes user with the corresponding user_id """
return database_utilities.execute_query(f"""delete from users where user_id = %s""", (user_id, )) | {
"deleted": [
{
"line_no": 4,
"char_start": 109,
"char_end": 210,
"line": " return database_utilities.execute_query(f\"\"\"delete from users where user_id = '{user_id}'\"\"\")\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 109,
"char_end": 214,
"line": " return database_utilities.execute_query(f\"\"\"delete from users where user_id = %s\"\"\", (user_id, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 195,
"char_end": 197,
"chars": "'{"
},
{
"char_start": 204,
"char_end": 209,
"chars": "}'\"\"\""
}
],
"added": [
{
"char_start": 195,
"char_end": 203,
"chars": "%s\"\"\", ("
},
{
"char_start": 210,
"char_end": 213,
"chars": ", )"
}
]
} | github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485 | apis/users.py | cwe-089 |
verify_rno | def verify_rno(self, rno):
query = "SELECT COUNT(rno) FROM rides WHERE rno = {rno}".format(rno = rno)
self.cursor.execute(query)
result = self.cursor.fetchone()
if (int(result[0]) > 0):
return True
else:
return False | def verify_rno(self, rno):
self.cursor.execute("SELECT COUNT(rno) FROM rides WHERE rno = :rno", {'rno': rno})
result = self.cursor.fetchone()
if (int(result[0]) > 0):
return True
else:
return False | {
"deleted": [
{
"line_no": 2,
"char_start": 31,
"char_end": 114,
"line": " query = \"SELECT COUNT(rno) FROM rides WHERE rno = {rno}\".format(rno = rno)\n"
},
{
"line_no": 3,
"char_start": 114,
"char_end": 149,
"line": " self.cursor.execute(query)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 31,
"char_end": 122,
"line": " self.cursor.execute(\"SELECT COUNT(rno) FROM rides WHERE rno = :rno\", {'rno': rno})\n"
}
]
} | {
"deleted": [
{
"char_start": 39,
"char_end": 41,
"chars": "qu"
},
{
"char_start": 43,
"char_end": 47,
"chars": "y = "
},
{
"char_start": 89,
"char_end": 90,
"chars": "{"
},
{
"char_start": 93,
"char_end": 94,
"chars": "}"
},
{
"char_start": 95,
"char_end": 103,
"chars": ".format("
},
{
"char_start": 106,
"char_end": 108,
"chars": " ="
},
{
"char_start": 112,
"char_end": 147,
"chars": ")\n self.cursor.execute(query"
}
],
"added": [
{
"char_start": 39,
"char_end": 55,
"chars": "self.cursor.exec"
},
{
"char_start": 56,
"char_end": 57,
"chars": "t"
},
{
"char_start": 58,
"char_end": 59,
"chars": "("
},
{
"char_start": 101,
"char_end": 102,
"chars": ":"
},
{
"char_start": 106,
"char_end": 107,
"chars": ","
},
{
"char_start": 108,
"char_end": 110,
"chars": "{'"
},
{
"char_start": 113,
"char_end": 115,
"chars": "':"
},
{
"char_start": 117,
"char_end": 118,
"chars": "n"
},
{
"char_start": 119,
"char_end": 120,
"chars": "}"
}
]
} | github.com/kenboo98/291-Mini-Project-I/commit/3080ccb687c79c83954ce703faee8fcceec8c9eb | book_rides/book_rides.py | cwe-089 |
get_requested_day | def get_requested_day(self, date):
data = dict()
day_start, day_end = self.get_epoch_day(date)
data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}
query = '''
SELECT TimeStamp, SUM(Power) AS Power
FROM DayData
WHERE TimeStamp BETWEEN %s AND %s
GROUP BY TimeStamp;
'''
data['data'] = list()
for row in self.c.execute(query % (day_start, day_end)):
data['data'].append({ 'time': row[0], 'power': row[1] })
if self.get_datetime(date).date() == datetime.today().date():
query = '''
SELECT SUM(EToday) as EToday
FROM Inverters;
'''
else:
query = '''
SELECT SUM(DayYield) AS Power
FROM MonthData
WHERE TimeStamp BETWEEN %s AND %s
GROUP BY TimeStamp
''' % (day_start, day_end)
self.c.execute(query)
row = self.c.fetchone()
if row and row[0]: data['total'] = row[0]
else: data['total'] = 0
query = '''
SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max
FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );
'''
self.c.execute(query)
first_data, last_data = self.c.fetchone()
if (first_data): data['hasPrevious'] = (first_data < day_start)
else: data['hasPrevious'] = False
if (last_data): data['hasNext'] = (last_data > day_end)
else: data['hasNext'] = False
#print(json.dumps(data, indent=4))
return data | def get_requested_day(self, date):
data = dict()
day_start, day_end = self.get_epoch_day(date)
data['interval'] = {'from': self.convert_local_ts_to_utc(day_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(day_end, self.local_timezone)}
query = '''
SELECT TimeStamp, SUM(Power) AS Power
FROM DayData
WHERE TimeStamp BETWEEN ? AND ?
GROUP BY TimeStamp;
'''
data['data'] = list()
for row in self.c.execute(query, (day_start, day_end)):
data['data'].append({ 'time': row[0], 'power': row[1] })
if self.get_datetime(date).date() == datetime.today().date():
query = '''
SELECT SUM(EToday) as EToday
FROM Inverters;
'''
self.c.execute(query)
else:
query = '''
SELECT SUM(DayYield) AS Power
FROM MonthData
WHERE TimeStamp BETWEEN ? AND ?
GROUP BY TimeStamp;
'''
self.c.execute(query, (day_start, day_end))
row = self.c.fetchone()
if row and row[0]: data['total'] = row[0]
else: data['total'] = 0
query = '''
SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max
FROM ( SELECT TimeStamp FROM DayData GROUP BY TimeStamp );
'''
self.c.execute(query)
first_data, last_data = self.c.fetchone()
if (first_data): data['hasPrevious'] = (first_data < day_start)
else: data['hasPrevious'] = False
if (last_data): data['hasNext'] = (last_data > day_end)
else: data['hasNext'] = False
#print(json.dumps(data, indent=4))
return data | {
"deleted": [
{
"line_no": 11,
"char_start": 379,
"char_end": 426,
"line": " WHERE TimeStamp BETWEEN %s AND %s \n"
},
{
"line_no": 16,
"char_start": 501,
"char_end": 566,
"line": " for row in self.c.execute(query % (day_start, day_end)):\n"
},
{
"line_no": 29,
"char_start": 945,
"char_end": 995,
"line": " WHERE TimeStamp BETWEEN %s AND %s\n"
},
{
"line_no": 30,
"char_start": 995,
"char_end": 1030,
"line": " GROUP BY TimeStamp\n"
},
{
"line_no": 31,
"char_start": 1030,
"char_end": 1073,
"line": " ''' % (day_start, day_end)\n"
},
{
"line_no": 32,
"char_start": 1073,
"char_end": 1103,
"line": " self.c.execute(query)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 379,
"char_end": 423,
"line": " WHERE TimeStamp BETWEEN ? AND ?\n"
},
{
"line_no": 16,
"char_start": 498,
"char_end": 562,
"line": " for row in self.c.execute(query, (day_start, day_end)):\n"
},
{
"line_no": 25,
"char_start": 824,
"char_end": 858,
"line": " self.c.execute(query)\n"
},
{
"line_no": 30,
"char_start": 975,
"char_end": 1023,
"line": " WHERE TimeStamp BETWEEN ? AND ?\n"
},
{
"line_no": 31,
"char_start": 1023,
"char_end": 1059,
"line": " GROUP BY TimeStamp;\n"
},
{
"line_no": 32,
"char_start": 1059,
"char_end": 1079,
"line": " '''\n"
},
{
"line_no": 33,
"char_start": 1079,
"char_end": 1135,
"line": " self.c.execute(query, (day_start, day_end))\n"
},
{
"line_no": 34,
"char_start": 1135,
"char_end": 1136,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 415,
"char_end": 417,
"chars": "%s"
},
{
"char_start": 422,
"char_end": 425,
"chars": "%s "
},
{
"char_start": 540,
"char_end": 542,
"chars": " %"
},
{
"char_start": 985,
"char_end": 987,
"chars": "%s"
},
{
"char_start": 992,
"char_end": 994,
"chars": "%s"
},
{
"char_start": 1050,
"char_end": 1051,
"chars": "%"
},
{
"char_start": 1052,
"char_end": 1063,
"chars": "(day_start,"
},
{
"char_start": 1064,
"char_end": 1073,
"chars": "day_end)\n"
}
],
"added": [
{
"char_start": 415,
"char_end": 416,
"chars": "?"
},
{
"char_start": 421,
"char_end": 422,
"chars": "?"
},
{
"char_start": 537,
"char_end": 538,
"chars": ","
},
{
"char_start": 824,
"char_end": 858,
"chars": " self.c.execute(query)\n"
},
{
"char_start": 1015,
"char_end": 1016,
"chars": "?"
},
{
"char_start": 1021,
"char_end": 1022,
"chars": "?"
},
{
"char_start": 1057,
"char_end": 1058,
"chars": ";"
},
{
"char_start": 1078,
"char_end": 1079,
"chars": "\n"
},
{
"char_start": 1082,
"char_end": 1083,
"chars": " "
},
{
"char_start": 1111,
"char_end": 1132,
"chars": ", (day_start, day_end"
},
{
"char_start": 1133,
"char_end": 1135,
"chars": ")\n"
}
]
} | github.com/philipptrenz/sunportal/commit/7eef493a168ed4e6731ff800713bfb8aee99a506 | util/database.py | cwe-089 |
add_language | def add_language(lang):
try:
cur.execute(f"INSERT INTO language (name) VALUES ('{lang}')")
except Exception as e:
pass
cur.execute(f"SELECT language_id FROM language where name='{lang}'")
lang_id = cur.fetchone()[0]
if conn.commit():
return lang_id
return lang_id | def add_language(lang):
try:
cur.execute("INSERT INTO language (name) VALUES (%s)", (lang, ))
except Exception as e:
pass
cur.execute("SELECT language_id FROM language where name=%s", (lang, ))
lang_id = cur.fetchone()[0]
if conn.commit():
return lang_id
return lang_id | {
"deleted": [
{
"line_no": 3,
"char_start": 33,
"char_end": 103,
"line": " cur.execute(f\"INSERT INTO language (name) VALUES ('{lang}')\")\n"
},
{
"line_no": 6,
"char_start": 143,
"char_end": 216,
"line": " cur.execute(f\"SELECT language_id FROM language where name='{lang}'\")\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 33,
"char_end": 106,
"line": " cur.execute(\"INSERT INTO language (name) VALUES (%s)\", (lang, ))\n"
},
{
"line_no": 6,
"char_start": 146,
"char_end": 222,
"line": " cur.execute(\"SELECT language_id FROM language where name=%s\", (lang, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 53,
"char_end": 54,
"chars": "f"
},
{
"char_start": 91,
"char_end": 93,
"chars": "'{"
},
{
"char_start": 97,
"char_end": 99,
"chars": "}'"
},
{
"char_start": 100,
"char_end": 101,
"chars": "\""
},
{
"char_start": 159,
"char_end": 160,
"chars": "f"
},
{
"char_start": 205,
"char_end": 207,
"chars": "'{"
},
{
"char_start": 211,
"char_end": 214,
"chars": "}'\""
}
],
"added": [
{
"char_start": 90,
"char_end": 97,
"chars": "%s)\", ("
},
{
"char_start": 101,
"char_end": 103,
"chars": ", "
},
{
"char_start": 207,
"char_end": 213,
"chars": "%s\", ("
},
{
"char_start": 217,
"char_end": 220,
"chars": ", )"
}
]
} | github.com/Elbertbiggs360/dvdrental/commit/ad144ae2a08a332498d0831bc255170d57ba754b | app.py | cwe-089 |
makeJudge | def makeJudge(judge):
db.execute("UPDATE players SET Judge = 1 WHERE Name = '%s' COLLATE NOCASE" % (judge))
database.commit() | def makeJudge(judge):
db.execute("UPDATE players SET Judge = 1 WHERE Name = ? COLLATE NOCASE", judge)
database.commit() | {
"deleted": [
{
"line_no": 2,
"char_start": 22,
"char_end": 110,
"line": "\tdb.execute(\"UPDATE players SET Judge = 1 WHERE Name = '%s' COLLATE NOCASE\" % (judge)) \n"
}
],
"added": [
{
"line_no": 2,
"char_start": 22,
"char_end": 104,
"line": "\tdb.execute(\"UPDATE players SET Judge = 1 WHERE Name = ? COLLATE NOCASE\", judge) \n"
}
]
} | {
"deleted": [
{
"char_start": 77,
"char_end": 81,
"chars": "'%s'"
},
{
"char_start": 97,
"char_end": 99,
"chars": " %"
},
{
"char_start": 100,
"char_end": 101,
"chars": "("
},
{
"char_start": 106,
"char_end": 107,
"chars": ")"
}
],
"added": [
{
"char_start": 77,
"char_end": 78,
"chars": "?"
},
{
"char_start": 94,
"char_end": 95,
"chars": ","
}
]
} | github.com/iScrE4m/XLeague/commit/59cab6e5fd8bd5e47f2418a7c71cb1d4e3cad0d2 | plugins/database.py | cwe-089 |
isValidAdmToken | def isValidAdmToken(adm_token):
conn, c = connectDB()
req = "SELECT * from {} where adm_token='{}'".format(CFG("admintoken_table_name"), adm_token)
answer = bool(queryOne(c, req))
closeDB(conn)
return answer | def isValidAdmToken(adm_token):
conn, c = connectDB()
req = "SELECT * from {} where adm_token=?".format(CFG("admintoken_table_name"))
answer = bool(queryOne(c, req, (adm_token,)))
closeDB(conn)
return answer | {
"deleted": [
{
"line_no": 3,
"char_start": 58,
"char_end": 157,
"line": " req = \"SELECT * from {} where adm_token='{}'\".format(CFG(\"admintoken_table_name\"), adm_token)\n"
},
{
"line_no": 4,
"char_start": 157,
"char_end": 193,
"line": " answer = bool(queryOne(c, req))\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 58,
"char_end": 143,
"line": " req = \"SELECT * from {} where adm_token=?\".format(CFG(\"admintoken_table_name\"))\n"
},
{
"line_no": 4,
"char_start": 143,
"char_end": 193,
"line": " answer = bool(queryOne(c, req, (adm_token,)))\n"
}
]
} | {
"deleted": [
{
"char_start": 103,
"char_end": 107,
"chars": "'{}'"
},
{
"char_start": 144,
"char_end": 155,
"chars": ", adm_token"
}
],
"added": [
{
"char_start": 103,
"char_end": 104,
"chars": "?"
},
{
"char_start": 176,
"char_end": 190,
"chars": ", (adm_token,)"
}
]
} | github.com/FAUSheppy/simple-python-poll/commit/186c5ff5cdf58272e253a1bb432419ee50d93109 | database.py | cwe-089 |
get_mapped_projects | @staticmethod
def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO:
""" Get all projects a user has mapped on """
# This query looks scary, but we're really just creating an outer join between the query that gets the
# counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to
# handle cases where users have only validated tasks on a project, or only mapped on a project.
sql = '''SELECT p.id,
p.status,
p.default_locale,
c.mapped,
c.validated,
st_asgeojson(p.centroid)
FROM projects p,
(SELECT coalesce(v.project_id, m.project_id) project_id,
coalesce(v.validated, 0) validated,
coalesce(m.mapped, 0) mapped
FROM (SELECT t.project_id,
count (t.validated_by) validated
FROM tasks t
WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})
AND t.validated_by = {0}
GROUP BY t.project_id, t.validated_by) v
FULL OUTER JOIN
(SELECT t.project_id,
count(t.mapped_by) mapped
FROM tasks t
WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})
AND t.mapped_by = {0}
GROUP BY t.project_id, t.mapped_by) m
ON v.project_id = m.project_id) c
WHERE p.id = c.project_id ORDER BY p.id DESC'''.format(user_id)
results = db.engine.execute(sql)
if results.rowcount == 0:
raise NotFound()
mapped_projects_dto = UserMappedProjectsDTO()
for row in results:
mapped_project = MappedProject()
mapped_project.project_id = row[0]
mapped_project.status = ProjectStatus(row[1]).name
mapped_project.tasks_mapped = row[3]
mapped_project.tasks_validated = row[4]
mapped_project.centroid = geojson.loads(row[5])
project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2])
mapped_project.name = project_info.name
mapped_projects_dto.mapped_projects.append(mapped_project)
return mapped_projects_dto | @staticmethod
def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO:
""" Get all projects a user has mapped on """
# This query looks scary, but we're really just creating an outer join between the query that gets the
# counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to
# handle cases where users have only validated tasks on a project, or only mapped on a project.
sql = '''SELECT p.id,
p.status,
p.default_locale,
c.mapped,
c.validated,
st_asgeojson(p.centroid)
FROM projects p,
(SELECT coalesce(v.project_id, m.project_id) project_id,
coalesce(v.validated, 0) validated,
coalesce(m.mapped, 0) mapped
FROM (SELECT t.project_id,
count (t.validated_by) validated
FROM tasks t
WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)
AND t.validated_by = :user_id
GROUP BY t.project_id, t.validated_by) v
FULL OUTER JOIN
(SELECT t.project_id,
count(t.mapped_by) mapped
FROM tasks t
WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)
AND t.mapped_by = :user_id
GROUP BY t.project_id, t.mapped_by) m
ON v.project_id = m.project_id) c
WHERE p.id = c.project_id ORDER BY p.id DESC'''
results = db.engine.execute(text(sql), user_id=user_id)
if results.rowcount == 0:
raise NotFound()
mapped_projects_dto = UserMappedProjectsDTO()
for row in results:
mapped_project = MappedProject()
mapped_project.project_id = row[0]
mapped_project.status = ProjectStatus(row[1]).name
mapped_project.tasks_mapped = row[3]
mapped_project.tasks_validated = row[4]
mapped_project.centroid = geojson.loads(row[5])
project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2])
mapped_project.name = project_info.name
mapped_projects_dto.mapped_projects.append(mapped_project)
return mapped_projects_dto | {
"deleted": [
{
"line_no": 21,
"char_start": 1137,
"char_end": 1251,
"line": " WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})\n"
},
{
"line_no": 22,
"char_start": 1251,
"char_end": 1311,
"line": " AND t.validated_by = {0}\n"
},
{
"line_no": 28,
"char_start": 1570,
"char_end": 1677,
"line": " WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = {0})\n"
},
{
"line_no": 29,
"char_start": 1677,
"char_end": 1727,
"line": " AND t.mapped_by = {0}\n"
},
{
"line_no": 32,
"char_start": 1850,
"char_end": 1933,
"line": " WHERE p.id = c.project_id ORDER BY p.id DESC'''.format(user_id)\n"
},
{
"line_no": 34,
"char_start": 1934,
"char_end": 1975,
"line": " results = db.engine.execute(sql)\n"
}
],
"added": [
{
"line_no": 21,
"char_start": 1137,
"char_end": 1256,
"line": " WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)\n"
},
{
"line_no": 22,
"char_start": 1256,
"char_end": 1321,
"line": " AND t.validated_by = :user_id\n"
},
{
"line_no": 28,
"char_start": 1580,
"char_end": 1692,
"line": " WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id)\n"
},
{
"line_no": 29,
"char_start": 1692,
"char_end": 1747,
"line": " AND t.mapped_by = :user_id\n"
},
{
"line_no": 32,
"char_start": 1870,
"char_end": 1937,
"line": " WHERE p.id = c.project_id ORDER BY p.id DESC'''\n"
},
{
"line_no": 34,
"char_start": 1938,
"char_end": 2002,
"line": " results = db.engine.execute(text(sql), user_id=user_id)\n"
}
]
} | {
"deleted": [
{
"char_start": 1246,
"char_end": 1249,
"chars": "{0}"
},
{
"char_start": 1307,
"char_end": 1310,
"chars": "{0}"
},
{
"char_start": 1672,
"char_end": 1675,
"chars": "{0}"
},
{
"char_start": 1723,
"char_end": 1726,
"chars": "{0}"
},
{
"char_start": 1916,
"char_end": 1932,
"chars": ".format(user_id)"
}
],
"added": [
{
"char_start": 1246,
"char_end": 1254,
"chars": ":user_id"
},
{
"char_start": 1312,
"char_end": 1320,
"chars": ":user_id"
},
{
"char_start": 1682,
"char_end": 1690,
"chars": ":user_id"
},
{
"char_start": 1738,
"char_end": 1746,
"chars": ":user_id"
},
{
"char_start": 1974,
"char_end": 1979,
"chars": "text("
},
{
"char_start": 1982,
"char_end": 2000,
"chars": "), user_id=user_id"
}
]
} | github.com/hotosm/tasking-manager/commit/dee040a2d22b3c4d5e38e2dbf8c6b651ad4c241a | server/models/postgis/user.py | cwe-089 |
delete_data | def delete_data(self, session, id):
self._openContainer(session)
sid = str(id)
if (self.idNormalizer is not None):
sid = self.idNormalizer.process_string(session, str(id))
query = "DELETE FROM %s WHERE identifier = '%s';" % (self.table, sid)
self._query(query)
return None | def delete_data(self, session, id):
self._openContainer(session)
sid = str(id)
if (self.idNormalizer is not None):
sid = self.idNormalizer.process_string(session, str(id))
query = "DELETE FROM %s WHERE identifier = $1;" % (self.table)
self._query(query, sid)
return None | {
"deleted": [
{
"line_no": 6,
"char_start": 212,
"char_end": 290,
"line": " query = \"DELETE FROM %s WHERE identifier = '%s';\" % (self.table, sid)\n"
},
{
"line_no": 7,
"char_start": 290,
"char_end": 317,
"line": " self._query(query)\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 212,
"char_end": 283,
"line": " query = \"DELETE FROM %s WHERE identifier = $1;\" % (self.table)\n"
},
{
"line_no": 7,
"char_start": 283,
"char_end": 315,
"line": " self._query(query, sid)\n"
}
]
} | {
"deleted": [
{
"char_start": 263,
"char_end": 267,
"chars": "'%s'"
},
{
"char_start": 283,
"char_end": 288,
"chars": ", sid"
}
],
"added": [
{
"char_start": 263,
"char_end": 265,
"chars": "$1"
},
{
"char_start": 308,
"char_end": 313,
"chars": ", sid"
}
]
} | github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e | cheshire3/sql/postgresStore.py | cwe-089 |
user_verify | def user_verify(self):
eid = self.email
code = self.password
if eid.strip() == '':
return
if code.strip() == '':
return
query = '''select * from usr where email like\''''+eid+'\''
cursor = g.conn.execute(query)
for row in cursor:
key = str(row.password)
if key.strip() == code.strip():
self.name = str(row.name)
self.email = eid
self.id = eid
self.valid = True
break | def user_verify(self):
eid = self.email
code = self.password
if eid.strip() == '':
return
if code.strip() == '':
return
query = 'select * from usr where email like %s'
cursor = g.conn.execute(query, (eid, ))
for row in cursor:
key = str(row.password)
if key.strip() == code.strip():
self.name = str(row.name)
self.email = eid
self.id = eid
self.valid = True
break | {
"deleted": [
{
"line_no": 8,
"char_start": 180,
"char_end": 248,
"line": " query = '''select * from usr where email like\\''''+eid+'\\''\n"
},
{
"line_no": 9,
"char_start": 248,
"char_end": 287,
"line": " cursor = g.conn.execute(query)\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 180,
"char_end": 236,
"line": " query = 'select * from usr where email like %s'\n"
},
{
"line_no": 9,
"char_start": 236,
"char_end": 284,
"line": " cursor = g.conn.execute(query, (eid, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 197,
"char_end": 199,
"chars": "''"
},
{
"char_start": 233,
"char_end": 246,
"chars": "\\''''+eid+'\\'"
}
],
"added": [
{
"char_start": 231,
"char_end": 234,
"chars": " %s"
},
{
"char_start": 273,
"char_end": 282,
"chars": ", (eid, )"
}
]
} | github.com/Daniel-Bu/w4111-project1/commit/fe04bedc72e62fd4c4ee046a9af29fd81e9b3340 | Web-app/User.py | cwe-089 |
search_films | @app.route('/movies/search', methods=['GET', 'POST'])
def search_films():
form = SearchForm()
if not form.validate_on_submit():
return render_template('search.html', title='Search for films', form=form)
search_terms = form.data['term'].split(' ')
search_string = ' & '.join(search_terms)
cur.execute(f"SELECT * FROM film where fulltext @@ to_tsquery('{search_string}')")
res = cur.fetchall()
return render_template('search_results.html', title='Home', res=len(res)) | @app.route('/movies/search', methods=['GET', 'POST'])
def search_films():
form = SearchForm()
if not form.validate_on_submit():
return render_template('search.html', title='Search for films', form=form)
search_terms = form.data['term'].split(' ')
search_string = ' & '.join(search_terms)
cur.execute("SELECT * FROM film where fulltext @@ to_tsquery(%s)", (search_string, ))
res = cur.fetchall()
return render_template('search_results.html', title='Home', res=len(res)) | {
"deleted": [
{
"line_no": 8,
"char_start": 312,
"char_end": 399,
"line": " cur.execute(f\"SELECT * FROM film where fulltext @@ to_tsquery('{search_string}')\")\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 312,
"char_end": 402,
"line": " cur.execute(\"SELECT * FROM film where fulltext @@ to_tsquery(%s)\", (search_string, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 328,
"char_end": 329,
"chars": "f"
},
{
"char_start": 378,
"char_end": 380,
"chars": "'{"
},
{
"char_start": 393,
"char_end": 395,
"chars": "}'"
},
{
"char_start": 396,
"char_end": 397,
"chars": "\""
}
],
"added": [
{
"char_start": 377,
"char_end": 384,
"chars": "%s)\", ("
},
{
"char_start": 397,
"char_end": 399,
"chars": ", "
}
]
} | github.com/Elbertbiggs360/dvdrental/commit/ad144ae2a08a332498d0831bc255170d57ba754b | app.py | cwe-089 |
getGameCountInSeriesSoFar | def getGameCountInSeriesSoFar(submission):
database = sqlite3.connect('database.db')
cursor = database.cursor()
return cursor.execute("SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = '" + getTitle(submission) + "' AND Date <= '" + getSubmissionDateFromDatabase(submission) + "'").fetchone()[0]
database.close() | def getGameCountInSeriesSoFar(submission):
database = sqlite3.connect('database.db')
cursor = database.cursor()
return cursor.execute("SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = ? AND Date <= ?", [getTitle(submission), getSubmissionDateFromDatabase(submission)]).fetchone()[0]
database.close() | {
"deleted": [
{
"line_no": 4,
"char_start": 120,
"char_end": 317,
"line": " return cursor.execute(\"SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = '\" + getTitle(submission) + \"' AND Date <= '\" + getSubmissionDateFromDatabase(submission) + \"'\").fetchone()[0]\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 120,
"char_end": 305,
"line": " return cursor.execute(\"SELECT COUNT(*) FROM ChallengeRankings WHERE SeriesTitle = ? AND Date <= ?\", [getTitle(submission), getSubmissionDateFromDatabase(submission)]).fetchone()[0]\n"
}
]
} | {
"deleted": [
{
"char_start": 206,
"char_end": 208,
"chars": "'\""
},
{
"char_start": 209,
"char_end": 210,
"chars": "+"
},
{
"char_start": 231,
"char_end": 253,
"chars": " + \"' AND Date <= '\" +"
},
{
"char_start": 295,
"char_end": 301,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 206,
"char_end": 207,
"chars": "?"
},
{
"char_start": 208,
"char_end": 211,
"chars": "AND"
},
{
"char_start": 212,
"char_end": 225,
"chars": "Date <= ?\", ["
},
{
"char_start": 245,
"char_end": 246,
"chars": ","
},
{
"char_start": 288,
"char_end": 289,
"chars": "]"
}
]
} | github.com/LiquidFun/Reddit-GeoGuessr-Tracking-Bot/commit/0cad2d52e24b05da32789fbc8face7a9999a71f9 | CheckAndPostForSeriesSubmissions.py | cwe-089 |
add | @mod.route('/add', methods=['GET', 'POST'])
def add():
if request.method == 'POST':
msg_id = int(request.form['msg_id'])
user_id = session['logged_id']
content = request.form['content']
c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
sql = "INSERT INTO comment(msg_id,user_id,content,c_time) " + \
"VALUES(%d,%d,'%s','%s');" % (msg_id, user_id, content, c_time)
cursor.execute(sql)
conn.commit()
return redirect(url_for('comment.show', msg_id=msg_id)) | @mod.route('/add', methods=['GET', 'POST'])
def add():
if request.method == 'POST':
msg_id = int(request.form['msg_id'])
user_id = session['logged_id']
content = request.form['content']
c_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cursor.execute("INSERT INTO comment(msg_id,user_id,content,c_time) VALUES(%s,%s,%s,%s);", (msg_id, user_id, content, c_time))
conn.commit()
return redirect(url_for('comment.show', msg_id=msg_id)) | {
"deleted": [
{
"line_no": 8,
"char_start": 276,
"char_end": 348,
"line": " sql = \"INSERT INTO comment(msg_id,user_id,content,c_time) \" + \\\n"
},
{
"line_no": 9,
"char_start": 348,
"char_end": 428,
"line": " \"VALUES(%d,%d,'%s','%s');\" % (msg_id, user_id, content, c_time)\n"
},
{
"line_no": 10,
"char_start": 428,
"char_end": 456,
"line": " cursor.execute(sql)\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 276,
"char_end": 410,
"line": " cursor.execute(\"INSERT INTO comment(msg_id,user_id,content,c_time) VALUES(%s,%s,%s,%s);\", (msg_id, user_id, content, c_time))\n"
}
]
} | {
"deleted": [
{
"char_start": 285,
"char_end": 290,
"chars": "ql = "
},
{
"char_start": 342,
"char_end": 365,
"chars": "\" + \\\n \""
},
{
"char_start": 373,
"char_end": 374,
"chars": "d"
},
{
"char_start": 376,
"char_end": 377,
"chars": "d"
},
{
"char_start": 378,
"char_end": 379,
"chars": "'"
},
{
"char_start": 381,
"char_end": 382,
"chars": "'"
},
{
"char_start": 383,
"char_end": 384,
"chars": "'"
},
{
"char_start": 386,
"char_end": 387,
"chars": "'"
},
{
"char_start": 390,
"char_end": 392,
"chars": " %"
},
{
"char_start": 427,
"char_end": 454,
"chars": "\n cursor.execute(sql"
}
],
"added": [
{
"char_start": 284,
"char_end": 287,
"chars": "cur"
},
{
"char_start": 288,
"char_end": 299,
"chars": "or.execute("
},
{
"char_start": 359,
"char_end": 360,
"chars": "s"
},
{
"char_start": 362,
"char_end": 363,
"chars": "s"
},
{
"char_start": 372,
"char_end": 373,
"chars": ","
}
]
} | github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9 | flaskr/flaskr/views/comment.py | cwe-089 |
get_mod_taken_together_with | def get_mod_taken_together_with(code):
'''
Retrieves the list of modules taken together with the specified
module code in the same semester.
Returns a table of lists (up to 10 top results). Each list contains
(specified code, module code of mod taken together, aySem, number of students)
e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students
taking CS1010 and CS1231 together in AY 16/17 Sem 1.
'''
NUM_TOP_RESULTS_TO_RETURN = 10
sql_command = "SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) " + \
"FROM studentPlans sp1, studentPlans sp2 " + \
"WHERE sp1.moduleCode = '" + code + "' AND " + \
"sp2.moduleCode <> sp1.moduleCode AND " + \
"sp1.studentId = sp2.studentId AND " + \
"sp1.acadYearAndSem = sp2.acadYearAndSem " + \
"GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem " + \
"ORDER BY COUNT(*) DESC"
DB_CURSOR.execute(sql_command)
return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN) | def get_mod_taken_together_with(code):
'''
Retrieves the list of modules taken together with the specified
module code in the same semester.
Returns a table of lists (up to 10 top results). Each list contains
(specified code, module code of mod taken together, aySem, number of students)
e.g. [(CS1010, CS1231, AY 16/17 Sem 1, 5)] means there are 5 students
taking CS1010 and CS1231 together in AY 16/17 Sem 1.
'''
NUM_TOP_RESULTS_TO_RETURN = 10
sql_command = "SELECT sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem, COUNT(*) " + \
"FROM studentPlans sp1, studentPlans sp2 " + \
"WHERE sp1.moduleCode = %s AND " + \
"sp2.moduleCode <> sp1.moduleCode AND " + \
"sp1.studentId = sp2.studentId AND " + \
"sp1.acadYearAndSem = sp2.acadYearAndSem " + \
"GROUP BY sp1.moduleCode, sp2.moduleCode, sp1.acadYearAndSem " + \
"ORDER BY COUNT(*) DESC"
DB_CURSOR.execute(sql_command, (code,))
return DB_CURSOR.fetchmany(NUM_TOP_RESULTS_TO_RETURN) | {
"deleted": [
{
"line_no": 16,
"char_start": 665,
"char_end": 730,
"line": " \"WHERE sp1.moduleCode = '\" + code + \"' AND \" + \\\n"
},
{
"line_no": 23,
"char_start": 1035,
"char_end": 1070,
"line": " DB_CURSOR.execute(sql_command)\n"
}
],
"added": [
{
"line_no": 16,
"char_start": 665,
"char_end": 718,
"line": " \"WHERE sp1.moduleCode = %s AND \" + \\\n"
},
{
"line_no": 23,
"char_start": 1023,
"char_end": 1067,
"line": " DB_CURSOR.execute(sql_command, (code,))\n"
}
]
} | {
"deleted": [
{
"char_start": 705,
"char_end": 719,
"chars": "'\" + code + \"'"
}
],
"added": [
{
"char_start": 705,
"char_end": 707,
"chars": "%s"
},
{
"char_start": 1056,
"char_end": 1065,
"chars": ", (code,)"
}
]
} | github.com/nus-mtp/cs-modify/commit/79b4b1dd7eba5445751808e4c50b49d2dd08366b | components/model.py | cwe-089 |
wins | @endpoints.route("/wins")
def wins():
if db == None:
init()
player = request.args.get('tag', default="christmasmike")
sql = "SELECT * FROM matches WHERE winner = '"+str(player)+"' ORDER BY date DESC;"
result = db.exec(sql)
result = [str(x) for x in result]
result = '\n'.join(result)
return json.dumps(result) | @endpoints.route("/wins")
def wins():
if db == None:
init()
player = request.args.get('tag', default="christmasmike")
sql = "SELECT * FROM matches WHERE winner = '{player}' ORDER BY date DESC;"
args = {'player': player}
result = db.exec(sql, args)
result = [str(x) for x in result]
result = '\n'.join(result)
return json.dumps(result) | {
"deleted": [
{
"line_no": 7,
"char_start": 135,
"char_end": 222,
"line": " sql = \"SELECT * FROM matches WHERE winner = '\"+str(player)+\"' ORDER BY date DESC;\"\n"
},
{
"line_no": 8,
"char_start": 222,
"char_end": 248,
"line": " result = db.exec(sql)\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 135,
"char_end": 215,
"line": " sql = \"SELECT * FROM matches WHERE winner = '{player}' ORDER BY date DESC;\"\n"
},
{
"line_no": 8,
"char_start": 215,
"char_end": 245,
"line": " args = {'player': player}\n"
},
{
"line_no": 9,
"char_start": 245,
"char_end": 277,
"line": " result = db.exec(sql, args)\n"
}
]
} | {
"deleted": [
{
"char_start": 184,
"char_end": 190,
"chars": "\"+str("
},
{
"char_start": 196,
"char_end": 199,
"chars": ")+\""
}
],
"added": [
{
"char_start": 184,
"char_end": 185,
"chars": "{"
},
{
"char_start": 191,
"char_end": 192,
"chars": "}"
},
{
"char_start": 219,
"char_end": 249,
"chars": "args = {'player': player}\n "
},
{
"char_start": 269,
"char_end": 275,
"chars": ", args"
}
]
} | github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63 | endpoints.py | cwe-089 |
delete_event | def delete_event(self, event_id):
sql = """DELETE FROM events
WHERE event_id = {0}
""".format(event_id)
affected_count = self.cur.execute(sql)
self.conn.commit()
return affected_count | def delete_event(self, event_id):
sql = """
DELETE FROM events
WHERE event_id = %s
"""
affected_count = self.cur.execute(sql, (event_id,))
self.conn.commit()
return affected_count | {
"deleted": [
{
"line_no": 2,
"char_start": 38,
"char_end": 74,
"line": " sql = \"\"\"DELETE FROM events\n"
},
{
"line_no": 3,
"char_start": 74,
"char_end": 112,
"line": " WHERE event_id = {0}\n"
},
{
"line_no": 4,
"char_start": 112,
"char_end": 150,
"line": " \"\"\".format(event_id)\n"
},
{
"line_no": 5,
"char_start": 150,
"char_end": 197,
"line": " affected_count = self.cur.execute(sql)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 38,
"char_end": 56,
"line": " sql = \"\"\"\n"
},
{
"line_no": 3,
"char_start": 56,
"char_end": 89,
"line": " DELETE FROM events\n"
},
{
"line_no": 4,
"char_start": 89,
"char_end": 123,
"line": " WHERE event_id = %s\n"
},
{
"line_no": 5,
"char_start": 123,
"char_end": 141,
"line": " \"\"\"\n"
},
{
"line_no": 6,
"char_start": 141,
"char_end": 201,
"line": " affected_count = self.cur.execute(sql, (event_id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 88,
"char_end": 91,
"chars": " "
},
{
"char_start": 108,
"char_end": 111,
"chars": "{0}"
},
{
"char_start": 112,
"char_end": 115,
"chars": " "
},
{
"char_start": 132,
"char_end": 149,
"chars": ".format(event_id)"
}
],
"added": [
{
"char_start": 55,
"char_end": 70,
"chars": "\n "
},
{
"char_start": 120,
"char_end": 122,
"chars": "%s"
},
{
"char_start": 186,
"char_end": 199,
"chars": ", (event_id,)"
}
]
} | github.com/jgayfer/spirit/commit/01c846c534c8d3cf6763f8b7444a0efe2caa3799 | db/dbase.py | cwe-089 |
add_item | def add_item(self, item):
""""Add new item."""
if self.connection:
self.cursor.execute('insert into item (name, shoppinglistid) values ("%s", "%s")' % (item[0], item[1]))
self.connection.commit() | def add_item(self, item):
""""Add new item."""
if self.connection:
t = (item[0], item[1], )
self.cursor.execute('insert into item (name, shoppinglistid) values (?, ?)', t)
self.connection.commit() | {
"deleted": [
{
"line_no": 4,
"char_start": 87,
"char_end": 203,
"line": " self.cursor.execute('insert into item (name, shoppinglistid) values (\"%s\", \"%s\")' % (item[0], item[1]))\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 87,
"char_end": 124,
"line": " t = (item[0], item[1], )\n"
},
{
"line_no": 5,
"char_start": 124,
"char_end": 216,
"line": " self.cursor.execute('insert into item (name, shoppinglistid) values (?, ?)', t)\n"
}
]
} | {
"deleted": [
{
"char_start": 168,
"char_end": 172,
"chars": "\"%s\""
},
{
"char_start": 174,
"char_end": 178,
"chars": "\"%s\""
},
{
"char_start": 180,
"char_end": 191,
"chars": " % (item[0]"
},
{
"char_start": 193,
"char_end": 194,
"chars": "i"
},
{
"char_start": 195,
"char_end": 201,
"chars": "em[1])"
}
],
"added": [
{
"char_start": 99,
"char_end": 136,
"chars": "t = (item[0], item[1], )\n "
},
{
"char_start": 205,
"char_end": 206,
"chars": "?"
},
{
"char_start": 208,
"char_end": 209,
"chars": "?"
}
]
} | github.com/ecosl-developers/ecosl/commit/8af050a513338bf68ff2a243e4a2482d24e9aa3a | ecosldb/ecosldb.py | cwe-089 |
fetch_issue | def fetch_issue(cursor, id):
"""
Fetch an issue by id along with its tags. Returns None if no issue
with the specified id exists in the database.
"""
cursor.execute(f"""
SELECT
issue.id,
issue.title,
issue.description,
tag.namespace,
tag.predicate,
tag.value
FROM
issue LEFT JOIN tag
ON issue.id = tag.issue_id
WHERE
issue.id = {id}
""")
issue = None
for row in cursor:
if issue is None:
issue = {
"id": row["id"],
"title": row["title"],
"description": row["description"],
"tags": [],
}
# If tag exists in row, add to issue.
if row["value"]:
issue["tags"].append({
"namespace": row["namespace"],
"predicate": row["predicate"],
"value": row["value"],
})
return issue | def fetch_issue(cursor, id):
"""
Fetch an issue by id along with its tags. Returns None if no issue
with the specified id exists in the database.
"""
cursor.execute("""
SELECT
issue.id,
issue.title,
issue.description,
tag.namespace,
tag.predicate,
tag.value
FROM
issue LEFT JOIN tag
ON issue.id = tag.issue_id
WHERE
issue.id = ?
""", (id,))
issue = None
for row in cursor:
if issue is None:
issue = {
"id": row["id"],
"title": row["title"],
"description": row["description"],
"tags": [],
}
# If tag exists in row, add to issue.
if row["value"]:
issue["tags"].append({
"namespace": row["namespace"],
"predicate": row["predicate"],
"value": row["value"],
})
return issue | {
"deleted": [
{
"line_no": 6,
"char_start": 166,
"char_end": 190,
"line": " cursor.execute(f\"\"\"\n"
},
{
"line_no": 18,
"char_start": 457,
"char_end": 485,
"line": " issue.id = {id}\n"
},
{
"line_no": 19,
"char_start": 485,
"char_end": 494,
"line": " \"\"\")\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 166,
"char_end": 189,
"line": " cursor.execute(\"\"\"\n"
},
{
"line_no": 18,
"char_start": 456,
"char_end": 481,
"line": " issue.id = ?\n"
},
{
"line_no": 19,
"char_start": 481,
"char_end": 497,
"line": " \"\"\", (id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 185,
"char_end": 186,
"chars": "f"
},
{
"char_start": 480,
"char_end": 484,
"chars": "{id}"
}
],
"added": [
{
"char_start": 479,
"char_end": 480,
"chars": "?"
},
{
"char_start": 488,
"char_end": 495,
"chars": ", (id,)"
}
]
} | github.com/nutty7t/tissue/commit/306dd094749bb39cbd5c74a6ded3d3b191033061 | server/server.py | cwe-089 |
also_add | def also_add(name, also):
db = db_connect()
cursor = db.cursor()
try:
cursor.execute('''
INSERT INTO isalso(name,also) VALUES('{}','{}')
'''.format(name, also))
db.commit()
logger.debug('added to isalso name {} with value {}'.format(
name, also))
db.close()
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise | def also_add(name, also):
db = db_connect()
cursor = db.cursor()
try:
cursor.execute('''
INSERT INTO isalso(name,also) VALUES(%(name)s,%(also)s)
''', (
name,
also,
))
db.commit()
logger.debug('added to isalso name {} with value {}'.format(
name, also))
db.close()
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise | {
"deleted": [
{
"line_no": 6,
"char_start": 109,
"char_end": 169,
"line": " INSERT INTO isalso(name,also) VALUES('{}','{}')\n"
},
{
"line_no": 7,
"char_start": 169,
"char_end": 205,
"line": " '''.format(name, also))\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 109,
"char_end": 177,
"line": " INSERT INTO isalso(name,also) VALUES(%(name)s,%(also)s)\n"
},
{
"line_no": 7,
"char_start": 177,
"char_end": 196,
"line": " ''', (\n"
},
{
"line_no": 8,
"char_start": 196,
"char_end": 214,
"line": " name,\n"
},
{
"line_no": 9,
"char_start": 214,
"char_end": 232,
"line": " also,\n"
},
{
"line_no": 10,
"char_start": 232,
"char_end": 243,
"line": " ))\n"
}
]
} | {
"deleted": [
{
"char_start": 158,
"char_end": 162,
"chars": "'{}'"
},
{
"char_start": 163,
"char_end": 167,
"chars": "'{}'"
},
{
"char_start": 184,
"char_end": 191,
"chars": ".format"
}
],
"added": [
{
"char_start": 158,
"char_end": 166,
"chars": "%(name)s"
},
{
"char_start": 167,
"char_end": 175,
"chars": "%(also)s"
},
{
"char_start": 192,
"char_end": 194,
"chars": ", "
},
{
"char_start": 195,
"char_end": 208,
"chars": "\n "
},
{
"char_start": 213,
"char_end": 225,
"chars": "\n "
},
{
"char_start": 230,
"char_end": 240,
"chars": ",\n "
}
]
} | github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a | KarmaBoi/dbopts.py | cwe-089 |
getCommentsLike | def getCommentsLike(self,commentid):
sqlText="select userid from comment_like where commentid=%d"%(commentid)
result=sql.queryDB(self.conn,sqlText)
return result; | def getCommentsLike(self,commentid):
sqlText="select userid from comment_like where commentid=%s"
params=[commentid]
result=sql.queryDB(self.conn,sqlText,params)
return result; | {
"deleted": [
{
"line_no": 2,
"char_start": 41,
"char_end": 122,
"line": " sqlText=\"select userid from comment_like where commentid=%d\"%(commentid)\n"
},
{
"line_no": 3,
"char_start": 122,
"char_end": 168,
"line": " result=sql.queryDB(self.conn,sqlText)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 41,
"char_end": 110,
"line": " sqlText=\"select userid from comment_like where commentid=%s\"\n"
},
{
"line_no": 3,
"char_start": 110,
"char_end": 137,
"line": " params=[commentid]\n"
},
{
"line_no": 4,
"char_start": 137,
"char_end": 190,
"line": " result=sql.queryDB(self.conn,sqlText,params)\n"
}
]
} | {
"deleted": [
{
"char_start": 107,
"char_end": 108,
"chars": "d"
},
{
"char_start": 109,
"char_end": 111,
"chars": "%("
},
{
"char_start": 120,
"char_end": 121,
"chars": ")"
}
],
"added": [
{
"char_start": 107,
"char_end": 108,
"chars": "s"
},
{
"char_start": 109,
"char_end": 126,
"chars": "\n params=["
},
{
"char_start": 135,
"char_end": 136,
"chars": "]"
},
{
"char_start": 181,
"char_end": 188,
"chars": ",params"
}
]
} | github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9 | modules/comment.py | cwe-089 |
update_theory_base | def update_theory_base(tag, link):
theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\theory.db")
conn = theory.cursor()
conn.execute("insert into " + str(tag) + " values (?)", (str(link), ))
theory.commit()
theory.close() | def update_theory_base(tag, link):
theory = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\theory.db")
conn = theory.cursor()
conn.execute("insert into ? values (?)", (tag, str(link)))
theory.commit()
theory.close() | {
"deleted": [
{
"line_no": 4,
"char_start": 151,
"char_end": 226,
"line": " conn.execute(\"insert into \" + str(tag) + \" values (?)\", (str(link), ))\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 151,
"char_end": 214,
"line": " conn.execute(\"insert into ? values (?)\", (tag, str(link)))\n"
}
]
} | {
"deleted": [
{
"char_start": 181,
"char_end": 197,
"chars": "\" + str(tag) + \""
},
{
"char_start": 221,
"char_end": 223,
"chars": ", "
}
],
"added": [
{
"char_start": 181,
"char_end": 182,
"chars": "?"
},
{
"char_start": 197,
"char_end": 202,
"chars": "tag, "
}
]
} | github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90 | bases/update.py | cwe-089 |
get_asset_and_volume | @app.route('/get_asset_and_volume')
def get_asset_and_volume():
asset_id = request.args.get('asset_id')
if not isObject(asset_id):
ws.send('{"id":1, "method":"call", "params":[0,"lookup_asset_symbols",[["' + asset_id + '"], 0]]}')
result_l = ws.recv()
j_l = json.loads(result_l)
asset_id = j_l["result"][0]["id"]
#print asset_id
ws.send('{"id":1, "method":"call", "params":[0,"get_assets",[["' + asset_id + '"], 0]]}')
result = ws.recv()
j = json.loads(result)
dynamic_asset_data_id = j["result"][0]["dynamic_asset_data_id"]
ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+dynamic_asset_data_id+'"]]]}')
result2 = ws.recv()
j2 = json.loads(result2)
#print j2["result"][0]["current_supply"]
j["result"][0]["current_supply"] = j2["result"][0]["current_supply"]
j["result"][0]["confidential_supply"] = j2["result"][0]["confidential_supply"]
#print j["result"]
j["result"][0]["accumulated_fees"] = j2["result"][0]["accumulated_fees"]
j["result"][0]["fee_pool"] = j2["result"][0]["fee_pool"]
issuer = j["result"][0]["issuer"]
ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+issuer+'"]]]}')
result3 = ws.recv()
j3 = json.loads(result3)
j["result"][0]["issuer_name"] = j3["result"][0]["name"]
con = psycopg2.connect(**config.POSTGRES)
cur = con.cursor()
query = "SELECT volume, mcap FROM assets WHERE aid='"+asset_id+"'"
cur.execute(query)
results = cur.fetchall()
con.close()
try:
j["result"][0]["volume"] = results[0][0]
j["result"][0]["mcap"] = results[0][1]
except:
j["result"][0]["volume"] = 0
j["result"][0]["mcap"] = 0
return jsonify(j["result"]) | @app.route('/get_asset_and_volume')
def get_asset_and_volume():
asset_id = request.args.get('asset_id')
if not isObject(asset_id):
ws.send('{"id":1, "method":"call", "params":[0,"lookup_asset_symbols",[["' + asset_id + '"], 0]]}')
result_l = ws.recv()
j_l = json.loads(result_l)
asset_id = j_l["result"][0]["id"]
#print asset_id
ws.send('{"id":1, "method":"call", "params":[0,"get_assets",[["' + asset_id + '"], 0]]}')
result = ws.recv()
j = json.loads(result)
dynamic_asset_data_id = j["result"][0]["dynamic_asset_data_id"]
ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+dynamic_asset_data_id+'"]]]}')
result2 = ws.recv()
j2 = json.loads(result2)
#print j2["result"][0]["current_supply"]
j["result"][0]["current_supply"] = j2["result"][0]["current_supply"]
j["result"][0]["confidential_supply"] = j2["result"][0]["confidential_supply"]
#print j["result"]
j["result"][0]["accumulated_fees"] = j2["result"][0]["accumulated_fees"]
j["result"][0]["fee_pool"] = j2["result"][0]["fee_pool"]
issuer = j["result"][0]["issuer"]
ws.send('{"id": 1, "method": "call", "params": [0, "get_objects", [["'+issuer+'"]]]}')
result3 = ws.recv()
j3 = json.loads(result3)
j["result"][0]["issuer_name"] = j3["result"][0]["name"]
con = psycopg2.connect(**config.POSTGRES)
cur = con.cursor()
query = "SELECT volume, mcap FROM assets WHERE aid=%s"
cur.execute(query, (asset_id,))
results = cur.fetchall()
con.close()
try:
j["result"][0]["volume"] = results[0][0]
j["result"][0]["mcap"] = results[0][1]
except:
j["result"][0]["volume"] = 0
j["result"][0]["mcap"] = 0
return jsonify(j["result"]) | {
"deleted": [
{
"line_no": 40,
"char_start": 1428,
"char_end": 1499,
"line": " query = \"SELECT volume, mcap FROM assets WHERE aid='\"+asset_id+\"'\"\n"
},
{
"line_no": 41,
"char_start": 1499,
"char_end": 1522,
"line": " cur.execute(query)\n"
}
],
"added": [
{
"line_no": 40,
"char_start": 1428,
"char_end": 1487,
"line": " query = \"SELECT volume, mcap FROM assets WHERE aid=%s\"\n"
},
{
"line_no": 41,
"char_start": 1487,
"char_end": 1523,
"line": " cur.execute(query, (asset_id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 1483,
"char_end": 1487,
"chars": "'\"+a"
},
{
"char_start": 1488,
"char_end": 1497,
"chars": "set_id+\"'"
}
],
"added": [
{
"char_start": 1483,
"char_end": 1484,
"chars": "%"
},
{
"char_start": 1508,
"char_end": 1521,
"chars": ", (asset_id,)"
}
]
} | github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60 | api.py | cwe-089 |
reportMatch | def reportMatch(winner, loser):
"""Records the outcome of a single match between two players.
Args:
winner: the id number of the player who won
loser: the id number of the player who lost
"""
try:
int(winner)
int(loser)
except ValueError:
raise ValueError(
"\"winner\" and/or \"loser\" input are not integers.\n"
"Please use the id number of each player to report match results."
)
w = str(winner)
l = str(loser)
db = connect()
c = db.cursor()
statement = "INSERT INTO matches values ({w}, {l})".format(w=w, l=l)
c.execute(statement)
db.commit()
db.close() | def reportMatch(winner, loser):
"""Records the outcome of a single match between two players.
Args:
winner: the id number of the player who won
loser: the id number of the player who lost
"""
try:
int(winner)
int(loser)
except ValueError:
raise ValueError(
"\"winner\" and/or \"loser\" input are not integers.\n"
"Please use the id number of each player to report match results."
)
w = str(winner)
l = str(loser)
db = connect()
c = db.cursor()
c.execute("INSERT INTO matches values (%s, %s)", (w,l))
db.commit()
db.close() | {
"deleted": [
{
"line_no": 20,
"char_start": 551,
"char_end": 624,
"line": " statement = \"INSERT INTO matches values ({w}, {l})\".format(w=w, l=l)\n"
},
{
"line_no": 21,
"char_start": 624,
"char_end": 649,
"line": " c.execute(statement)\n"
}
],
"added": [
{
"line_no": 20,
"char_start": 551,
"char_end": 611,
"line": " c.execute(\"INSERT INTO matches values (%s, %s)\", (w,l))\n"
}
]
} | {
"deleted": [
{
"char_start": 555,
"char_end": 559,
"chars": "stat"
},
{
"char_start": 560,
"char_end": 561,
"chars": "m"
},
{
"char_start": 562,
"char_end": 563,
"chars": "n"
},
{
"char_start": 564,
"char_end": 567,
"chars": " = "
},
{
"char_start": 596,
"char_end": 599,
"chars": "{w}"
},
{
"char_start": 601,
"char_end": 604,
"chars": "{l}"
},
{
"char_start": 606,
"char_end": 613,
"chars": ".format"
},
{
"char_start": 615,
"char_end": 617,
"chars": "=w"
},
{
"char_start": 618,
"char_end": 621,
"chars": " l="
},
{
"char_start": 623,
"char_end": 647,
"chars": "\n c.execute(statement"
}
],
"added": [
{
"char_start": 555,
"char_end": 557,
"chars": "c."
},
{
"char_start": 558,
"char_end": 559,
"chars": "x"
},
{
"char_start": 560,
"char_end": 562,
"chars": "cu"
},
{
"char_start": 563,
"char_end": 565,
"chars": "e("
},
{
"char_start": 594,
"char_end": 596,
"chars": "%s"
},
{
"char_start": 598,
"char_end": 600,
"chars": "%s"
},
{
"char_start": 602,
"char_end": 604,
"chars": ", "
}
]
} | github.com/tdnelson2/tournament-db/commit/00f3caeed0e12e806c2808d100908698777d9e98 | tournament.py | cwe-089 |
getPlayer | def getPlayer(player):
db.execute("SELECT * FROM players WHERE Name = '%s' COLLATE NOCASE" % player)
playerstats = dict(db.fetchone())
return playerstats | def getPlayer(player):
db.execute("SELECT * FROM players WHERE Name = ? COLLATE NOCASE", player)
playerstats = dict(db.fetchone())
return playerstats | {
"deleted": [
{
"line_no": 2,
"char_start": 23,
"char_end": 102,
"line": "\tdb.execute(\"SELECT * FROM players WHERE Name = '%s' COLLATE NOCASE\" % player)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 23,
"char_end": 98,
"line": "\tdb.execute(\"SELECT * FROM players WHERE Name = ? COLLATE NOCASE\", player)\n"
}
]
} | {
"deleted": [
{
"char_start": 71,
"char_end": 75,
"chars": "'%s'"
},
{
"char_start": 91,
"char_end": 93,
"chars": " %"
}
],
"added": [
{
"char_start": 71,
"char_end": 72,
"chars": "?"
},
{
"char_start": 88,
"char_end": 89,
"chars": ","
}
]
} | github.com/iScrE4m/XLeague/commit/59cab6e5fd8bd5e47f2418a7c71cb1d4e3cad0d2 | plugins/database.py | cwe-089 |
karma_sub | def karma_sub(name):
karma = karma_ask(name)
db = db_connect()
cursor = db.cursor()
if karma is None:
try:
cursor.execute('''
INSERT INTO people(name,karma,shame) VALUES('{}',-1,0)
'''.format(name))
db.commit()
logger.debug('Inserted into karmadb -1 karma for {}'.format(name))
db.close()
return -1
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise
else:
karma = karma - 1
try:
cursor.execute('''
UPDATE people SET karma = {0} WHERE name = '{1}'
'''.format(karma, name))
db.commit()
logger.debug('Inserted into karmadb -1 karma for {}'.format(name))
db.close()
return karma
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise | def karma_sub(name):
karma = karma_ask(name)
db = db_connect()
cursor = db.cursor()
if karma is None:
try:
cursor.execute('''
INSERT INTO people(name,karma,shame) VALUES(%(name)s,-1,0)
''', (name, ))
db.commit()
logger.debug('Inserted into karmadb -1 karma for {}'.format(name))
db.close()
return -1
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise
else:
karma = karma - 1
try:
cursor.execute('''
UPDATE people SET karma = %(karma)s WHERE name = %(name)s
''', (
karma,
name,
))
db.commit()
logger.debug('Inserted into karmadb -1 karma for {}'.format(name))
db.close()
return karma
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise | {
"deleted": [
{
"line_no": 8,
"char_start": 162,
"char_end": 233,
"line": " INSERT INTO people(name,karma,shame) VALUES('{}',-1,0)\n"
},
{
"line_no": 9,
"char_start": 233,
"char_end": 267,
"line": " '''.format(name))\n"
},
{
"line_no": 22,
"char_start": 615,
"char_end": 680,
"line": " UPDATE people SET karma = {0} WHERE name = '{1}'\n"
},
{
"line_no": 23,
"char_start": 680,
"char_end": 721,
"line": " '''.format(karma, name))\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 162,
"char_end": 237,
"line": " INSERT INTO people(name,karma,shame) VALUES(%(name)s,-1,0)\n"
},
{
"line_no": 9,
"char_start": 237,
"char_end": 268,
"line": " ''', (name, ))\n"
},
{
"line_no": 22,
"char_start": 616,
"char_end": 690,
"line": " UPDATE people SET karma = %(karma)s WHERE name = %(name)s\n"
},
{
"line_no": 23,
"char_start": 690,
"char_end": 713,
"line": " ''', (\n"
},
{
"line_no": 24,
"char_start": 713,
"char_end": 736,
"line": " karma,\n"
},
{
"line_no": 25,
"char_start": 736,
"char_end": 758,
"line": " name,\n"
},
{
"line_no": 26,
"char_start": 758,
"char_end": 773,
"line": " ))\n"
}
]
} | {
"deleted": [
{
"char_start": 222,
"char_end": 226,
"chars": "'{}'"
},
{
"char_start": 252,
"char_end": 259,
"chars": ".format"
},
{
"char_start": 657,
"char_end": 660,
"chars": "{0}"
},
{
"char_start": 674,
"char_end": 679,
"chars": "'{1}'"
},
{
"char_start": 699,
"char_end": 706,
"chars": ".format"
}
],
"added": [
{
"char_start": 222,
"char_end": 230,
"chars": "%(name)s"
},
{
"char_start": 256,
"char_end": 258,
"chars": ", "
},
{
"char_start": 263,
"char_end": 265,
"chars": ", "
},
{
"char_start": 658,
"char_end": 667,
"chars": "%(karma)s"
},
{
"char_start": 681,
"char_end": 689,
"chars": "%(name)s"
},
{
"char_start": 709,
"char_end": 711,
"chars": ", "
},
{
"char_start": 712,
"char_end": 729,
"chars": "\n "
},
{
"char_start": 735,
"char_end": 751,
"chars": "\n "
},
{
"char_start": 756,
"char_end": 770,
"chars": ",\n "
}
]
} | github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a | KarmaBoi/dbopts.py | cwe-089 |
login | @app.route('/', methods=['POST'])
def login():
print('login')
user = str(request.form['username'])
password = str(request.form['password'])
cur.execute('SELECT * FROM users WHERE name = \'{}\' AND password = \'{}\';'.format(user, password))
response = cur.fetchone()
if response != None:
print(response, 'OK')
return redirect(url_for('enter_test_point'))
else:
print(response, 'not OK')
flash('Invalid login or password')
return render_template('login.html') | @app.route('/', methods=['POST'])
def login():
print('login')
user = str(request.form['username'])
password = str(request.form['password'])
cur.execute("SELECT * FROM users WHERE name = ? AND password = ?;", [user, password])
response = cur.fetchone()
if response != None:
print(response, 'OK')
return redirect(url_for('enter_test_point'))
else:
print(response, 'not OK')
flash('Invalid login or password')
return render_template('login.html') | {
"deleted": [
{
"line_no": 6,
"char_start": 152,
"char_end": 257,
"line": " cur.execute('SELECT * FROM users WHERE name = \\'{}\\' AND password = \\'{}\\';'.format(user, password))\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 152,
"char_end": 242,
"line": " cur.execute(\"SELECT * FROM users WHERE name = ? AND password = ?;\", [user, password])\n"
}
]
} | {
"deleted": [
{
"char_start": 168,
"char_end": 169,
"chars": "'"
},
{
"char_start": 202,
"char_end": 208,
"chars": "\\'{}\\'"
},
{
"char_start": 224,
"char_end": 230,
"chars": "\\'{}\\'"
},
{
"char_start": 231,
"char_end": 240,
"chars": "'.format("
},
{
"char_start": 254,
"char_end": 255,
"chars": ")"
}
],
"added": [
{
"char_start": 168,
"char_end": 169,
"chars": "\""
},
{
"char_start": 202,
"char_end": 203,
"chars": "?"
},
{
"char_start": 219,
"char_end": 220,
"chars": "?"
},
{
"char_start": 221,
"char_end": 225,
"chars": "\", ["
},
{
"char_start": 239,
"char_end": 240,
"chars": "]"
}
]
} | github.com/ChemiKyle/Waterspots/commit/3f9d5099496336f3f34c48abf0cf55acaaa29011 | app.py | cwe-089 |
fetch_data | def fetch_data(self, session, id):
self._openContainer(session)
sid = str(id)
if (self.idNormalizer is not None):
sid = self.idNormalizer.process_string(session, sid)
query = ("SELECT data FROM %s WHERE identifier = '%s';" %
(self.table, sid)
)
res = self._query(query)
try:
data = res.dictresult()[0]['data']
except IndexError:
raise ObjectDoesNotExistException(id)
try:
ndata = pg.unescape_bytea(data)
except:
# insufficient PyGreSQL version
ndata = data.replace("\\'", "'")
ndata = ndata.replace('\\000\\001', nonTextToken)
ndata = ndata.replace('\\012', '\n')
return ndata | def fetch_data(self, session, id):
self._openContainer(session)
sid = str(id)
if (self.idNormalizer is not None):
sid = self.idNormalizer.process_string(session, sid)
query = ("SELECT data FROM %s WHERE identifier = $1;" %
(self.table)
)
res = self._query(query, sid)
try:
data = res.dictresult()[0]['data']
except IndexError:
raise ObjectDoesNotExistException(id)
try:
ndata = pg.unescape_bytea(data)
except:
# insufficient PyGreSQL version
ndata = data.replace("\\'", "'")
ndata = ndata.replace('\\000\\001', nonTextToken)
ndata = ndata.replace('\\012', '\n')
return ndata | {
"deleted": [
{
"line_no": 6,
"char_start": 207,
"char_end": 273,
"line": " query = (\"SELECT data FROM %s WHERE identifier = '%s';\" %\n"
},
{
"line_no": 7,
"char_start": 273,
"char_end": 308,
"line": " (self.table, sid)\n"
},
{
"line_no": 9,
"char_start": 327,
"char_end": 360,
"line": " res = self._query(query)\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 207,
"char_end": 271,
"line": " query = (\"SELECT data FROM %s WHERE identifier = $1;\" %\n"
},
{
"line_no": 7,
"char_start": 271,
"char_end": 301,
"line": " (self.table)\n"
},
{
"line_no": 9,
"char_start": 320,
"char_end": 358,
"line": " res = self._query(query, sid)\n"
}
]
} | {
"deleted": [
{
"char_start": 264,
"char_end": 268,
"chars": "'%s'"
},
{
"char_start": 301,
"char_end": 306,
"chars": ", sid"
}
],
"added": [
{
"char_start": 264,
"char_end": 266,
"chars": "$1"
},
{
"char_start": 351,
"char_end": 356,
"chars": ", sid"
}
]
} | github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e | cheshire3/sql/postgresStore.py | cwe-089 |
registerPlayer | def registerPlayer(name):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
"""
conn = connect()
cursor = conn.cursor()
cursor.execute("INSERT INTO players (name) VALUES ('%s')" % (name,));
conn.commit()
conn.close() | def registerPlayer(name):
"""Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique).
"""
conn = connect()
cursor = conn.cursor()
query = "INSERT INTO players (name) VALUES (%s);"
cursor.execute(query, (name,))
conn.commit()
conn.close() | {
"deleted": [
{
"line_no": 12,
"char_start": 351,
"char_end": 425,
"line": " cursor.execute(\"INSERT INTO players (name) VALUES ('%s')\" % (name,));\n"
}
],
"added": [
{
"line_no": 12,
"char_start": 351,
"char_end": 405,
"line": " query = \"INSERT INTO players (name) VALUES (%s);\"\n"
},
{
"line_no": 13,
"char_start": 405,
"char_end": 440,
"line": " cursor.execute(query, (name,))\n"
}
]
} | {
"deleted": [
{
"char_start": 355,
"char_end": 356,
"chars": "c"
},
{
"char_start": 357,
"char_end": 360,
"chars": "rso"
},
{
"char_start": 361,
"char_end": 370,
"chars": ".execute("
},
{
"char_start": 406,
"char_end": 407,
"chars": "'"
},
{
"char_start": 409,
"char_end": 410,
"chars": "'"
},
{
"char_start": 413,
"char_end": 414,
"chars": "%"
},
{
"char_start": 423,
"char_end": 424,
"chars": ";"
}
],
"added": [
{
"char_start": 355,
"char_end": 356,
"chars": "q"
},
{
"char_start": 358,
"char_end": 363,
"chars": "ry = "
},
{
"char_start": 402,
"char_end": 403,
"chars": ";"
},
{
"char_start": 404,
"char_end": 405,
"chars": "\n"
},
{
"char_start": 406,
"char_end": 430,
"chars": " cursor.execute(query,"
}
]
} | github.com/sarahkcaplan/tournament/commit/40aba5686059f5f398f6323b1483412c56140cc0 | tournament.py | cwe-089 |
register | @mod.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
error = None
email = request.form['email'].strip()
nickname = request.form['nickname'].strip()
password = request.form['password'].strip()
password2 = request.form['password2'].strip()
email = email.lower()
if email == "" or nickname == "" or password == "" or password2 == "":
error = 'Please input all the information'
elif password2 != password:
error = 'The password is not repeated correctly'
elif len(password) < 6:
error = 'The password has at least 6 characters'
elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +
'[0-9a-zA-Z]{1,15}\.[com,cn,net]', email):
error = 'Please input the right email'
sql = "SELECT * FROM users where email = '%s';" % (email)
cursor.execute(sql)
u = cursor.fetchone()
if u is not None:
error = 'The email has already exsit'
if error is not None:
return render_template('register.html', error=error)
else:
password = bcrypt.generate_password_hash(password)
cursor.execute("INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);", (email, nickname, password))
conn.commit()
flash('Register Success!')
return redirect(url_for('users.login'))
return render_template('register.html') | @mod.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
error = None
email = request.form['email'].strip()
nickname = request.form['nickname'].strip()
password = request.form['password'].strip()
password2 = request.form['password2'].strip()
email = email.lower()
if email == "" or nickname == "" or password == "" or password2 == "":
error = 'Please input all the information'
elif password2 != password:
error = 'The password is not repeated correctly'
elif len(password) < 6:
error = 'The password has at least 6 characters'
elif not re.match(r'^[0-9a-zA-Z_]{0,19}@' +
'[0-9a-zA-Z]{1,15}\.[com,cn,net]', email):
error = 'Please input the right email'
cursor.execute("SELECT * FROM users where email = %s;", (email,))
u = cursor.fetchone()
if u is not None:
error = 'The email has already exsit'
if error is not None:
return render_template('register.html', error=error)
else:
password = bcrypt.generate_password_hash(password)
cursor.execute("INSERT INTO users(email,nickname,password) VALUES(%s,%s,%s);", (email, nickname, password))
conn.commit()
flash('Register Success!')
return redirect(url_for('users.login'))
return render_template('register.html') | {
"deleted": [
{
"line_no": 22,
"char_start": 852,
"char_end": 918,
"line": " sql = \"SELECT * FROM users where email = '%s';\" % (email)\n"
},
{
"line_no": 23,
"char_start": 918,
"char_end": 946,
"line": " cursor.execute(sql)\n"
}
],
"added": [
{
"line_no": 22,
"char_start": 852,
"char_end": 926,
"line": " cursor.execute(\"SELECT * FROM users where email = %s;\", (email,))\n"
}
]
} | {
"deleted": [
{
"char_start": 861,
"char_end": 866,
"chars": "ql = "
},
{
"char_start": 901,
"char_end": 902,
"chars": "'"
},
{
"char_start": 904,
"char_end": 905,
"chars": "'"
},
{
"char_start": 907,
"char_end": 909,
"chars": " %"
},
{
"char_start": 917,
"char_end": 944,
"chars": "\n cursor.execute(sql"
}
],
"added": [
{
"char_start": 860,
"char_end": 863,
"chars": "cur"
},
{
"char_start": 864,
"char_end": 875,
"chars": "or.execute("
},
{
"char_start": 914,
"char_end": 915,
"chars": ","
},
{
"char_start": 922,
"char_end": 923,
"chars": ","
}
]
} | github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9 | flaskr/flaskr/views/users.py | cwe-089 |
process_form | def process_form():
# see https://docs.python.org/3.4/library/cgi.html for the basic usage
# here.
form = cgi.FieldStorage()
# connect to the database
conn = MySQLdb.connect(host = pnsdp.SQL_HOST,
user = pnsdp.SQL_USER,
passwd = pnsdp.SQL_PASSWD,
db = pnsdp.SQL_DB)
if "user" not in form or "game" not in form:
raise FormError("Invalid parameters.")
if "pos" not in form and "resign" not in form:
raise FormError("Invalid parameters.")
game = int(form["game"].value)
(players,size,state) = get_game_info(conn, game)
user = form["user"].value
if user not in players:
raise FormError("Invalid player ID - player is not part of this game")
if "resign" in form:
resign = True
else:
resign = False
pos = form["pos"].value.split(",")
assert len(pos) == 2
x = int(pos[0])
y = int(pos[1])
(board,nextPlayer,letter) = build_board(conn, game,size)
if user != players[nextPlayer]:
raise FormError("Internal error, incorrect player is attempting to move.")
if resign:
# this user is choosing to resign. Update the game state to reflect that.
other_player_name = players[1-nextPlayer]
cursor = conn.cursor()
cursor.execute("""UPDATE games SET state="%s:resignation" WHERE id=%d;""" % (other_player_name,game))
cursor.close()
else:
assert x >= 0 and x < size
assert y >= 0 and y < size
assert board[x][y] == ""
board[x][y] = "XO"[nextPlayer]
# we've done all of our sanity checks. We now know enough to say that
# it's safe to add a new move.
cursor = conn.cursor()
cursor.execute("""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,"%s",NOW());""" % (game,x,y,letter))
if cursor.rowcount != 1:
raise FormError("Could not make move, reason unknown.")
cursor.close()
result = analyze_board(board)
if result != "":
if result == "win":
result = players[nextPlayer]+":win"
cursor = conn.cursor()
cursor.execute("""UPDATE games SET state="%s" WHERE id=%d;""" % (result,game))
cursor.close()
# we've made changes, make sure to commit them!
conn.commit()
conn.close()
# return the parms to the caller, so that they can build a good redirect
return (user,game) | def process_form():
# see https://docs.python.org/3.4/library/cgi.html for the basic usage
# here.
form = cgi.FieldStorage()
# connect to the database
conn = MySQLdb.connect(host = pnsdp.SQL_HOST,
user = pnsdp.SQL_USER,
passwd = pnsdp.SQL_PASSWD,
db = pnsdp.SQL_DB)
if "user" not in form or "game" not in form:
raise FormError("Invalid parameters.")
if "pos" not in form and "resign" not in form:
raise FormError("Invalid parameters.")
game = int(form["game"].value)
(players,size,state) = get_game_info(conn, game)
user = form["user"].value
if user not in players:
raise FormError("Invalid player ID - player is not part of this game")
if "resign" in form:
resign = True
else:
resign = False
pos = form["pos"].value.split(",")
assert len(pos) == 2
x = int(pos[0])
y = int(pos[1])
(board,nextPlayer,letter) = build_board(conn, game,size)
if user != players[nextPlayer]:
raise FormError("Internal error, incorrect player is attempting to move.")
if resign:
# this user is choosing to resign. Update the game state to reflect that.
other_player_name = players[1-nextPlayer]
cursor = conn.cursor()
cursor.execute("""UPDATE games SET state="%s:resignation" WHERE id=%d;""", (other_player_name,game))
cursor.close()
else:
assert x >= 0 and x < size
assert y >= 0 and y < size
assert board[x][y] == ""
board[x][y] = "XO"[nextPlayer]
# we've done all of our sanity checks. We now know enough to say that
# it's safe to add a new move.
cursor = conn.cursor()
cursor.execute("""INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,"%s",NOW());""", (game,x,y,letter))
if cursor.rowcount != 1:
raise FormError("Could not make move, reason unknown.")
cursor.close()
result = analyze_board(board)
if result != "":
if result == "win":
result = players[nextPlayer]+":win"
cursor = conn.cursor()
cursor.execute("""UPDATE games SET state="%s" WHERE id=%d;""", (result,game))
cursor.close()
# we've made changes, make sure to commit them!
conn.commit()
conn.close()
# return the parms to the caller, so that they can build a good redirect
return (user,game) | {
"deleted": [
{
"line_no": 50,
"char_start": 1369,
"char_end": 1479,
"line": " cursor.execute(\"\"\"UPDATE games SET state=\"%s:resignation\" WHERE id=%d;\"\"\" % (other_player_name,game))\n"
},
{
"line_no": 63,
"char_start": 1806,
"char_end": 1927,
"line": " cursor.execute(\"\"\"INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,\"%s\",NOW());\"\"\" % (game,x,y,letter))\n"
},
{
"line_no": 76,
"char_start": 2237,
"char_end": 2328,
"line": " cursor.execute(\"\"\"UPDATE games SET state=\"%s\" WHERE id=%d;\"\"\" % (result,game))\n"
}
],
"added": [
{
"line_no": 50,
"char_start": 1369,
"char_end": 1478,
"line": " cursor.execute(\"\"\"UPDATE games SET state=\"%s:resignation\" WHERE id=%d;\"\"\", (other_player_name,game))\n"
},
{
"line_no": 63,
"char_start": 1805,
"char_end": 1925,
"line": " cursor.execute(\"\"\"INSERT INTO moves(gameID,x,y,letter,time) VALUES(%d,%d,%d,\"%s\",NOW());\"\"\", (game,x,y,letter))\n"
},
{
"line_no": 76,
"char_start": 2235,
"char_end": 2325,
"line": " cursor.execute(\"\"\"UPDATE games SET state=\"%s\" WHERE id=%d;\"\"\", (result,game))\n"
}
]
} | {
"deleted": [
{
"char_start": 1450,
"char_end": 1452,
"chars": " %"
},
{
"char_start": 1905,
"char_end": 1907,
"chars": " %"
},
{
"char_start": 2310,
"char_end": 2312,
"chars": " %"
}
],
"added": [
{
"char_start": 1450,
"char_end": 1451,
"chars": ","
},
{
"char_start": 1904,
"char_end": 1905,
"chars": ","
},
{
"char_start": 2308,
"char_end": 2309,
"chars": ","
}
]
} | github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da | cgi/move.py | cwe-089 |
load_user | @login_manager.user_loader
def load_user(s_id):
email = str(s_id)
query = '''select * from usr where email like\'''' + email + '\''
cursor = g.conn.execute(query)
user = User()
for row in cursor:
user.name = str(row.name)
user.email = str(row.email)
break
return user | @login_manager.user_loader
def load_user(s_id):
email = str(s_id)
query = 'select * from usr where email like %s'
cursor = g.conn.execute(query, (email, ))
user = User()
for row in cursor:
user.name = str(row.name)
user.email = str(row.email)
break
return user | {
"deleted": [
{
"line_no": 4,
"char_start": 70,
"char_end": 140,
"line": " query = '''select * from usr where email like\\'''' + email + '\\''\n"
},
{
"line_no": 5,
"char_start": 140,
"char_end": 175,
"line": " cursor = g.conn.execute(query)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 70,
"char_end": 122,
"line": " query = 'select * from usr where email like %s'\n"
},
{
"line_no": 5,
"char_start": 122,
"char_end": 168,
"line": " cursor = g.conn.execute(query, (email, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 83,
"char_end": 85,
"chars": "''"
},
{
"char_start": 119,
"char_end": 124,
"chars": "\\''''"
},
{
"char_start": 125,
"char_end": 138,
"chars": "+ email + '\\'"
}
],
"added": [
{
"char_start": 118,
"char_end": 120,
"chars": "%s"
},
{
"char_start": 155,
"char_end": 166,
"chars": ", (email, )"
}
]
} | github.com/Daniel-Bu/w4111-project1/commit/fe04bedc72e62fd4c4ee046a9af29fd81e9b3340 | Web-app/Server.py | cwe-089 |
delete | @mod.route('/delete/<int:cmt_id>', methods=['GET', 'POST'])
def delete(cmt_id):
if request.method == 'GET':
sql = "SELECT msg_id FROM comment where cmt_id = %d;" % (cmt_id)
cursor.execute(sql)
m = cursor.fetchone()
sql = "DELETE FROM comment where cmt_id = '%d';" % (cmt_id)
cursor.execute(sql)
conn.commit()
flash('Delete Success!')
return redirect(url_for('comment.show', msg_id=m[0])) | @mod.route('/delete/<int:cmt_id>', methods=['GET', 'POST'])
def delete(cmt_id):
if request.method == 'GET':
cursor.execute("SELECT msg_id FROM comment where cmt_id = %s;", (cmt_id,))
m = cursor.fetchone()
cursor.execute("DELETE FROM comment where cmt_id = %s;", (cmt_id,))
conn.commit()
flash('Delete Success!')
return redirect(url_for('comment.show', msg_id=m[0])) | {
"deleted": [
{
"line_no": 4,
"char_start": 112,
"char_end": 185,
"line": " sql = \"SELECT msg_id FROM comment where cmt_id = %d;\" % (cmt_id)\n"
},
{
"line_no": 5,
"char_start": 185,
"char_end": 213,
"line": " cursor.execute(sql)\n"
},
{
"line_no": 7,
"char_start": 243,
"char_end": 311,
"line": " sql = \"DELETE FROM comment where cmt_id = '%d';\" % (cmt_id)\n"
},
{
"line_no": 8,
"char_start": 311,
"char_end": 339,
"line": " cursor.execute(sql)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 112,
"char_end": 195,
"line": " cursor.execute(\"SELECT msg_id FROM comment where cmt_id = %s;\", (cmt_id,))\n"
},
{
"line_no": 6,
"char_start": 225,
"char_end": 301,
"line": " cursor.execute(\"DELETE FROM comment where cmt_id = %s;\", (cmt_id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 121,
"char_end": 126,
"chars": "ql = "
},
{
"char_start": 170,
"char_end": 171,
"chars": "d"
},
{
"char_start": 173,
"char_end": 175,
"chars": " %"
},
{
"char_start": 184,
"char_end": 211,
"chars": "\n cursor.execute(sql"
},
{
"char_start": 252,
"char_end": 257,
"chars": "ql = "
},
{
"char_start": 293,
"char_end": 294,
"chars": "'"
},
{
"char_start": 295,
"char_end": 297,
"chars": "d'"
},
{
"char_start": 299,
"char_end": 301,
"chars": " %"
},
{
"char_start": 310,
"char_end": 337,
"chars": "\n cursor.execute(sql"
}
],
"added": [
{
"char_start": 120,
"char_end": 123,
"chars": "cur"
},
{
"char_start": 124,
"char_end": 135,
"chars": "or.execute("
},
{
"char_start": 179,
"char_end": 180,
"chars": "s"
},
{
"char_start": 182,
"char_end": 183,
"chars": ","
},
{
"char_start": 191,
"char_end": 193,
"chars": ",)"
},
{
"char_start": 203,
"char_end": 207,
"chars": "m = "
},
{
"char_start": 214,
"char_end": 215,
"chars": "f"
},
{
"char_start": 217,
"char_end": 221,
"chars": "chon"
},
{
"char_start": 241,
"char_end": 245,
"chars": "xecu"
},
{
"char_start": 285,
"char_end": 286,
"chars": "s"
},
{
"char_start": 288,
"char_end": 289,
"chars": ","
},
{
"char_start": 297,
"char_end": 298,
"chars": ","
}
]
} | github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9 | flaskr/flaskr/views/comment.py | cwe-089 |
get_markets | @app.route('/get_markets')
def get_markets():
asset_id = request.args.get('asset_id')
if not isObject(asset_id):
ws.send('{"id":1, "method":"call", "params":[0,"lookup_asset_symbols",[["' + asset_id + '"], 0]]}')
result_l = ws.recv()
j_l = json.loads(result_l)
asset_id = j_l["result"][0]["id"]
con = psycopg2.connect(**config.POSTGRES)
cur = con.cursor()
query = "SELECT * FROM markets WHERE aid='"+asset_id+"'"
cur.execute(query)
results = cur.fetchall()
con.close()
return jsonify(results) | @app.route('/get_markets')
def get_markets():
asset_id = request.args.get('asset_id')
if not isObject(asset_id):
ws.send('{"id":1, "method":"call", "params":[0,"lookup_asset_symbols",[["' + asset_id + '"], 0]]}')
result_l = ws.recv()
j_l = json.loads(result_l)
asset_id = j_l["result"][0]["id"]
con = psycopg2.connect(**config.POSTGRES)
cur = con.cursor()
query = "SELECT * FROM markets WHERE aid=%s"
cur.execute(query, (asset_id,))
results = cur.fetchall()
con.close()
return jsonify(results) | {
"deleted": [
{
"line_no": 15,
"char_start": 408,
"char_end": 469,
"line": " query = \"SELECT * FROM markets WHERE aid='\"+asset_id+\"'\"\n"
},
{
"line_no": 16,
"char_start": 469,
"char_end": 492,
"line": " cur.execute(query)\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 408,
"char_end": 457,
"line": " query = \"SELECT * FROM markets WHERE aid=%s\"\n"
},
{
"line_no": 16,
"char_start": 457,
"char_end": 493,
"line": " cur.execute(query, (asset_id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 453,
"char_end": 457,
"chars": "'\"+a"
},
{
"char_start": 458,
"char_end": 467,
"chars": "set_id+\"'"
}
],
"added": [
{
"char_start": 453,
"char_end": 454,
"chars": "%"
},
{
"char_start": 478,
"char_end": 491,
"chars": ", (asset_id,)"
}
]
} | github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60 | api.py | cwe-089 |
get_secrets | def get_secrets(self, from_date_added=0):
secrets = []
for row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > %s ORDER BY date_added DESC' % from_date_added):
aes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2]
if aes_key != None:
secrets.append([aes_key, json_id])
from_date_added = max(from_date_added, date_added)
return (secrets, from_date_added) | def get_secrets(self, from_date_added=0):
secrets = []
for row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > ? ORDER BY date_added DESC', (from_date_added,)):
aes_key, json_id, date_added = cryptlib.eciesDecrypt(row[0], self.privkey), row[1], row[2]
if aes_key != None:
secrets.append([aes_key, json_id])
from_date_added = max(from_date_added, date_added)
return (secrets, from_date_added) | {
"deleted": [
{
"line_no": 3,
"char_start": 58,
"char_end": 210,
"line": "\t\tfor row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > %s ORDER BY date_added DESC' % from_date_added):\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 58,
"char_end": 211,
"line": "\t\tfor row in self.cursor.execute('SELECT encrypted, json_id, date_added FROM secret WHERE date_added > ? ORDER BY date_added DESC', (from_date_added,)):\n"
}
]
} | {
"deleted": [
{
"char_start": 161,
"char_end": 163,
"chars": "%s"
},
{
"char_start": 189,
"char_end": 191,
"chars": " %"
}
],
"added": [
{
"char_start": 161,
"char_end": 162,
"chars": "?"
},
{
"char_start": 188,
"char_end": 189,
"chars": ","
},
{
"char_start": 190,
"char_end": 191,
"chars": "("
},
{
"char_start": 206,
"char_end": 208,
"chars": ",)"
}
]
} | github.com/imachug/ZeroMailProxy/commit/8f62d024c6c4c957079d147e59f26d15c07dc888 | zeromail.py | cwe-089 |
add_consumption_data_row | def add_consumption_data_row(self, ts, energy_used, power_used):
if power_used > 0:
query = '''
INSERT OR IGNORE INTO Consumption (
TimeStamp,
EnergyUsed,
PowerUsed
) VALUES (
%s,
%s,
%s
);
''' % (ts, 0, 0)
self.c.execute(query)
query = '''
UPDATE Consumption SET
EnergyUsed = EnergyUsed + %s,
PowerUsed = PowerUsed + %s
WHERE TimeStamp = %s;
''' % (energy_used, power_used, ts)
self.c.execute(query)
self.db.commit() | def add_consumption_data_row(self, ts, energy_used, power_used):
if power_used > 0:
query = '''
INSERT OR IGNORE INTO Consumption (
TimeStamp,
EnergyUsed,
PowerUsed
) VALUES (
?,
?,
?
);
'''
self.c.execute(query, (ts, 0, 0))
query = '''
UPDATE Consumption SET
EnergyUsed = EnergyUsed + ?,
PowerUsed = PowerUsed + ?
WHERE TimeStamp=?;
'''
self.c.execute(query, (energy_used, power_used, ts))
self.db.commit() | {
"deleted": [
{
"line_no": 11,
"char_start": 326,
"char_end": 350,
"line": " %s,\n"
},
{
"line_no": 12,
"char_start": 350,
"char_end": 374,
"line": " %s,\n"
},
{
"line_no": 13,
"char_start": 374,
"char_end": 397,
"line": " %s\n"
},
{
"line_no": 15,
"char_start": 416,
"char_end": 445,
"line": " ''' % (ts, 0, 0)\n"
},
{
"line_no": 16,
"char_start": 445,
"char_end": 479,
"line": " self.c.execute(query)\n"
},
{
"line_no": 20,
"char_start": 544,
"char_end": 590,
"line": " EnergyUsed = EnergyUsed + %s,\n"
},
{
"line_no": 21,
"char_start": 590,
"char_end": 633,
"line": " PowerUsed = PowerUsed + %s\n"
},
{
"line_no": 22,
"char_start": 633,
"char_end": 671,
"line": " WHERE TimeStamp = %s;\n"
},
{
"line_no": 23,
"char_start": 671,
"char_end": 719,
"line": " ''' % (energy_used, power_used, ts)\n"
},
{
"line_no": 25,
"char_start": 720,
"char_end": 754,
"line": " self.c.execute(query)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 326,
"char_end": 349,
"line": " ?,\n"
},
{
"line_no": 12,
"char_start": 349,
"char_end": 372,
"line": " ?,\n"
},
{
"line_no": 13,
"char_start": 372,
"char_end": 394,
"line": " ?\n"
},
{
"line_no": 15,
"char_start": 413,
"char_end": 429,
"line": " '''\n"
},
{
"line_no": 16,
"char_start": 429,
"char_end": 475,
"line": " self.c.execute(query, (ts, 0, 0))\n"
},
{
"line_no": 20,
"char_start": 540,
"char_end": 585,
"line": " EnergyUsed = EnergyUsed + ?,\n"
},
{
"line_no": 21,
"char_start": 585,
"char_end": 627,
"line": " PowerUsed = PowerUsed + ?\n"
},
{
"line_no": 22,
"char_start": 627,
"char_end": 662,
"line": " WHERE TimeStamp=?;\n"
},
{
"line_no": 23,
"char_start": 662,
"char_end": 678,
"line": " '''\n"
},
{
"line_no": 25,
"char_start": 679,
"char_end": 744,
"line": " self.c.execute(query, (energy_used, power_used, ts))\n"
}
]
} | {
"deleted": [
{
"char_start": 346,
"char_end": 348,
"chars": "%s"
},
{
"char_start": 370,
"char_end": 372,
"chars": "%s"
},
{
"char_start": 394,
"char_end": 396,
"chars": "%s"
},
{
"char_start": 431,
"char_end": 444,
"chars": " % (ts, 0, 0)"
},
{
"char_start": 586,
"char_end": 588,
"chars": "%s"
},
{
"char_start": 630,
"char_end": 632,
"chars": "%s"
},
{
"char_start": 664,
"char_end": 665,
"chars": " "
},
{
"char_start": 666,
"char_end": 669,
"chars": " %s"
},
{
"char_start": 686,
"char_end": 718,
"chars": " % (energy_used, power_used, ts)"
}
],
"added": [
{
"char_start": 346,
"char_end": 347,
"chars": "?"
},
{
"char_start": 369,
"char_end": 370,
"chars": "?"
},
{
"char_start": 392,
"char_end": 393,
"chars": "?"
},
{
"char_start": 461,
"char_end": 473,
"chars": ", (ts, 0, 0)"
},
{
"char_start": 582,
"char_end": 583,
"chars": "?"
},
{
"char_start": 625,
"char_end": 626,
"chars": "?"
},
{
"char_start": 659,
"char_end": 660,
"chars": "?"
},
{
"char_start": 711,
"char_end": 742,
"chars": ", (energy_used, power_used, ts)"
}
]
} | github.com/philipptrenz/s0-bridge/commit/269b48caa05377b7c58c3e6d1622a4429cb5ba65 | util/database.py | cwe-089 |
lookup_assets | @app.route('/lookup_assets')
def lookup_assets():
start = request.args.get('start')
con = psycopg2.connect(**config.POSTGRES)
cur = con.cursor()
query = "SELECT aname FROM assets WHERE aname LIKE '"+start+"%'"
cur.execute(query)
results = cur.fetchall()
con.close()
return jsonify(results) | @app.route('/lookup_assets')
def lookup_assets():
start = request.args.get('start')
con = psycopg2.connect(**config.POSTGRES)
cur = con.cursor()
query = "SELECT aname FROM assets WHERE aname LIKE %s"
cur.execute(query, (start+'%',))
results = cur.fetchall()
con.close()
return jsonify(results) | {
"deleted": [
{
"line_no": 8,
"char_start": 159,
"char_end": 228,
"line": " query = \"SELECT aname FROM assets WHERE aname LIKE '\"+start+\"%'\"\n"
},
{
"line_no": 9,
"char_start": 228,
"char_end": 251,
"line": " cur.execute(query)\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 159,
"char_end": 218,
"line": " query = \"SELECT aname FROM assets WHERE aname LIKE %s\"\n"
},
{
"line_no": 9,
"char_start": 218,
"char_end": 255,
"line": " cur.execute(query, (start+'%',))\n"
}
]
} | {
"deleted": [
{
"char_start": 214,
"char_end": 224,
"chars": "'\"+start+\""
},
{
"char_start": 225,
"char_end": 226,
"chars": "'"
}
],
"added": [
{
"char_start": 214,
"char_end": 215,
"chars": "%"
},
{
"char_start": 239,
"char_end": 253,
"chars": ", (start+'%',)"
}
]
} | github.com/VinChain/vinchain-python-api-backend/commit/b78088a551fbb712121269c6eb7f43ede120ff60 | api.py | cwe-089 |
set_state | def set_state(chat_id, value):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("update users set state ='" + str(value) + "' where chat_id = '" + str(chat_id) + "'")
settings.commit()
settings.close() | def set_state(chat_id, value):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("update users set state = ? where chat_id = ?", (str(value), str(chat_id)))
settings.commit()
settings.close() | {
"deleted": [
{
"line_no": 4,
"char_start": 160,
"char_end": 264,
"line": " conn.execute(\"update users set state ='\" + str(value) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 160,
"char_end": 253,
"line": " conn.execute(\"update users set state = ? where chat_id = ?\", (str(value), str(chat_id)))\n"
}
]
} | {
"deleted": [
{
"char_start": 202,
"char_end": 204,
"chars": "'\""
},
{
"char_start": 205,
"char_end": 222,
"chars": "+ str(value) + \"'"
},
{
"char_start": 239,
"char_end": 240,
"chars": "'"
},
{
"char_start": 242,
"char_end": 243,
"chars": "+"
},
{
"char_start": 256,
"char_end": 262,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 203,
"char_end": 204,
"chars": "?"
},
{
"char_start": 221,
"char_end": 222,
"chars": "?"
},
{
"char_start": 223,
"char_end": 224,
"chars": ","
},
{
"char_start": 225,
"char_end": 237,
"chars": "(str(value),"
},
{
"char_start": 250,
"char_end": 251,
"chars": ")"
}
]
} | github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90 | bot.py | cwe-089 |
_get_degree_2 | def _get_degree_2(user_id, cnx):
"""Get all users of degree 2 follow that are not currently followed.
Example:
this user (follows) user B (follows) user B
AND user (does NOT follow) user B
means that user B will be in the list
Args:
user_id (int): id of user
cnx: DB connection
Returns:
list: list of user_ids
"""
sql = 'WITH tmp_suggest (followed_id) AS ' \
'(' \
'SELECT b.followed_id AS followed_id ' \
'FROM ' \
'tbl_follow a INNER JOIN tbl_follow b ' \
'ON a.followed_id = b.follower_id ' \
'WHERE a.follower_id = %s ' \
'AND b.followed_id NOT IN ' \
'(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \
'AND b.followed_id != %s ' \
') ' \
'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \
'GROUP BY followed_id ' \
'ORDER BY num_mutual DESC' % (user_id, user_id, user_id)
with cnx.cursor() as cursor:
cursor.execute(sql)
res = cursor.fetchall()
return list(map(lambda x: x[0], res)) | def _get_degree_2(user_id, cnx):
"""Get all users of degree 2 follow that are not currently followed.
Example:
this user (follows) user B (follows) user B
AND user (does NOT follow) user B
means that user B will be in the list
Args:
user_id (int): id of user
cnx: DB connection
Returns:
list: list of user_ids
"""
sql = 'WITH tmp_suggest (followed_id) AS ' \
'(' \
'SELECT b.followed_id AS followed_id ' \
'FROM ' \
'tbl_follow a INNER JOIN tbl_follow b ' \
'ON a.followed_id = b.follower_id ' \
'WHERE a.follower_id = %s ' \
'AND b.followed_id NOT IN ' \
'(SELECT followed_id FROM tbl_follow WHERE follower_id = %s) ' \
'AND b.followed_id != %s ' \
') ' \
'SELECT followed_id, COUNT(*) AS num_mutual FROM tmp_suggest ' \
'GROUP BY followed_id ' \
'ORDER BY num_mutual DESC'
with cnx.cursor() as cursor:
cursor.execute(sql, (user_id, user_id, user_id))
res = cursor.fetchall()
return list(map(lambda x: x[0], res)) | {
"deleted": [
{
"line_no": 26,
"char_start": 912,
"char_end": 973,
"line": " 'ORDER BY num_mutual DESC' % (user_id, user_id, user_id)\n"
},
{
"line_no": 28,
"char_start": 1006,
"char_end": 1034,
"line": " cursor.execute(sql)\n"
}
],
"added": [
{
"line_no": 26,
"char_start": 912,
"char_end": 943,
"line": " 'ORDER BY num_mutual DESC'\n"
},
{
"line_no": 28,
"char_start": 976,
"char_end": 1033,
"line": " cursor.execute(sql, (user_id, user_id, user_id))\n"
}
]
} | {
"deleted": [
{
"char_start": 942,
"char_end": 972,
"chars": " % (user_id, user_id, user_id)"
}
],
"added": [
{
"char_start": 1002,
"char_end": 1031,
"chars": ", (user_id, user_id, user_id)"
}
]
} | github.com/young-goons/rifflo-server/commit/fb311df76713b638c9486250f9badb288ffb2189 | server/ygoons/modules/user/follow_suggest.py | cwe-089 |
get_tournaments_during_month | def get_tournaments_during_month(db, scene, date):
y, m, d = date.split('-')
ym_date = '{}-{}'.format(y, m)
sql = "select url, date from matches where scene='{}' and date like '%{}%' group by url, date order by date".format(scene, ym_date)
res = db.exec(sql)
urls = [r[0] for r in res]
return urls | def get_tournaments_during_month(db, scene, date):
y, m, d = date.split('-')
ym_date = '{}-{}'.format(y, m)
sql = "select url, date from matches where scene='{scene}' and date like '%{date}%' group by url, date order by date"
args = {'scene': scene, 'date': ym_date}
res = db.exec(sql, args)
urls = [r[0] for r in res]
return urls | {
"deleted": [
{
"line_no": 4,
"char_start": 116,
"char_end": 252,
"line": " sql = \"select url, date from matches where scene='{}' and date like '%{}%' group by url, date order by date\".format(scene, ym_date)\n"
},
{
"line_no": 5,
"char_start": 252,
"char_end": 275,
"line": " res = db.exec(sql)\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 116,
"char_end": 238,
"line": " sql = \"select url, date from matches where scene='{scene}' and date like '%{date}%' group by url, date order by date\"\n"
},
{
"line_no": 5,
"char_start": 238,
"char_end": 283,
"line": " args = {'scene': scene, 'date': ym_date}\n"
},
{
"line_no": 6,
"char_start": 283,
"char_end": 312,
"line": " res = db.exec(sql, args)\n"
}
]
} | {
"deleted": [
{
"char_start": 228,
"char_end": 231,
"chars": ".fo"
},
{
"char_start": 232,
"char_end": 236,
"chars": "mat("
},
{
"char_start": 250,
"char_end": 251,
"chars": ")"
}
],
"added": [
{
"char_start": 171,
"char_end": 176,
"chars": "scene"
},
{
"char_start": 196,
"char_end": 200,
"chars": "date"
},
{
"char_start": 237,
"char_end": 242,
"chars": "\n "
},
{
"char_start": 243,
"char_end": 259,
"chars": "rgs = {'scene': "
},
{
"char_start": 266,
"char_end": 274,
"chars": "'date': "
},
{
"char_start": 281,
"char_end": 282,
"chars": "}"
},
{
"char_start": 304,
"char_end": 310,
"chars": ", args"
}
]
} | github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63 | bracket_utils.py | cwe-089 |
add_input | def add_input(self,data):
connection = self.connect()
try:
# The following is a flaw
query = "INSERT INTO crimes(description) VALUES ('{}');".format(data)
with connection.cursor() as cursor:
cursor.execute(query)
connection.commit()
finally:
connection.close() | def add_input(self,data):
connection = self.connect()
try:
# The following is a flaw
query = "INSERT INTO crimes(description) VALUES (%s);"
with connection.cursor() as cursor:
cursor.execute(query, data)
connection.commit()
finally:
connection.close() | {
"deleted": [
{
"line_no": 5,
"char_start": 117,
"char_end": 199,
"line": " query = \"INSERT INTO crimes(description) VALUES ('{}');\".format(data)\n"
},
{
"line_no": 7,
"char_start": 247,
"char_end": 285,
"line": " cursor.execute(query)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 117,
"char_end": 184,
"line": " query = \"INSERT INTO crimes(description) VALUES (%s);\"\n"
},
{
"line_no": 7,
"char_start": 232,
"char_end": 276,
"line": " cursor.execute(query, data)\n"
}
]
} | {
"deleted": [
{
"char_start": 178,
"char_end": 182,
"chars": "'{}'"
},
{
"char_start": 185,
"char_end": 198,
"chars": ".format(data)"
}
],
"added": [
{
"char_start": 178,
"char_end": 180,
"chars": "%s"
},
{
"char_start": 268,
"char_end": 274,
"chars": ", data"
}
]
} | github.com/amrishc/crimemap/commit/51b3d51aa031d7c285295de36f5464d43debf6de | dbhelper.py | cwe-089 |
get_error_days | def get_error_days(cur, error_percent):
"""Fetches the days in which requests led to errors.
Fetches the days in which the specified percentage
of requests led to errors.
Args:
cur(obj): The cursor to execute the query.
error_percent(int): The percentage of requests that led to errors.
Return:
True if success, False otherwise.
"""
query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'),
round((log_errors.errors * 100
/ log_requests.total::numeric), 2) as percent
FROM log_errors, log_requests
WHERE log_errors.date = log_requests.date AND
log_errors.errors * 100
/ log_requests.total::numeric > {}
ORDER BY log_errors.date'''.format(error_percent)
rows = get_data(cur, query)
# Write data to txt file.
if rows is not None:
file = open("error_report.txt", "w")
for row in rows:
file.write("{} - {}% errors \n".format(row[0], row[1]))
file.close()
return True
else:
return False | def get_error_days(cur, error_percent):
"""Fetches the days in which requests led to errors.
Fetches the days in which the specified percentage
of requests led to errors.
Args:
cur(obj): The cursor to execute the query.
error_percent(int): The percentage of requests that led to errors.
Return:
True if success, False otherwise.
"""
data = (error_percent, )
query = '''SELECT to_char(log_errors.date, 'Mon DD YYYY'),
round((log_errors.errors * 100
/ log_requests.total::numeric), 2) as percent
FROM log_errors, log_requests
WHERE log_errors.date = log_requests.date AND
log_errors.errors * 100
/ log_requests.total::numeric > %s
ORDER BY log_errors.date'''
rows = get_data(cur, query, data)
# Write data to txt file.
if rows is not None:
file = open("error_report.txt", "w")
for row in rows:
file.write("{} - {}% errors \n".format(row[0], row[1]))
file.close()
return True
else:
return False | {
"deleted": [
{
"line_no": 20,
"char_start": 684,
"char_end": 731,
"line": " / log_requests.total::numeric > {}\n"
},
{
"line_no": 21,
"char_start": 731,
"char_end": 793,
"line": " ORDER BY log_errors.date'''.format(error_percent)\n"
},
{
"line_no": 22,
"char_start": 793,
"char_end": 825,
"line": " rows = get_data(cur, query)\n"
}
],
"added": [
{
"line_no": 14,
"char_start": 384,
"char_end": 413,
"line": " data = (error_percent, )\n"
},
{
"line_no": 21,
"char_start": 713,
"char_end": 760,
"line": " / log_requests.total::numeric > %s\n"
},
{
"line_no": 22,
"char_start": 760,
"char_end": 800,
"line": " ORDER BY log_errors.date'''\n"
},
{
"line_no": 23,
"char_start": 800,
"char_end": 838,
"line": " rows = get_data(cur, query, data)\n"
}
]
} | {
"deleted": [
{
"char_start": 728,
"char_end": 730,
"chars": "{}"
},
{
"char_start": 770,
"char_end": 792,
"chars": ".format(error_percent)"
}
],
"added": [
{
"char_start": 388,
"char_end": 417,
"chars": "data = (error_percent, )\n "
},
{
"char_start": 757,
"char_end": 759,
"chars": "%s"
},
{
"char_start": 830,
"char_end": 836,
"chars": ", data"
}
]
} | github.com/rrbiz662/log-analysis/commit/20fefbde3738088586a3c5679f743493d0a504f6 | news_data_analysis.py | cwe-089 |
all_deposits | def all_deposits(self,coin):
sql = "SELECT * FROM deposits WHERE coin='%s'" % coin
self.cursor.execute(sql)
return self.cursor.fetchall() | def all_deposits(self,coin):
sql = "SELECT * FROM deposits WHERE coin='%s'"
self.cursor.execute(sql, (coin,))
return self.cursor.fetchall() | {
"deleted": [
{
"line_no": 2,
"char_start": 33,
"char_end": 95,
"line": " sql = \"SELECT * FROM deposits WHERE coin='%s'\" % coin\n"
},
{
"line_no": 3,
"char_start": 95,
"char_end": 128,
"line": " self.cursor.execute(sql)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 33,
"char_end": 88,
"line": " sql = \"SELECT * FROM deposits WHERE coin='%s'\"\n"
},
{
"line_no": 3,
"char_start": 88,
"char_end": 130,
"line": " self.cursor.execute(sql, (coin,))\n"
}
]
} | {
"deleted": [
{
"char_start": 87,
"char_end": 94,
"chars": " % coin"
}
],
"added": [
{
"char_start": 119,
"char_end": 128,
"chars": ", (coin,)"
}
]
} | github.com/ktechmidas/garlictipsbot/commit/7c262255f933cb721109ac4be752b5b7599275aa | deposit.py | cwe-089 |
get_user | def get_user(self):
if not hasattr(self, '_user'):
qs = "select * from account_access where access_token = '%s'" % self.access_token
result = self.db.get(qs)
if result:
self._user = result
else:
self._user = None
return self._user | def get_user(self):
if not hasattr(self, '_user'):
qs = "select * from account_access where access_token = %s"
result = self.db.get(qs, self.access_token)
if result:
self._user = result
else:
self._user = None
return self._user | {
"deleted": [
{
"line_no": 3,
"char_start": 63,
"char_end": 157,
"line": " qs = \"select * from account_access where access_token = '%s'\" % self.access_token\n"
},
{
"line_no": 4,
"char_start": 157,
"char_end": 194,
"line": " result = self.db.get(qs)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 63,
"char_end": 135,
"line": " qs = \"select * from account_access where access_token = %s\"\n"
},
{
"line_no": 4,
"char_start": 135,
"char_end": 191,
"line": " result = self.db.get(qs, self.access_token)\n"
}
]
} | {
"deleted": [
{
"char_start": 131,
"char_end": 132,
"chars": "'"
},
{
"char_start": 134,
"char_end": 135,
"chars": "'"
},
{
"char_start": 136,
"char_end": 156,
"chars": " % self.access_token"
}
],
"added": [
{
"char_start": 170,
"char_end": 189,
"chars": ", self.access_token"
}
]
} | github.com/bonbondirac/tsunami/commit/396cc394bd6daaf0ee9c16b1b55a4082eeaac208 | src/auth.py | cwe-089 |
compare_and_update | @staticmethod
def compare_and_update(user, message):
"""
This method compare a user object from the bot and his info from
the Telegram message to check whether a user has changed his bio
or not. If yes, the user object that represents him in the bot will
be updated accordingly. Now this function is called only when a user
asks the bot for showing the most popular cams
:param user: user object that represents a Telegram user in this bot
:param message: object from Telegram that contains info about user's
message and about himself
:return: None
"""
log.info('Checking whether user have changed his info or not...')
msg = message.from_user
usr_from_message = User(message.chat.id, msg.first_name, msg.username,
msg.last_name)
if user.chat_id != usr_from_message.chat_id:
log.error("Wrong user to compare!")
return
if user.first_name != usr_from_message.first_name:
user.first_name = usr_from_message.first_name
elif user.nickname != usr_from_message.nickname:
user.nickname = usr_from_message.nickname
elif user.last_name != usr_from_message.last_name:
user.last_name = usr_from_message.last_name
else:
log.debug("User's info hasn't changed")
return
log.info("User has changed his info")
log.debug("Updating user's info in the database...")
query = (f"UPDATE users "
f"SET first_name='{user.first_name}', "
f"nickname='{user.nickname}', "
f"last_name='{user.last_name}' "
f"WHERE chat_id={user.chat_id}")
try:
db.add(query)
except DatabaseError:
log.error("Could not update info about %s in the database",
user)
else:
log.debug("User's info has been updated") | @staticmethod
def compare_and_update(user, message):
"""
This method compare a user object from the bot and his info from
the Telegram message to check whether a user has changed his bio
or not. If yes, the user object that represents him in the bot will
be updated accordingly. Now this function is called only when a user
asks the bot for showing the most popular cams
:param user: user object that represents a Telegram user in this bot
:param message: object from Telegram that contains info about user's
message and about himself
:return: None
"""
log.info('Checking whether user have changed his info or not...')
msg = message.from_user
usr_from_message = User(message.chat.id, msg.first_name, msg.username,
msg.last_name)
if user.chat_id != usr_from_message.chat_id:
log.error("Wrong user to compare!")
return
if user.first_name != usr_from_message.first_name:
user.first_name = usr_from_message.first_name
elif user.nickname != usr_from_message.nickname:
user.nickname = usr_from_message.nickname
elif user.last_name != usr_from_message.last_name:
user.last_name = usr_from_message.last_name
else:
log.debug("User's info hasn't changed")
return
log.info("User has changed his info")
log.debug("Updating user's info in the database...")
query = (f"UPDATE users "
f"SET first_name=%s, "
f"nickname=%s, "
f"last_name=%s "
f"WHERE chat_id=%s")
parameters = (user.first_name, user.nickname, user.last_name,
user.chat_id)
try:
db.add(query, parameters)
except DatabaseError:
log.error("Could not update info about %s in the database",
user)
else:
log.debug("User's info has been updated") | {
"deleted": [
{
"line_no": 41,
"char_start": 1578,
"char_end": 1635,
"line": " f\"SET first_name='{user.first_name}', \"\n"
},
{
"line_no": 42,
"char_start": 1635,
"char_end": 1684,
"line": " f\"nickname='{user.nickname}', \"\n"
},
{
"line_no": 43,
"char_start": 1684,
"char_end": 1734,
"line": " f\"last_name='{user.last_name}' \"\n"
},
{
"line_no": 44,
"char_start": 1734,
"char_end": 1784,
"line": " f\"WHERE chat_id={user.chat_id}\")\n"
},
{
"line_no": 47,
"char_start": 1798,
"char_end": 1824,
"line": " db.add(query)\n"
}
],
"added": [
{
"line_no": 41,
"char_start": 1578,
"char_end": 1618,
"line": " f\"SET first_name=%s, \"\n"
},
{
"line_no": 42,
"char_start": 1618,
"char_end": 1652,
"line": " f\"nickname=%s, \"\n"
},
{
"line_no": 43,
"char_start": 1652,
"char_end": 1686,
"line": " f\"last_name=%s \"\n"
},
{
"line_no": 44,
"char_start": 1686,
"char_end": 1724,
"line": " f\"WHERE chat_id=%s\")\n"
},
{
"line_no": 45,
"char_start": 1724,
"char_end": 1725,
"line": "\n"
},
{
"line_no": 46,
"char_start": 1725,
"char_end": 1795,
"line": " parameters = (user.first_name, user.nickname, user.last_name,\n"
},
{
"line_no": 47,
"char_start": 1795,
"char_end": 1831,
"line": " user.chat_id)\n"
},
{
"line_no": 50,
"char_start": 1845,
"char_end": 1883,
"line": " db.add(query, parameters)\n"
}
]
} | {
"deleted": [
{
"char_start": 1612,
"char_end": 1615,
"chars": "'{u"
},
{
"char_start": 1616,
"char_end": 1631,
"chars": "er.first_name}'"
},
{
"char_start": 1663,
"char_end": 1666,
"chars": "'{u"
},
{
"char_start": 1667,
"char_end": 1680,
"chars": "er.nickname}'"
},
{
"char_start": 1713,
"char_end": 1722,
"chars": "'{user.la"
},
{
"char_start": 1723,
"char_end": 1731,
"chars": "t_name}'"
},
{
"char_start": 1767,
"char_end": 1768,
"chars": "{"
},
{
"char_start": 1780,
"char_end": 1782,
"chars": "}\""
}
],
"added": [
{
"char_start": 1612,
"char_end": 1613,
"chars": "%"
},
{
"char_start": 1646,
"char_end": 1647,
"chars": "%"
},
{
"char_start": 1681,
"char_end": 1682,
"chars": "%"
},
{
"char_start": 1719,
"char_end": 1817,
"chars": "%s\")\n\n parameters = (user.first_name, user.nickname, user.last_name,\n "
},
{
"char_start": 1869,
"char_end": 1881,
"chars": ", parameters"
}
]
} | github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a | photogpsbot/users.py | cwe-089 |
GameNewPlayed | def GameNewPlayed(Played, ID):
db.execute("UPDATE games set GamesPlayed = %i WHERE ID = %i" % (Played, ID))
database.commit() | def GameNewPlayed(Played, ID):
db.execute("UPDATE games set GamesPlayed = ? WHERE ID = ?", Played, ID)
database.commit() | {
"deleted": [
{
"line_no": 2,
"char_start": 31,
"char_end": 109,
"line": "\tdb.execute(\"UPDATE games set GamesPlayed = %i WHERE ID = %i\" % (Played, ID))\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 31,
"char_end": 104,
"line": "\tdb.execute(\"UPDATE games set GamesPlayed = ? WHERE ID = ?\", Played, ID)\n"
}
]
} | {
"deleted": [
{
"char_start": 75,
"char_end": 77,
"chars": "%i"
},
{
"char_start": 89,
"char_end": 91,
"chars": "%i"
},
{
"char_start": 92,
"char_end": 94,
"chars": " %"
},
{
"char_start": 95,
"char_end": 96,
"chars": "("
},
{
"char_start": 106,
"char_end": 107,
"chars": ")"
}
],
"added": [
{
"char_start": 75,
"char_end": 76,
"chars": "?"
},
{
"char_start": 88,
"char_end": 89,
"chars": "?"
},
{
"char_start": 90,
"char_end": 91,
"chars": ","
}
]
} | github.com/iScrE4m/XLeague/commit/59cab6e5fd8bd5e47f2418a7c71cb1d4e3cad0d2 | plugins/database.py | cwe-089 |
insertNPC | def insertNPC(name, race,classe,sex,level,image,legit):
c, conn = getConnection()
date = now()
c.execute("INSERT INTO npc VALUES ('"+date+"','"+str(name)+"','"+race+"','"+classe+"','"+sex+"','"+str(level)+"','"+image+"','"+str(legit)+"')")
conn.commit()
conn.close() | def insertNPC(name, race,classe,sex,level,image,legit):
c, conn = getConnection()
date = now()
c.execute("INSERT INTO npc VALUES (?,?,?,?,?,?,?,?)",(date,str(name),race,classe,sex,str(level),image,str(legit)))
conn.commit()
conn.close() | {
"deleted": [
{
"line_no": 4,
"char_start": 97,
"char_end": 243,
"line": "\tc.execute(\"INSERT INTO npc VALUES ('\"+date+\"','\"+str(name)+\"','\"+race+\"','\"+classe+\"','\"+sex+\"','\"+str(level)+\"','\"+image+\"','\"+str(legit)+\"')\")\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 97,
"char_end": 213,
"line": "\tc.execute(\"INSERT INTO npc VALUES (?,?,?,?,?,?,?,?)\",(date,str(name),race,classe,sex,str(level),image,str(legit)))\n"
}
]
} | {
"deleted": [
{
"char_start": 133,
"char_end": 134,
"chars": "'"
},
{
"char_start": 135,
"char_end": 136,
"chars": "+"
},
{
"char_start": 140,
"char_end": 143,
"chars": "+\"'"
},
{
"char_start": 144,
"char_end": 147,
"chars": "'\"+"
},
{
"char_start": 156,
"char_end": 159,
"chars": "+\"'"
},
{
"char_start": 160,
"char_end": 163,
"chars": "'\"+"
},
{
"char_start": 167,
"char_end": 170,
"chars": "+\"'"
},
{
"char_start": 171,
"char_end": 174,
"chars": "'\"+"
},
{
"char_start": 180,
"char_end": 183,
"chars": "+\"'"
},
{
"char_start": 184,
"char_end": 187,
"chars": "'\"+"
},
{
"char_start": 190,
"char_end": 193,
"chars": "+\"'"
},
{
"char_start": 194,
"char_end": 197,
"chars": "'\"+"
},
{
"char_start": 207,
"char_end": 210,
"chars": "+\"'"
},
{
"char_start": 211,
"char_end": 214,
"chars": "'\"+"
},
{
"char_start": 219,
"char_end": 222,
"chars": "+\"'"
},
{
"char_start": 223,
"char_end": 226,
"chars": "'\"+"
},
{
"char_start": 236,
"char_end": 239,
"chars": "+\"'"
},
{
"char_start": 240,
"char_end": 241,
"chars": "\""
}
],
"added": [
{
"char_start": 133,
"char_end": 149,
"chars": "?,?,?,?,?,?,?,?)"
},
{
"char_start": 150,
"char_end": 152,
"chars": ",("
}
]
} | github.com/DangerBlack/DungeonsAndDragonsMasterBot/commit/63f980c6dff746f5fcf3005d0646b6c24f81cdc0 | database.py | cwe-089 |
get | def get(self, user_id):
""" Fetch data for user with corresponding user_id """
return database_utilities.execute_query(f"""select * from users where user_id = '{user_id}'""") | def get(self, user_id):
""" Fetch data for user with corresponding user_id """
return database_utilities.execute_query(f"""select * from users where user_id = %s""", (user_id, )) | {
"deleted": [
{
"line_no": 3,
"char_start": 91,
"char_end": 194,
"line": " return database_utilities.execute_query(f\"\"\"select * from users where user_id = '{user_id}'\"\"\")\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 91,
"char_end": 198,
"line": " return database_utilities.execute_query(f\"\"\"select * from users where user_id = %s\"\"\", (user_id, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 179,
"char_end": 181,
"chars": "'{"
},
{
"char_start": 188,
"char_end": 193,
"chars": "}'\"\"\""
}
],
"added": [
{
"char_start": 179,
"char_end": 187,
"chars": "%s\"\"\", ("
},
{
"char_start": 194,
"char_end": 197,
"chars": ", )"
}
]
} | github.com/sgosal2/tiger-boards-backend/commit/4670109dd613df2f2fe7e8403ebd149df2b55485 | apis/users.py | cwe-089 |
h2h | @endpoints.route("/h2h")
def h2h():
if db == None:
init()
player1 = request.args.get('tag1', default="christmasmike")
player2 = request.args.get('tag2', default="christmasmike")
sql = "SELECT * FROM matches WHERE (player1 = '"+str(player1)+"' OR "\
+"player2 = '"+str(player1)+"') AND (player1 = '"+str(player2)+"' OR "\
+"player2 = '"+str(player2)+"') ORDER BY date DESC;"
result = db.exec(sql)
return json.dumps(result) | @endpoints.route("/h2h")
def h2h():
if db == None:
init()
player1 = request.args.get('tag1', default="christmasmike")
player2 = request.args.get('tag2', default="christmasmike")
sql = "SELECT * FROM matches WHERE (player1 = '{player1}' OR "\
+"player2 = '{player1}') AND (player1 = '{player2}' OR "\
+"player2 = '{player2}') ORDER BY date DESC;"
args = {'player1': player1, 'player2': player2}
result = db.exec(sql, args)
return json.dumps(result) | {
"deleted": [
{
"line_no": 8,
"char_start": 199,
"char_end": 274,
"line": " sql = \"SELECT * FROM matches WHERE (player1 = '\"+str(player1)+\"' OR \"\\\n"
},
{
"line_no": 9,
"char_start": 274,
"char_end": 358,
"line": " +\"player2 = '\"+str(player1)+\"') AND (player1 = '\"+str(player2)+\"' OR \"\\\n"
},
{
"line_no": 10,
"char_start": 358,
"char_end": 423,
"line": " +\"player2 = '\"+str(player2)+\"') ORDER BY date DESC;\"\n"
},
{
"line_no": 11,
"char_start": 423,
"char_end": 449,
"line": " result = db.exec(sql)\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 199,
"char_end": 267,
"line": " sql = \"SELECT * FROM matches WHERE (player1 = '{player1}' OR \"\\\n"
},
{
"line_no": 9,
"char_start": 267,
"char_end": 337,
"line": " +\"player2 = '{player1}') AND (player1 = '{player2}' OR \"\\\n"
},
{
"line_no": 10,
"char_start": 337,
"char_end": 395,
"line": " +\"player2 = '{player2}') ORDER BY date DESC;\"\n"
},
{
"line_no": 11,
"char_start": 395,
"char_end": 447,
"line": " args = {'player1': player1, 'player2': player2}\n"
},
{
"line_no": 12,
"char_start": 447,
"char_end": 479,
"line": " result = db.exec(sql, args)\n"
}
]
} | {
"deleted": [
{
"char_start": 250,
"char_end": 256,
"chars": "\"+str("
},
{
"char_start": 263,
"char_end": 266,
"chars": ")+\""
},
{
"char_start": 299,
"char_end": 305,
"chars": "\"+str("
},
{
"char_start": 312,
"char_end": 315,
"chars": ")+\""
},
{
"char_start": 334,
"char_end": 340,
"chars": "\"+str("
},
{
"char_start": 347,
"char_end": 350,
"chars": ")+\""
},
{
"char_start": 383,
"char_end": 389,
"chars": "\"+str("
},
{
"char_start": 396,
"char_end": 399,
"chars": ")+\""
}
],
"added": [
{
"char_start": 250,
"char_end": 251,
"chars": "{"
},
{
"char_start": 258,
"char_end": 259,
"chars": "}"
},
{
"char_start": 292,
"char_end": 293,
"chars": "{"
},
{
"char_start": 300,
"char_end": 301,
"chars": "}"
},
{
"char_start": 320,
"char_end": 321,
"chars": "{"
},
{
"char_start": 328,
"char_end": 329,
"chars": "}"
},
{
"char_start": 362,
"char_end": 363,
"chars": "{"
},
{
"char_start": 370,
"char_end": 371,
"chars": "}"
},
{
"char_start": 399,
"char_end": 451,
"chars": "args = {'player1': player1, 'player2': player2}\n "
},
{
"char_start": 471,
"char_end": 477,
"chars": ", args"
}
]
} | github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63 | endpoints.py | cwe-089 |
insertData | def insertData(self,userid,post):
sqlText="insert into post(userid,date,comment) \
values(%d,current_timestamp(0),'%s');"%(userid,post);
result=sql.insertDB(self.conn,sqlText)
return result; | def insertData(self,userid,post):
sqlText="insert into post(userid,date,comment) \
values(%s,current_timestamp(0),%s);"
params=[userid,post];
result=sql.insertDB(self.conn,sqlText,params)
return result; | {
"deleted": [
{
"line_no": 3,
"char_start": 95,
"char_end": 165,
"line": " values(%d,current_timestamp(0),'%s');\"%(userid,post);\n"
},
{
"line_no": 4,
"char_start": 165,
"char_end": 212,
"line": " result=sql.insertDB(self.conn,sqlText)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 95,
"char_end": 148,
"line": " values(%s,current_timestamp(0),%s);\"\n"
},
{
"line_no": 4,
"char_start": 148,
"char_end": 178,
"line": " params=[userid,post];\n"
},
{
"line_no": 5,
"char_start": 178,
"char_end": 232,
"line": " result=sql.insertDB(self.conn,sqlText,params)\n"
}
]
} | {
"deleted": [
{
"char_start": 119,
"char_end": 120,
"chars": "d"
},
{
"char_start": 142,
"char_end": 143,
"chars": "'"
},
{
"char_start": 145,
"char_end": 146,
"chars": "'"
},
{
"char_start": 149,
"char_end": 151,
"chars": "%("
},
{
"char_start": 162,
"char_end": 163,
"chars": ")"
}
],
"added": [
{
"char_start": 119,
"char_end": 120,
"chars": "s"
},
{
"char_start": 147,
"char_end": 164,
"chars": "\n params=["
},
{
"char_start": 175,
"char_end": 176,
"chars": "]"
},
{
"char_start": 223,
"char_end": 230,
"chars": ",params"
}
]
} | github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9 | modules/post.py | cwe-089 |
get_requested_month_for_inverter | def get_requested_month_for_inverter(self, inverter_serial, date):
data = dict()
month_start, month_end = self.get_epoch_month(date)
data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}
month_total = 0
query = '''
SELECT TimeStamp, DayYield AS Power
FROM MonthData
WHERE TimeStamp BETWEEN %s AND %s AND Serial = %s
'''
data['data'] = list()
for row in self.c.execute(query % (month_start, month_end, inverter_serial)):
data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})
month_total += row[1]
data['total'] = month_total
query = '''
SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max
FROM MonthData
WHERE Serial = %s;
''' % inverter_serial
self.c.execute(query)
first_data, last_data = self.c.fetchone()
if first_data: data['hasPrevious'] = (first_data < month_start)
else: data['hasPrevious'] = False
if last_data: data['hasNext'] = (last_data > month_end)
else: data['hasNext'] = False
return data | def get_requested_month_for_inverter(self, inverter_serial, date):
data = dict()
month_start, month_end = self.get_epoch_month(date)
data['interval'] = {'from': self.convert_local_ts_to_utc(month_start, self.local_timezone), 'to': self.convert_local_ts_to_utc(month_end, self.local_timezone)}
month_total = 0
query = '''
SELECT TimeStamp, DayYield AS Power
FROM MonthData
WHERE TimeStamp BETWEEN ? AND ? AND Serial=?;
'''
data['data'] = list()
for row in self.c.execute(query, (month_start, month_end, inverter_serial)):
data['data'].append({'time': self.convert_local_ts_to_utc(row[0], self.local_timezone), 'power': row[1]})
month_total += row[1]
data['total'] = month_total
query = '''
SELECT MIN(TimeStamp) as Min, MAX(TimeStamp) as Max
FROM MonthData
WHERE Serial=?;
'''
self.c.execute(query, (inverter_serial,))
first_data, last_data = self.c.fetchone()
if first_data: data['hasPrevious'] = (first_data < month_start)
else: data['hasPrevious'] = False
if last_data: data['hasNext'] = (last_data > month_end)
else: data['hasNext'] = False
return data | {
"deleted": [
{
"line_no": 11,
"char_start": 444,
"char_end": 506,
"line": " WHERE TimeStamp BETWEEN %s AND %s AND Serial = %s\n"
},
{
"line_no": 15,
"char_start": 553,
"char_end": 639,
"line": " for row in self.c.execute(query % (month_start, month_end, inverter_serial)):\n"
},
{
"line_no": 24,
"char_start": 942,
"char_end": 973,
"line": " WHERE Serial = %s;\n"
},
{
"line_no": 25,
"char_start": 973,
"char_end": 1007,
"line": " ''' % inverter_serial\n"
},
{
"line_no": 27,
"char_start": 1008,
"char_end": 1038,
"line": " self.c.execute(query)\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 444,
"char_end": 502,
"line": " WHERE TimeStamp BETWEEN ? AND ? AND Serial=?;\n"
},
{
"line_no": 15,
"char_start": 549,
"char_end": 634,
"line": " for row in self.c.execute(query, (month_start, month_end, inverter_serial)):\n"
},
{
"line_no": 24,
"char_start": 937,
"char_end": 965,
"line": " WHERE Serial=?;\n"
},
{
"line_no": 25,
"char_start": 965,
"char_end": 981,
"line": " '''\n"
},
{
"line_no": 27,
"char_start": 982,
"char_end": 1032,
"line": " self.c.execute(query, (inverter_serial,))\n"
}
]
} | {
"deleted": [
{
"char_start": 480,
"char_end": 482,
"chars": "%s"
},
{
"char_start": 487,
"char_end": 489,
"chars": "%s"
},
{
"char_start": 500,
"char_end": 501,
"chars": " "
},
{
"char_start": 502,
"char_end": 505,
"chars": " %s"
},
{
"char_start": 592,
"char_end": 594,
"chars": " %"
},
{
"char_start": 966,
"char_end": 967,
"chars": " "
},
{
"char_start": 968,
"char_end": 971,
"chars": " %s"
},
{
"char_start": 988,
"char_end": 1006,
"chars": " % inverter_serial"
}
],
"added": [
{
"char_start": 480,
"char_end": 481,
"chars": "?"
},
{
"char_start": 486,
"char_end": 487,
"chars": "?"
},
{
"char_start": 499,
"char_end": 501,
"chars": "?;"
},
{
"char_start": 588,
"char_end": 589,
"chars": ","
},
{
"char_start": 962,
"char_end": 963,
"chars": "?"
},
{
"char_start": 1010,
"char_end": 1030,
"chars": ", (inverter_serial,)"
}
]
} | github.com/philipptrenz/sunportal/commit/7eef493a168ed4e6731ff800713bfb8aee99a506 | util/database.py | cwe-089 |
delete_resultSet | def delete_resultSet(self, session, id):
self._openContainer(session)
sid = str(id)
if (self.idNormalizer is not None):
sid = self.idNormalizer.process_string(session, sid)
query = "DELETE FROM %s WHERE identifier = '%s';" % (self.table, sid)
self._query(query) | def delete_resultSet(self, session, id):
self._openContainer(session)
sid = str(id)
if (self.idNormalizer is not None):
sid = self.idNormalizer.process_string(session, sid)
query = "DELETE FROM %s WHERE identifier = $1;" % (self.table)
self._query(query, sid) | {
"deleted": [
{
"line_no": 6,
"char_start": 213,
"char_end": 291,
"line": " query = \"DELETE FROM %s WHERE identifier = '%s';\" % (self.table, sid)\n"
},
{
"line_no": 7,
"char_start": 291,
"char_end": 317,
"line": " self._query(query)\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 213,
"char_end": 284,
"line": " query = \"DELETE FROM %s WHERE identifier = $1;\" % (self.table)\n"
},
{
"line_no": 7,
"char_start": 284,
"char_end": 315,
"line": " self._query(query, sid)"
}
]
} | {
"deleted": [
{
"char_start": 264,
"char_end": 268,
"chars": "'%s'"
},
{
"char_start": 284,
"char_end": 289,
"chars": ", sid"
}
],
"added": [
{
"char_start": 264,
"char_end": 266,
"chars": "$1"
},
{
"char_start": 309,
"char_end": 314,
"chars": ", sid"
}
]
} | github.com/cheshire3/cheshire3/commit/d350363b4ea10f102c24c8f26d7b76b006323e8e | cheshire3/sql/resultSetStore.py | cwe-089 |
getSeriesDateFromDatabase | def getSeriesDateFromDatabase(submission):
database = sqlite3.connect('database.db')
cursor = database.cursor()
return cursor.execute("SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = '" + str(getTitle(submission)) + "'").fetchone()[0]
database.close() | def getSeriesDateFromDatabase(submission):
database = sqlite3.connect('database.db')
cursor = database.cursor()
return cursor.execute("SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = ?", [getTitle(submission)]).fetchone()[0]
database.close() | {
"deleted": [
{
"line_no": 4,
"char_start": 120,
"char_end": 256,
"line": " return cursor.execute(\"SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = '\" + str(getTitle(submission)) + \"'\").fetchone()[0]\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 120,
"char_end": 246,
"line": " return cursor.execute(\"SELECT StartDate FROM SeriesTracking WHERE SeriesTitle = ?\", [getTitle(submission)]).fetchone()[0]\n"
}
]
} | {
"deleted": [
{
"char_start": 204,
"char_end": 205,
"chars": "'"
},
{
"char_start": 206,
"char_end": 208,
"chars": " +"
},
{
"char_start": 209,
"char_end": 213,
"chars": "str("
},
{
"char_start": 233,
"char_end": 240,
"chars": ") + \"'\""
}
],
"added": [
{
"char_start": 204,
"char_end": 205,
"chars": "?"
},
{
"char_start": 206,
"char_end": 207,
"chars": ","
},
{
"char_start": 208,
"char_end": 209,
"chars": "["
},
{
"char_start": 229,
"char_end": 230,
"chars": "]"
}
]
} | github.com/LiquidFun/Reddit-GeoGuessr-Tracking-Bot/commit/0cad2d52e24b05da32789fbc8face7a9999a71f9 | CheckAndPostForSeriesSubmissions.py | cwe-089 |
karma_add | def karma_add(name):
karma = karma_ask(name)
db = db_connect()
cursor = db.cursor()
if karma is None:
try:
cursor.execute('''
INSERT INTO people(name,karma,shame) VALUES('{}',1,0)
'''.format(name))
db.commit()
logger.debug('Inserted into karmadb 1 karma for {}'.format(name))
return 1
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise
else:
karma = karma + 1
try:
cursor.execute('''
UPDATE people SET karma = {0} WHERE name = '{1}'
'''.format(karma, name))
db.commit()
logger.debug('Inserted into karmadb {} karma for {}'.format(
karma, name))
return karma
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise
db.close() | def karma_add(name):
karma = karma_ask(name)
db = db_connect()
cursor = db.cursor()
if karma is None:
try:
cursor.execute('''
INSERT INTO people(name,karma,shame) VALUES(%(name)s,1,0)
''', name)
db.commit()
logger.debug('Inserted into karmadb 1 karma for {}'.format(name))
return 1
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise
else:
karma = karma + 1
try:
cursor.execute('''
UPDATE people SET karma = %(karma)s WHERE name = %(name)s
''', (karma, name))
db.commit()
logger.debug('Inserted into karmadb {} karma for {}'.format(
karma,
name,
))
return karma
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise
db.close() | {
"deleted": [
{
"line_no": 8,
"char_start": 162,
"char_end": 232,
"line": " INSERT INTO people(name,karma,shame) VALUES('{}',1,0)\n"
},
{
"line_no": 9,
"char_start": 232,
"char_end": 266,
"line": " '''.format(name))\n"
},
{
"line_no": 20,
"char_start": 588,
"char_end": 653,
"line": " UPDATE people SET karma = {0} WHERE name = '{1}'\n"
},
{
"line_no": 21,
"char_start": 653,
"char_end": 694,
"line": " '''.format(karma, name))\n"
},
{
"line_no": 24,
"char_start": 791,
"char_end": 821,
"line": " karma, name))\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 162,
"char_end": 236,
"line": " INSERT INTO people(name,karma,shame) VALUES(%(name)s,1,0)\n"
},
{
"line_no": 9,
"char_start": 236,
"char_end": 263,
"line": " ''', name)\n"
},
{
"line_no": 20,
"char_start": 585,
"char_end": 659,
"line": " UPDATE people SET karma = %(karma)s WHERE name = %(name)s\n"
},
{
"line_no": 21,
"char_start": 659,
"char_end": 695,
"line": " ''', (karma, name))\n"
},
{
"line_no": 24,
"char_start": 792,
"char_end": 815,
"line": " karma,\n"
},
{
"line_no": 25,
"char_start": 815,
"char_end": 837,
"line": " name,\n"
},
{
"line_no": 26,
"char_start": 837,
"char_end": 852,
"line": " ))\n"
}
]
} | {
"deleted": [
{
"char_start": 222,
"char_end": 226,
"chars": "'{}'"
},
{
"char_start": 251,
"char_end": 259,
"chars": ".format("
},
{
"char_start": 263,
"char_end": 264,
"chars": ")"
},
{
"char_start": 630,
"char_end": 633,
"chars": "{0}"
},
{
"char_start": 647,
"char_end": 652,
"chars": "'{1}'"
},
{
"char_start": 672,
"char_end": 679,
"chars": ".format"
}
],
"added": [
{
"char_start": 222,
"char_end": 230,
"chars": "%(name)s"
},
{
"char_start": 255,
"char_end": 257,
"chars": ", "
},
{
"char_start": 627,
"char_end": 636,
"chars": "%(karma)s"
},
{
"char_start": 650,
"char_end": 658,
"chars": "%(name)s"
},
{
"char_start": 678,
"char_end": 680,
"chars": ", "
},
{
"char_start": 814,
"char_end": 830,
"chars": "\n "
},
{
"char_start": 835,
"char_end": 849,
"chars": ",\n "
}
]
} | github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a | KarmaBoi/dbopts.py | cwe-089 |
update_date_modified | def update_date_modified(self):
sql = "UPDATE jdk_entries " + \
"SET date_last_modified = " + CURRENT_DATESTAMP + " " + \
"WHERE jdk_entries.id = '" + self.entry_id + "';"
db_execute(sql)
return None | def update_date_modified(self):
quote_tuple = CURRENT_DATESTAMP, self.entry_id
sql = "UPDATE jdk_entries " + \
"SET date_last_modified = ? " + \
"WHERE jdk_entries.id = ?;"
db_execute(sql, quote_tuple)
return None | {
"deleted": [
{
"line_no": 3,
"char_start": 70,
"char_end": 134,
"line": " \"SET date_last_modified = \" + CURRENT_DATESTAMP + \" \" + \\\n"
},
{
"line_no": 4,
"char_start": 134,
"char_end": 190,
"line": " \"WHERE jdk_entries.id = '\" + self.entry_id + \"';\"\n"
},
{
"line_no": 6,
"char_start": 195,
"char_end": 215,
"line": " db_execute(sql)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 34,
"char_end": 85,
"line": " quote_tuple = CURRENT_DATESTAMP, self.entry_id\n"
},
{
"line_no": 3,
"char_start": 85,
"char_end": 86,
"line": "\n"
},
{
"line_no": 5,
"char_start": 122,
"char_end": 162,
"line": " \"SET date_last_modified = ? \" + \\\n"
},
{
"line_no": 6,
"char_start": 162,
"char_end": 196,
"line": " \"WHERE jdk_entries.id = ?;\"\n"
},
{
"line_no": 8,
"char_start": 201,
"char_end": 234,
"line": " db_execute(sql, quote_tuple)\n"
}
]
} | {
"deleted": [
{
"char_start": 102,
"char_end": 127,
"chars": "\" + CURRENT_DATESTAMP + \""
},
{
"char_start": 164,
"char_end": 187,
"chars": "'\" + self.entry_id + \"'"
}
],
"added": [
{
"char_start": 38,
"char_end": 90,
"chars": "quote_tuple = CURRENT_DATESTAMP, self.entry_id\n\n "
},
{
"char_start": 154,
"char_end": 155,
"chars": "?"
},
{
"char_start": 192,
"char_end": 193,
"chars": "?"
},
{
"char_start": 219,
"char_end": 232,
"chars": ", quote_tuple"
}
]
} | github.com/peterlebrun/jdk/commit/000238566fbe55ba09676c3d57af04ae207235ae | entry.py | cwe-089 |
system_search | def system_search(self, search):
search = search.lower()
conn = sqlite3.connect('data/ed.db').cursor()
table = conn.execute(f"select * from populated where lower(name) = '{search}'")
results = table.fetchone()
if not results:
table = conn.execute(f"select * from systems where lower(name) = '{search}'")
results = table.fetchone()
if results:
keys = tuple(i[0] for i in table.description)
return '\n'.join(f'{key.replace("_", " ").title()}: {field}'
for key, field in zip(keys[1:], results[1:]) if field)
else:
return 'No systems found.' | def system_search(self, search):
search = search.lower()
conn = sqlite3.connect('data/ed.db').cursor()
table = conn.execute('select * from populated where lower(name) = ?', (search,))
results = table.fetchone()
if not results:
table = conn.execute('select * from systems where lower(name) = ?', (search,))
results = table.fetchone()
if results:
keys = tuple(i[0] for i in table.description)
return '\n'.join(f'{key.replace("_", " ").title()}: {field}'
for key, field in zip(keys[1:], results[1:]) if field)
else:
return 'No systems found.' | {
"deleted": [
{
"line_no": 4,
"char_start": 126,
"char_end": 215,
"line": " table = conn.execute(f\"select * from populated where lower(name) = '{search}'\")\r\n"
},
{
"line_no": 7,
"char_start": 276,
"char_end": 367,
"line": " table = conn.execute(f\"select * from systems where lower(name) = '{search}'\")\r\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 126,
"char_end": 216,
"line": " table = conn.execute('select * from populated where lower(name) = ?', (search,))\r\n"
},
{
"line_no": 7,
"char_start": 277,
"char_end": 369,
"line": " table = conn.execute('select * from systems where lower(name) = ?', (search,))\r\n"
}
]
} | {
"deleted": [
{
"char_start": 155,
"char_end": 157,
"chars": "f\""
},
{
"char_start": 202,
"char_end": 203,
"chars": "{"
},
{
"char_start": 209,
"char_end": 212,
"chars": "}'\""
},
{
"char_start": 309,
"char_end": 311,
"chars": "f\""
},
{
"char_start": 354,
"char_end": 355,
"chars": "{"
},
{
"char_start": 361,
"char_end": 364,
"chars": "}'\""
}
],
"added": [
{
"char_start": 155,
"char_end": 156,
"chars": "'"
},
{
"char_start": 200,
"char_end": 201,
"chars": "?"
},
{
"char_start": 202,
"char_end": 205,
"chars": ", ("
},
{
"char_start": 211,
"char_end": 213,
"chars": ",)"
},
{
"char_start": 310,
"char_end": 311,
"chars": "'"
},
{
"char_start": 353,
"char_end": 354,
"chars": "?"
},
{
"char_start": 355,
"char_end": 358,
"chars": ", ("
},
{
"char_start": 364,
"char_end": 366,
"chars": ",)"
}
]
} | github.com/BeatButton/beattie/commit/ab36b2053ee09faf4cc9a279cf7a4c010864cb29 | eddb.py | cwe-089 |
add_input | def add_input(self, data):
connection = self.connect()
try:
# The following introduces a deliberate security flaw - SQL Injection
query = "INSERT INTO crimes (description) VALUES ('{}');".format(data)
with connection.cursor() as cursor:
cursor.execute(query)
connection.commit()
finally:
connection.close() | def add_input(self, data):
connection = self.connect()
try:
# The following introduces a deliberate security flaw - SQL Injection
query = "INSERT INTO crimes (description) VALUES (%s);"
with connection.cursor() as cursor:
cursor.execute(query, data)
connection.commit()
finally:
connection.close() | {
"deleted": [
{
"line_no": 5,
"char_start": 162,
"char_end": 245,
"line": " query = \"INSERT INTO crimes (description) VALUES ('{}');\".format(data)\n"
},
{
"line_no": 7,
"char_start": 293,
"char_end": 331,
"line": " cursor.execute(query)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 162,
"char_end": 230,
"line": " query = \"INSERT INTO crimes (description) VALUES (%s);\"\n"
},
{
"line_no": 7,
"char_start": 278,
"char_end": 322,
"line": " cursor.execute(query, data)\n"
}
]
} | {
"deleted": [
{
"char_start": 224,
"char_end": 228,
"chars": "'{}'"
},
{
"char_start": 231,
"char_end": 244,
"chars": ".format(data)"
}
],
"added": [
{
"char_start": 224,
"char_end": 226,
"chars": "%s"
},
{
"char_start": 314,
"char_end": 320,
"chars": ", data"
}
]
} | github.com/rwolf527/crimemap/commit/50b0695e0b4c46165e6146f6fac4cd6871d9fdf6 | dbhelper.py | cwe-089 |
get_login | @bot.message_handler(commands =['login'])
def get_login(message):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = '" + str(message.chat.id) + "'")
name = conn.fetchone()
if name != None:
bot.send_message(message.chat.id, "Previous handle: " + str(name[1]))
else:
bot.send_message(message.chat.id, "Previous handle: None")
settings.close()
bot.send_message(message.chat.id, "Type new handle: ")
set_state(message.chat.id, config.States.S_LOGIN.value) | @bot.message_handler(commands =['login'])
def get_login(message):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = ?", (str(message.chat.id),))
name = conn.fetchone()
if name != None:
bot.send_message(message.chat.id, "Previous handle: " + str(name[1]))
else:
bot.send_message(message.chat.id, "Previous handle: None")
settings.close()
bot.send_message(message.chat.id, "Type new handle: ")
set_state(message.chat.id, config.States.S_LOGIN.value) | {
"deleted": [
{
"line_no": 5,
"char_start": 195,
"char_end": 282,
"line": " conn.execute(\"select * from users where chat_id = '\" + str(message.chat.id) + \"'\")\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 195,
"char_end": 278,
"line": " conn.execute(\"select * from users where chat_id = ?\", (str(message.chat.id),))\n"
}
]
} | {
"deleted": [
{
"char_start": 249,
"char_end": 250,
"chars": "'"
},
{
"char_start": 251,
"char_end": 253,
"chars": " +"
},
{
"char_start": 274,
"char_end": 280,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 249,
"char_end": 250,
"chars": "?"
},
{
"char_start": 251,
"char_end": 252,
"chars": ","
},
{
"char_start": 253,
"char_end": 254,
"chars": "("
},
{
"char_start": 274,
"char_end": 276,
"chars": ",)"
}
]
} | github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90 | bot.py | cwe-089 |
login | def login(self, username, password):
select_query = """
SELECT client_id, username, balance, message
FROM Clients
WHERE username = '{}' AND password = '{}'
LIMIT 1
""".format(username, password)
cursor = self.__conn.cursor()
cursor.execute(select_query)
user = cursor.fetchone()
if(user):
return Client(user[0], user[1], user[2], user[3])
else:
return False | def login(self, username, password):
select_query = """
SELECT client_id, username, balance, message
FROM Clients
WHERE username = ? AND password = ?
LIMIT 1
"""
cursor = self.__conn.cursor()
cursor.execute(select_query, (username, password))
user = cursor.fetchone()
if(user):
return Client(user[0], user[1], user[2], user[3])
else:
return False | {
"deleted": [
{
"line_no": 5,
"char_start": 150,
"char_end": 204,
"line": " WHERE username = '{}' AND password = '{}'\n"
},
{
"line_no": 7,
"char_start": 224,
"char_end": 263,
"line": " \"\"\".format(username, password)\n"
},
{
"line_no": 11,
"char_start": 303,
"char_end": 340,
"line": " cursor.execute(select_query)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 150,
"char_end": 198,
"line": " WHERE username = ? AND password = ?\n"
},
{
"line_no": 7,
"char_start": 218,
"char_end": 230,
"line": " \"\"\"\n"
},
{
"line_no": 11,
"char_start": 270,
"char_end": 329,
"line": " cursor.execute(select_query, (username, password))\n"
}
]
} | {
"deleted": [
{
"char_start": 179,
"char_end": 183,
"chars": "'{}'"
},
{
"char_start": 199,
"char_end": 203,
"chars": "'{}'"
},
{
"char_start": 235,
"char_end": 262,
"chars": ".format(username, password)"
}
],
"added": [
{
"char_start": 179,
"char_end": 180,
"chars": "?"
},
{
"char_start": 196,
"char_end": 197,
"chars": "?"
},
{
"char_start": 305,
"char_end": 327,
"chars": ", (username, password)"
}
]
} | github.com/AnetaStoycheva/Programming101_HackBulgaria/commit/c0d6f4b8fe83a375832845a45952b5153e4c34f3 | Week_9/sql_manager.py | cwe-089 |
get_current_state | def get_current_state(chat_id):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+"\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = '" + str(chat_id) + "'")
name = conn.fetchone()
if name != None:
return name[4]
else:
return False
settings.close() | def get_current_state(chat_id):
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__))+"\\bases\\settings.db")
conn = settings.cursor()
conn.execute("select * from users where chat_id = ?", (str(chat_id),))
name = conn.fetchone()
if name != None:
return name[4]
else:
return False
settings.close() | {
"deleted": [
{
"line_no": 4,
"char_start": 159,
"char_end": 238,
"line": " conn.execute(\"select * from users where chat_id = '\" + str(chat_id) + \"'\")\n"
}
],
"added": [
{
"line_no": 4,
"char_start": 159,
"char_end": 234,
"line": " conn.execute(\"select * from users where chat_id = ?\", (str(chat_id),))\n"
}
]
} | {
"deleted": [
{
"char_start": 213,
"char_end": 214,
"chars": "'"
},
{
"char_start": 215,
"char_end": 217,
"chars": " +"
},
{
"char_start": 230,
"char_end": 236,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 213,
"char_end": 214,
"chars": "?"
},
{
"char_start": 215,
"char_end": 216,
"chars": ","
},
{
"char_start": 217,
"char_end": 218,
"chars": "("
},
{
"char_start": 230,
"char_end": 232,
"chars": ",)"
}
]
} | github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90 | bot.py | cwe-089 |
fetch_page_name | def fetch_page_name(self, page_id):
'''
Returns the page name corresponding to the provided page ID.
Args:
page_id: The page ID whose ID to fetch.
Returns:
str: The page name corresponding to the provided page ID.
Raises:
ValueError: If the provided page ID is invalid or does not exist.
'''
helpers.validate_page_id(page_id)
query = 'SELECT name FROM pages WHERE id="{0}"'.format(page_id)
self.cursor.execute(query)
page_name = self.cursor.fetchone()
if not page_name:
raise ValueError('Invalid page ID "{0}" provided. Page ID does not exist.'.format(page_id))
return page_name[0].encode('utf-8').replace('_', ' ') | def fetch_page_name(self, page_id):
'''
Returns the page name corresponding to the provided page ID.
Args:
page_id: The page ID whose ID to fetch.
Returns:
str: The page name corresponding to the provided page ID.
Raises:
ValueError: If the provided page ID is invalid or does not exist.
'''
helpers.validate_page_id(page_id)
query = 'SELECT name FROM pages WHERE id = ?;'
query_bindings = (page_id,)
self.cursor.execute(query, query_bindings)
page_name = self.cursor.fetchone()
if not page_name:
raise ValueError('Invalid page ID "{0}" provided. Page ID does not exist.'.format(page_id))
return page_name[0].encode('utf-8').replace('_', ' ') | {
"deleted": [
{
"line_no": 16,
"char_start": 378,
"char_end": 446,
"line": " query = 'SELECT name FROM pages WHERE id=\"{0}\"'.format(page_id)\n"
},
{
"line_no": 17,
"char_start": 446,
"char_end": 477,
"line": " self.cursor.execute(query)\n"
}
],
"added": [
{
"line_no": 16,
"char_start": 378,
"char_end": 429,
"line": " query = 'SELECT name FROM pages WHERE id = ?;'\n"
},
{
"line_no": 17,
"char_start": 429,
"char_end": 461,
"line": " query_bindings = (page_id,)\n"
},
{
"line_no": 18,
"char_start": 461,
"char_end": 508,
"line": " self.cursor.execute(query, query_bindings)\n"
}
]
} | {
"deleted": [
{
"char_start": 423,
"char_end": 428,
"chars": "\"{0}\""
},
{
"char_start": 429,
"char_end": 432,
"chars": ".fo"
},
{
"char_start": 433,
"char_end": 436,
"chars": "mat"
}
],
"added": [
{
"char_start": 422,
"char_end": 423,
"chars": " "
},
{
"char_start": 424,
"char_end": 427,
"chars": " ?;"
},
{
"char_start": 428,
"char_end": 436,
"chars": "\n que"
},
{
"char_start": 437,
"char_end": 450,
"chars": "y_bindings = "
},
{
"char_start": 458,
"char_end": 459,
"chars": ","
},
{
"char_start": 490,
"char_end": 506,
"chars": ", query_bindings"
}
]
} | github.com/jwngr/sdow/commit/4db98f3521592f17550d2b723336f33fec5e112a | sdow/database.py | cwe-089 |
save_page_edit | @app.route('/<page_name>/save', methods=['POST'])
def save_page_edit(page_name):
# grab the new content from the user
content = request.form.get('content')
# check if 'page_name' exists in the database
query = db.query("select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1" % page_name)
result = query.namedresult()
# if it doesn't exist, create a new page in the database
if len(result) < 1:
db.insert(
'page', {
'page_name': page_name
}
)
else:
pass
# now that we're certain that the page exists in the database, we again grab the query
# and insert new content in the database
query = db.query("select id from page where page_name = '%s'" % page_name)
page_id = query.namedresult()[0].id
db.insert(
'page_content', {
'page_id': page_id,
'content': content,
'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", localtime())
}
)
return redirect("/%s" % page_name) | @app.route('/<page_name>/save', methods=['POST'])
def save_page_edit(page_name):
# grab the new content from the user
content = request.form.get('content')
# check if 'page_name' exists in the database
query = db.query("select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1", page_name)
result = query.namedresult()
# if it doesn't exist, create a new page in the database
if len(result) < 1:
db.insert(
'page', {
'page_name': page_name
}
)
else:
pass
# now that we're certain that the page exists in the database, we again grab the query
# and insert new content in the database
query = db.query("select id from page where page_name = '%s'" % page_name)
page_id = query.namedresult()[0].id
db.insert(
'page_content', {
'page_id': page_id,
'content': content,
'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", localtime())
}
)
return redirect("/%s" % page_name) | {
"deleted": [
{
"line_no": 6,
"char_start": 214,
"char_end": 454,
"line": " query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1\" % page_name)\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 214,
"char_end": 451,
"line": " query = db.query(\"select page_content.content, page.id as page_id, page_content.id as content_id from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1\", page_name)\n"
}
]
} | {
"deleted": [
{
"char_start": 397,
"char_end": 401,
"chars": "'%s'"
},
{
"char_start": 440,
"char_end": 442,
"chars": " %"
}
],
"added": [
{
"char_start": 397,
"char_end": 399,
"chars": "$1"
},
{
"char_start": 438,
"char_end": 439,
"chars": ","
}
]
} | github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b | server.py | cwe-089 |
get_top_popular | def get_top_popular(top_num):
""" query the top(top_num) popular articles
top_num => list of [title, count]
"""
cmd = """SELECT title, views FROM articles
INNER JOIN (
SELECT path, count(path) AS views
FROM log GROUP BY log.path
) AS log
ON log.path = '/article/' || articles.slug
ORDER BY views DESC
LIMIT {}""".format(top_num)
return execute_query(cmd) | def get_top_popular(top_num):
""" query the top(top_num) popular articles
top_num => list of [title, count]
"""
cmd = """SELECT title, views FROM articles
INNER JOIN (
SELECT path, count(path) AS views
FROM log GROUP BY log.path
) AS log
ON log.path = '/article/' || articles.slug
ORDER BY views DESC
LIMIT %s"""
data = [top_num, ]
return execute_query(cmd, data) | {
"deleted": [
{
"line_no": 12,
"char_start": 410,
"char_end": 452,
"line": " LIMIT {}\"\"\".format(top_num)\r\n"
},
{
"line_no": 13,
"char_start": 452,
"char_end": 481,
"line": " return execute_query(cmd)\r\n"
}
],
"added": [
{
"line_no": 12,
"char_start": 410,
"char_end": 436,
"line": " LIMIT %s\"\"\"\r\n"
},
{
"line_no": 13,
"char_start": 436,
"char_end": 460,
"line": " data = [top_num, ]\r\n"
},
{
"line_no": 14,
"char_start": 460,
"char_end": 495,
"line": " return execute_query(cmd, data)\r\n"
}
]
} | {
"deleted": [
{
"char_start": 429,
"char_end": 431,
"chars": "{}"
},
{
"char_start": 434,
"char_end": 439,
"chars": ".form"
},
{
"char_start": 441,
"char_end": 442,
"chars": "("
},
{
"char_start": 449,
"char_end": 450,
"chars": ")"
}
],
"added": [
{
"char_start": 429,
"char_end": 431,
"chars": "%s"
},
{
"char_start": 434,
"char_end": 441,
"chars": "\r\n d"
},
{
"char_start": 443,
"char_end": 448,
"chars": "a = ["
},
{
"char_start": 455,
"char_end": 458,
"chars": ", ]"
},
{
"char_start": 488,
"char_end": 494,
"chars": ", data"
}
]
} | github.com/thugasin/udacity-homework-logAnalyzer/commit/506f25f9a1caee7f17034adf7c75e0efbc88082b | logAnalyzerDb.py | cwe-089 |
render_page_edit | @app.route('/<page_name>/edit')
def render_page_edit(page_name):
query = db.query("select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1" % page_name)
wiki_page = query.namedresult()
if len(wiki_page) > 0:
content = wiki_page[0].content
else:
content = ""
return render_template(
'edit_page.html',
page_name = page_name,
content = content
) | @app.route('/<page_name>/edit')
def render_page_edit(page_name):
query = db.query("select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1", page_name)
wiki_page = query.namedresult()
if len(wiki_page) > 0:
content = wiki_page[0].content
else:
content = ""
return render_template(
'edit_page.html',
page_name = page_name,
content = content
) | {
"deleted": [
{
"line_no": 3,
"char_start": 65,
"char_end": 254,
"line": " query = db.query(\"select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = '%s' order by page_content.id desc limit 1\" % page_name)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 65,
"char_end": 251,
"line": " query = db.query(\"select page_content.content from page, page_content where page.id = page_content.page_id and page.page_name = $1 order by page_content.id desc limit 1\", page_name)\n"
}
]
} | {
"deleted": [
{
"char_start": 197,
"char_end": 201,
"chars": "'%s'"
},
{
"char_start": 240,
"char_end": 242,
"chars": " %"
}
],
"added": [
{
"char_start": 197,
"char_end": 199,
"chars": "$1"
},
{
"char_start": 238,
"char_end": 239,
"chars": ","
}
]
} | github.com/Pumala/python_wiki_app_redo/commit/65d60747cd8efb05970304234d3bd949d2088e8b | server.py | cwe-089 |
get_monthly_ranks_for_scene | def get_monthly_ranks_for_scene(db, scene, tag):
sql = "SELECT date, rank FROM ranks WHERE scene='{}' AND player='{}'".format(scene, tag)
res = db.exec(sql)
res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))]
# Build up a dict of {date: rank}
ranks = {}
for r in res:
ranks[r[0]] = r[1]
return ranks | def get_monthly_ranks_for_scene(db, scene, tag):
sql = "SELECT date, rank FROM ranks WHERE scene='{scene}' AND player='{tag}'"
args = {'scene': scene, 'tag': tag}
res = db.exec(sql, args)
res = [r for r in res if played_during_month(db, scene, tag, get_previous_month(r[0]))]
# Build up a dict of {date: rank}
ranks = {}
for r in res:
ranks[r[0]] = r[1]
return ranks | {
"deleted": [
{
"line_no": 3,
"char_start": 50,
"char_end": 143,
"line": " sql = \"SELECT date, rank FROM ranks WHERE scene='{}' AND player='{}'\".format(scene, tag)\n"
},
{
"line_no": 4,
"char_start": 143,
"char_end": 166,
"line": " res = db.exec(sql)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 50,
"char_end": 132,
"line": " sql = \"SELECT date, rank FROM ranks WHERE scene='{scene}' AND player='{tag}'\"\n"
},
{
"line_no": 4,
"char_start": 132,
"char_end": 172,
"line": " args = {'scene': scene, 'tag': tag}\n"
},
{
"line_no": 5,
"char_start": 172,
"char_end": 201,
"line": " res = db.exec(sql, args)\n"
}
]
} | {
"deleted": [
{
"char_start": 123,
"char_end": 126,
"chars": ".fo"
},
{
"char_start": 127,
"char_end": 131,
"chars": "mat("
},
{
"char_start": 141,
"char_end": 142,
"chars": ")"
}
],
"added": [
{
"char_start": 104,
"char_end": 109,
"chars": "scene"
},
{
"char_start": 125,
"char_end": 128,
"chars": "tag"
},
{
"char_start": 131,
"char_end": 136,
"chars": "\n "
},
{
"char_start": 137,
"char_end": 153,
"chars": "rgs = {'scene': "
},
{
"char_start": 160,
"char_end": 161,
"chars": "'"
},
{
"char_start": 164,
"char_end": 171,
"chars": "': tag}"
},
{
"char_start": 193,
"char_end": 199,
"chars": ", args"
}
]
} | github.com/DKelle/Smash_stats/commit/4bb83f3f6ce7d6bebbeb512cd015f9e72cf36d63 | bracket_utils.py | cwe-089 |
auto_unlock_tasks | @staticmethod
def auto_unlock_tasks(project_id: int):
"""Unlock all tasks locked for longer than the auto-unlock delta"""
expiry_delta = Task.auto_unlock_delta()
lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat()
expiry_date = datetime.datetime.utcnow() - expiry_delta
old_locks_query = '''SELECT t.id
FROM tasks t, task_history th
WHERE t.id = th.task_id
AND t.project_id = th.project_id
AND t.task_status IN (1,3)
AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' )
AND th.action_text IS NULL
AND t.project_id = {0}
AND th.action_date <= '{1}'
'''.format(project_id, str(expiry_date))
old_tasks = db.engine.execute(old_locks_query)
if old_tasks.rowcount == 0:
# no tasks older than the delta found, return without further processing
return
for old_task in old_tasks:
task = Task.get(old_task[0], project_id)
task.auto_unlock_expired_tasks(expiry_date, lock_duration) | @staticmethod
def auto_unlock_tasks(project_id: int):
"""Unlock all tasks locked for longer than the auto-unlock delta"""
expiry_delta = Task.auto_unlock_delta()
lock_duration = (datetime.datetime.min + expiry_delta).time().isoformat()
expiry_date = datetime.datetime.utcnow() - expiry_delta
old_locks_query = '''SELECT t.id
FROM tasks t, task_history th
WHERE t.id = th.task_id
AND t.project_id = th.project_id
AND t.task_status IN (1,3)
AND th.action IN ( 'LOCKED_FOR_VALIDATION','LOCKED_FOR_MAPPING' )
AND th.action_text IS NULL
AND t.project_id = :project_id
AND th.action_date <= :expiry_date
'''
old_tasks = db.engine.execute(text(old_locks_query), project_id=project_id, expiry_date=str(expiry_date))
if old_tasks.rowcount == 0:
# no tasks older than the delta found, return without further processing
return
for old_task in old_tasks:
task = Task.get(old_task[0], project_id)
task.auto_unlock_expired_tasks(expiry_date, lock_duration) | {
"deleted": [
{
"line_no": 14,
"char_start": 652,
"char_end": 687,
"line": " AND t.project_id = {0}\n"
},
{
"line_no": 15,
"char_start": 687,
"char_end": 727,
"line": " AND th.action_date <= '{1}'\n"
},
{
"line_no": 16,
"char_start": 727,
"char_end": 780,
"line": " '''.format(project_id, str(expiry_date))\n"
},
{
"line_no": 18,
"char_start": 781,
"char_end": 836,
"line": " old_tasks = db.engine.execute(old_locks_query)\n"
}
],
"added": [
{
"line_no": 14,
"char_start": 652,
"char_end": 695,
"line": " AND t.project_id = :project_id\n"
},
{
"line_no": 15,
"char_start": 695,
"char_end": 742,
"line": " AND th.action_date <= :expiry_date\n"
},
{
"line_no": 16,
"char_start": 742,
"char_end": 758,
"line": " '''\n"
},
{
"line_no": 18,
"char_start": 759,
"char_end": 873,
"line": " old_tasks = db.engine.execute(text(old_locks_query), project_id=project_id, expiry_date=str(expiry_date))\n"
}
]
} | {
"deleted": [
{
"char_start": 683,
"char_end": 686,
"chars": "{0}"
},
{
"char_start": 721,
"char_end": 726,
"chars": "'{1}'"
},
{
"char_start": 742,
"char_end": 779,
"chars": ".format(project_id, str(expiry_date))"
}
],
"added": [
{
"char_start": 683,
"char_end": 694,
"chars": ":project_id"
},
{
"char_start": 729,
"char_end": 741,
"chars": ":expiry_date"
},
{
"char_start": 797,
"char_end": 802,
"chars": "text("
},
{
"char_start": 817,
"char_end": 871,
"chars": "), project_id=project_id, expiry_date=str(expiry_date)"
}
]
} | github.com/hotosm/tasking-manager/commit/dee040a2d22b3c4d5e38e2dbf8c6b651ad4c241a | server/models/postgis/task.py | cwe-089 |
add_input | def add_input(self, data):
connection = self.connect()
try:
# The following introduces a deliberate security flaw.
# See section on SQL injection below
query = "INSERT INTO crimes (description) VALUES('{}');".format(data)
with connection.cursor() as cursor:
cursor.execute(query)
connection.commit()
finally:
connection.close() | def add_input(self, data):
connection = self.connect()
try:
# The following introduces a deliberate security flaw.
# See section on SQL injection below
query = "INSERT INTO crimes (description) VALUES(%s);"
with connection.cursor() as cursor:
cursor.execute(query, data)
connection.commit()
finally:
connection.close() | {
"deleted": [
{
"line_no": 6,
"char_start": 197,
"char_end": 279,
"line": " query = \"INSERT INTO crimes (description) VALUES('{}');\".format(data)\n"
},
{
"line_no": 8,
"char_start": 327,
"char_end": 365,
"line": " cursor.execute(query)\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 197,
"char_end": 264,
"line": " query = \"INSERT INTO crimes (description) VALUES(%s);\"\n"
},
{
"line_no": 8,
"char_start": 312,
"char_end": 356,
"line": " cursor.execute(query, data)\n"
}
]
} | {
"deleted": [
{
"char_start": 258,
"char_end": 262,
"chars": "'{}'"
},
{
"char_start": 265,
"char_end": 278,
"chars": ".format(data)"
}
],
"added": [
{
"char_start": 258,
"char_end": 260,
"chars": "%s"
},
{
"char_start": 348,
"char_end": 354,
"chars": ", data"
}
]
} | github.com/mudspringhiker/crimemap/commit/35e78962e7288c643cdde0f886ff7aa5ac77cb8c | dbhelper.py | cwe-089 |
getAllComments | def getAllComments(self):
sqlText="select comment from comments where userid=%d order by date;"
allposts=sql.queryDB(self.conn,sqlText)
return allposts; | def getAllComments(self):
sqlText="select comment from comments where userid=%s order by date;"
params = [self.userid]
allposts=sql.queryDB(self.conn,sqlText,params)
return allposts; | {
"deleted": [
{
"line_no": 2,
"char_start": 30,
"char_end": 108,
"line": " sqlText=\"select comment from comments where userid=%d order by date;\"\n"
},
{
"line_no": 3,
"char_start": 108,
"char_end": 156,
"line": " allposts=sql.queryDB(self.conn,sqlText)\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 30,
"char_end": 108,
"line": " sqlText=\"select comment from comments where userid=%s order by date;\"\n"
},
{
"line_no": 3,
"char_start": 108,
"char_end": 139,
"line": " params = [self.userid]\n"
},
{
"line_no": 4,
"char_start": 139,
"char_end": 194,
"line": " allposts=sql.queryDB(self.conn,sqlText,params)\n"
}
]
} | {
"deleted": [
{
"char_start": 90,
"char_end": 91,
"chars": "d"
}
],
"added": [
{
"char_start": 90,
"char_end": 91,
"chars": "s"
},
{
"char_start": 116,
"char_end": 147,
"chars": "params = [self.userid]\n "
},
{
"char_start": 185,
"char_end": 192,
"chars": ",params"
}
]
} | github.com/ShaominLi/Twitter_project/commit/5329d91f9e569c95184053c8e7ef596949c33ce9 | modules/users.py | cwe-089 |
update_user | def update_user(username, chat_id, last_update):
conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\users\\" + username + '.db')
conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\cf.db')
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\settings.db")
cursor = conn.cursor()
cursor2 = conn2.cursor()
cursor_settings = settings.cursor()
cursor_settings.execute("select last_problem from users where chat_id = '" + str(chat_id) + "'")
update_eq = cursor_settings.fetchone()
cursor_settings.execute("select * from last_update_problemset")
update_base = cursor_settings.fetchone()
last_problem = update_base[0]
if update_eq[0] != update_base[0]:
cursor2.execute("SELECT * FROM problems")
x = cursor2.fetchone()
while x != None:
cursor.execute("select * from result where problem = '" + str(x[0]) + "' and diff = '" + str(x[1]) + "'")
x2 = cursor.fetchone()
if x2 == None:
cursor.execute("insert into result values (?, ?, ? )", (x[0], x[1], "NULL"))
last_problem = x
x = cursor2.fetchone()
conn2.close()
settings.close()
if len(last_problem) == 2:
last_problem = last_problem[0] + last_problem[1]
url = 'http://codeforces.com/submissions/' + username
r = requests.get(url)
max_page = 1
soup = BeautifulSoup(r.text, "lxml")
for link in soup.find_all(attrs={"class": "page-index"}):
s = link.find('a')
s2 = s.get("href").split('/')
max_page = max(max_page, int(s2[4]))
v = False
r = requests.get('http://codeforces.com/submissions/' + username + '/page/0')
soup = BeautifulSoup(r.text, "lxml")
last_try_new = soup.find(attrs={"class": "status-small"})
last_try_new = str(last_try_new).split()
last_try_new = str(last_try_new[2]) + str(last_try_new[3])
for i in range(1, max_page + 1):
r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i))
soup = BeautifulSoup(r.text, "lxml")
count = 0
j = 0
ver = soup.find_all(attrs={"class": "submissionVerdictWrapper"})
last_try = soup.find_all(attrs={"class": "status-small"})
for link in soup.find_all('a'):
last_try_date = str(last_try[j]).split()
last_try_date = str(last_try_date[2]) + str(last_try_date[3])
if last_try_date == last_update:
v = True
break
s = link.get('href')
if s != None and s.find('/problemset') != -1:
s = s.split('/')
if len(s) == 5:
s2 = str(ver[count]).split()
s2 = s2[5].split('\"')
count += 1
j += 1
cursor.execute("select * from result where problem = '" + s[3] + "'and diff = '" + s[4] + "'")
x = cursor.fetchone()
if s2[1] == 'OK' and x != None:
cursor.execute(
"update result set verdict = '" + s2[1] + "' where problem = '" + s[3] + "' and diff = '" +
s[4] + "'")
if x[2] != 'OK':
cursor.execute(
"update result set verdict = '" + s2[1] + "' where problem = '" + s[3] + "' and diff = '" +
s[4] + "'")
if v:
break
conn.commit()
conn.close()
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\settings.db")
conn = settings.cursor()
conn.execute("update users set username = '" + str(username) + "' where chat_id = '" + str(chat_id) + "'")
conn.execute("update users set last_update = '" + str(last_try_new) + "' where chat_id = '" + str(chat_id) + "'")
conn.execute("update users set last_problem = '" + str(last_problem) + "' where chat_id = '" + str(chat_id) + "'")
settings.commit()
settings.close() | def update_user(username, chat_id, last_update):
conn = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\users\\" + username + '.db')
conn2 = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + '\\cf.db')
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\settings.db")
cursor = conn.cursor()
cursor2 = conn2.cursor()
cursor_settings = settings.cursor()
cursor_settings.execute("select last_problem from users where chat_id = ?", (str(chat_id), ))
update_eq = cursor_settings.fetchone()
cursor_settings.execute("select * from last_update_problemset")
update_base = cursor_settings.fetchone()
last_problem = update_base[0]
if update_eq[0] != update_base[0]:
cursor2.execute("SELECT * FROM problems")
x = cursor2.fetchone()
while x != None:
cursor.execute("select * from result where problem = ? and diff = ?", (str(x[0]), str(x[1])))
x2 = cursor.fetchone()
if x2 == None:
cursor.execute("insert into result values (?, ?, ? )", (x[0], x[1], "NULL"))
last_problem = x
x = cursor2.fetchone()
conn2.close()
settings.close()
if len(last_problem) == 2:
last_problem = last_problem[0] + last_problem[1]
url = 'http://codeforces.com/submissions/' + username
r = requests.get(url)
max_page = 1
soup = BeautifulSoup(r.text, "lxml")
for link in soup.find_all(attrs={"class": "page-index"}):
s = link.find('a')
s2 = s.get("href").split('/')
max_page = max(max_page, int(s2[4]))
v = False
r = requests.get('http://codeforces.com/submissions/' + username + '/page/0')
soup = BeautifulSoup(r.text, "lxml")
last_try_new = soup.find(attrs={"class": "status-small"})
last_try_new = str(last_try_new).split()
last_try_new = str(last_try_new[2]) + str(last_try_new[3])
for i in range(1, max_page + 1):
r = requests.get('http://codeforces.com/submissions/' + username + '/page/' + str(i))
soup = BeautifulSoup(r.text, "lxml")
count = 0
j = 0
ver = soup.find_all(attrs={"class": "submissionVerdictWrapper"})
last_try = soup.find_all(attrs={"class": "status-small"})
for link in soup.find_all('a'):
last_try_date = str(last_try[j]).split()
last_try_date = str(last_try_date[2]) + str(last_try_date[3])
if last_try_date == last_update:
v = True
break
s = link.get('href')
if s != None and s.find('/problemset') != -1:
s = s.split('/')
if len(s) == 5:
s2 = str(ver[count]).split()
s2 = s2[5].split('\"')
count += 1
j += 1
cursor.execute("select * from result where problem = ? and diff = ?", (s[3], s[4]))
x = cursor.fetchone()
if s2[1] == 'OK' and x != None:
cursor.execute("update result set verdict = ? where problem = ? and diff = ?", (s2[1], s[3], s[4]))
if x[2] != 'OK':
cursor.execute("update result set verdict = ? where problem = ? and diff = ?", (s2[1], s[3], s[4]))
if v:
break
conn.commit()
conn.close()
settings = sqlite3.connect(os.path.abspath(os.path.dirname(__file__)) + "\\settings.db")
conn = settings.cursor()
conn.execute("update users set username = ? where chat_id = ?", (str(username), str(chat_id)))
conn.execute("update users set last_update = ? where chat_id = ?", (str(last_try_new), str(chat_id)))
conn.execute("update users set last_problem = ? where chat_id = ?", (str(last_problem), str(chat_id)))
settings.commit()
settings.close() | {
"deleted": [
{
"line_no": 8,
"char_start": 426,
"char_end": 527,
"line": " cursor_settings.execute(\"select last_problem from users where chat_id = '\" + str(chat_id) + \"'\")\n"
},
{
"line_no": 17,
"char_start": 862,
"char_end": 980,
"line": " cursor.execute(\"select * from result where problem = '\" + str(x[0]) + \"' and diff = '\" + str(x[1]) + \"'\")\n"
},
{
"line_no": 65,
"char_start": 2870,
"char_end": 2985,
"line": " cursor.execute(\"select * from result where problem = '\" + s[3] + \"'and diff = '\" + s[4] + \"'\")\n"
},
{
"line_no": 68,
"char_start": 3079,
"char_end": 3119,
"line": " cursor.execute(\n"
},
{
"line_no": 69,
"char_start": 3119,
"char_end": 3239,
"line": " \"update result set verdict = '\" + s2[1] + \"' where problem = '\" + s[3] + \"' and diff = '\" +\n"
},
{
"line_no": 70,
"char_start": 3239,
"char_end": 3279,
"line": " s[4] + \"'\")\n"
},
{
"line_no": 72,
"char_start": 3316,
"char_end": 3356,
"line": " cursor.execute(\n"
},
{
"line_no": 73,
"char_start": 3356,
"char_end": 3476,
"line": " \"update result set verdict = '\" + s2[1] + \"' where problem = '\" + s[3] + \"' and diff = '\" +\n"
},
{
"line_no": 74,
"char_start": 3476,
"char_end": 3516,
"line": " s[4] + \"'\")\n"
},
{
"line_no": 83,
"char_start": 3707,
"char_end": 3818,
"line": " conn.execute(\"update users set username = '\" + str(username) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n"
},
{
"line_no": 84,
"char_start": 3818,
"char_end": 3936,
"line": " conn.execute(\"update users set last_update = '\" + str(last_try_new) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n"
},
{
"line_no": 85,
"char_start": 3936,
"char_end": 4055,
"line": " conn.execute(\"update users set last_problem = '\" + str(last_problem) + \"' where chat_id = '\" + str(chat_id) + \"'\")\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 426,
"char_end": 524,
"line": " cursor_settings.execute(\"select last_problem from users where chat_id = ?\", (str(chat_id), ))\n"
},
{
"line_no": 17,
"char_start": 859,
"char_end": 965,
"line": " cursor.execute(\"select * from result where problem = ? and diff = ?\", (str(x[0]), str(x[1])))\n"
},
{
"line_no": 65,
"char_start": 2855,
"char_end": 2959,
"line": " cursor.execute(\"select * from result where problem = ? and diff = ?\", (s[3], s[4]))\n"
},
{
"line_no": 68,
"char_start": 3053,
"char_end": 3177,
"line": " cursor.execute(\"update result set verdict = ? where problem = ? and diff = ?\", (s2[1], s[3], s[4]))\n"
},
{
"line_no": 70,
"char_start": 3214,
"char_end": 3338,
"line": " cursor.execute(\"update result set verdict = ? where problem = ? and diff = ?\", (s2[1], s[3], s[4]))\n"
},
{
"line_no": 79,
"char_start": 3529,
"char_end": 3628,
"line": " conn.execute(\"update users set username = ? where chat_id = ?\", (str(username), str(chat_id)))\n"
},
{
"line_no": 80,
"char_start": 3628,
"char_end": 3734,
"line": " conn.execute(\"update users set last_update = ? where chat_id = ?\", (str(last_try_new), str(chat_id)))\n"
},
{
"line_no": 81,
"char_start": 3734,
"char_end": 3841,
"line": " conn.execute(\"update users set last_problem = ? where chat_id = ?\", (str(last_problem), str(chat_id)))\n"
}
]
} | {
"deleted": [
{
"char_start": 502,
"char_end": 503,
"chars": "'"
},
{
"char_start": 504,
"char_end": 506,
"chars": " +"
},
{
"char_start": 519,
"char_end": 521,
"chars": " +"
},
{
"char_start": 522,
"char_end": 525,
"chars": "\"'\""
},
{
"char_start": 927,
"char_end": 946,
"chars": "'\" + str(x[0]) + \"'"
},
{
"char_start": 958,
"char_end": 959,
"chars": "'"
},
{
"char_start": 961,
"char_end": 962,
"chars": "+"
},
{
"char_start": 972,
"char_end": 978,
"chars": " + \"'\""
},
{
"char_start": 2943,
"char_end": 2954,
"chars": "'\" + s[3] +"
},
{
"char_start": 2955,
"char_end": 2957,
"chars": "\"'"
},
{
"char_start": 2968,
"char_end": 2969,
"chars": "'"
},
{
"char_start": 2971,
"char_end": 2972,
"chars": "+"
},
{
"char_start": 2977,
"char_end": 2983,
"chars": " + \"'\""
},
{
"char_start": 3118,
"char_end": 3147,
"chars": "\n "
},
{
"char_start": 3176,
"char_end": 3191,
"chars": "'\" + s2[1] + \"'"
},
{
"char_start": 3208,
"char_end": 3222,
"chars": "'\" + s[3] + \"'"
},
{
"char_start": 3234,
"char_end": 3235,
"chars": "'"
},
{
"char_start": 3236,
"char_end": 3258,
"chars": " +\n "
},
{
"char_start": 3260,
"char_end": 3266,
"chars": " "
},
{
"char_start": 3271,
"char_end": 3277,
"chars": " + \"'\""
},
{
"char_start": 3355,
"char_end": 3384,
"chars": "\n "
},
{
"char_start": 3413,
"char_end": 3428,
"chars": "'\" + s2[1] + \"'"
},
{
"char_start": 3445,
"char_end": 3459,
"chars": "'\" + s[3] + \"'"
},
{
"char_start": 3471,
"char_end": 3472,
"chars": "'"
},
{
"char_start": 3473,
"char_end": 3494,
"chars": " +\n "
},
{
"char_start": 3495,
"char_end": 3496,
"chars": " "
},
{
"char_start": 3497,
"char_end": 3503,
"chars": " "
},
{
"char_start": 3508,
"char_end": 3514,
"chars": " + \"'\""
},
{
"char_start": 3753,
"char_end": 3776,
"chars": "'\" + str(username) + \"'"
},
{
"char_start": 3793,
"char_end": 3794,
"chars": "'"
},
{
"char_start": 3796,
"char_end": 3797,
"chars": "+"
},
{
"char_start": 3810,
"char_end": 3816,
"chars": " + \"'\""
},
{
"char_start": 3867,
"char_end": 3868,
"chars": "'"
},
{
"char_start": 3869,
"char_end": 3871,
"chars": " +"
},
{
"char_start": 3889,
"char_end": 3915,
"chars": " + \"' where chat_id = '\" +"
},
{
"char_start": 3928,
"char_end": 3934,
"chars": " + \"'\""
},
{
"char_start": 3986,
"char_end": 4013,
"chars": "'\" + str(last_problem) + \"'"
},
{
"char_start": 4030,
"char_end": 4031,
"chars": "'"
},
{
"char_start": 4033,
"char_end": 4034,
"chars": "+"
},
{
"char_start": 4047,
"char_end": 4053,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 502,
"char_end": 503,
"chars": "?"
},
{
"char_start": 504,
"char_end": 505,
"chars": ","
},
{
"char_start": 506,
"char_end": 507,
"chars": "("
},
{
"char_start": 519,
"char_end": 520,
"chars": ","
},
{
"char_start": 521,
"char_end": 522,
"chars": ")"
},
{
"char_start": 924,
"char_end": 925,
"chars": "?"
},
{
"char_start": 937,
"char_end": 938,
"chars": "?"
},
{
"char_start": 939,
"char_end": 940,
"chars": ","
},
{
"char_start": 941,
"char_end": 952,
"chars": "(str(x[0]),"
},
{
"char_start": 962,
"char_end": 963,
"chars": ")"
},
{
"char_start": 2928,
"char_end": 2929,
"chars": "?"
},
{
"char_start": 2941,
"char_end": 2942,
"chars": "?"
},
{
"char_start": 2943,
"char_end": 2944,
"chars": ","
},
{
"char_start": 2945,
"char_end": 2951,
"chars": "(s[3],"
},
{
"char_start": 2956,
"char_end": 2957,
"chars": ")"
},
{
"char_start": 3121,
"char_end": 3122,
"chars": "?"
},
{
"char_start": 3139,
"char_end": 3140,
"chars": "?"
},
{
"char_start": 3152,
"char_end": 3153,
"chars": "?"
},
{
"char_start": 3154,
"char_end": 3155,
"chars": ","
},
{
"char_start": 3156,
"char_end": 3163,
"chars": "(s2[1],"
},
{
"char_start": 3164,
"char_end": 3169,
"chars": "s[3],"
},
{
"char_start": 3174,
"char_end": 3175,
"chars": ")"
},
{
"char_start": 3282,
"char_end": 3283,
"chars": "?"
},
{
"char_start": 3300,
"char_end": 3301,
"chars": "?"
},
{
"char_start": 3313,
"char_end": 3314,
"chars": "?"
},
{
"char_start": 3315,
"char_end": 3316,
"chars": ","
},
{
"char_start": 3317,
"char_end": 3324,
"chars": "(s2[1],"
},
{
"char_start": 3325,
"char_end": 3330,
"chars": "s[3],"
},
{
"char_start": 3335,
"char_end": 3336,
"chars": ")"
},
{
"char_start": 3575,
"char_end": 3576,
"chars": "?"
},
{
"char_start": 3593,
"char_end": 3594,
"chars": "?"
},
{
"char_start": 3595,
"char_end": 3596,
"chars": ","
},
{
"char_start": 3597,
"char_end": 3612,
"chars": "(str(username),"
},
{
"char_start": 3625,
"char_end": 3626,
"chars": ")"
},
{
"char_start": 3677,
"char_end": 3678,
"chars": "?"
},
{
"char_start": 3695,
"char_end": 3696,
"chars": "?"
},
{
"char_start": 3697,
"char_end": 3698,
"chars": ","
},
{
"char_start": 3699,
"char_end": 3718,
"chars": "(str(last_try_new),"
},
{
"char_start": 3731,
"char_end": 3732,
"chars": ")"
},
{
"char_start": 3784,
"char_end": 3801,
"chars": "? where chat_id ="
},
{
"char_start": 3802,
"char_end": 3805,
"chars": "?\","
},
{
"char_start": 3806,
"char_end": 3807,
"chars": "("
},
{
"char_start": 3824,
"char_end": 3825,
"chars": ","
},
{
"char_start": 3838,
"char_end": 3839,
"chars": ")"
}
]
} | github.com/lissrbay/codeforces_bot/commit/cc7f5143445a0030b1149ac60a65b1b1b9c92a90 | bases/update.py | cwe-089 |
save_accepted_transaction | def save_accepted_transaction(self, user_id, project_id, money):
self.cursor.execute("update users set money = money - %s where id = %s"%(money, user_id))
self.cursor.execute("update projects set money = money + %s where id = %s" % (money, project_id))
self.cursor.execute("insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, %s, now(), 'accepted' )" % (project_id, user_id, money))
self.db.commit() | def save_accepted_transaction(self, user_id, project_id, money):
self.cursor.execute("update users set money = money - %s where id = %s", (money, user_id))
self.cursor.execute("update projects set money = money + %s where id = %s", (money, project_id))
self.cursor.execute("insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, "
"%s, now(), 'accepted' )", (project_id, user_id, money))
self.db.commit() | {
"deleted": [
{
"line_no": 2,
"char_start": 69,
"char_end": 167,
"line": " self.cursor.execute(\"update users set money = money - %s where id = %s\"%(money, user_id))\n"
},
{
"line_no": 3,
"char_start": 167,
"char_end": 273,
"line": " self.cursor.execute(\"update projects set money = money + %s where id = %s\" % (money, project_id))\n"
},
{
"line_no": 4,
"char_start": 273,
"char_end": 447,
"line": " self.cursor.execute(\"insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, %s, now(), 'accepted' )\" % (project_id, user_id, money))\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 69,
"char_end": 168,
"line": " self.cursor.execute(\"update users set money = money - %s where id = %s\", (money, user_id))\n"
},
{
"line_no": 3,
"char_start": 168,
"char_end": 273,
"line": " self.cursor.execute(\"update projects set money = money + %s where id = %s\", (money, project_id))\n"
},
{
"line_no": 4,
"char_start": 273,
"char_end": 392,
"line": " self.cursor.execute(\"insert into transactions (project_id, user_id, money, timestamp, state) values (%s, %s, \"\n"
},
{
"line_no": 5,
"char_start": 392,
"char_end": 477,
"line": " \"%s, now(), 'accepted' )\", (project_id, user_id, money))\n"
}
]
} | {
"deleted": [
{
"char_start": 148,
"char_end": 149,
"chars": "%"
},
{
"char_start": 249,
"char_end": 251,
"chars": " %"
},
{
"char_start": 414,
"char_end": 416,
"chars": " %"
}
],
"added": [
{
"char_start": 148,
"char_end": 150,
"chars": ", "
},
{
"char_start": 250,
"char_end": 251,
"chars": ","
},
{
"char_start": 390,
"char_end": 421,
"chars": "\"\n \""
},
{
"char_start": 445,
"char_end": 446,
"chars": ","
}
]
} | github.com/JLucka/kickstarter-dev/commit/e2ffa062697e060fdfbd2eccbb89a8c53a569e0b | backend/transactions/TransactionConnector.py | cwe-089 |
shame_ask | def shame_ask(name):
db = db_connect()
cursor = db.cursor()
try:
cursor.execute('''
SELECT shame FROM people WHERE name='{}'
'''.format(name))
shame = cursor.fetchone()
db.close()
if shame is None:
logger.debug('No shame found for name {}'.format(name))
return shame
else:
shame = shame[0]
logger.debug('shame of {} found for name {}'.format(shame, name))
return shame
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise | def shame_ask(name):
db = db_connect()
cursor = db.cursor()
try:
cursor.execute('''
SELECT shame FROM people WHERE name=%(name)s
''', (name, ))
shame = cursor.fetchone()
db.close()
if shame is None:
logger.debug('No shame found for name {}'.format(name))
return shame
else:
shame = shame[0]
logger.debug('shame of {} found for name {}'.format(shame, name))
return shame
except Exception as e:
logger.error('Execution failed with error: {}'.format(e))
raise | {
"deleted": [
{
"line_no": 6,
"char_start": 104,
"char_end": 157,
"line": " SELECT shame FROM people WHERE name='{}'\n"
},
{
"line_no": 7,
"char_start": 157,
"char_end": 187,
"line": " '''.format(name))\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 104,
"char_end": 161,
"line": " SELECT shame FROM people WHERE name=%(name)s\n"
},
{
"line_no": 7,
"char_start": 161,
"char_end": 188,
"line": " ''', (name, ))\n"
}
]
} | {
"deleted": [
{
"char_start": 152,
"char_end": 156,
"chars": "'{}'"
},
{
"char_start": 172,
"char_end": 179,
"chars": ".format"
}
],
"added": [
{
"char_start": 152,
"char_end": 160,
"chars": "%(name)s"
},
{
"char_start": 176,
"char_end": 178,
"chars": ", "
},
{
"char_start": 183,
"char_end": 185,
"chars": ", "
}
]
} | github.com/tylarb/KarmaBoi-PCF/commit/c1d00a27d7f6b7eb6f15a3dacd4269654a32c10a | KarmaBoi/dbopts.py | cwe-089 |
incrementOption | def incrementOption(cursor, poll_name, option):
key = poll_name+"-"+option
req = "UPDATE {} SET count=count+1 WHERE name_option = '{}';".format(CFG("options_table_name"), key)
cursor.execute(req) | def incrementOption(cursor, poll_name, option):
key = poll_name+"-"+option
req = "UPDATE {} SET count=count+1 WHERE name_option=?".format(CFG("options_table_name"))
cursor.execute(req, (key,)) | {
"deleted": [
{
"line_no": 3,
"char_start": 79,
"char_end": 184,
"line": " req = \"UPDATE {} SET count=count+1 WHERE name_option = '{}';\".format(CFG(\"options_table_name\"), key)\n"
},
{
"line_no": 4,
"char_start": 184,
"char_end": 207,
"line": " cursor.execute(req)\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 79,
"char_end": 173,
"line": " req = \"UPDATE {} SET count=count+1 WHERE name_option=?\".format(CFG(\"options_table_name\"))\n"
},
{
"line_no": 4,
"char_start": 173,
"char_end": 204,
"line": " cursor.execute(req, (key,))\n"
}
]
} | {
"deleted": [
{
"char_start": 135,
"char_end": 136,
"chars": " "
},
{
"char_start": 137,
"char_end": 143,
"chars": " '{}';"
},
{
"char_start": 177,
"char_end": 182,
"chars": ", key"
}
],
"added": [
{
"char_start": 136,
"char_end": 137,
"chars": "?"
},
{
"char_start": 195,
"char_end": 203,
"chars": ", (key,)"
}
]
} | github.com/FAUSheppy/simple-python-poll/commit/186c5ff5cdf58272e253a1bb432419ee50d93109 | database.py | cwe-089 |
overview | @app.route('/overview/<classNum>')
def overview(classNum):
if 'username' in session:
classNoSpace = classNum.split(' ')[0]+classNum.split(' ')[1]
#Save the current course as a session variable.
session['currentCourse'] = classNoSpace
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("SELECT courseName,courseOverview from courses where courseAbbreviation='" + classNoSpace + "'")
data = cursor.fetchone()
return render_template('overview.html', className = classNum, courseTitle = data[0], courseOverview = data[1])
return redirect(url_for('index')) | @app.route('/overview/<classNum>')
def overview(classNum):
if 'username' in session:
classNoSpace = classNum.split(' ')[0]+classNum.split(' ')[1]
#Save the current course as a session variable.
session['currentCourse'] = classNoSpace
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("SELECT courseName,courseOverview from courses where courseAbbreviation=%s", (classNoSpace))
data = cursor.fetchone()
return render_template('overview.html', className = classNum, courseTitle = data[0], courseOverview = data[1])
return redirect(url_for('index')) | {
"deleted": [
{
"line_no": 12,
"char_start": 294,
"char_end": 408,
"line": "\t\tcursor.execute(\"SELECT courseName,courseOverview from courses where courseAbbreviation='\" + classNoSpace + \"'\")\n"
}
],
"added": [
{
"line_no": 12,
"char_start": 294,
"char_end": 404,
"line": "\t\tcursor.execute(\"SELECT courseName,courseOverview from courses where courseAbbreviation=%s\", (classNoSpace))\n"
}
]
} | {
"deleted": [
{
"char_start": 383,
"char_end": 384,
"chars": "'"
},
{
"char_start": 386,
"char_end": 388,
"chars": "+ "
},
{
"char_start": 400,
"char_end": 406,
"chars": " + \"'\""
}
],
"added": [
{
"char_start": 383,
"char_end": 385,
"chars": "%s"
},
{
"char_start": 386,
"char_end": 387,
"chars": ","
},
{
"char_start": 388,
"char_end": 389,
"chars": "("
},
{
"char_start": 401,
"char_end": 402,
"chars": ")"
}
]
} | github.com/CaitlinKennedy/Tech-Track/commit/20ef2d4010f9497b8221524edd0c706e2c6a4147 | src/tech_track.py | cwe-089 |
addTags | def addTags(tag_list, listing_id):
"""
Adds a list of tags tag_list for a given listing with listing_id to the database
"""
cur = conn.cursor()
for x in tag_list:
sql = "INSERT INTO {} VALUES {}".format(listing_tags_table_name, str((listing_id, x)))
cur.execute(sql) | def addTags(tag_list, listing_id):
"""
Adds a list of tags tag_list for a given listing with listing_id to the database
"""
cur = conn.cursor()
for x in tag_list:
sql = "INSERT INTO %s VALUES (%s %s)"
cur.execute(sql, (listing_tags_table_name, listing_id, x)) | {
"deleted": [
{
"line_no": 7,
"char_start": 183,
"char_end": 278,
"line": " sql = \"INSERT INTO {} VALUES {}\".format(listing_tags_table_name, str((listing_id, x)))\n"
},
{
"line_no": 8,
"char_start": 278,
"char_end": 302,
"line": " cur.execute(sql)\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 183,
"char_end": 229,
"line": " sql = \"INSERT INTO %s VALUES (%s %s)\"\n"
},
{
"line_no": 8,
"char_start": 229,
"char_end": 295,
"line": " cur.execute(sql, (listing_tags_table_name, listing_id, x))\n"
}
]
} | {
"deleted": [
{
"char_start": 210,
"char_end": 212,
"chars": "{}"
},
{
"char_start": 220,
"char_end": 222,
"chars": "{}"
},
{
"char_start": 223,
"char_end": 226,
"chars": ".fo"
},
{
"char_start": 227,
"char_end": 229,
"chars": "ma"
},
{
"char_start": 256,
"char_end": 261,
"chars": "str(("
},
{
"char_start": 276,
"char_end": 302,
"chars": ")\n cur.execute(sql)"
}
],
"added": [
{
"char_start": 210,
"char_end": 212,
"chars": "%s"
},
{
"char_start": 220,
"char_end": 227,
"chars": "(%s %s)"
},
{
"char_start": 228,
"char_end": 239,
"chars": "\n cu"
},
{
"char_start": 240,
"char_end": 246,
"chars": ".execu"
},
{
"char_start": 247,
"char_end": 254,
"chars": "e(sql, "
}
]
} | github.com/tasbir49/BreadWinner/commit/332a9f2c619be399ae94244bb8bd0977fc62bc16 | backend-api/backend-api.py | cwe-089 |
edit | @mod.route('/edit/<int:cmt_id>', methods=['GET', 'POST'])
def edit(cmt_id):
m = None
if request.method == 'GET':
sql = "SELECT * FROM comment where cmt_id = %d;" % (cmt_id)
cursor.execute(sql)
m = cursor.fetchone()
return render_template('comment/edit.html', m=m, cmt_id=cmt_id)
if request.method == 'POST':
content = request.form['content']
sql = "UPDATE comment SET content = '%s' where cmt_id = '%d';" \
% (content, cmt_id)
cursor.execute(sql)
conn.commit()
sql = "SELECT msg_id FROM comment where cmt_id = %d;" % (cmt_id)
cursor.execute(sql)
m = cursor.fetchone()
flash('Edit Success!')
return redirect(url_for('comment.show', msg_id=m[0]))
return render_template('comment/edit.html', m=m, cmt_id=cmt_id) | @mod.route('/edit/<int:cmt_id>', methods=['GET', 'POST'])
def edit(cmt_id):
m = None
if request.method == 'GET':
cursor.execute("SELECT * FROM comment where cmt_id = %s;", (cmt_id,))
m = cursor.fetchone()
return render_template('comment/edit.html', m=m, cmt_id=cmt_id)
if request.method == 'POST':
content = request.form['content']
cursor.execute("UPDATE comment SET content = %s where cmt_id = %s;", (content, cmt_id))
conn.commit()
cursor.execute("SELECT msg_id FROM comment where cmt_id = %s;", (cmt_id,))
m = cursor.fetchone()
flash('Edit Success!')
return redirect(url_for('comment.show', msg_id=m[0]))
return render_template('comment/edit.html', m=m, cmt_id=cmt_id) | {
"deleted": [
{
"line_no": 5,
"char_start": 121,
"char_end": 189,
"line": " sql = \"SELECT * FROM comment where cmt_id = %d;\" % (cmt_id)\n"
},
{
"line_no": 6,
"char_start": 189,
"char_end": 217,
"line": " cursor.execute(sql)\n"
},
{
"line_no": 12,
"char_start": 395,
"char_end": 468,
"line": " sql = \"UPDATE comment SET content = '%s' where cmt_id = '%d';\" \\\n"
},
{
"line_no": 13,
"char_start": 468,
"char_end": 500,
"line": " % (content, cmt_id)\n"
},
{
"line_no": 14,
"char_start": 500,
"char_end": 528,
"line": " cursor.execute(sql)\n"
},
{
"line_no": 16,
"char_start": 550,
"char_end": 623,
"line": " sql = \"SELECT msg_id FROM comment where cmt_id = %d;\" % (cmt_id)\n"
},
{
"line_no": 17,
"char_start": 623,
"char_end": 651,
"line": " cursor.execute(sql)\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 121,
"char_end": 199,
"line": " cursor.execute(\"SELECT * FROM comment where cmt_id = %s;\", (cmt_id,))\n"
},
{
"line_no": 11,
"char_start": 377,
"char_end": 473,
"line": " cursor.execute(\"UPDATE comment SET content = %s where cmt_id = %s;\", (content, cmt_id))\n"
},
{
"line_no": 13,
"char_start": 495,
"char_end": 578,
"line": " cursor.execute(\"SELECT msg_id FROM comment where cmt_id = %s;\", (cmt_id,))\n"
}
]
} | {
"deleted": [
{
"char_start": 130,
"char_end": 135,
"chars": "ql = "
},
{
"char_start": 174,
"char_end": 175,
"chars": "d"
},
{
"char_start": 177,
"char_end": 179,
"chars": " %"
},
{
"char_start": 188,
"char_end": 215,
"chars": "\n cursor.execute(sql"
},
{
"char_start": 404,
"char_end": 409,
"chars": "ql = "
},
{
"char_start": 439,
"char_end": 440,
"chars": "'"
},
{
"char_start": 442,
"char_end": 443,
"chars": "'"
},
{
"char_start": 459,
"char_end": 460,
"chars": "'"
},
{
"char_start": 461,
"char_end": 463,
"chars": "d'"
},
{
"char_start": 465,
"char_end": 481,
"chars": " \\\n %"
},
{
"char_start": 499,
"char_end": 526,
"chars": "\n cursor.execute(sql"
},
{
"char_start": 559,
"char_end": 564,
"chars": "ql = "
},
{
"char_start": 608,
"char_end": 609,
"chars": "d"
},
{
"char_start": 611,
"char_end": 613,
"chars": " %"
},
{
"char_start": 622,
"char_end": 649,
"chars": "\n cursor.execute(sql"
}
],
"added": [
{
"char_start": 129,
"char_end": 132,
"chars": "cur"
},
{
"char_start": 133,
"char_end": 144,
"chars": "or.execute("
},
{
"char_start": 183,
"char_end": 184,
"chars": "s"
},
{
"char_start": 186,
"char_end": 187,
"chars": ","
},
{
"char_start": 195,
"char_end": 196,
"chars": ","
},
{
"char_start": 385,
"char_end": 388,
"chars": "cur"
},
{
"char_start": 389,
"char_end": 400,
"chars": "or.execute("
},
{
"char_start": 449,
"char_end": 450,
"chars": "s"
},
{
"char_start": 452,
"char_end": 453,
"chars": ","
},
{
"char_start": 503,
"char_end": 506,
"chars": "cur"
},
{
"char_start": 507,
"char_end": 518,
"chars": "or.execute("
},
{
"char_start": 562,
"char_end": 563,
"chars": "s"
},
{
"char_start": 565,
"char_end": 566,
"chars": ","
},
{
"char_start": 574,
"char_end": 575,
"chars": ","
}
]
} | github.com/ulyssetsd/bjtu-sql/commit/17d7b21864b72ba5666f15236474a93268b32ec9 | flaskr/flaskr/views/comment.py | cwe-089 |
process_form | def process_form():
# see https://docs.python.org/3.4/library/cgi.html for the basic usage
# here.
form = cgi.FieldStorage()
if "player1" not in form or "player2" not in form or "size" not in form:
raise FormError("Invalid parameters.")
player1 = form["player1"].value
player2 = form["player2"].value
for c in player1+player2:
if c not in "_-" and not c.isdigit() and not c.isalpha():
raise FormError("Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens")
return
try:
size = int(form["size"].value)
except:
raise FormError("Invalid parameters: 'size' is not an integer.")
return
if size < 2 or size > 9:
raise FormError("The 'size' must be in the range 2-9, inclusive.")
# connect to the database
conn = MySQLdb.connect(host = pnsdp.SQL_HOST,
user = pnsdp.SQL_USER,
passwd = pnsdp.SQL_PASSWD,
db = pnsdp.SQL_DB)
cursor = conn.cursor()
# insert the new row
cursor.execute("""INSERT INTO games(player1,player2,size) VALUES("%s","%s",%d);""" % (player1,player2,size))
gameID = cursor.lastrowid
# MySQLdb has been building a transaction as we run. Commit them now, and
# also clean up the other resources we've allocated.
conn.commit()
cursor.close()
conn.close()
return gameID | def process_form():
# see https://docs.python.org/3.4/library/cgi.html for the basic usage
# here.
form = cgi.FieldStorage()
if "player1" not in form or "player2" not in form or "size" not in form:
raise FormError("Invalid parameters.")
player1 = form["player1"].value
player2 = form["player2"].value
for c in player1+player2:
if c not in "_-" and not c.isdigit() and not c.isalpha():
raise FormError("Invalid parameters: The player names can only contains upper and lowercase characters, digits, underscores, and hypens")
return
try:
size = int(form["size"].value)
except:
raise FormError("Invalid parameters: 'size' is not an integer.")
return
if size < 2 or size > 9:
raise FormError("The 'size' must be in the range 2-9, inclusive.")
# connect to the database
conn = MySQLdb.connect(host = pnsdp.SQL_HOST,
user = pnsdp.SQL_USER,
passwd = pnsdp.SQL_PASSWD,
db = pnsdp.SQL_DB)
cursor = conn.cursor()
# insert the new row
cursor.execute("""INSERT INTO games(player1,player2,size) VALUES("%s","%s",%d);""", (player1,player2,size))
gameID = cursor.lastrowid
# MySQLdb has been building a transaction as we run. Commit them now, and
# also clean up the other resources we've allocated.
conn.commit()
cursor.close()
conn.close()
return gameID | {
"deleted": [
{
"line_no": 35,
"char_start": 1148,
"char_end": 1261,
"line": " cursor.execute(\"\"\"INSERT INTO games(player1,player2,size) VALUES(\"%s\",\"%s\",%d);\"\"\" % (player1,player2,size))\n"
}
],
"added": [
{
"line_no": 35,
"char_start": 1148,
"char_end": 1260,
"line": " cursor.execute(\"\"\"INSERT INTO games(player1,player2,size) VALUES(\"%s\",\"%s\",%d);\"\"\", (player1,player2,size))\n"
}
]
} | {
"deleted": [
{
"char_start": 1234,
"char_end": 1236,
"chars": " %"
}
],
"added": [
{
"char_start": 1234,
"char_end": 1235,
"chars": ","
}
]
} | github.com/russ-lewis/ttt_-_python_cgi/commit/6096f43fd4b2d91211eec4614b7960c0816900da | cgi/create_game.py | cwe-089 |
clean_cache | def clean_cache(self, limit):
"""
Method that remove several User objects from cache - the least
active users
:param limit: number of the users that the method should remove
from cache
:return: None
"""
log.info('Figuring out the least active users...')
# Select users that the least active recently
user_ids = tuple(self.users.keys())
query = ('SELECT chat_id '
'FROM photo_queries_table2 '
f'WHERE chat_id in {user_ids} '
'GROUP BY chat_id '
'ORDER BY MAX(time) '
f'LIMIT {limit}')
try:
cursor = db.execute_query(query)
except DatabaseConnectionError:
log.error("Can't figure out the least active users...")
return
if not cursor.rowcount:
log.warning("There are no users in the db")
return
# Make list out of tuple of tuples that is returned by MySQL
least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]
log.info('Removing %d least active users from cache...', limit)
num_deleted_entries = 0
for entry in least_active_users:
log.debug('Deleting %s...', entry)
deleted_entry = self.users.pop(entry, None)
if deleted_entry:
num_deleted_entries += 1
log.debug("%d users were removed from cache.", num_deleted_entries) | def clean_cache(self, limit):
"""
Method that remove several User objects from cache - the least
active users
:param limit: number of the users that the method should remove
from cache
:return: None
"""
log.info('Figuring out the least active users...')
# Select users that the least active recently
user_ids = tuple(self.users.keys())
query = ('SELECT chat_id '
'FROM photo_queries_table2 '
f'WHERE chat_id in {user_ids} '
'GROUP BY chat_id '
'ORDER BY MAX(time) '
f'LIMIT %s')
parameters = limit,
try:
cursor = db.execute_query(query, parameters)
except DatabaseConnectionError:
log.error("Can't figure out the least active users...")
return
if not cursor.rowcount:
log.warning("There are no users in the db")
return
# Make list out of tuple of tuples that is returned by MySQL
least_active_users = [chat_id[0] for chat_id in cursor.fetchall()]
log.info('Removing %d least active users from cache...', limit)
num_deleted_entries = 0
for entry in least_active_users:
log.debug('Deleting %s...', entry)
deleted_entry = self.users.pop(entry, None)
if deleted_entry:
num_deleted_entries += 1
log.debug("%d users were removed from cache.", num_deleted_entries) | {
"deleted": [
{
"line_no": 18,
"char_start": 628,
"char_end": 663,
"line": " f'LIMIT {limit}')\n"
},
{
"line_no": 21,
"char_start": 677,
"char_end": 722,
"line": " cursor = db.execute_query(query)\n"
}
],
"added": [
{
"line_no": 18,
"char_start": 628,
"char_end": 658,
"line": " f'LIMIT %s')\n"
},
{
"line_no": 19,
"char_start": 658,
"char_end": 659,
"line": "\n"
},
{
"line_no": 20,
"char_start": 659,
"char_end": 687,
"line": " parameters = limit,\n"
},
{
"line_no": 23,
"char_start": 701,
"char_end": 758,
"line": " cursor = db.execute_query(query, parameters)\n"
}
]
} | {
"deleted": [
{
"char_start": 653,
"char_end": 654,
"chars": "{"
},
{
"char_start": 659,
"char_end": 662,
"chars": "}')"
}
],
"added": [
{
"char_start": 653,
"char_end": 680,
"chars": "%s')\n\n parameters = "
},
{
"char_start": 685,
"char_end": 686,
"chars": ","
},
{
"char_start": 744,
"char_end": 756,
"chars": ", parameters"
}
]
} | github.com/RandyRomero/photoGPSbot/commit/0e9f57f13e61863b3672f5730e27f149da00786a | photogpsbot/users.py | cwe-089 |