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.
 
 
 
 
 
 

444 line
13 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. """
  24. Syncs a database table to the `DocType` (metadata)
  25. .. note:: This module is only used internally
  26. """
  27. import os
  28. import webnotes
  29. from webnotes.utils import cstr
  30. type_map = {
  31. 'currency': ('decimal', '18,6')
  32. ,'int': ('int', '11')
  33. ,'float': ('decimal', '18,6')
  34. ,'percent': ('decimal', '18,6')
  35. ,'check': ('int', '1')
  36. ,'small text': ('text', '')
  37. ,'long text': ('longtext', '')
  38. ,'code': ('text', '')
  39. ,'text editor': ('text', '')
  40. ,'date': ('date', '')
  41. ,'datetime': ('datetime', '')
  42. ,'time': ('time', '')
  43. ,'text': ('text', '')
  44. ,'data': ('varchar', '180')
  45. ,'link': ('varchar', '180')
  46. ,'password': ('varchar', '180')
  47. ,'select': ('varchar', '180')
  48. ,'read only': ('varchar', '180')
  49. }
  50. default_columns = ['name', 'creation', 'modified', 'modified_by', 'owner', 'docstatus', 'parent',\
  51. 'parentfield', 'parenttype', 'idx']
  52. default_shortcuts = ['_Login', '__user', '_Full Name', 'Today', '__today']
  53. import _mysql_exceptions
  54. # -------------------------------------------------
  55. # Class database table
  56. # -------------------------------------------------
  57. class DbTable:
  58. def __init__(self, doctype, prefix = 'tab'):
  59. self.doctype = doctype
  60. self.name = prefix + doctype
  61. self.columns = {}
  62. self.current_columns = {}
  63. # lists for change
  64. self.add_column = []
  65. self.change_type = []
  66. self.add_index = []
  67. self.drop_index = []
  68. self.set_default = []
  69. # load
  70. self.get_columns_from_docfields()
  71. def create(self):
  72. add_text = ''
  73. # columns
  74. t = self.get_column_definitions()
  75. if t: add_text += ',\n'.join(self.get_column_definitions()) + ',\n'
  76. # index
  77. t = self.get_index_definitions()
  78. if t: add_text += ',\n'.join(self.get_index_definitions()) + ',\n'
  79. # create table
  80. webnotes.conn.sql("""create table `%s` (
  81. name varchar(120) not null primary key,
  82. creation datetime,
  83. modified datetime,
  84. modified_by varchar(40),
  85. owner varchar(40),
  86. docstatus int(1) default '0',
  87. parent varchar(120),
  88. parentfield varchar(120),
  89. parenttype varchar(120),
  90. idx int(8),
  91. %sindex parent(parent))
  92. ENGINE=InnoDB
  93. CHARACTER SET=utf8""" % (self.name, add_text))
  94. def get_columns_from_docfields(self):
  95. """
  96. get columns from docfields and custom fields
  97. """
  98. fl = webnotes.conn.sql("SELECT * FROM tabDocField WHERE parent = '%s'" % self.doctype, as_dict = 1)
  99. try:
  100. custom_fl = webnotes.conn.sql("""\
  101. SELECT * FROM `tabCustom Field`
  102. WHERE dt = %s AND docstatus < 2""", self.doctype, as_dict=1)
  103. if custom_fl: fl += custom_fl
  104. except Exception, e:
  105. if e.args[0]!=1146: # ignore no custom field
  106. raise e
  107. for f in fl:
  108. self.columns[f['fieldname']] = DbColumn(self, f['fieldname'],
  109. f['fieldtype'], f.get('length'), f.get('default'),
  110. f.get('search_index'), f.get('options'))
  111. def get_columns_from_db(self):
  112. self.show_columns = webnotes.conn.sql("desc `%s`" % self.name)
  113. for c in self.show_columns:
  114. self.current_columns[c[0]] = {'name': c[0], 'type':c[1], 'index':c[3], 'default':c[4]}
  115. def get_column_definitions(self):
  116. column_list = [] + default_columns
  117. ret = []
  118. for k in self.columns.keys():
  119. if k not in column_list:
  120. d = self.columns[k].get_definition()
  121. if d:
  122. ret.append('`'+ k+ '` ' + d)
  123. column_list.append(k)
  124. return ret
  125. def get_index_definitions(self):
  126. ret = []
  127. for k in self.columns.keys():
  128. if type_map.get(self.columns[k].fieldtype) and type_map.get(self.columns[k].fieldtype.lower())[0] not in ('text', 'blob'):
  129. ret.append('index `' + k + '`(`' + k + '`)')
  130. return ret
  131. # GET foreign keys
  132. def get_foreign_keys(self):
  133. fk_list = []
  134. txt = webnotes.conn.sql("show create table `%s`" % self.name)[0][1]
  135. for line in txt.split('\n'):
  136. if line.strip().startswith('CONSTRAINT') and line.find('FOREIGN')!=-1:
  137. try:
  138. fk_list.append((line.split('`')[3], line.split('`')[1]))
  139. except IndexError, e:
  140. pass
  141. return fk_list
  142. # Drop foreign keys
  143. def drop_foreign_keys(self):
  144. if not self.drop_foreign_key:
  145. return
  146. fk_list = self.get_foreign_keys()
  147. # make dictionary of constraint names
  148. fk_dict = {}
  149. for f in fk_list:
  150. fk_dict[f[0]] = f[1]
  151. # drop
  152. for col in self.drop_foreign_key:
  153. webnotes.conn.sql("set foreign_key_checks=0")
  154. webnotes.conn.sql("alter table `%s` drop foreign key `%s`" % (self.name, fk_dict[col.fieldname]))
  155. webnotes.conn.sql("set foreign_key_checks=1")
  156. def sync(self):
  157. if not self.name in DbManager(webnotes.conn).get_tables_list(webnotes.conn.cur_db_name):
  158. self.create()
  159. else:
  160. self.alter()
  161. def alter(self):
  162. self.get_columns_from_db()
  163. for col in self.columns.values():
  164. col.check(self.current_columns.get(col.fieldname, None))
  165. for col in self.add_column:
  166. webnotes.conn.sql("alter table `%s` add column `%s` %s" % (self.name, col.fieldname, col.get_definition()))
  167. for col in self.change_type:
  168. webnotes.conn.sql("alter table `%s` change `%s` `%s` %s" % (self.name, col.fieldname, col.fieldname, col.get_definition()))
  169. for col in self.add_index:
  170. # if index key not exists
  171. if not webnotes.conn.sql("show index from `%s` where key_name = '%s'" % (self.name, col.fieldname)):
  172. webnotes.conn.sql("alter table `%s` add index `%s`(`%s`)" % (self.name, col.fieldname, col.fieldname))
  173. for col in self.drop_index:
  174. if col.fieldname != 'name': # primary key
  175. # if index key exists
  176. if webnotes.conn.sql("show index from `%s` where key_name = '%s'" % (self.name, col.fieldname)):
  177. webnotes.conn.sql("alter table `%s` drop index `%s`" % (self.name, col.fieldname))
  178. for col in self.set_default:
  179. webnotes.conn.sql("alter table `%s` alter column `%s` set default %s" % (self.name, col.fieldname, '%s'), (col.default,))
  180. class DbColumn:
  181. def __init__(self, table, fieldname, fieldtype, length, default, set_index, options):
  182. self.table = table
  183. self.fieldname = fieldname
  184. self.fieldtype = fieldtype
  185. self.length = length
  186. self.set_index = set_index
  187. self.default = default
  188. self.options = options
  189. def get_definition(self, with_default=1):
  190. d = type_map.get(self.fieldtype.lower())
  191. if not d:
  192. return
  193. ret = d[0]
  194. if d[1]:
  195. ret += '(' + d[1] + ')'
  196. if with_default and self.default and (self.default not in default_shortcuts) \
  197. and not self.default.startswith(":") and d[0] not in ['text', 'longblob']:
  198. ret += ' default "' + self.default.replace('"', '\"') + '"'
  199. return ret
  200. def check(self, current_def):
  201. column_def = self.get_definition(0)
  202. # no columns
  203. if not column_def:
  204. return
  205. # to add?
  206. if not current_def:
  207. self.fieldname = validate_column_name(self.fieldname)
  208. self.table.add_column.append(self)
  209. return
  210. # type
  211. if current_def['type'] != column_def:
  212. self.table.change_type.append(self)
  213. # index
  214. else:
  215. if (current_def['index'] and not self.set_index):
  216. self.table.drop_index.append(self)
  217. if (not current_def['index'] and self.set_index and not (column_def in ['text','blob'])):
  218. self.table.add_index.append(self)
  219. # default
  220. if (self.default_changed(current_def) and (self.default not in default_shortcuts) and not cstr(self.default).startswith(":") and not (column_def in ['text','blob'])):
  221. self.table.set_default.append(self)
  222. def default_changed(self, current_def):
  223. if "decimal" in current_def['type']:
  224. try:
  225. return float(current_def['default'])!=float(self.default)
  226. except TypeError, e:
  227. return True
  228. else:
  229. return current_def['default'] != self.default
  230. class DbManager:
  231. """
  232. Basically, a wrapper for oft-used mysql commands. like show tables,databases, variables etc...
  233. #TODO:
  234. 0. Simplify / create settings for the restore database source folder
  235. 0a. Merge restore database and extract_sql(from webnotes_server_tools).
  236. 1. Setter and getter for different mysql variables.
  237. 2. Setter and getter for mysql variables at global level??
  238. """
  239. def __init__(self,conn):
  240. """
  241. Pass root_conn here for access to all databases.
  242. """
  243. if conn:
  244. self.conn = conn
  245. def get_variables(self,regex):
  246. """
  247. Get variables that match the passed pattern regex
  248. """
  249. return list(self.conn.sql("SHOW VARIABLES LIKE '%s'"%regex))
  250. def get_table_schema(self,table):
  251. """
  252. Just returns the output of Desc tables.
  253. """
  254. return list(self.conn.sql("DESC `%s`"%table))
  255. def get_tables_list(self,target=None):
  256. """get list of tables"""
  257. if target:
  258. self.conn.use(target)
  259. return [t[0] for t in self.conn.sql("SHOW TABLES")]
  260. def create_user(self,user,password):
  261. #Create user if it doesn't exist.
  262. try:
  263. if password:
  264. self.conn.sql("CREATE USER '%s'@'localhost' IDENTIFIED BY '%s';" % (user[:16], password))
  265. else:
  266. self.conn.sql("CREATE USER '%s'@'localhost';"%user[:16])
  267. except Exception, e:
  268. raise e
  269. def delete_user(self,target):
  270. # delete user if exists
  271. try:
  272. self.conn.sql("DROP USER '%s'@'localhost';" % target)
  273. except Exception, e:
  274. if e.args[0]==1396:
  275. pass
  276. else:
  277. raise e
  278. def create_database(self,target):
  279. if target in self.get_database_list():
  280. self.drop_database(target)
  281. self.conn.sql("CREATE DATABASE IF NOT EXISTS `%s` ;" % target)
  282. def drop_database(self,target):
  283. try:
  284. self.conn.sql("DROP DATABASE IF EXISTS `%s`;"%target)
  285. except Exception,e:
  286. raise e
  287. def grant_all_privileges(self,target,user):
  288. try:
  289. self.conn.sql("GRANT ALL PRIVILEGES ON `%s`.* TO '%s'@'localhost';" % (target, user))
  290. except Exception,e:
  291. raise e
  292. def grant_select_privilges(self,db,table,user):
  293. try:
  294. if table:
  295. self.conn.sql("GRANT SELECT ON %s.%s to '%s'@'localhost';" % (db,table,user))
  296. else:
  297. self.conn.sql("GRANT SELECT ON %s.* to '%s'@'localhost';" % (db,user))
  298. except Exception,e:
  299. raise e
  300. def flush_privileges(self):
  301. try:
  302. self.conn.sql("FLUSH PRIVILEGES")
  303. except Exception,e:
  304. raise e
  305. def get_database_list(self):
  306. """get list of databases"""
  307. return [d[0] for d in self.conn.sql("SHOW DATABASES")]
  308. def restore_database(self,target,source,user,password):
  309. from webnotes.utils import make_esc
  310. esc = make_esc('$ ')
  311. try:
  312. ret = os.system("mysql -u %s -p%s %s < %s" % \
  313. (esc(user), esc(password), esc(target), source))
  314. except Exception,e:
  315. raise e
  316. def drop_table(self,table_name):
  317. """drop table if exists"""
  318. if not table_name in self.get_tables_list():
  319. return
  320. try:
  321. self.conn.sql("DROP TABLE IF EXISTS %s "%(table_name))
  322. except Exception,e:
  323. raise e
  324. def set_transaction_isolation_level(self,scope='SESSION',level='READ COMMITTED'):
  325. #Sets the transaction isolation level. scope = global/session
  326. try:
  327. self.conn.sql("SET %s TRANSACTION ISOLATION LEVEL %s"%(scope,level))
  328. except Exception,e:
  329. raise e
  330. def validate_column_name(n):
  331. n = n.replace(' ','_').strip().lower()
  332. import re
  333. if re.search("[\W]", n):
  334. webnotes.msgprint('err:%s is not a valid fieldname.<br>A valid name must contain letters / numbers / spaces.<br><b>Tip: </b>You can change the Label after the fieldname has been set' % n)
  335. raise Exception
  336. return n
  337. def updatedb(dt):
  338. """
  339. Syncs a `DocType` to the table
  340. * creates if required
  341. * updates columns
  342. * updates indices
  343. """
  344. res = webnotes.conn.sql("select ifnull(issingle, 0) from tabDocType where name=%s", dt)
  345. if not res:
  346. raise Exception, 'Wrong doctype "%s" in updatedb' % dt
  347. if not res[0][0]:
  348. webnotes.conn.commit()
  349. tab = DbTable(dt, 'tab')
  350. tab.sync()
  351. webnotes.conn.begin()
  352. def remove_all_foreign_keys():
  353. webnotes.conn.sql("set foreign_key_checks = 0")
  354. webnotes.conn.commit()
  355. for t in webnotes.conn.sql("select name from tabDocType where ifnull(issingle,0)=0"):
  356. dbtab = webnotes.model.db_schema.DbTable(t[0])
  357. try:
  358. fklist = dbtab.get_foreign_keys()
  359. except Exception, e:
  360. if e.args[0]==1146:
  361. fklist = []
  362. else:
  363. raise e
  364. for f in fklist:
  365. webnotes.conn.sql("alter table `tab%s` drop foreign key `%s`" % (t[0], f[1]))