refactor: Moved raw queries to frappe orm

This commit is contained in:
Aradhya-Tripathi 2021-07-23 23:14:24 +05:30
parent 36c4be9a8d
commit 2f3371d873
13 changed files with 90 additions and 52 deletions

View file

@ -44,6 +44,6 @@ def clear_activity_logs(days=None):
if not days:
days = 90
frappe.db.sql("""delete from `tabActivity Log` where \
creation< (NOW() - INTERVAL '{0}' DAY)""".format(days))
frappe.db.delete("Activity Log", filters={"creation": ("<", ["NOW()", "-", f"INTERVAL {days} DAY"])})
# frappe.db.sql("""delete from `tabActivity Log` where \
# creation< (NOW() - INTERVAL '{0}' DAY)""".format(days))

View file

@ -13,10 +13,10 @@ class LogSettings(Document):
self.clear_email_queue()
def clear_error_logs(self):
# frappe.db.delete(doctype="Error Log", conditions="")
frappe.db.sql(""" DELETE FROM `tabError Log`
WHERE `creation` < (NOW() - INTERVAL '{0}' DAY)
""".format(self.clear_error_log_after))
frappe.db.delete("Error Log", {"creation": ("<", ["NOW()", "-", f"INTERVAL {self.clear_error_log_after} DAY"])})
# frappe.db.sql(""" DELETE FROM `tabError Log`
# WHERE `creation` < (NOW() - INTERVAL '{0}' DAY)
# """.format(self.clear_error_log_after))
def clear_activity_logs(self):
from frappe.core.doctype.activity_log.activity_log import clear_activity_logs

View file

@ -952,7 +952,7 @@ class Database(object):
query = sql_dict.get(current_dialect)
return self.sql(query, values, **kwargs)
def delete(self, doctype: str, filters: Union[Dict, List], debug=False, **kwargs):
def delete(self, doctype: str, filters: Union[Dict, List] = None, debug=False, **kwargs):
"""Delete rows from a table in site which match the passed filters. This
does trigger DocType hooks. Simply runs a DELETE query in the database.
@ -960,14 +960,15 @@ class Database(object):
"""
if kwargs:
filters = filters or kwargs.get("conditions")
if not filters:
raise TypeError(
"No filters passed for `frappe.db.delete`. If you wish to clear the whole "
"table, consider using `frappe.db.truncate` instead?"
)
if "debug" not in kwargs:
kwargs["debug"] = debug
if not filters:
table = doctype if doctype.startswith("__") else f"tab{doctype}"
query = f"DELETE FROM `{table}`"
return self.sql(query, **kwargs)
table = doctype if doctype.startswith("__") else f"tab{doctype}"
conditions, values = self.build_conditions(filters)
query = f"DELETE FROM `{table}` WHERE {conditions}"

View file

