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.
 
 
 
 
 
 

438 line
12 KiB

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