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.
 
 
 
 
 
 

608 regels
17 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. """
  5. Syncs a database table to the `DocType` (metadata)
  6. .. note:: This module is only used internally
  7. """
  8. import re
  9. import os
  10. import frappe
  11. from frappe import _
  12. from frappe.utils import cstr, cint, flt
  13. import MySQLdb
  14. class InvalidColumnName(frappe.ValidationError): pass
  15. varchar_len = '140'
  16. standard_varchar_columns = ('name', 'owner', 'modified_by', 'parent', 'parentfield', 'parenttype')
  17. type_map = {
  18. 'Currency': ('decimal', '18,6')
  19. ,'Int': ('int', '11')
  20. ,'Float': ('decimal', '18,6')
  21. ,'Percent': ('decimal', '18,6')
  22. ,'Check': ('int', '1')
  23. ,'Small Text': ('text', '')
  24. ,'Long Text': ('longtext', '')
  25. ,'Code': ('longtext', '')
  26. ,'Text Editor': ('longtext', '')
  27. ,'Date': ('date', '')
  28. ,'Datetime': ('datetime', '6')
  29. ,'Time': ('time', '6')
  30. ,'Text': ('text', '')
  31. ,'Data': ('varchar', varchar_len)
  32. ,'Link': ('varchar', varchar_len)
  33. ,'Dynamic Link':('varchar', varchar_len)
  34. ,'Password': ('varchar', varchar_len)
  35. ,'Select': ('varchar', varchar_len)
  36. ,'Read Only': ('varchar', varchar_len)
  37. ,'Attach': ('text', '')
  38. ,'Attach Image':('text', '')
  39. }
  40. default_columns = ['name', 'creation', 'modified', 'modified_by', 'owner',
  41. 'docstatus', 'parent', 'parentfield', 'parenttype', 'idx']
  42. optional_columns = ["_user_tags", "_comments", "_assign", "_liked_by"]
  43. default_shortcuts = ['_Login', '__user', '_Full Name', 'Today', '__today', "now", "Now"]
  44. def updatedb(dt, meta=None):
  45. """
  46. Syncs a `DocType` to the table
  47. * creates if required
  48. * updates columns
  49. * updates indices
  50. """
  51. res = frappe.db.sql("select issingle from tabDocType where name=%s", (dt,))
  52. if not res:
  53. raise Exception, 'Wrong doctype "%s" in updatedb' % dt
  54. if not res[0][0]:
  55. tab = DbTable(dt, 'tab', meta)
  56. tab.validate()
  57. frappe.db.commit()
  58. tab.sync()
  59. frappe.db.begin()
  60. class DbTable:
  61. def __init__(self, doctype, prefix = 'tab', meta = None):
  62. self.doctype = doctype
  63. self.name = prefix + doctype
  64. self.columns = {}
  65. self.current_columns = {}
  66. self.meta = meta
  67. if not self.meta:
  68. self.meta = frappe.get_meta(self.doctype)
  69. # lists for change
  70. self.add_column = []
  71. self.change_type = []
  72. self.add_index = []
  73. self.drop_index = []
  74. self.set_default = []
  75. # load
  76. self.get_columns_from_docfields()
  77. def validate(self):
  78. """Check if change in varchar length isn't truncating the columns"""
  79. if self.is_new():
  80. return
  81. self.get_columns_from_db()
  82. columns = [frappe._dict({"fieldname": f, "fieldtype": "Data"}) for f in standard_varchar_columns]
  83. columns += self.columns.values()
  84. for col in columns:
  85. if col.fieldtype in type_map and type_map[col.fieldtype][0]=="varchar":
  86. # validate length range
  87. new_length = cint(col.length) or cint(varchar_len)
  88. if not (1 <= new_length <= 255):
  89. frappe.throw(_("Length of {0} should be between 1 and 255").format(col.fieldname))
  90. try:
  91. # check for truncation
  92. max_length = frappe.db.sql("""select max(char_length(`{fieldname}`)) from `tab{doctype}`"""\
  93. .format(fieldname=col.fieldname, doctype=self.doctype))
  94. except MySQLdb.OperationalError, e:
  95. if e.args[0]==1054:
  96. # Unknown column 'column_name' in 'field list'
  97. continue
  98. else:
  99. raise
  100. if max_length and max_length[0][0] > new_length:
  101. current_type = self.current_columns[col.fieldname]["type"]
  102. current_length = re.findall('varchar\(([\d]+)\)', current_type)
  103. if not current_length:
  104. # case when the field is no longer a varchar
  105. continue
  106. current_length = current_length[0]
  107. if col.fieldname in self.columns:
  108. self.columns[col.fieldname].length = current_length
  109. frappe.msgprint(_("Reverting length to {0} for '{1}' in '{2}'; Setting the length as {3} will cause truncation of data.")\
  110. .format(current_length, col.fieldname, self.doctype, new_length))
  111. def sync(self):
  112. if self.is_new():
  113. self.create()
  114. else:
  115. self.alter()
  116. def is_new(self):
  117. return self.name not in DbManager(frappe.db).get_tables_list(frappe.db.cur_db_name)
  118. def create(self):
  119. add_text = ''
  120. # columns
  121. column_defs = self.get_column_definitions()
  122. if column_defs: add_text += ',\n'.join(column_defs) + ',\n'
  123. # index
  124. index_defs = self.get_index_definitions()
  125. if index_defs: add_text += ',\n'.join(index_defs) + ',\n'
  126. # create table
  127. frappe.db.sql("""create table `%s` (
  128. name varchar({varchar_len}) not null primary key,
  129. creation datetime(6),
  130. modified datetime(6),
  131. modified_by varchar({varchar_len}),
  132. owner varchar({varchar_len}),
  133. docstatus int(1) not null default '0',
  134. parent varchar({varchar_len}),
  135. parentfield varchar({varchar_len}),
  136. parenttype varchar({varchar_len}),
  137. idx int(8) not null default '0',
  138. %sindex parent(parent))
  139. ENGINE=InnoDB
  140. ROW_FORMAT=COMPRESSED
  141. CHARACTER SET=utf8mb4
  142. COLLATE=utf8mb4_unicode_ci""".format(varchar_len=varchar_len) % (self.name, add_text))
  143. def get_column_definitions(self):
  144. column_list = [] + default_columns
  145. ret = []
  146. for k in self.columns.keys():
  147. if k not in column_list:
  148. d = self.columns[k].get_definition()
  149. if d:
  150. ret.append('`'+ k+ '` ' + d)
  151. column_list.append(k)
  152. return ret
  153. def get_index_definitions(self):
  154. ret = []
  155. for key, col in self.columns.items():
  156. if col.set_index and not col.unique and col.fieldtype in type_map and \
  157. type_map.get(col.fieldtype)[0] not in ('text', 'longtext'):
  158. ret.append('index `' + key + '`(`' + key + '`)')
  159. return ret
  160. def get_columns_from_docfields(self):
  161. """
  162. get columns from docfields and custom fields
  163. """
  164. fl = frappe.db.sql("SELECT * FROM tabDocField WHERE parent = %s", self.doctype, as_dict = 1)
  165. lengths = {}
  166. precisions = {}
  167. uniques = {}
  168. # optional fields like _comments
  169. if not self.meta.istable:
  170. for fieldname in optional_columns:
  171. fl.append({
  172. "fieldname": fieldname,
  173. "fieldtype": "Text"
  174. })
  175. # add _seen column if track_seen
  176. if getattr(self.meta, 'track_seen', False):
  177. fl.append({
  178. 'fieldname': '_seen',
  179. 'fieldtype': 'Text'
  180. })
  181. if not frappe.flags.in_install_db and frappe.flags.in_install != "frappe":
  182. custom_fl = frappe.db.sql("""\
  183. SELECT * FROM `tabCustom Field`
  184. WHERE dt = %s AND docstatus < 2""", (self.doctype,), as_dict=1)
  185. if custom_fl: fl += custom_fl
  186. # apply length, precision and unique from property setters
  187. for ps in frappe.get_all("Property Setter", fields=["field_name", "property", "value"],
  188. filters={
  189. "doc_type": self.doctype,
  190. "doctype_or_field": "DocField",
  191. "property": ["in", ["precision", "length", "unique"]]
  192. }):
  193. if ps.property=="length":
  194. lengths[ps.field_name] = cint(ps.value)
  195. elif ps.property=="precision":
  196. precisions[ps.field_name] = cint(ps.value)
  197. elif ps.property=="unique":
  198. uniques[ps.field_name] = cint(ps.value)
  199. for f in fl:
  200. self.columns[f['fieldname']] = DbColumn(self, f['fieldname'],
  201. f['fieldtype'], lengths.get(f["fieldname"]) or f.get('length'), f.get('default'), f.get('search_index'),
  202. f.get('options'), uniques.get(f["fieldname"], f.get('unique')), precisions.get(f['fieldname']) or f.get('precision'))
  203. def get_columns_from_db(self):
  204. self.show_columns = frappe.db.sql("desc `%s`" % self.name)
  205. for c in self.show_columns:
  206. self.current_columns[c[0]] = {'name': c[0],
  207. 'type':c[1], 'index':c[3]=="MUL", 'default':c[4], "unique":c[3]=="UNI"}
  208. # GET foreign keys
  209. def get_foreign_keys(self):
  210. fk_list = []
  211. txt = frappe.db.sql("show create table `%s`" % self.name)[0][1]
  212. for line in txt.split('\n'):
  213. if line.strip().startswith('CONSTRAINT') and line.find('FOREIGN')!=-1:
  214. try:
  215. fk_list.append((line.split('`')[3], line.split('`')[1]))
  216. except IndexError:
  217. pass
  218. return fk_list
  219. # Drop foreign keys
  220. def drop_foreign_keys(self):
  221. if not self.drop_foreign_key:
  222. return
  223. fk_list = self.get_foreign_keys()
  224. # make dictionary of constraint names
  225. fk_dict = {}
  226. for f in fk_list:
  227. fk_dict[f[0]] = f[1]
  228. # drop
  229. for col in self.drop_foreign_key:
  230. frappe.db.sql("set foreign_key_checks=0")
  231. frappe.db.sql("alter table `%s` drop foreign key `%s`" % (self.name, fk_dict[col.fieldname]))
  232. frappe.db.sql("set foreign_key_checks=1")
  233. def alter(self):
  234. for col in self.columns.values():
  235. col.build_for_alter_table(self.current_columns.get(col.fieldname, None))
  236. query = []
  237. for col in self.add_column:
  238. query.append("add column `{}` {}".format(col.fieldname, col.get_definition()))
  239. for col in self.change_type:
  240. query.append("change `{}` `{}` {}".format(col.fieldname, col.fieldname, col.get_definition()))
  241. for col in self.add_index:
  242. # if index key not exists
  243. if not frappe.db.sql("show index from `%s` where key_name = %s" %
  244. (self.name, '%s'), col.fieldname):
  245. query.append("add index `{}`(`{}`)".format(col.fieldname, col.fieldname))
  246. for col in self.drop_index:
  247. if col.fieldname != 'name': # primary key
  248. # if index key exists
  249. if frappe.db.sql("""show index from `{0}`
  250. where key_name=%s
  251. and Non_unique=%s""".format(self.name), (col.fieldname, 1 if col.unique else 0)):
  252. query.append("drop index `{}`".format(col.fieldname))
  253. for col in self.set_default:
  254. if col.fieldname=="name":
  255. continue
  256. if col.fieldtype in ("Check", "Int"):
  257. col_default = cint(col.default)
  258. elif col.fieldtype in ("Currency", "Float", "Percent"):
  259. col_default = flt(col.default)
  260. elif not col.default:
  261. col_default = "null"
  262. else:
  263. col_default = '"{}"'.format(col.default.replace('"', '\\"'))
  264. query.append('alter column `{}` set default {}'.format(col.fieldname, col_default))
  265. if query:
  266. try:
  267. frappe.db.sql("alter table `{}` {}".format(self.name, ", ".join(query)))
  268. except Exception, e:
  269. # sanitize
  270. if e.args[0]==1060:
  271. frappe.throw(str(e))
  272. elif e.args[0]==1062:
  273. fieldname = str(e).split("'")[-2]
  274. frappe.throw(_("{0} field cannot be set as unique in {1}, as there are non-unique existing values".format(fieldname, self.name)))
  275. else:
  276. raise e
  277. class DbColumn:
  278. def __init__(self, table, fieldname, fieldtype, length, default,
  279. set_index, options, unique, precision):
  280. self.table = table
  281. self.fieldname = fieldname
  282. self.fieldtype = fieldtype
  283. self.length = length
  284. self.set_index = set_index
  285. self.default = default
  286. self.options = options
  287. self.unique = unique
  288. self.precision = precision
  289. def get_definition(self, with_default=1):
  290. column_def = get_definition(self.fieldtype, precision=self.precision, length=self.length)
  291. if not column_def:
  292. return column_def
  293. if self.fieldtype in ("Check", "Int"):
  294. default_value = cint(self.default) or 0
  295. column_def += ' not null default {0}'.format(default_value)
  296. elif self.fieldtype in ("Currency", "Float", "Percent"):
  297. default_value = flt(self.default) or 0
  298. column_def += ' not null default {0}'.format(default_value)
  299. elif self.default and (self.default not in default_shortcuts) \
  300. and not self.default.startswith(":") and column_def not in ('text', 'longtext'):
  301. column_def += ' default "' + self.default.replace('"', '\"') + '"'
  302. if self.unique and (column_def not in ('text', 'longtext')):
  303. column_def += ' unique'
  304. return column_def
  305. def build_for_alter_table(self, current_def):
  306. column_def = get_definition(self.fieldtype, self.precision, self.length)
  307. # no columns
  308. if not column_def:
  309. return
  310. # to add?
  311. if not current_def:
  312. self.fieldname = validate_column_name(self.fieldname)
  313. self.table.add_column.append(self)
  314. return
  315. # type
  316. if (current_def['type'] != column_def) or \
  317. ((self.unique and not current_def['unique']) and column_def not in ('text', 'longtext')):
  318. self.table.change_type.append(self)
  319. else:
  320. # default
  321. if (self.default_changed(current_def) \
  322. and (self.default not in default_shortcuts) \
  323. and not cstr(self.default).startswith(":") \
  324. and not (column_def in ['text','longtext'])):
  325. self.table.set_default.append(self)
  326. # index should be applied or dropped irrespective of type change
  327. if ( (current_def['index'] and not self.set_index and not self.unique)
  328. or (current_def['unique'] and not self.unique) ):
  329. # to drop unique you have to drop index
  330. self.table.drop_index.append(self)
  331. elif (not current_def['index'] and self.set_index) and not (column_def in ('text', 'longtext')):
  332. self.table.add_index.append(self)
  333. def default_changed(self, current_def):
  334. if "decimal" in current_def['type']:
  335. return self.default_changed_for_decimal(current_def)
  336. else:
  337. return current_def['default'] != self.default
  338. def default_changed_for_decimal(self, current_def):
  339. try:
  340. if current_def['default'] in ("", None) and self.default in ("", None):
  341. # both none, empty
  342. return False
  343. elif current_def['default'] in ("", None):
  344. try:
  345. # check if new default value is valid
  346. float(self.default)
  347. return True
  348. except ValueError:
  349. return False
  350. elif self.default in ("", None):
  351. # new default value is empty
  352. return True
  353. else:
  354. # NOTE float() raise ValueError when "" or None is passed
  355. return float(current_def['default'])!=float(self.default)
  356. except TypeError:
  357. return True
  358. class DbManager:
  359. """
  360. Basically, a wrapper for oft-used mysql commands. like show tables,databases, variables etc...
  361. #TODO:
  362. 0. Simplify / create settings for the restore database source folder
  363. 0a. Merge restore database and extract_sql(from frappe_server_tools).
  364. 1. Setter and getter for different mysql variables.
  365. 2. Setter and getter for mysql variables at global level??
  366. """
  367. def __init__(self,db):
  368. """
  369. Pass root_conn here for access to all databases.
  370. """
  371. if db:
  372. self.db = db
  373. def get_current_host(self):
  374. return self.db.sql("select user()")[0][0].split('@')[1]
  375. def get_variables(self,regex):
  376. """
  377. Get variables that match the passed pattern regex
  378. """
  379. return list(self.db.sql("SHOW VARIABLES LIKE '%s'"%regex))
  380. def get_table_schema(self,table):
  381. """
  382. Just returns the output of Desc tables.
  383. """
  384. return list(self.db.sql("DESC `%s`"%table))
  385. def get_tables_list(self,target=None):
  386. """get list of tables"""
  387. if target:
  388. self.db.use(target)
  389. return [t[0] for t in self.db.sql("SHOW TABLES")]
  390. def create_user(self, user, password, host=None):
  391. #Create user if it doesn't exist.
  392. if not host:
  393. host = self.get_current_host()
  394. try:
  395. if password:
  396. self.db.sql("CREATE USER '%s'@'%s' IDENTIFIED BY '%s';" % (user[:16], host, password))
  397. else:
  398. self.db.sql("CREATE USER '%s'@'%s';" % (user[:16], host))
  399. except Exception:
  400. raise
  401. def delete_user(self, target, host=None):
  402. if not host:
  403. host = self.get_current_host()
  404. try:
  405. self.db.sql("DROP USER '%s'@'%s';" % (target, host))
  406. except Exception, e:
  407. if e.args[0]==1396:
  408. pass
  409. else:
  410. raise
  411. def create_database(self,target):
  412. if target in self.get_database_list():
  413. self.drop_database(target)
  414. self.db.sql("CREATE DATABASE `%s` ;" % target)
  415. def drop_database(self,target):
  416. self.db.sql("DROP DATABASE IF EXISTS `%s`;"%target)
  417. def grant_all_privileges(self, target, user, host=None):
  418. if not host:
  419. host = self.get_current_host()
  420. self.db.sql("GRANT ALL PRIVILEGES ON `%s`.* TO '%s'@'%s';" % (target, user, host))
  421. def grant_select_privilges(self, db, table, user, host=None):
  422. if not host:
  423. host = self.get_current_host()
  424. if table:
  425. self.db.sql("GRANT SELECT ON %s.%s to '%s'@'%s';" % (db, table, user, host))
  426. else:
  427. self.db.sql("GRANT SELECT ON %s.* to '%s'@'%s';" % (db, user, host))
  428. def flush_privileges(self):
  429. self.db.sql("FLUSH PRIVILEGES")
  430. def get_database_list(self):
  431. """get list of databases"""
  432. return [d[0] for d in self.db.sql("SHOW DATABASES")]
  433. def restore_database(self,target,source,user,password):
  434. from frappe.utils import make_esc
  435. esc = make_esc('$ ')
  436. os.system("mysql -u %s -p%s -h%s %s < %s" % \
  437. (esc(user), esc(password), esc(frappe.db.host), esc(target), source))
  438. def drop_table(self,table_name):
  439. """drop table if exists"""
  440. if not table_name in self.get_tables_list():
  441. return
  442. self.db.sql("DROP TABLE IF EXISTS %s "%(table_name))
  443. def validate_column_name(n):
  444. n = n.replace(' ','_').strip().lower()
  445. special_characters = re.findall("[\W]", n, re.UNICODE)
  446. if special_characters:
  447. special_characters = ", ".join('"{0}"'.format(c) for c in special_characters)
  448. frappe.throw(_("Fieldname {0} cannot have special characters like {1}").format(cstr(n), special_characters), InvalidColumnName)
  449. return n
  450. def remove_all_foreign_keys():
  451. frappe.db.sql("set foreign_key_checks = 0")
  452. frappe.db.commit()
  453. for t in frappe.db.sql("select name from tabDocType where issingle=0"):
  454. dbtab = DbTable(t[0])
  455. try:
  456. fklist = dbtab.get_foreign_keys()
  457. except Exception, e:
  458. if e.args[0]==1146:
  459. fklist = []
  460. else:
  461. raise
  462. for f in fklist:
  463. frappe.db.sql("alter table `tab%s` drop foreign key `%s`" % (t[0], f[1]))
  464. def get_definition(fieldtype, precision=None, length=None):
  465. d = type_map.get(fieldtype)
  466. if not d:
  467. return
  468. coltype = d[0]
  469. size = None
  470. if d[1]:
  471. size = d[1]
  472. if size:
  473. if fieldtype in ["Float", "Currency", "Percent"] and cint(precision) > 6:
  474. size = '21,9'
  475. if coltype == "varchar" and length:
  476. size = length
  477. if size is not None:
  478. coltype = "{coltype}({size})".format(coltype=coltype, size=size)
  479. return coltype
  480. def add_column(doctype, column_name, fieldtype, precision=None):
  481. if column_name in frappe.db.get_table_columns(doctype):
  482. # already exists
  483. return
  484. frappe.db.commit()
  485. frappe.db.sql("alter table `tab%s` add column %s %s" % (doctype,
  486. column_name, get_definition(fieldtype, precision)))