@ -40,11 +40,15 @@ class ToDo(Document):
def on_trash(self):
# unlink todo from linked comments
frappe.db.sql("""
delete from `tabCommunication Link`
where link_doctype=%(doctype)s and link_name=%(name)s""", {
"doctype": self.doctype, "name": self.name
frappe.db.delete("Communication Link", {
"link_doctype": self.doctype,
"link_name": self.name
})
# frappe.db.sql("""
# delete from `tabCommunication Link`
# where link_doctype=%(doctype)s and link_name=%(name)s""", {
# "doctype": self.doctype, "name": self.name
# })
self.update_in_reference()

View file

@ -390,9 +390,15 @@ class Document(BaseDocument):
else:
# no rows found, delete all rows
frappe.db.sql("""delete from `tab{0}` where parent=%s
and parenttype=%s and parentfield=%s""".format(df.options),
(self.name, self.doctype, fieldname))
frappe.db.delete(df.options, {
"parent": self.name,
"parenttype": self.doctype,
"parentfield": fieldname
})
# frappe.db.sql("""delete from `tab{0}` where parent=%s
# and parenttype=%s and parentfield=%s""".format(df.options),
# (self.name, self.doctype, fieldname))
def get_doc_before_save(self):
return getattr(self, '_doc_before_save', None)
@ -451,7 +457,10 @@ class Document(BaseDocument):
def update_single(self, d):
"""Updates values for Single type Document in `tabSingles`."""
frappe.db.sql("""delete from `tabSingles` where doctype=%s""", self.doctype)
frappe.db.delete("Singles", {
"doctype": self.doctype
})
# frappe.db.sql("""delete from `tabSingles` where doctype=%s""", self.doctype)
for field, value in d.items():
if field != "doctype":
frappe.db.sql("""insert into `tabSingles` (doctype, field, value)

View file

@ -1,21 +1,24 @@
import frappe
def execute():
#if current = 0, simply delete the key as it'll be recreated on first entry
frappe.db.sql('delete from `tabSeries` where current = 0')
duplicate_keys = frappe.db.sql('''
SELECT name, max(current) as current
from
`tabSeries`
group by
name
having count(name) > 1
''', as_dict=True)
for row in duplicate_keys:
frappe.db.sql('delete from `tabSeries` where name = %(key)s', {
'key': row.name
})
if row.current:
frappe.db.sql('insert into `tabSeries`(`name`, `current`) values (%(name)s, %(current)s)', row)
frappe.db.commit()
frappe.db.sql('ALTER table `tabSeries` ADD PRIMARY KEY IF NOT EXISTS (name)')
#if current = 0, simply delete the key as it'll be recreated on first entry
frappe.db.sql('delete from `tabSeries` where current = 0')
duplicate_keys = frappe.db.sql('''
SELECT name, max(current) as current
from
`tabSeries`
group by
name
having count(name) > 1
''', as_dict=True)
for row in duplicate_keys:
frappe.db.delete("Series", {
"name": row.name
})
# frappe.db.sql('delete from `tabSeries` where name = %(key)s', {
# 'key': row.name
# })
if row.current:
frappe.db.sql('insert into `tabSeries`(`name`, `current`) values (%(name)s, %(current)s)', row)
frappe.db.commit()
frappe.db.sql('ALTER table `tabSeries` ADD PRIMARY KEY IF NOT EXISTS (name)')

View file

@ -29,4 +29,7 @@ def execute():
frappe.db.auto_commit_on_many_writes = False
# clean up
frappe.db.sql("delete from `tabCommunication` where communication_type = 'Comment'")
frappe.db.delete("Communication", {
"communication_type": "Comment"
})
# frappe.db.sql("delete from `tabCommunication` where communication_type = 'Comment'")

View file

@ -12,7 +12,10 @@ def execute():
frappe.delete_doc_if_exists('DocType', 'Twilio Number Group')
if twilio_settings_doctype_in_integrations():
frappe.delete_doc_if_exists('DocType', 'Twilio Settings')
frappe.db.sql("delete from `tabSingles` where `doctype`=%s", 'Twilio Settings')
frappe.db.delete("Singles", {
"doctype": "Twilio Settings"
})
# frappe.db.sql("delete from `tabSingles` where `doctype`=%s", 'Twilio Settings')
def twilio_settings_doctype_in_integrations() -> bool:
"""Check Twilio Settings doctype exists in integrations module or not.

View file

@ -176,8 +176,11 @@ def collect_error_snapshots():
def clear_old_snapshots():
"""Clear snapshots that are older than a month"""
frappe.db.sql("""delete from `tabError Snapshot`
where creation < (NOW() - INTERVAL '1' MONTH)""")
frappe.db.delete("Error Snapshot", filters={"creation": ("<", ["NOW()", "-", f"INTERVAL '1' MONTH"])})
# frappe.db.sql("""delete from `tabError Snapshot`
# where creation < (NOW() - INTERVAL '1' MONTH)""")
path = get_error_snapshot_path()
today = datetime.datetime.now()

View file

@ -111,8 +111,10 @@ def before_tests():
# don't run before tests if any other app is installed
return
frappe.db.sql("delete from `tabCustom Field`")
frappe.db.sql("delete from `tabEvent`")
frappe.db.delete("Custom Field")
frappe.db.delete("Event")
# frappe.db.sql("delete from `tabCustom Field`")
# frappe.db.sql("delete from `tabEvent`")
frappe.db.commit()
frappe.clear_cache()

View file

@ -136,8 +136,12 @@ def update_password(user, pwd, doctype='User', fieldname='password', logout_all_
def delete_all_passwords_for(doctype, name):
try:
frappe.db.sql("""delete from `__Auth` where `doctype`=%(doctype)s and `name`=%(name)s""",
{ 'doctype': doctype, 'name': name })
frappe.db.delete("__Auth", {
"doctype": doctype,
"name": name
})
# frappe.db.sql("""delete from `__Auth` where `doctype`=%(doctype)s and `name`=%(name)s""",
# { 'doctype': doctype, 'name': name })
except Exception as e:
if not frappe.db.is_missing_column(e):
raise

View file

@ -12,5 +12,8 @@ def add_custom_field(doctype, fieldname, fieldtype='Data', options=None):
}).insert()
def clear_custom_fields(doctype):
frappe.db.sql('delete from `tabCustom Field` where dt=%s', doctype)
frappe.db.delete("Custom Field", {
"dt": doctype
})
# frappe.db.sql('delete from `tabCustom Field` where dt=%s', doctype)
frappe.clear_cache(doctype=doctype)

View file

@ -259,10 +259,13 @@ def is_workflow_action_already_created(doc):
def clear_workflow_actions(doctype, name):
if not (doctype and name):
return
frappe.db.sql('''delete from `tabWorkflow Action`
where reference_doctype=%s and reference_name=%s''',
(doctype, name))
frappe.db.delete("Workflow Action", {
"reference_doctype": doctype,
"reference_name": name
})
# frappe.db.sql('''delete from `tabWorkflow Action`
# where reference_doctype=%s and reference_name=%s''',
# (doctype, name))
def get_doc_workflow_state(doc):
workflow_name = get_workflow_name(doc.get('doctype'))