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