25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

410 lines
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,
  107. debug=0, ignore_ddl=0, as_utf8=0, auto_commit=0):
  108. """
  109. * Execute a `query`, with given `values`
  110. * returns as a dictionary if as_dict = 1
  111. * returns as a list of lists (with cleaned up dates) if as_list = 1
  112. """
  113. # in transaction validations
  114. self.check_transaction_status(query)
  115. # autocommit
  116. if auto_commit and self.in_transaction: self.commit()
  117. if auto_commit: self.begin()
  118. # execute
  119. try:
  120. if 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. # ======================================================================================
  205. def replace_tab_by_test(self, query):
  206. """
  207. Relace all ``tab`` + doctype to ``test`` + doctype
  208. """
  209. if self.is_testing:
  210. tl = self.get_testing_tables()
  211. for t in tl:
  212. query = query.replace(t, 'test' + t[3:])
  213. return query
  214. def get_testing_tables(self):
  215. """
  216. Get list of all tables for which `tab` is to be replaced by `test` before a query is executed
  217. """
  218. if not self.testing_tables:
  219. 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)]
  220. testing_tables+=['tabSeries','tabSingles'] # tabSessions is not included here
  221. return self.testing_tables
  222. # ======================================================================================
  223. # get a single value from a record
  224. def get_value(self, doctype, docname, fieldname, ignore=None):
  225. """
  226. Get a single / multiple value from a record.
  227. For Single DocType, let docname be = None
  228. """
  229. fl = fieldname
  230. if docname and (docname!=doctype or docname=='DocType'):
  231. if type(fieldname) in (list, tuple):
  232. fl = '`, `'.join(fieldname)
  233. try:
  234. r = self.sql("select `%s` from `tab%s` where name='%s'" % (fl, doctype, docname))
  235. except Exception, e:
  236. if e.args[0]==1054 and ignore:
  237. return None
  238. else:
  239. raise e
  240. return r and (len(r[0]) > 1 and r[0] or r[0][0]) or None
  241. else:
  242. if type(fieldname) in (list, tuple):
  243. fl = "', '".join(fieldname)
  244. r = self.sql("select value from tabSingles where field in ('%s') and doctype='%s'" % \
  245. (fieldname, doctype))
  246. return r and (len(r) > 1 and (i[0] for i in r) or r[0][0]) or None
  247. def set_value(self, dt, dn, field, val, modified = None):
  248. from webnotes.utils import now
  249. if dn and dt!=dn:
  250. self.sql("update `tab"+dt+"` set `"+field+"`=%s, modified=%s where name=%s", (val, modified or now(), dn))
  251. else:
  252. if self.sql("select value from tabSingles where field=%s and doctype=%s", (field, dt)):
  253. self.sql("update tabSingles set value=%s where field=%s and doctype=%s", (val, field, dt))
  254. else:
  255. self.sql("insert into tabSingles(doctype, field, value) values (%s, %s, %s)", (dt, field, val))
  256. def set(self, doc, field, val):
  257. from webnotes.utils import now
  258. doc.modified = now()
  259. self.set_value(doc.doctype, doc.name, field, val, doc.modified)
  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):
  273. """set control panel default (tabDefaultVal)"""
  274. if self.sql("""select defkey from `tabDefaultValue` where
  275. defkey=%s and parent = "Control Panel" """, key):
  276. # update
  277. self.sql("""update `tabDefaultValue` set defvalue=%s
  278. where parent = "Control Panel" and defkey=%s""", (val, key))
  279. else:
  280. from webnotes.model.doc import Document
  281. d = Document('DefaultValue')
  282. d.parent = 'Control Panel'
  283. d.parenttype = 'Control Panel'
  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 tabDefaultValue where defkey=%s""", key)
  291. return ret and ret[0][0] or None
  292. def get_defaults(self, key=None):
  293. """get all defaults"""
  294. if key:
  295. return self.get_default(key)
  296. else:
  297. res = self.sql("""select defkey, defvalue from `tabDefaultValue`
  298. where parent = "Control Panel" """)
  299. d = {}
  300. for rec in res:
  301. d[rec[0]] = rec[1] or ''
  302. return d
  303. def begin(self):
  304. if not self.in_transaction:
  305. self.sql("start transaction")
  306. def commit(self):
  307. self.sql("commit")
  308. def rollback(self):
  309. self.sql("ROLLBACK")
  310. # ======================================================================================
  311. def field_exists(self, dt, fn):
  312. """
  313. Returns True if `fn` exists in `DocType` `dt`
  314. """
  315. return self.sql("select name from tabDocField where fieldname=%s and parent=%s", (dt, fn))
  316. def exists(self, dt, dn=None):
  317. """
  318. Returns true if the record exists
  319. """
  320. if isinstance(dt, basestring):
  321. try:
  322. return self.sql('select name from `tab%s` where name=%s' % (dt, '%s'), dn)
  323. except:
  324. return None
  325. elif isinstance(dt, dict) and dt.get('doctype'):
  326. try:
  327. conditions = []
  328. for d in dt:
  329. if d == 'doctype': continue
  330. conditions.append('`%s` = "%s"' % (d, dt[d].replace('"', '\"')))
  331. return self.sql('select name from `tab%s` where %s' % \
  332. (dt['doctype'], " and ".join(conditions)))
  333. except:
  334. return None
  335. # ======================================================================================
  336. def close(self):
  337. """
  338. Close my connection
  339. """
  340. if self._conn:
  341. self._cursor.close()
  342. self._conn.close()
  343. self._cursor = None
  344. self._conn = None