You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1170 lines
34 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: MIT. See LICENSE
  3. # Database Module
  4. # --------------------
  5. import datetime
  6. import random
  7. import re
  8. import string
  9. from contextlib import contextmanager
  10. from time import time
  11. from typing import Dict, List, Tuple, Union
  12. from pypika.terms import Criterion, NullValue, PseudoColumn
  13. import frappe
  14. import frappe.defaults
  15. import frappe.model.meta
  16. from frappe import _
  17. from frappe.model.utils.link_count import flush_local_link_count
  18. from frappe.query_builder.functions import Count
  19. from frappe.query_builder.utils import DocType
  20. from frappe.utils import cast, get_datetime, getdate, now, sbool
  21. from .query import Query
  22. class Database(object):
  23. """
  24. Open a database connection with the given parmeters, if use_default is True, use the
  25. login details from `conf.py`. This is called by the request handler and is accessible using
  26. the `db` global variable. the `sql` method is also global to run queries
  27. """
  28. VARCHAR_LEN = 140
  29. MAX_COLUMN_LENGTH = 64
  30. OPTIONAL_COLUMNS = ["_user_tags", "_comments", "_assign", "_liked_by"]
  31. DEFAULT_SHORTCUTS = ['_Login', '__user', '_Full Name', 'Today', '__today', "now", "Now"]
  32. STANDARD_VARCHAR_COLUMNS = ('name', 'owner', 'modified_by')
  33. DEFAULT_COLUMNS = ['name', 'creation', 'modified', 'modified_by', 'owner', 'docstatus', 'idx']
  34. CHILD_TABLE_COLUMNS = ('parent', 'parenttype', 'parentfield')
  35. MAX_WRITES_PER_TRANSACTION = 200_000
  36. class InvalidColumnName(frappe.ValidationError): pass
  37. def __init__(self, host=None, user=None, password=None, ac_name=None, use_default=0, port=None):
  38. self.setup_type_map()
  39. self.host = host or frappe.conf.db_host or '127.0.0.1'
  40. self.port = port or frappe.conf.db_port or ''
  41. self.user = user or frappe.conf.db_name
  42. self.db_name = frappe.conf.db_name
  43. self._conn = None
  44. if ac_name:
  45. self.user = ac_name or frappe.conf.db_name
  46. if use_default:
  47. self.user = frappe.conf.db_name
  48. self.transaction_writes = 0
  49. self.auto_commit_on_many_writes = 0
  50. self.password = password or frappe.conf.db_password
  51. self.value_cache = {}
  52. self.query = Query()
  53. def setup_type_map(self):
  54. pass
  55. def connect(self):
  56. """Connects to a database as set in `site_config.json`."""
  57. self.cur_db_name = self.user
  58. self._conn = self.get_connection()
  59. self._cursor = self._conn.cursor()
  60. frappe.local.rollback_observers = []
  61. def use(self, db_name):
  62. """`USE` db_name."""
  63. self._conn.select_db(db_name)
  64. def get_connection(self):
  65. pass
  66. def get_database_size(self):
  67. pass
  68. def sql(self, query, values=(), as_dict = 0, as_list = 0, formatted = 0,
  69. debug=0, ignore_ddl=0, as_utf8=0, auto_commit=0, update=None,
  70. explain=False, run=True, pluck=False):
  71. """Execute a SQL query and fetch all rows.
  72. :param query: SQL query.
  73. :param values: List / dict of values to be escaped and substituted in the query.
  74. :param as_dict: Return as a dictionary.
  75. :param as_list: Always return as a list.
  76. :param formatted: Format values like date etc.
  77. :param debug: Print query and `EXPLAIN` in debug log.
  78. :param ignore_ddl: Catch exception if table, column missing.
  79. :param as_utf8: Encode values as UTF 8.
  80. :param auto_commit: Commit after executing the query.
  81. :param update: Update this dict to all rows (if returned `as_dict`).
  82. :param run: Returns query without executing it if False.
  83. Examples:
  84. # return customer names as dicts
  85. frappe.db.sql("select name from tabCustomer", as_dict=True)
  86. # return names beginning with a
  87. frappe.db.sql("select name from tabCustomer where name like %s", "a%")
  88. # values as dict
  89. frappe.db.sql("select name from tabCustomer where name like %(name)s and owner=%(owner)s",
  90. {"name": "a%", "owner":"test@example.com"})
  91. """
  92. query = str(query)
  93. if not run:
  94. return query
  95. if re.search(r'ifnull\(', query, flags=re.IGNORECASE):
  96. # replaces ifnull in query with coalesce
  97. query = re.sub(r'ifnull\(', 'coalesce(', query, flags=re.IGNORECASE)
  98. if not self._conn:
  99. self.connect()
  100. # in transaction validations
  101. self.check_transaction_status(query)
  102. self.clear_db_table_cache(query)
  103. # autocommit
  104. if auto_commit: self.commit()
  105. # execute
  106. try:
  107. if debug:
  108. time_start = time()
  109. self.log_query(query, values, debug, explain)
  110. if values!=():
  111. # MySQL-python==1.2.5 hack!
  112. if not isinstance(values, (dict, tuple, list)):
  113. values = (values,)
  114. self._cursor.execute(query, values)
  115. if frappe.flags.in_migrate:
  116. self.log_touched_tables(query, values)
  117. else:
  118. self._cursor.execute(query)
  119. if frappe.flags.in_migrate:
  120. self.log_touched_tables(query)
  121. if debug:
  122. time_end = time()
  123. frappe.errprint(("Execution time: {0} sec").format(round(time_end - time_start, 2)))
  124. except Exception as e:
  125. if self.is_syntax_error(e):
  126. # only for mariadb
  127. frappe.errprint('Syntax error in query:')
  128. frappe.errprint(query)
  129. elif self.is_deadlocked(e):
  130. raise frappe.QueryDeadlockError(e)
  131. elif self.is_timedout(e):
  132. raise frappe.QueryTimeoutError(e)
  133. elif frappe.conf.db_type == 'postgres':
  134. # TODO: added temporarily
  135. print(e)
  136. raise
  137. if ignore_ddl and (self.is_missing_column(e) or self.is_table_missing(e) or self.cant_drop_field_or_key(e)):
  138. pass
  139. else:
  140. raise
  141. if auto_commit: self.commit()
  142. if not self._cursor.description:
  143. return ()
  144. if pluck:
  145. return [r[0] for r in self._cursor.fetchall()]
  146. # scrub output if required
  147. if as_dict:
  148. ret = self.fetch_as_dict(formatted, as_utf8)
  149. if update:
  150. for r in ret:
  151. r.update(update)
  152. return ret
  153. elif as_list:
  154. return self.convert_to_lists(self._cursor.fetchall(), formatted, as_utf8)
  155. elif as_utf8:
  156. return self.convert_to_lists(self._cursor.fetchall(), formatted, as_utf8)
  157. else:
  158. return self._cursor.fetchall()
  159. def log_query(self, query, values, debug, explain):
  160. # for debugging in tests
  161. if frappe.conf.get('allow_tests') and frappe.cache().get_value('flag_print_sql'):
  162. print(self.mogrify(query, values))
  163. # debug
  164. if debug:
  165. if explain and query.strip().lower().startswith('select'):
  166. self.explain_query(query, values)
  167. frappe.errprint(self.mogrify(query, values))
  168. # info
  169. if (frappe.conf.get("logging") or False)==2:
  170. frappe.log("<<<< query")
  171. frappe.log(self.mogrify(query, values))
  172. frappe.log(">>>>")
  173. def mogrify(self, query, values):
  174. '''build the query string with values'''
  175. if not values:
  176. return query
  177. else:
  178. try:
  179. return self._cursor.mogrify(query, values)
  180. except: # noqa: E722
  181. return (query, values)
  182. def explain_query(self, query, values=None):
  183. """Print `EXPLAIN` in error log."""
  184. try:
  185. frappe.errprint("--- query explain ---")
  186. if values is None:
  187. self._cursor.execute("explain " + query)
  188. else:
  189. self._cursor.execute("explain " + query, values)
  190. import json
  191. frappe.errprint(json.dumps(self.fetch_as_dict(), indent=1))
  192. frappe.errprint("--- query explain end ---")
  193. except Exception:
  194. frappe.errprint("error in query explain")
  195. def sql_list(self, query, values=(), debug=False, **kwargs):
  196. """Return data as list of single elements (first column).
  197. Example:
  198. # doctypes = ["DocType", "DocField", "User", ...]
  199. doctypes = frappe.db.sql_list("select name from DocType")
  200. """
  201. return [r[0] for r in self.sql(query, values, **kwargs, debug=debug)]
  202. def sql_ddl(self, query, values=(), debug=False):
  203. """Commit and execute a query. DDL (Data Definition Language) queries that alter schema
  204. autocommit in MariaDB."""
  205. self.commit()
  206. self.sql(query, debug=debug)
  207. def check_transaction_status(self, query):
  208. """Raises exception if more than 20,000 `INSERT`, `UPDATE` queries are
  209. executed in one transaction. This is to ensure that writes are always flushed otherwise this
  210. could cause the system to hang."""
  211. self.check_implicit_commit(query)
  212. if query and query.strip().lower() in ('commit', 'rollback'):
  213. self.transaction_writes = 0
  214. if query[:6].lower() in ('update', 'insert', 'delete'):
  215. self.transaction_writes += 1
  216. if self.transaction_writes > self.MAX_WRITES_PER_TRANSACTION:
  217. if self.auto_commit_on_many_writes:
  218. self.commit()
  219. else:
  220. msg = "<br><br>" + _("Too many changes to database in single action.") + "<br>"
  221. msg += _("The changes have been reverted.") + "<br>"
  222. raise frappe.TooManyWritesError(msg)
  223. def check_implicit_commit(self, query):
  224. if self.transaction_writes and \
  225. query and query.strip().split()[0].lower() in ['start', 'alter', 'drop', 'create', "begin", "truncate"]:
  226. raise Exception('This statement can cause implicit commit')
  227. def fetch_as_dict(self, formatted=0, as_utf8=0):
  228. """Internal. Converts results to dict."""
  229. result = self._cursor.fetchall()
  230. ret = []
  231. if result:
  232. keys = [column[0] for column in self._cursor.description]
  233. for r in result:
  234. values = []
  235. for value in r:
  236. if as_utf8 and isinstance(value, str):
  237. value = value.encode('utf-8')
  238. values.append(value)
  239. ret.append(frappe._dict(zip(keys, values)))
  240. return ret
  241. @staticmethod
  242. def clear_db_table_cache(query):
  243. if query and query.strip().split()[0].lower() in {'drop', 'create'}:
  244. frappe.cache().delete_key('db_tables')
  245. @staticmethod
  246. def needs_formatting(result, formatted):
  247. """Returns true if the first row in the result has a Date, Datetime, Long Int."""
  248. if result and result[0]:
  249. for v in result[0]:
  250. if isinstance(v, (datetime.date, datetime.timedelta, datetime.datetime, int)):
  251. return True
  252. if formatted and isinstance(v, (int, float)):
  253. return True
  254. return False
  255. def get_description(self):
  256. """Returns result metadata."""
  257. return self._cursor.description
  258. @staticmethod
  259. def convert_to_lists(res, formatted=0, as_utf8=0):
  260. """Convert tuple output to lists (internal)."""
  261. nres = []
  262. for r in res:
  263. nr = []
  264. for val in r:
  265. if as_utf8 and isinstance(val, str):
  266. val = val.encode('utf-8')
  267. nr.append(val)
  268. nres.append(nr)
  269. return nres
  270. def get(self, doctype, filters=None, as_dict=True, cache=False):
  271. """Returns `get_value` with fieldname='*'"""
  272. return self.get_value(doctype, filters, "*", as_dict=as_dict, cache=cache)
  273. def get_value(
  274. self,
  275. doctype,
  276. filters=None,
  277. fieldname="name",
  278. ignore=None,
  279. as_dict=False,
  280. debug=False,
  281. order_by="KEEP_DEFAULT_ORDERING",
  282. cache=False,
  283. for_update=False,
  284. run=True,
  285. pluck=False,
  286. distinct=False,
  287. ):
  288. """Returns a document property or list of properties.
  289. :param doctype: DocType name.
  290. :param filters: Filters like `{"x":"y"}` or name of the document. `None` if Single DocType.
  291. :param fieldname: Column name.
  292. :param ignore: Don't raise exception if table, column is missing.
  293. :param as_dict: Return values as dict.
  294. :param debug: Print query in error log.
  295. :param order_by: Column to order by
  296. Example:
  297. # return first customer starting with a
  298. frappe.db.get_value("Customer", {"name": ("like a%")})
  299. # return last login of **User** `test@example.com`
  300. frappe.db.get_value("User", "test@example.com", "last_login")
  301. last_login, last_ip = frappe.db.get_value("User", "test@example.com",
  302. ["last_login", "last_ip"])
  303. # returns default date_format
  304. frappe.db.get_value("System Settings", None, "date_format")
  305. """
  306. ret = self.get_values(doctype, filters, fieldname, ignore, as_dict, debug,
  307. order_by, cache=cache, for_update=for_update, run=run, pluck=pluck, distinct=distinct, limit=1)
  308. if not run:
  309. return ret
  310. return ((len(ret[0]) > 1 or as_dict) and ret[0] or ret[0][0]) if ret else None
  311. def get_values(self, doctype, filters=None, fieldname="name", ignore=None, as_dict=False,
  312. debug=False, order_by="KEEP_DEFAULT_ORDERING", update=None, cache=False, for_update=False,
  313. run=True, pluck=False, distinct=False, limit=None):
  314. """Returns multiple document properties.
  315. :param doctype: DocType name.
  316. :param filters: Filters like `{"x":"y"}` or name of the document.
  317. :param fieldname: Column name.
  318. :param ignore: Don't raise exception if table, column is missing.
  319. :param as_dict: Return values as dict.
  320. :param debug: Print query in error log.
  321. :param order_by: Column to order by,
  322. :param distinct: Get Distinct results.
  323. Example:
  324. # return first customer starting with a
  325. customers = frappe.db.get_values("Customer", {"name": ("like a%")})
  326. # return last login of **User** `test@example.com`
  327. user = frappe.db.get_values("User", "test@example.com", "*")[0]
  328. """
  329. out = None
  330. if cache and isinstance(filters, str) and \
  331. (doctype, filters, fieldname) in self.value_cache:
  332. return self.value_cache[(doctype, filters, fieldname)]
  333. if distinct:
  334. order_by = None
  335. if isinstance(filters, list):
  336. out = self._get_value_for_many_names(
  337. doctype=doctype,
  338. names=filters,
  339. field=fieldname,
  340. order_by=order_by,
  341. debug=debug,
  342. run=run,
  343. pluck=pluck,
  344. distinct=distinct,
  345. limit=limit,
  346. )
  347. else:
  348. fields = fieldname
  349. if fieldname != "*":
  350. if isinstance(fieldname, str):
  351. fields = [fieldname]
  352. if (filters is not None) and (filters!=doctype or doctype=="DocType"):
  353. try:
  354. if order_by:
  355. order_by = "modified" if order_by == "KEEP_DEFAULT_ORDERING" else order_by
  356. out = self._get_values_from_table(
  357. fields=fields,
  358. filters=filters,
  359. doctype=doctype,
  360. as_dict=as_dict,
  361. debug=debug,
  362. order_by=order_by,
  363. update=update,
  364. for_update=for_update,
  365. run=run,
  366. pluck=pluck,
  367. distinct=distinct,
  368. limit=limit,
  369. )
  370. except Exception as e:
  371. if ignore and (frappe.db.is_missing_column(e) or frappe.db.is_table_missing(e)):
  372. # table or column not found, return None
  373. out = None
  374. elif (not ignore) and frappe.db.is_table_missing(e):
  375. # table not found, look in singles
  376. out = self.get_values_from_single(fields, filters, doctype, as_dict, debug, update, run=run, distinct=distinct)
  377. else:
  378. raise
  379. else:
  380. out = self.get_values_from_single(fields, filters, doctype, as_dict, debug, update, run=run, pluck=pluck, distinct=distinct)
  381. if cache and isinstance(filters, str):
  382. self.value_cache[(doctype, filters, fieldname)] = out
  383. return out
  384. def get_values_from_single(
  385. self,
  386. fields,
  387. filters,
  388. doctype,
  389. as_dict=False,
  390. debug=False,
  391. update=None,
  392. run=True,
  393. pluck=False,
  394. distinct=False,
  395. ):
  396. """Get values from `tabSingles` (Single DocTypes) (internal).
  397. :param fields: List of fields,
  398. :param filters: Filters (dict).
  399. :param doctype: DocType name.
  400. """
  401. # TODO
  402. # if not frappe.model.meta.is_single(doctype):
  403. # raise frappe.DoesNotExistError("DocType", doctype)
  404. if fields=="*" or isinstance(filters, dict):
  405. # check if single doc matches with filters
  406. values = self.get_singles_dict(doctype)
  407. if isinstance(filters, dict):
  408. for key, value in filters.items():
  409. if values.get(key) != value:
  410. return []
  411. if as_dict:
  412. return values and [values] or []
  413. if isinstance(fields, list):
  414. return [map(values.get, fields)]
  415. else:
  416. r = self.query.get_sql(
  417. "Singles",
  418. filters={"field": ("in", tuple(fields)), "doctype": doctype},
  419. fields=["field", "value"],
  420. distinct=distinct,
  421. ).run(pluck=pluck, debug=debug, as_dict=False)
  422. if not run:
  423. return r
  424. if as_dict:
  425. if r:
  426. r = frappe._dict(r)
  427. if update:
  428. r.update(update)
  429. return [r]
  430. else:
  431. return []
  432. else:
  433. return r and [[i[1] for i in r]] or []
  434. def get_singles_dict(self, doctype, debug = False):
  435. """Get Single DocType as dict.
  436. :param doctype: DocType of the single object whose value is requested
  437. Example:
  438. # Get coulmn and value of the single doctype Accounts Settings
  439. account_settings = frappe.db.get_singles_dict("Accounts Settings")
  440. """
  441. result = self.query.get_sql(
  442. "Singles", filters={"doctype": doctype}, fields=["field", "value"]
  443. ).run()
  444. dict_ = frappe._dict(result)
  445. return dict_
  446. @staticmethod
  447. def get_all(*args, **kwargs):
  448. return frappe.get_all(*args, **kwargs)
  449. @staticmethod
  450. def get_list(*args, **kwargs):
  451. return frappe.get_list(*args, **kwargs)
  452. def set_single_value(self, doctype, fieldname, value, *args, **kwargs):
  453. """Set field value of Single DocType.
  454. :param doctype: DocType of the single object
  455. :param fieldname: `fieldname` of the property
  456. :param value: `value` of the property
  457. Example:
  458. # Update the `deny_multiple_sessions` field in System Settings DocType.
  459. company = frappe.db.set_single_value("System Settings", "deny_multiple_sessions", True)
  460. """
  461. return self.set_value(doctype, doctype, fieldname, value, *args, **kwargs)
  462. def get_single_value(self, doctype, fieldname, cache=True):
  463. """Get property of Single DocType. Cache locally by default
  464. :param doctype: DocType of the single object whose value is requested
  465. :param fieldname: `fieldname` of the property whose value is requested
  466. Example:
  467. # Get the default value of the company from the Global Defaults doctype.
  468. company = frappe.db.get_single_value('Global Defaults', 'default_company')
  469. """
  470. if doctype not in self.value_cache:
  471. self.value_cache[doctype] = {}
  472. if cache and fieldname in self.value_cache[doctype]:
  473. return self.value_cache[doctype][fieldname]
  474. val = self.query.get_sql(
  475. table="Singles",
  476. filters={"doctype": doctype, "field": fieldname},
  477. fields="value",
  478. ).run()
  479. val = val[0][0] if val else None
  480. df = frappe.get_meta(doctype).get_field(fieldname)
  481. if not df:
  482. frappe.throw(_('Invalid field name: {0}').format(frappe.bold(fieldname)), self.InvalidColumnName)
  483. val = cast(df.fieldtype, val)
  484. self.value_cache[doctype][fieldname] = val
  485. return val
  486. def get_singles_value(self, *args, **kwargs):
  487. """Alias for get_single_value"""
  488. return self.get_single_value(*args, **kwargs)
  489. def _get_values_from_table(
  490. self,
  491. fields,
  492. filters,
  493. doctype,
  494. as_dict,
  495. debug,
  496. order_by=None,
  497. update=None,
  498. for_update=False,
  499. run=True,
  500. pluck=False,
  501. distinct=False,
  502. limit=None,
  503. ):
  504. field_objects = []
  505. if not isinstance(fields, Criterion):
  506. for field in fields:
  507. if "(" in str(field) or " as " in str(field):
  508. field_objects.append(PseudoColumn(field))
  509. else:
  510. field_objects.append(field)
  511. query = self.query.get_sql(
  512. table=doctype,
  513. filters=filters,
  514. orderby=order_by,
  515. for_update=for_update,
  516. field_objects=field_objects,
  517. fields=fields,
  518. distinct=distinct,
  519. limit=limit,
  520. )
  521. if (
  522. fields == "*"
  523. and not isinstance(fields, (list, tuple))
  524. and not isinstance(fields, Criterion)
  525. ):
  526. as_dict = True
  527. r = self.sql(
  528. query, as_dict=as_dict, debug=debug, update=update, run=run, pluck=pluck
  529. )
  530. return r
  531. def _get_value_for_many_names(self, doctype, names, field, order_by, debug=False, run=True, pluck=False, distinct=False, limit=None):
  532. names = list(filter(None, names))
  533. if names:
  534. return self.get_all(
  535. doctype,
  536. fields=field,
  537. filters=names,
  538. order_by=order_by,
  539. pluck=pluck,
  540. debug=debug,
  541. as_list=1,
  542. run=run,
  543. distinct=distinct,
  544. limit_page_length=limit
  545. )
  546. else:
  547. return {}
  548. def update(self, *args, **kwargs):
  549. """Update multiple values. Alias for `set_value`."""
  550. return self.set_value(*args, **kwargs)
  551. def set_value(self, dt, dn, field, val=None, modified=None, modified_by=None,
  552. update_modified=True, debug=False, for_update=True):
  553. """Set a single value in the database, do not call the ORM triggers
  554. but update the modified timestamp (unless specified not to).
  555. **Warning:** this function will not call Document events and should be avoided in normal cases.
  556. :param dt: DocType name.
  557. :param dn: Document name.
  558. :param field: Property / field name or dictionary of values to be updated
  559. :param value: Value to be updated.
  560. :param modified: Use this as the `modified` timestamp.
  561. :param modified_by: Set this user as `modified_by`.
  562. :param update_modified: default True. Set as false, if you don't want to update the timestamp.
  563. :param debug: Print the query in the developer / js console.
  564. :param for_update: Will add a row-level lock to the value that is being set so that it can be released on commit.
  565. """
  566. is_single_doctype = not (dn and dt != dn)
  567. to_update = field if isinstance(field, dict) else {field: val}
  568. if update_modified:
  569. modified = modified or now()
  570. modified_by = modified_by or frappe.session.user
  571. to_update.update({"modified": modified, "modified_by": modified_by})
  572. if is_single_doctype:
  573. frappe.db.delete(
  574. "Singles",
  575. filters={"field": ("in", tuple(to_update)), "doctype": dt}, debug=debug
  576. )
  577. singles_data = ((dt, key, sbool(value)) for key, value in to_update.items())
  578. query = (
  579. frappe.qb.into("Singles")
  580. .columns("doctype", "field", "value")
  581. .insert(*singles_data)
  582. ).run(debug=debug)
  583. frappe.clear_document_cache(dt, dt)
  584. else:
  585. table = DocType(dt)
  586. if for_update:
  587. docnames = tuple(
  588. self.get_values(dt, dn, "name", debug=debug, for_update=for_update, pluck=True)
  589. ) or (NullValue(),)
  590. query = frappe.qb.update(table).where(table.name.isin(docnames))
  591. for docname in docnames:
  592. frappe.clear_document_cache(dt, docname)
  593. else:
  594. query = self.query.build_conditions(table=dt, filters=dn, update=True)
  595. # TODO: Fix this; doesn't work rn - gavin@frappe.io
  596. # frappe.cache().hdel_keys(dt, "document_cache")
  597. # Workaround: clear all document caches
  598. frappe.cache().delete_value('document_cache')
  599. for column, value in to_update.items():
  600. query = query.set(column, value)
  601. query.run(debug=debug)
  602. if dt in self.value_cache:
  603. del self.value_cache[dt]
  604. @staticmethod
  605. def set(doc, field, val):
  606. """Set value in document. **Avoid**"""
  607. doc.db_set(field, val)
  608. def touch(self, doctype, docname):
  609. """Update the modified timestamp of this document."""
  610. modified = now()
  611. self.sql("""update `tab{doctype}` set `modified`=%s
  612. where name=%s""".format(doctype=doctype), (modified, docname))
  613. return modified
  614. @staticmethod
  615. def set_temp(value):
  616. """Set a temperory value and return a key."""
  617. key = frappe.generate_hash()
  618. frappe.cache().hset("temp", key, value)
  619. return key
  620. @staticmethod
  621. def get_temp(key):
  622. """Return the temperory value and delete it."""
  623. return frappe.cache().hget("temp", key)
  624. def set_global(self, key, val, user='__global'):
  625. """Save a global key value. Global values will be automatically set if they match fieldname."""
  626. self.set_default(key, val, user)
  627. def get_global(self, key, user='__global'):
  628. """Returns a global key value."""
  629. return self.get_default(key, user)
  630. def get_default(self, key, parent="__default"):
  631. """Returns default value as a list if multiple or single"""
  632. d = self.get_defaults(key, parent)
  633. return isinstance(d, list) and d[0] or d
  634. @staticmethod
  635. def set_default(key, val, parent="__default", parenttype=None):
  636. """Sets a global / user default value."""
  637. frappe.defaults.set_default(key, val, parent, parenttype)
  638. @staticmethod
  639. def add_default(key, val, parent="__default", parenttype=None):
  640. """Append a default value for a key, there can be multiple default values for a particular key."""
  641. frappe.defaults.add_default(key, val, parent, parenttype)
  642. @staticmethod
  643. def get_defaults(key=None, parent="__default"):
  644. """Get all defaults"""
  645. if key:
  646. defaults = frappe.defaults.get_defaults(parent)
  647. d = defaults.get(key, None)
  648. if(not d and key != frappe.scrub(key)):
  649. d = defaults.get(frappe.scrub(key), None)
  650. return d
  651. else:
  652. return frappe.defaults.get_defaults(parent)
  653. def begin(self):
  654. self.sql("START TRANSACTION")
  655. def commit(self):
  656. """Commit current transaction. Calls SQL `COMMIT`."""
  657. for method in frappe.local.before_commit:
  658. frappe.call(method[0], *(method[1] or []), **(method[2] or {}))
  659. self.sql("commit")
  660. frappe.local.rollback_observers = []
  661. self.flush_realtime_log()
  662. enqueue_jobs_after_commit()
  663. flush_local_link_count()
  664. def add_before_commit(self, method, args=None, kwargs=None):
  665. frappe.local.before_commit.append([method, args, kwargs])
  666. @staticmethod
  667. def flush_realtime_log():
  668. for args in frappe.local.realtime_log:
  669. frappe.realtime.emit_via_redis(*args)
  670. frappe.local.realtime_log = []
  671. def savepoint(self, save_point):
  672. """Savepoints work as a nested transaction.
  673. Changes can be undone to a save point by doing frappe.db.rollback(save_point)
  674. Note: rollback watchers can not work with save points.
  675. so only changes to database are undone when rolling back to a savepoint.
  676. Avoid using savepoints when writing to filesystem."""
  677. self.sql(f"savepoint {save_point}")
  678. def release_savepoint(self, save_point):
  679. self.sql(f"release savepoint {save_point}")
  680. def rollback(self, *, save_point=None):
  681. """`ROLLBACK` current transaction. Optionally rollback to a known save_point."""
  682. if save_point:
  683. self.sql(f"rollback to savepoint {save_point}")
  684. else:
  685. self.sql("rollback")
  686. self.begin()
  687. for obj in frappe.local.rollback_observers:
  688. if hasattr(obj, "on_rollback"):
  689. obj.on_rollback()
  690. frappe.local.rollback_observers = []
  691. def field_exists(self, dt, fn):
  692. """Return true of field exists."""
  693. return self.exists('DocField', {
  694. 'fieldname': fn,
  695. 'parent': dt
  696. })
  697. def table_exists(self, doctype, cached=True):
  698. """Returns True if table for given doctype exists."""
  699. return ("tab" + doctype) in self.get_tables(cached=cached)
  700. def has_table(self, doctype):
  701. return self.table_exists(doctype)
  702. def get_tables(self, cached=True):
  703. tables = frappe.cache().get_value('db_tables')
  704. if not tables or not cached:
  705. table_rows = self.sql("""
  706. SELECT table_name
  707. FROM information_schema.tables
  708. WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
  709. """)
  710. tables = {d[0] for d in table_rows}
  711. frappe.cache().set_value('db_tables', tables)
  712. return tables
  713. def a_row_exists(self, doctype):
  714. """Returns True if atleast one row exists."""
  715. return self.sql("select name from `tab{doctype}` limit 1".format(doctype=doctype))
  716. def exists(self, dt, dn=None, cache=False):
  717. """Return the document name of a matching document, or None.
  718. Note: `cache` only works if `dt` and `dn` are of type `str`.
  719. ## Examples
  720. Pass doctype and docname (only in this case we can cache the result)
  721. ```
  722. exists("User", "jane@example.org", cache=True)
  723. ```
  724. Pass a dict of filters including the `"doctype"` key:
  725. ```
  726. exists({"doctype": "User", "full_name": "Jane Doe"})
  727. ```
  728. Pass the doctype and a dict of filters:
  729. ```
  730. exists("User", {"full_name": "Jane Doe"})
  731. ```
  732. """
  733. if dt != "DocType" and dt == dn:
  734. # single always exists (!)
  735. return dn
  736. if isinstance(dt, dict):
  737. _dt = dt.pop("doctype")
  738. dt, dn = _dt, dt
  739. return self.get_value(dt, dn, ignore=True, cache=cache)
  740. def count(self, dt, filters=None, debug=False, cache=False):
  741. """Returns `COUNT(*)` for given DocType and filters."""
  742. if cache and not filters:
  743. cache_count = frappe.cache().get_value('doctype:count:{}'.format(dt))
  744. if cache_count is not None:
  745. return cache_count
  746. query = self.query.get_sql(table=dt, filters=filters, fields=Count("*"))
  747. if filters:
  748. count = self.sql(query, debug=debug)[0][0]
  749. return count
  750. else:
  751. count = self.sql(query, debug=debug)[0][0]
  752. if cache:
  753. frappe.cache().set_value('doctype:count:{}'.format(dt), count, expires_in_sec = 86400)
  754. return count
  755. @staticmethod
  756. def format_date(date):
  757. return getdate(date).strftime("%Y-%m-%d")
  758. @staticmethod
  759. def format_datetime(datetime):
  760. if not datetime:
  761. return '0001-01-01 00:00:00.000000'
  762. if isinstance(datetime, str):
  763. if ':' not in datetime:
  764. datetime = datetime + ' 00:00:00.000000'
  765. else:
  766. datetime = datetime.strftime("%Y-%m-%d %H:%M:%S.%f")
  767. return datetime
  768. def get_creation_count(self, doctype, minutes):
  769. """Get count of records created in the last x minutes"""
  770. from frappe.utils import now_datetime
  771. from dateutil.relativedelta import relativedelta
  772. return self.sql("""select count(name) from `tab{doctype}`
  773. where creation >= %s""".format(doctype=doctype),
  774. now_datetime() - relativedelta(minutes=minutes))[0][0]
  775. def get_db_table_columns(self, table):
  776. """Returns list of column names from given table."""
  777. columns = frappe.cache().hget('table_columns', table)
  778. if columns is None:
  779. columns = [r[0] for r in self.sql('''
  780. select column_name
  781. from information_schema.columns
  782. where table_name = %s ''', table)]
  783. if columns:
  784. frappe.cache().hset('table_columns', table, columns)
  785. return columns
  786. def get_table_columns(self, doctype):
  787. """Returns list of column names from given doctype."""
  788. columns = self.get_db_table_columns('tab' + doctype)
  789. if not columns:
  790. raise self.TableMissingError('DocType', doctype)
  791. return columns
  792. def has_column(self, doctype, column):
  793. """Returns True if column exists in database."""
  794. return column in self.get_table_columns(doctype)
  795. def get_column_type(self, doctype, column):
  796. return self.sql('''SELECT column_type FROM INFORMATION_SCHEMA.COLUMNS
  797. WHERE table_name = 'tab{0}' AND column_name = '{1}' '''.format(doctype, column))[0][0]
  798. def has_index(self, table_name, index_name):
  799. raise NotImplementedError
  800. def add_index(self, doctype, fields, index_name=None):
  801. raise NotImplementedError
  802. def add_unique(self, doctype, fields, constraint_name=None):
  803. raise NotImplementedError
  804. @staticmethod
  805. def get_index_name(fields):
  806. index_name = "_".join(fields) + "_index"
  807. # remove index length if present e.g. (10) from index name
  808. index_name = re.sub(r"\s*\([^)]+\)\s*", r"", index_name)
  809. return index_name
  810. def get_system_setting(self, key):
  811. def _load_system_settings():
  812. return self.get_singles_dict("System Settings")
  813. return frappe.cache().get_value("system_settings", _load_system_settings).get(key)
  814. def close(self):
  815. """Close database connection."""
  816. if self._conn:
  817. # self._cursor.close()
  818. self._conn.close()
  819. self._cursor = None
  820. self._conn = None
  821. @staticmethod
  822. def escape(s, percent=True):
  823. """Excape quotes and percent in given string."""
  824. # implemented in specific class
  825. raise NotImplementedError
  826. @staticmethod
  827. def is_column_missing(e):
  828. return frappe.db.is_missing_column(e)
  829. def get_descendants(self, doctype, name):
  830. '''Return descendants of the current record'''
  831. node_location_indexes = self.get_value(doctype, name, ('lft', 'rgt'))
  832. if node_location_indexes:
  833. lft, rgt = node_location_indexes
  834. return self.sql_list('''select name from `tab{doctype}`
  835. where lft > {lft} and rgt < {rgt}'''.format(doctype=doctype, lft=lft, rgt=rgt))
  836. else:
  837. # when document does not exist
  838. return []
  839. def is_missing_table_or_column(self, e):
  840. return self.is_missing_column(e) or self.is_table_missing(e)
  841. def multisql(self, sql_dict, values=(), **kwargs):
  842. current_dialect = frappe.db.db_type or 'mariadb'
  843. query = sql_dict.get(current_dialect)
  844. return self.sql(query, values, **kwargs)
  845. def delete(self, doctype: str, filters: Union[Dict, List] = None, debug=False, **kwargs):
  846. """Delete rows from a table in site which match the passed filters. This
  847. does trigger DocType hooks. Simply runs a DELETE query in the database.
  848. Doctype name can be passed directly, it will be pre-pended with `tab`.
  849. """
  850. values = ()
  851. filters = filters or kwargs.get("conditions")
  852. query = self.query.build_conditions(table=doctype, filters=filters).delete()
  853. if "debug" not in kwargs:
  854. kwargs["debug"] = debug
  855. return self.sql(query, values, **kwargs)
  856. def truncate(self, doctype: str):
  857. """Truncate a table in the database. This runs a DDL command `TRUNCATE TABLE`.
  858. This cannot be rolled back.
  859. Doctype name can be passed directly, it will be pre-pended with `tab`.
  860. """
  861. table = doctype if doctype.startswith("__") else f"tab{doctype}"
  862. return self.sql_ddl(f"truncate `{table}`")
  863. def clear_table(self, doctype):
  864. return self.truncate(doctype)
  865. def get_last_created(self, doctype):
  866. last_record = self.get_all(doctype, ('creation'), limit=1, order_by='creation desc')
  867. if last_record:
  868. return get_datetime(last_record[0].creation)
  869. else:
  870. return None
  871. def log_touched_tables(self, query, values=None):
  872. if values:
  873. query = frappe.safe_decode(self._cursor.mogrify(query, values))
  874. if query.strip().lower().split()[0] in ('insert', 'delete', 'update', 'alter', 'drop', 'rename'):
  875. # single_word_regex is designed to match following patterns
  876. # `tabXxx`, tabXxx and "tabXxx"
  877. # multi_word_regex is designed to match following patterns
  878. # `tabXxx Xxx` and "tabXxx Xxx"
  879. # ([`"]?) Captures " or ` at the begining of the table name (if provided)
  880. # \1 matches the first captured group (quote character) at the end of the table name
  881. # multi word table name must have surrounding quotes.
  882. # (tab([A-Z]\w+)( [A-Z]\w+)*) Captures table names that start with "tab"
  883. # and are continued with multiple words that start with a captital letter
  884. # e.g. 'tabXxx' or 'tabXxx Xxx' or 'tabXxx Xxx Xxx' and so on
  885. single_word_regex = r'([`"]?)(tab([A-Z]\w+))\1'
  886. multi_word_regex = r'([`"])(tab([A-Z]\w+)( [A-Z]\w+)+)\1'
  887. tables = []
  888. for regex in (single_word_regex, multi_word_regex):
  889. tables += [groups[1] for groups in re.findall(regex, query)]
  890. if frappe.flags.touched_tables is None:
  891. frappe.flags.touched_tables = set()
  892. frappe.flags.touched_tables.update(tables)
  893. def bulk_insert(self, doctype, fields, values, ignore_duplicates=False):
  894. """
  895. Insert multiple records at a time
  896. :param doctype: Doctype name
  897. :param fields: list of fields
  898. :params values: list of list of values
  899. """
  900. insert_list = []
  901. fields = ", ".join("`"+field+"`" for field in fields)
  902. for idx, value in enumerate(values):
  903. insert_list.append(tuple(value))
  904. if idx and (idx%10000 == 0 or idx < len(values)-1):
  905. self.sql("""INSERT {ignore_duplicates} INTO `tab{doctype}` ({fields}) VALUES {values}""".format(
  906. ignore_duplicates="IGNORE" if ignore_duplicates else "",
  907. doctype=doctype,
  908. fields=fields,
  909. values=", ".join(['%s'] * len(insert_list))
  910. ), tuple(insert_list))
  911. insert_list = []
  912. def enqueue_jobs_after_commit():
  913. from frappe.utils.background_jobs import execute_job, get_queue
  914. if frappe.flags.enqueue_after_commit and len(frappe.flags.enqueue_after_commit) > 0:
  915. for job in frappe.flags.enqueue_after_commit:
  916. q = get_queue(job.get("queue"), is_async=job.get("is_async"))
  917. q.enqueue_call(execute_job, timeout=job.get("timeout"),
  918. kwargs=job.get("queue_args"))
  919. frappe.flags.enqueue_after_commit = []
  920. @contextmanager
  921. def savepoint(catch: Union[type, Tuple[type, ...]] = Exception):
  922. """ Wrapper for wrapping blocks of DB operations in a savepoint.
  923. as contextmanager:
  924. for doc in docs:
  925. with savepoint(catch=DuplicateError):
  926. doc.insert()
  927. as decorator (wraps FULL function call):
  928. @savepoint(catch=DuplicateError)
  929. def process_doc(doc):
  930. doc.insert()
  931. """
  932. try:
  933. savepoint = ''.join(random.sample(string.ascii_lowercase, 10))
  934. frappe.db.savepoint(savepoint)
  935. yield # control back to calling function
  936. except catch:
  937. frappe.db.rollback(save_point=savepoint)
  938. else:
  939. frappe.db.release_savepoint(savepoint)