Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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