Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

786 righe
22 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: MIT. See LICENSE
  3. # metadata
  4. """
  5. Load metadata (DocType) class
  6. Example:
  7. meta = frappe.get_meta('User')
  8. if meta.has_field('first_name'):
  9. print("DocType" table has field "first_name")
  10. """
  11. import json
  12. import os
  13. from datetime import datetime
  14. import click
  15. import frappe
  16. from frappe import _
  17. from frappe.model import (
  18. child_table_fields,
  19. data_fieldtypes,
  20. default_fields,
  21. no_value_fields,
  22. optional_fields,
  23. table_fields,
  24. )
  25. from frappe.model.base_document import (
  26. DOCTYPE_TABLE_FIELDS,
  27. TABLE_DOCTYPES_FOR_DOCTYPE,
  28. BaseDocument,
  29. )
  30. from frappe.model.document import Document
  31. from frappe.model.workflow import get_workflow_name
  32. from frappe.modules import load_doctype_module
  33. from frappe.utils import cast, cint, cstr
  34. def get_meta(doctype, cached=True):
  35. if cached:
  36. if not frappe.local.meta_cache.get(doctype):
  37. meta = frappe.cache().hget("meta", doctype)
  38. if meta:
  39. meta = Meta(meta)
  40. else:
  41. meta = Meta(doctype)
  42. frappe.cache().hset("meta", doctype, meta.as_dict())
  43. frappe.local.meta_cache[doctype] = meta
  44. return frappe.local.meta_cache[doctype]
  45. else:
  46. return load_meta(doctype)
  47. def load_meta(doctype):
  48. return Meta(doctype)
  49. def get_table_columns(doctype):
  50. return frappe.db.get_table_columns(doctype)
  51. def load_doctype_from_file(doctype):
  52. fname = frappe.scrub(doctype)
  53. with open(frappe.get_app_path("frappe", "core", "doctype", fname, fname + ".json"), "r") as f:
  54. txt = json.loads(f.read())
  55. for d in txt.get("fields", []):
  56. d["doctype"] = "DocField"
  57. for d in txt.get("permissions", []):
  58. d["doctype"] = "DocPerm"
  59. txt["fields"] = [BaseDocument(d) for d in txt["fields"]]
  60. if "permissions" in txt:
  61. txt["permissions"] = [BaseDocument(d) for d in txt["permissions"]]
  62. return txt
  63. class Meta(Document):
  64. _metaclass = True
  65. default_fields = list(default_fields)[1:]
  66. special_doctypes = (
  67. "DocField",
  68. "DocPerm",
  69. "DocType",
  70. "Module Def",
  71. "DocType Action",
  72. "DocType Link",
  73. "DocType State",
  74. )
  75. standard_set_once_fields = [
  76. frappe._dict(fieldname="creation", fieldtype="Datetime"),
  77. frappe._dict(fieldname="owner", fieldtype="Data"),
  78. ]
  79. def __init__(self, doctype):
  80. self._fields = {}
  81. if isinstance(doctype, dict):
  82. super(Meta, self).__init__(doctype)
  83. elif isinstance(doctype, Document):
  84. super(Meta, self).__init__(doctype.as_dict())
  85. self.process()
  86. else:
  87. super(Meta, self).__init__("DocType", doctype)
  88. self.process()
  89. def load_from_db(self):
  90. try:
  91. super(Meta, self).load_from_db()
  92. except frappe.DoesNotExistError:
  93. if self.doctype == "DocType" and self.name in self.special_doctypes:
  94. self.__dict__.update(load_doctype_from_file(self.name))
  95. else:
  96. raise
  97. def process(self):
  98. # don't process for special doctypes
  99. # prevent's circular dependency
  100. if self.name in self.special_doctypes:
  101. return
  102. self.add_custom_fields()
  103. self.apply_property_setters()
  104. self.sort_fields()
  105. self.get_valid_columns()
  106. self.set_custom_permissions()
  107. self.add_custom_links_and_actions()
  108. def as_dict(self, no_nulls=False):
  109. def serialize(doc):
  110. out = {}
  111. for key, value in doc.__dict__.items():
  112. if isinstance(value, (list, tuple)):
  113. if not value or not isinstance(value[0], BaseDocument):
  114. # non standard list object, skip
  115. continue
  116. value = [serialize(d) for d in value]
  117. if (not no_nulls and value is None) or isinstance(
  118. value, (str, int, float, datetime, list, tuple)
  119. ):
  120. out[key] = value
  121. # set empty lists for unset table fields
  122. for fieldname in TABLE_DOCTYPES_FOR_DOCTYPE.keys():
  123. if out.get(fieldname) is None:
  124. out[fieldname] = []
  125. return out
  126. return serialize(self)
  127. def get_link_fields(self):
  128. return self.get("fields", {"fieldtype": "Link", "options": ["!=", "[Select]"]})
  129. def get_data_fields(self):
  130. return self.get("fields", {"fieldtype": "Data"})
  131. def get_phone_fields(self):
  132. return self.get("fields", {"fieldtype": "Phone"})
  133. def get_dynamic_link_fields(self):
  134. if not hasattr(self, "_dynamic_link_fields"):
  135. self._dynamic_link_fields = self.get("fields", {"fieldtype": "Dynamic Link"})
  136. return self._dynamic_link_fields
  137. def get_select_fields(self):
  138. return self.get(
  139. "fields", {"fieldtype": "Select", "options": ["not in", ["[Select]", "Loading..."]]}
  140. )
  141. def get_image_fields(self):
  142. return self.get("fields", {"fieldtype": "Attach Image"})
  143. def get_code_fields(self):
  144. return self.get("fields", {"fieldtype": "Code"})
  145. def get_set_only_once_fields(self):
  146. """Return fields with `set_only_once` set"""
  147. if not hasattr(self, "_set_only_once_fields"):
  148. self._set_only_once_fields = self.get("fields", {"set_only_once": 1})
  149. fieldnames = [d.fieldname for d in self._set_only_once_fields]
  150. for df in self.standard_set_once_fields:
  151. if df.fieldname not in fieldnames:
  152. self._set_only_once_fields.append(df)
  153. return self._set_only_once_fields
  154. def get_table_fields(self):
  155. if not hasattr(self, "_table_fields"):
  156. if self.name != "DocType":
  157. self._table_fields = self.get("fields", {"fieldtype": ["in", table_fields]})
  158. else:
  159. self._table_fields = DOCTYPE_TABLE_FIELDS
  160. return self._table_fields
  161. def get_global_search_fields(self):
  162. """Returns list of fields with `in_global_search` set and `name` if set"""
  163. fields = self.get("fields", {"in_global_search": 1, "fieldtype": ["not in", no_value_fields]})
  164. if getattr(self, "show_name_in_global_search", None):
  165. fields.append(frappe._dict(fieldtype="Data", fieldname="name", label="Name"))
  166. return fields
  167. def get_valid_columns(self):
  168. if not hasattr(self, "_valid_columns"):
  169. table_exists = frappe.db.table_exists(self.name)
  170. if self.name in self.special_doctypes and table_exists:
  171. self._valid_columns = get_table_columns(self.name)
  172. else:
  173. self._valid_columns = self.default_fields + [
  174. df.fieldname for df in self.get("fields") if df.fieldtype in data_fieldtypes
  175. ]
  176. if self.istable:
  177. self._valid_columns += list(child_table_fields)
  178. return self._valid_columns
  179. def get_table_field_doctype(self, fieldname):
  180. return TABLE_DOCTYPES_FOR_DOCTYPE.get(fieldname)
  181. def get_field(self, fieldname):
  182. """Return docfield from meta"""
  183. if not self._fields:
  184. for f in self.get("fields"):
  185. self._fields[f.fieldname] = f
  186. return self._fields.get(fieldname)
  187. def has_field(self, fieldname):
  188. """Returns True if fieldname exists"""
  189. return True if self.get_field(fieldname) else False
  190. def get_label(self, fieldname):
  191. """Get label of the given fieldname"""
  192. df = self.get_field(fieldname)
  193. if df:
  194. label = df.label
  195. else:
  196. label = {
  197. "name": _("ID"),
  198. "owner": _("Created By"),
  199. "modified_by": _("Modified By"),
  200. "creation": _("Created On"),
  201. "modified": _("Last Modified On"),
  202. "_assign": _("Assigned To"),
  203. }.get(fieldname) or _("No Label")
  204. return label
  205. def get_options(self, fieldname):
  206. return self.get_field(fieldname).options
  207. def get_link_doctype(self, fieldname):
  208. df = self.get_field(fieldname)
  209. if df.fieldtype == "Link":
  210. return df.options
  211. elif df.fieldtype == "Dynamic Link":
  212. return self.get_options(df.options)
  213. else:
  214. return None
  215. def get_search_fields(self):
  216. search_fields = self.search_fields or "name"
  217. search_fields = [d.strip() for d in search_fields.split(",")]
  218. if "name" not in search_fields:
  219. search_fields.append("name")
  220. return search_fields
  221. def get_fields_to_fetch(self, link_fieldname=None):
  222. """Returns a list of docfield objects for fields whose values
  223. are to be fetched and updated for a particular link field
  224. These fields are of type Data, Link, Text, Readonly and their
  225. fetch_from property is set as `link_fieldname`.`source_fieldname`"""
  226. out = []
  227. if not link_fieldname:
  228. link_fields = [df.fieldname for df in self.get_link_fields()]
  229. for df in self.fields:
  230. if df.fieldtype not in no_value_fields and getattr(df, "fetch_from", None):
  231. if link_fieldname:
  232. if df.fetch_from.startswith(link_fieldname + "."):
  233. out.append(df)
  234. else:
  235. if "." in df.fetch_from:
  236. fieldname = df.fetch_from.split(".", 1)[0]
  237. if fieldname in link_fields:
  238. out.append(df)
  239. return out
  240. def get_list_fields(self):
  241. list_fields = ["name"] + [
  242. d.fieldname for d in self.fields if (d.in_list_view and d.fieldtype in data_fieldtypes)
  243. ]
  244. if self.title_field and self.title_field not in list_fields:
  245. list_fields.append(self.title_field)
  246. return list_fields
  247. def get_custom_fields(self):
  248. return [d for d in self.fields if d.get("is_custom_field")]
  249. def get_title_field(self):
  250. """Return the title field of this doctype,
  251. explict via `title_field`, or `title` or `name`"""
  252. title_field = getattr(self, "title_field", None)
  253. if not title_field and self.has_field("title"):
  254. title_field = "title"
  255. if not title_field:
  256. title_field = "name"
  257. return title_field
  258. def get_translatable_fields(self):
  259. """Return all fields that are translation enabled"""
  260. return [d.fieldname for d in self.fields if d.translatable]
  261. def is_translatable(self, fieldname):
  262. """Return true of false given a field"""
  263. field = self.get_field(fieldname)
  264. return field and field.translatable
  265. def get_workflow(self):
  266. return get_workflow_name(self.name)
  267. def add_custom_fields(self):
  268. if not frappe.db.table_exists("Custom Field"):
  269. return
  270. custom_fields = frappe.db.sql(
  271. """
  272. SELECT * FROM `tabCustom Field`
  273. WHERE dt = %s AND docstatus < 2
  274. """,
  275. (self.name,),
  276. as_dict=1,
  277. update={"is_custom_field": 1},
  278. )
  279. self.extend("fields", custom_fields)
  280. def apply_property_setters(self):
  281. """
  282. Property Setters are set via Customize Form. They override standard properties
  283. of the doctype or its child properties like fields, links etc. This method
  284. applies the customized properties over the standard meta object
  285. """
  286. if not frappe.db.table_exists("Property Setter"):
  287. return
  288. property_setters = frappe.db.sql(
  289. """select * from `tabProperty Setter` where
  290. doc_type=%s""",
  291. (self.name,),
  292. as_dict=1,
  293. )
  294. if not property_setters:
  295. return
  296. for ps in property_setters:
  297. if ps.doctype_or_field == "DocType":
  298. self.set(ps.property, cast(ps.property_type, ps.value))
  299. elif ps.doctype_or_field == "DocField":
  300. for d in self.fields:
  301. if d.fieldname == ps.field_name:
  302. d.set(ps.property, cast(ps.property_type, ps.value))
  303. break
  304. elif ps.doctype_or_field == "DocType Link":
  305. for d in self.links:
  306. if d.name == ps.row_name:
  307. d.set(ps.property, cast(ps.property_type, ps.value))
  308. break
  309. elif ps.doctype_or_field == "DocType Action":
  310. for d in self.actions:
  311. if d.name == ps.row_name:
  312. d.set(ps.property, cast(ps.property_type, ps.value))
  313. break
  314. elif ps.doctype_or_field == "DocType State":
  315. for d in self.states:
  316. if d.name == ps.row_name:
  317. d.set(ps.property, cast(ps.property_type, ps.value))
  318. break
  319. def add_custom_links_and_actions(self):
  320. for doctype, fieldname in (
  321. ("DocType Link", "links"),
  322. ("DocType Action", "actions"),
  323. ("DocType State", "states"),
  324. ):
  325. # ignore_ddl because the `custom` column was added later via a patch
  326. for d in frappe.get_all(
  327. doctype, fields="*", filters=dict(parent=self.name, custom=1), ignore_ddl=True
  328. ):
  329. self.append(fieldname, d)
  330. # set the fields in order if specified
  331. # order is saved as `links_order`
  332. order = json.loads(self.get("{}_order".format(fieldname)) or "[]")
  333. if order:
  334. name_map = {d.name: d for d in self.get(fieldname)}
  335. new_list = []
  336. for name in order:
  337. if name in name_map:
  338. new_list.append(name_map[name])
  339. # add the missing items that have not be added
  340. # maybe these items were added to the standard product
  341. # after the customization was done
  342. for d in self.get(fieldname):
  343. if d not in new_list:
  344. new_list.append(d)
  345. self.set(fieldname, new_list)
  346. def sort_fields(self):
  347. """sort on basis of insert_after"""
  348. custom_fields = sorted(self.get_custom_fields(), key=lambda df: df.idx)
  349. if custom_fields:
  350. newlist = []
  351. # if custom field is at top
  352. # insert_after is false
  353. for c in list(custom_fields):
  354. if not c.insert_after:
  355. newlist.append(c)
  356. custom_fields.pop(custom_fields.index(c))
  357. # standard fields
  358. newlist += [df for df in self.get("fields") if not df.get("is_custom_field")]
  359. newlist_fieldnames = [df.fieldname for df in newlist]
  360. for i in range(2):
  361. for df in list(custom_fields):
  362. if df.insert_after in newlist_fieldnames:
  363. cf = custom_fields.pop(custom_fields.index(df))
  364. idx = newlist_fieldnames.index(df.insert_after)
  365. newlist.insert(idx + 1, cf)
  366. newlist_fieldnames.insert(idx + 1, cf.fieldname)
  367. if not custom_fields:
  368. break
  369. # worst case, add remaining custom fields to last
  370. if custom_fields:
  371. newlist += custom_fields
  372. # renum idx
  373. for i, f in enumerate(newlist):
  374. f.idx = i + 1
  375. self.fields = newlist
  376. def set_custom_permissions(self):
  377. """Reset `permissions` with Custom DocPerm if exists"""
  378. if frappe.flags.in_patch or frappe.flags.in_install:
  379. return
  380. if not self.istable and self.name not in ("DocType", "DocField", "DocPerm", "Custom DocPerm"):
  381. custom_perms = frappe.get_all(
  382. "Custom DocPerm",
  383. fields="*",
  384. filters=dict(parent=self.name),
  385. update=dict(doctype="Custom DocPerm"),
  386. )
  387. if custom_perms:
  388. self.permissions = [Document(d) for d in custom_perms]
  389. def get_fieldnames_with_value(self, with_field_meta=False):
  390. def is_value_field(docfield):
  391. return not (docfield.get("is_virtual") or docfield.fieldtype in no_value_fields)
  392. if with_field_meta:
  393. return [df for df in self.fields if is_value_field(df)]
  394. return [df.fieldname for df in self.fields if is_value_field(df)]
  395. def get_fields_to_check_permissions(self, user_permission_doctypes):
  396. fields = self.get(
  397. "fields",
  398. {
  399. "fieldtype": "Link",
  400. "parent": self.name,
  401. "ignore_user_permissions": ("!=", 1),
  402. "options": ("in", user_permission_doctypes),
  403. },
  404. )
  405. if self.name in user_permission_doctypes:
  406. fields.append(frappe._dict({"label": "Name", "fieldname": "name", "options": self.name}))
  407. return fields
  408. def get_high_permlevel_fields(self):
  409. """Build list of fields with high perm level and all the higher perm levels defined."""
  410. if not hasattr(self, "high_permlevel_fields"):
  411. self.high_permlevel_fields = []
  412. for df in self.fields:
  413. if df.permlevel > 0:
  414. self.high_permlevel_fields.append(df)
  415. return self.high_permlevel_fields
  416. def get_permlevel_access(self, permission_type="read", parenttype=None):
  417. has_access_to = []
  418. roles = frappe.get_roles()
  419. for perm in self.get_permissions(parenttype):
  420. if perm.role in roles and perm.get(permission_type):
  421. if perm.permlevel not in has_access_to:
  422. has_access_to.append(perm.permlevel)
  423. return has_access_to
  424. def get_permissions(self, parenttype=None):
  425. if self.istable and parenttype:
  426. # use parent permissions
  427. permissions = frappe.get_meta(parenttype).permissions
  428. else:
  429. permissions = self.get("permissions", [])
  430. return permissions
  431. def get_dashboard_data(self):
  432. """Returns dashboard setup related to this doctype.
  433. This method will return the `data` property in the `[doctype]_dashboard.py`
  434. file in the doctype's folder, along with any overrides or extensions
  435. implemented in other Frappe applications via hooks.
  436. """
  437. data = frappe._dict()
  438. if not self.custom:
  439. try:
  440. module = load_doctype_module(self.name, suffix="_dashboard")
  441. if hasattr(module, "get_data"):
  442. data = frappe._dict(module.get_data())
  443. except ImportError:
  444. pass
  445. self.add_doctype_links(data)
  446. if not self.custom:
  447. for hook in frappe.get_hooks("override_doctype_dashboards", {}).get(self.name, []):
  448. data = frappe._dict(frappe.get_attr(hook)(data=data))
  449. return data
  450. def add_doctype_links(self, data):
  451. """add `links` child table in standard link dashboard format"""
  452. dashboard_links = []
  453. if getattr(self, "links", None):
  454. dashboard_links.extend(self.links)
  455. if not data.transactions:
  456. # init groups
  457. data.transactions = []
  458. if not data.non_standard_fieldnames:
  459. data.non_standard_fieldnames = {}
  460. if not data.internal_links:
  461. data.internal_links = {}
  462. for link in dashboard_links:
  463. link.added = False
  464. if link.hidden:
  465. continue
  466. for group in data.transactions:
  467. group = frappe._dict(group)
  468. # For internal links parent doctype will be the key
  469. doctype = link.parent_doctype or link.link_doctype
  470. # group found
  471. if link.group and _(group.label) == _(link.group):
  472. if doctype not in group.get("items"):
  473. group.get("items").append(doctype)
  474. link.added = True
  475. if not link.added:
  476. # group not found, make a new group
  477. data.transactions.append(
  478. dict(label=link.group, items=[link.parent_doctype or link.link_doctype])
  479. )
  480. if not link.is_child_table:
  481. if link.link_fieldname != data.fieldname:
  482. if data.fieldname:
  483. data.non_standard_fieldnames[link.link_doctype] = link.link_fieldname
  484. else:
  485. data.fieldname = link.link_fieldname
  486. elif link.is_child_table:
  487. if not data.fieldname:
  488. data.fieldname = link.link_fieldname
  489. data.internal_links[link.parent_doctype] = [link.table_fieldname, link.link_fieldname]
  490. def get_row_template(self):
  491. return self.get_web_template(suffix="_row")
  492. def get_list_template(self):
  493. return self.get_web_template(suffix="_list")
  494. def get_web_template(self, suffix=""):
  495. """Returns the relative path of the row template for this doctype"""
  496. module_name = frappe.scrub(self.module)
  497. doctype = frappe.scrub(self.name)
  498. template_path = frappe.get_module_path(
  499. module_name, "doctype", doctype, "templates", doctype + suffix + ".html"
  500. )
  501. if os.path.exists(template_path):
  502. return "{module_name}/doctype/{doctype_name}/templates/{doctype_name}{suffix}.html".format(
  503. module_name=module_name, doctype_name=doctype, suffix=suffix
  504. )
  505. return None
  506. def is_nested_set(self):
  507. return self.has_field("lft") and self.has_field("rgt")
  508. #######
  509. def is_single(doctype):
  510. try:
  511. return frappe.db.get_value("DocType", doctype, "issingle")
  512. except IndexError:
  513. raise Exception("Cannot determine whether %s is single" % doctype)
  514. def get_parent_dt(dt):
  515. parent_dt = frappe.db.get_all(
  516. "DocField", "parent", dict(fieldtype=["in", frappe.model.table_fields], options=dt), limit=1
  517. )
  518. return parent_dt and parent_dt[0].parent or ""
  519. def set_fieldname(field_id, fieldname):
  520. frappe.db.set_value("DocField", field_id, "fieldname", fieldname)
  521. def get_field_currency(df, doc=None):
  522. """get currency based on DocField options and fieldvalue in doc"""
  523. currency = None
  524. if not df.get("options"):
  525. return None
  526. if not doc:
  527. return None
  528. if not getattr(frappe.local, "field_currency", None):
  529. frappe.local.field_currency = frappe._dict()
  530. if not (
  531. frappe.local.field_currency.get((doc.doctype, doc.name), {}).get(df.fieldname)
  532. or (
  533. doc.get("parent")
  534. and frappe.local.field_currency.get((doc.doctype, doc.parent), {}).get(df.fieldname)
  535. )
  536. ):
  537. ref_docname = doc.get("parent") or doc.name
  538. if ":" in cstr(df.get("options")):
  539. split_opts = df.get("options").split(":")
  540. if len(split_opts) == 3 and doc.get(split_opts[1]):
  541. currency = frappe.get_cached_value(split_opts[0], doc.get(split_opts[1]), split_opts[2])
  542. else:
  543. currency = doc.get(df.get("options"))
  544. if doc.get("parenttype"):
  545. if currency:
  546. ref_docname = doc.name
  547. else:
  548. if frappe.get_meta(doc.parenttype).has_field(df.get("options")):
  549. # only get_value if parent has currency field
  550. currency = frappe.db.get_value(doc.parenttype, doc.parent, df.get("options"))
  551. if currency:
  552. frappe.local.field_currency.setdefault((doc.doctype, ref_docname), frappe._dict()).setdefault(
  553. df.fieldname, currency
  554. )
  555. return frappe.local.field_currency.get((doc.doctype, doc.name), {}).get(df.fieldname) or (
  556. doc.get("parent")
  557. and frappe.local.field_currency.get((doc.doctype, doc.parent), {}).get(df.fieldname)
  558. )
  559. def get_field_precision(df, doc=None, currency=None):
  560. """get precision based on DocField options and fieldvalue in doc"""
  561. from frappe.utils import get_number_format_info
  562. if df.precision:
  563. precision = cint(df.precision)
  564. elif df.fieldtype == "Currency":
  565. precision = cint(frappe.db.get_default("currency_precision"))
  566. if not precision:
  567. number_format = frappe.db.get_default("number_format") or "#,###.##"
  568. decimal_str, comma_str, precision = get_number_format_info(number_format)
  569. else:
  570. precision = cint(frappe.db.get_default("float_precision")) or 3
  571. return precision
  572. def get_default_df(fieldname):
  573. if fieldname in (default_fields + child_table_fields):
  574. if fieldname in ("creation", "modified"):
  575. return frappe._dict(fieldname=fieldname, fieldtype="Datetime")
  576. elif fieldname in ("idx", "docstatus"):
  577. return frappe._dict(fieldname=fieldname, fieldtype="Int")
  578. return frappe._dict(fieldname=fieldname, fieldtype="Data")
  579. def trim_tables(doctype=None, dry_run=False, quiet=False):
  580. """
  581. Removes database fields that don't exist in the doctype (json or custom field). This may be needed
  582. as maintenance since removing a field in a DocType doesn't automatically
  583. delete the db field.
  584. """
  585. UPDATED_TABLES = {}
  586. filters = {"issingle": 0}
  587. if doctype:
  588. filters["name"] = doctype
  589. for doctype in frappe.db.get_all("DocType", filters=filters, pluck="name"):
  590. try:
  591. dropped_columns = trim_table(doctype, dry_run=dry_run)
  592. if dropped_columns:
  593. UPDATED_TABLES[doctype] = dropped_columns
  594. except frappe.db.TableMissingError:
  595. if quiet:
  596. continue
  597. click.secho(f"Ignoring missing table for DocType: {doctype}", fg="yellow", err=True)
  598. click.secho(
  599. f"Consider removing record in the DocType table for {doctype}", fg="yellow", err=True
  600. )
  601. except Exception as e:
  602. if quiet:
  603. continue
  604. click.echo(e, err=True)
  605. return UPDATED_TABLES
  606. def trim_table(doctype, dry_run=True):
  607. frappe.cache().hdel("table_columns", f"tab{doctype}")
  608. ignore_fields = default_fields + optional_fields + child_table_fields
  609. columns = frappe.db.get_table_columns(doctype)
  610. fields = frappe.get_meta(doctype, cached=False).get_fieldnames_with_value()
  611. is_internal = lambda f: f not in ignore_fields and not f.startswith("_")
  612. columns_to_remove = [f for f in list(set(columns) - set(fields)) if is_internal(f)]
  613. DROPPED_COLUMNS = columns_to_remove[:]
  614. if columns_to_remove and not dry_run:
  615. columns_to_remove = ", ".join(f"DROP `{c}`" for c in columns_to_remove)
  616. frappe.db.sql_ddl(f"ALTER TABLE `tab{doctype}` {columns_to_remove}")
  617. return DROPPED_COLUMNS