Merge pull request #16200 from alyf-de/refactor-db-exists

refactor: `frappe.db.exists`
This commit is contained in:
mergify[bot] 2022-03-21 05:47:27 +00:00 committed by GitHub
commit f47331cd1d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 20 deletions

View file

@ -882,27 +882,39 @@ class Database(object):
return self.sql("select name from `tab{doctype}` limit 1".format(doctype=doctype))
def exists(self, dt, dn=None, cache=False):
"""Returns true if document exists.
"""Return the document name of a matching document, or None.
:param dt: DocType name.
:param dn: Document name or filter dict."""
if isinstance(dt, str):
if dt!="DocType" and dt==dn:
return True # single always exists (!)
try:
return self.get_value(dt, dn, "name", cache=cache)
except Exception:
return None
Note: `cache` only works if `dt` and `dn` are of type `str`.
elif isinstance(dt, dict) and dt.get('doctype'):
try:
conditions = []
for d in dt:
if d == 'doctype': continue
conditions.append([d, '=', dt[d]])
return self.get_all(dt['doctype'], filters=conditions, as_list=1)
except Exception:
return None
## Examples
Pass doctype and docname (only in this case we can cache the result)
```
exists("User", "jane@example.org", cache=True)
```
Pass a dict of filters including the `"doctype"` key:
```
exists({"doctype": "User", "full_name": "Jane Doe"})
```
Pass the doctype and a dict of filters:
```
exists("User", {"full_name": "Jane Doe"})
```
"""
if dt != "DocType" and dt == dn:
# single always exists (!)
return dn
if isinstance(dt, dict):
_dt = dt.pop("doctype")
dt, dn = _dt, dt
return self.get_value(dt, dn, ignore=True, cache=cache)
def count(self, dt, filters=None, debug=False, cache=False):
"""Returns `COUNT(*)` for given DocType and filters."""

View file

@ -963,7 +963,7 @@ class BaseDocument(object):
from frappe.model.meta import get_default_df
df = get_default_df(fieldname)
if not currency and df:
if df.fieldtype == "Currency" and not currency:
currency = self.get(df.get("options"))
if not frappe.db.exists('Currency', currency, cache=True):
currency = None

View file

@ -301,6 +301,14 @@ class TestDB(unittest.TestCase):
# recover transaction to continue other tests
raise Exception
def test_exists(self):
dt, dn = "User", "Administrator"
self.assertEqual(frappe.db.exists(dt, dn, cache=True), dn)
self.assertEqual(frappe.db.exists(dt, dn), dn)
self.assertEqual(frappe.db.exists(dt, {"name": ("=", dn)}), dn)
self.assertEqual(frappe.db.exists({"doctype": dt, "name": ("like", "Admin%")}), dn)
self.assertEqual(frappe.db.exists(dt, [["name", "=", dn]]), dn)
@run_only_if(db_type_is.MARIADB)
class TestDDLCommandsMaria(unittest.TestCase):