25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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