您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

411 行
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. # Database Module
  23. # --------------------
  24. from __future__ import unicode_literals
  25. import MySQLdb
  26. import webnotes
  27. import conf
  28. class Database:
  29. """
  30. Open a database connection with the given parmeters, if use_default is True, use the
  31. login details from `conf.py`. This is called by the request handler and is accessible using
  32. the `conn` global variable. the `sql` method is also global to run queries
  33. """
  34. def __init__(self, host=None, user=None, password=None, ac_name=None, use_default = 0):
  35. self.host = host or 'localhost'
  36. self.user = user or conf.db_name
  37. if ac_name:
  38. self.user = self.get_db_login(ac_name) or conf.db_name
  39. if use_default:
  40. self.user = conf.db_name
  41. self.in_transaction = 0
  42. self.transaction_writes = 0
  43. self.auto_commit_on_many_writes = 0
  44. self.password = password or webnotes.get_db_password(self.user)
  45. self.connect()
  46. if self.user != 'root':
  47. self.use(self.user)
  48. def get_db_login(self, ac_name):
  49. return ac_name
  50. def connect(self):
  51. """
  52. Connect to a database
  53. """
  54. self._conn = MySQLdb.connect(user=self.user, host=self.host, passwd=self.password, use_unicode=True, charset='utf8')
  55. self._conn.converter[246]=float
  56. self._cursor = self._conn.cursor()
  57. def use(self, db_name):
  58. """
  59. `USE` db_name
  60. """
  61. self._conn.select_db(db_name)
  62. self.cur_db_name = db_name
  63. def check_transaction_status(self, query):
  64. """
  65. Update *in_transaction* and check if "START TRANSACTION" is not called twice
  66. """
  67. if self.in_transaction and query and query.strip().split()[0].lower() in ['start', 'alter', 'drop', 'create']:
  68. raise Exception, 'This statement can cause implicit commit'
  69. if query and query.strip().lower()=='start transaction':
  70. self.in_transaction = 1
  71. self.transaction_writes = 0
  72. if query and query.strip().split()[0].lower() in ['commit', 'rollback']:
  73. self.in_transaction = 0
  74. if self.in_transaction and query[:6].lower() in ['update', 'insert']:
  75. self.transaction_writes += 1
  76. if self.transaction_writes > 10000:
  77. if self.auto_commit_on_many_writes:
  78. webnotes.conn.commit()
  79. webnotes.conn.begin()
  80. else:
  81. webnotes.msgprint('A very long query was encountered. If you are trying to import data, please do so using smaller files')
  82. raise Exception, 'Bad Query!!! Too many writes'
  83. def fetch_as_dict(self, formatted=0, as_utf8=0):
  84. """
  85. Internal - get results as dictionary
  86. """
  87. result = self._cursor.fetchall()
  88. ret = []
  89. for r in result:
  90. row_dict = webnotes.DictObj({})
  91. for i in range(len(r)):
  92. val = self.convert_to_simple_type(r[i], formatted)
  93. if as_utf8 and type(val) is unicode:
  94. val = val.encode('utf-8')
  95. row_dict[self._cursor.description[i][0]] = val
  96. ret.append(row_dict)
  97. return ret
  98. def validate_query(self, q):
  99. cmd = q.strip().lower().split()[0]
  100. if cmd in ['alter', 'drop', 'truncate'] and webnotes.user.name != 'Administrator':
  101. webnotes.msgprint('Not allowed to execute query')
  102. raise Execption
  103. # ======================================================================================
  104. def sql(self, query, values=(), as_dict = 0, as_list = 0, formatted = 0,
  105. debug=0, ignore_ddl=0, as_utf8=0, auto_commit=0):
  106. """
  107. * Execute a `query`, with given `values`
  108. * returns as a dictionary if as_dict = 1
  109. * returns as a list of lists (with cleaned up dates) if as_list = 1
  110. """
  111. # in transaction validations
  112. self.check_transaction_status(query)
  113. # autocommit
  114. if auto_commit and self.in_transaction: self.commit()
  115. if auto_commit: self.begin()
  116. # execute
  117. try:
  118. if values!=():
  119. if isinstance(values, dict):
  120. values = dict(values)
  121. if debug: webnotes.errprint(query % values)
  122. self._cursor.execute(query, values)
  123. else:
  124. if debug: webnotes.errprint(query)
  125. self._cursor.execute(query)
  126. except Exception, e:
  127. # ignore data definition errors
  128. if ignore_ddl and e.args[0] in (1146,1054,1091):
  129. pass
  130. else:
  131. raise e
  132. if auto_commit: self.commit()
  133. # scrub output if required
  134. if as_dict:
  135. return self.fetch_as_dict(formatted, as_utf8)
  136. elif as_list:
  137. return self.convert_to_lists(self._cursor.fetchall(), formatted, as_utf8)
  138. elif as_utf8:
  139. return self.convert_to_lists(self._cursor.fetchall(), formatted, as_utf8)
  140. else:
  141. return self._cursor.fetchall()
  142. def get_description(self):
  143. """
  144. Get metadata of the last query
  145. """
  146. return self._cursor.description
  147. # ======================================================================================
  148. def convert_to_simple_type(self, v, formatted=0):
  149. import datetime
  150. from webnotes.utils import formatdate, fmt_money
  151. # date
  152. if type(v)==datetime.date:
  153. v = str(v)
  154. if formatted:
  155. v = formatdate(v)
  156. # time
  157. elif type(v)==datetime.timedelta:
  158. h = int(v.seconds/60/60)
  159. v = str(h) + ':' + str(v.seconds/60 - h*60)
  160. if v[1]==':':
  161. v='0'+v
  162. # datetime
  163. elif type(v)==datetime.datetime:
  164. v = str(v)
  165. # long
  166. elif type(v)==long:
  167. v=int(v)
  168. # convert to strings... (if formatted)
  169. if formatted:
  170. if type(v)==float:
  171. v=fmt_money(v)
  172. if type(v)==int:
  173. v=str(v)
  174. return v
  175. # ======================================================================================
  176. def convert_to_lists(self, res, formatted=0, as_utf8=0):
  177. """
  178. Convert the given result set to a list of lists (with cleaned up dates and decimals)
  179. """
  180. nres = []
  181. for r in res:
  182. nr = []
  183. for c in r:
  184. val = self.convert_to_simple_type(c, formatted)
  185. if as_utf8 and type(val) is unicode:
  186. val = val.encode('utf-8')
  187. nr.append(val)
  188. nres.append(nr)
  189. return nres
  190. # ======================================================================================
  191. def convert_to_utf8(self, res, formatted=0):
  192. """
  193. Convert the given result set to a list of lists and as utf8 (with cleaned up dates and decimals)
  194. """
  195. nres = []
  196. for r in res:
  197. nr = []
  198. for c in r:
  199. if type(c) is unicode:
  200. c = c.encode('utf-8')
  201. nr.append(self.convert_to_simple_type(c, formatted))
  202. nres.append(nr)
  203. return nres
  204. def build_conditions(self, filters):
  205. def _build_condition(key):
  206. """
  207. filter's key is passed by map function
  208. build conditions like:
  209. * ifnull(`fieldname`, default_value) = %(fieldname)s
  210. * `fieldname` = %(fieldname)s
  211. """
  212. if "[" in key:
  213. split_key = key.split("[")
  214. return "ifnull(`" + split_key[0] + "`, " + split_key[1][:-1] + ") = %(" + key + ")s"
  215. else:
  216. return "`" + key + "` = %(" + key + ")s"
  217. if isinstance(filters, basestring):
  218. filters = { "name": filters }
  219. conditions = map(_build_condition, filters)
  220. return " and ".join(conditions), filters
  221. def get_value(self, doctype, filters=None, fieldname="name", ignore=None, as_dict=False):
  222. """Get a single / multiple value from a record.
  223. For Single DocType, let filters be = None"""
  224. if filters is not None and (filters!=doctype or filters=='DocType'):
  225. fl = isinstance(fieldname, basestring) and fieldname or "`, `".join(fieldname)
  226. conditions, filters = self.build_conditions(filters)
  227. try:
  228. r = self.sql("select `%s` from `tab%s` where %s" % (fl, doctype,
  229. conditions), filters, as_dict)
  230. except Exception, e:
  231. if e.args[0]==1054 and ignore:
  232. return None
  233. else:
  234. raise e
  235. return r and (len(r[0]) > 1 and r[0] or r[0][0]) or None
  236. else:
  237. fieldname = isinstance(fieldname, basestring) and [fieldname] or fieldname
  238. r = self.sql("select field, value from tabSingles where field in (%s) and \
  239. doctype=%s" % (', '.join(['%s']*len(fieldname)), '%s'), tuple(fieldname) + (doctype,), as_dict=False)
  240. if as_dict:
  241. return r and webnotes.DictObj(r) or None
  242. else:
  243. return r and (len(r) > 1 and [i[0] for i in r] or r[0][1]) or None
  244. def set_value(self, dt, dn, field, val, modified=None, modified_by=None):
  245. from webnotes.utils import now
  246. if dn and dt!=dn:
  247. self.sql("""update `tab%s` set `%s`=%s, modified=%s, modified_by=%s
  248. where name=%s""" % (dt, field, "%s", "%s", "%s", "%s"),
  249. (val, modified or now(), modified_by or webnotes.session["user"], dn))
  250. else:
  251. if self.sql("select value from tabSingles where field=%s and doctype=%s", (field, dt)):
  252. self.sql("update tabSingles set value=%s where field=%s and doctype=%s", (val, field, dt))
  253. else:
  254. self.sql("insert into tabSingles(doctype, field, value) values (%s, %s, %s)", (dt, field, val))
  255. def set(self, doc, field, val):
  256. from webnotes.utils import now
  257. doc.modified = now()
  258. doc.modified_by = webnotes.session["user"]
  259. self.set_value(doc.doctype, doc.name, field, val, doc.modified, doc.modified_by)
  260. doc.fields[field] = val
  261. # ======================================================================================
  262. def set_global(self, key, val, user='__global'):
  263. res = self.sql('select defkey from `tabDefaultValue` where defkey=%s and parent=%s', (key, user))
  264. if res:
  265. self.sql('update `tabDefaultValue` set defvalue=%s where parent=%s and defkey=%s', (str(val), user, key))
  266. else:
  267. self.sql('insert into `tabDefaultValue` (name, defkey, defvalue, parent) values (%s,%s,%s,%s)', (user+'_'+key, key, str(val), user))
  268. def get_global(self, key, user='__global'):
  269. g = self.sql("select defvalue from tabDefaultValue where defkey=%s and parent=%s", (key, user))
  270. return g and g[0][0] or None
  271. # ======================================================================================
  272. def set_default(self, key, val, parent="Control Panel"):
  273. """set control panel default (tabDefaultVal)"""
  274. if self.sql("""select defkey from `tabDefaultValue` where
  275. defkey=%s and parent=%s """, (key, parent)):
  276. # update
  277. self.sql("""update `tabDefaultValue` set defvalue=%s
  278. where parent=%s and defkey=%s""", (val, parent, key))
  279. else:
  280. from webnotes.model.doc import Document
  281. d = Document('DefaultValue')
  282. d.parent = parent
  283. d.parenttype = 'Control Panel' # does not matter
  284. d.parentfield = 'system_defaults'
  285. d.defkey = key
  286. d.defvalue = val
  287. d.save(1)
  288. def get_default(self, key):
  289. """get default value"""
  290. ret = self.sql("""select defvalue from \
  291. tabDefaultValue where defkey=%s""", key)
  292. return ret and ret[0][0] or None
  293. def get_defaults(self, key=None):
  294. """get all defaults"""
  295. if key:
  296. return self.get_default(key)
  297. else:
  298. res = self.sql("""select defkey, defvalue from `tabDefaultValue`
  299. where parent = "Control Panel" """)
  300. d = {}
  301. for rec in res:
  302. d[rec[0]] = rec[1] or ''
  303. return d
  304. def begin(self):
  305. if not self.in_transaction:
  306. self.sql("start transaction")
  307. def commit(self):
  308. self.sql("commit")
  309. def rollback(self):
  310. self.sql("ROLLBACK")
  311. # ======================================================================================
  312. def field_exists(self, dt, fn):
  313. """
  314. Returns True if `fn` exists in `DocType` `dt`
  315. """
  316. return self.sql("select name from tabDocField where fieldname=%s and parent=%s", (dt, fn))
  317. def exists(self, dt, dn=None):
  318. """
  319. Returns true if the record exists
  320. """
  321. if isinstance(dt, basestring):
  322. try:
  323. return self.sql('select name from `tab%s` where name=%s' % (dt, '%s'), dn)
  324. except:
  325. return None
  326. elif isinstance(dt, dict) and dt.get('doctype'):
  327. try:
  328. conditions = []
  329. for d in dt:
  330. if d == 'doctype': continue
  331. conditions.append('`%s` = "%s"' % (d, dt[d].replace('"', '\"')))
  332. return self.sql('select name from `tab%s` where %s' % \
  333. (dt['doctype'], " and ".join(conditions)))
  334. except:
  335. return None
  336. # ======================================================================================
  337. def close(self):
  338. """
  339. Close my connection
  340. """
  341. if self._conn:
  342. self._cursor.close()
  343. self._conn.close()
  344. self._cursor = None
  345. self._conn = None