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.
 
 
 
 
 
 

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