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.

query_builder.py 9.5 KiB

12 years ago
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. import webnotes
  24. session = webnotes.session
  25. sql = webnotes.conn.sql
  26. out = webnotes.response
  27. from webnotes.utils import cint
  28. import webnotes.defaults
  29. def get_sql_tables(q):
  30. if q.find('WHERE') != -1:
  31. tl = q.split('FROM')[1].split('WHERE')[0].split(',')
  32. elif q.find('GROUP BY') != -1:
  33. tl = q.split('FROM')[1].split('GROUP BY')[0].split(',')
  34. else:
  35. tl = q.split('FROM')[1].split('ORDER BY')[0].split(',')
  36. return [t.strip().strip('`')[3:] for t in tl]
  37. def get_parent_dt(dt):
  38. pdt = ''
  39. if sql('select name from `tabDocType` where istable=1 and name="%s"' % dt):
  40. import webnotes.model.meta
  41. return webnotes.model.meta.get_parent_dt(dt)
  42. return pdt
  43. def get_sql_meta(tl):
  44. std_columns = {
  45. 'owner':('Owner', '', '', '100'),
  46. 'creation':('Created on', 'Date', '', '100'),
  47. 'modified':('Last modified on', 'Date', '', '100'),
  48. 'modified_by':('Modified By', '', '', '100')
  49. }
  50. meta = {}
  51. for dt in tl:
  52. meta[dt] = std_columns.copy()
  53. # for table doctype, the ID is the parent id
  54. pdt = get_parent_dt(dt)
  55. if pdt:
  56. meta[dt]['parent'] = ('ID', 'Link', pdt, '200')
  57. # get the field properties from DocField
  58. res = sql("select fieldname, label, fieldtype, options, width from tabDocField where parent='%s'" % dt)
  59. for r in res:
  60. if r[0]:
  61. meta[dt][r[0]] = (r[1], r[2], r[3], r[4]);
  62. # name
  63. meta[dt]['name'] = ('ID', 'Link', dt, '200')
  64. return meta
  65. def add_match_conditions(q, tl):
  66. sl = []
  67. ur = webnotes.user.get_roles()
  68. for dt in tl:
  69. s = getmatchcondition(dt, ur)
  70. if s:
  71. sl.append(s)
  72. # insert the conditions
  73. if sl:
  74. condition_st = q.find('WHERE')!=-1 and ' AND ' or ' WHERE '
  75. condition_end = q.find('ORDER BY')!=-1 and 'ORDER BY' or 'LIMIT'
  76. condition_end = q.find('GROUP BY')!=-1 and 'GROUP BY' or condition_end
  77. if q.find('ORDER BY')!=-1 or q.find('LIMIT')!=-1 or q.find('GROUP BY')!=-1: # if query continues beyond conditions
  78. q = q.split(condition_end)
  79. q = q[0] + condition_st + '(' + ' OR '.join(sl) + ') ' + condition_end + q[1]
  80. else:
  81. q = q + condition_st + '(' + ' OR '.join(sl) + ')'
  82. return q
  83. def getmatchcondition(dt, ur):
  84. res = sql("SELECT `role`, `match` FROM tabDocPerm WHERE parent = '%s' AND (`read`=1) AND permlevel = 0" % dt)
  85. cond = []
  86. for r in res:
  87. if r[0] in ur: # role applicable to user
  88. if r[1]:
  89. for d in webnotes.defaults.get_user_default_as_list(default_key) or ["** No Match **"]:
  90. cond.append('`tab%s`.`%s`="%s"' % (dt, r[1], d))
  91. else:
  92. return ''
  93. return ' OR '.join(cond)
  94. def exec_report(code, res, colnames=[], colwidths=[], coltypes=[], coloptions=[], filter_values={}, query='', from_export=0):
  95. col_idx, i, out, style, header_html, footer_html, page_template = {}, 0, None, [], '', '', ''
  96. for c in colnames:
  97. col_idx[c] = i
  98. i+=1
  99. # load globals (api)
  100. from webnotes import *
  101. from webnotes.utils import *
  102. from webnotes.model.doc import *
  103. set = webnotes.conn.set
  104. sql = webnotes.conn.sql
  105. get_value = webnotes.conn.get_value
  106. convert_to_lists = webnotes.conn.convert_to_lists
  107. NEWLINE = '\n'
  108. exec str(code)
  109. if out!=None:
  110. res = out
  111. return res, style, header_html, footer_html, page_template
  112. def guess_type(m):
  113. """
  114. Returns fieldtype depending on the MySQLdb Description
  115. """
  116. import MySQLdb
  117. if m in MySQLdb.NUMBER:
  118. return 'Currency'
  119. elif m in MySQLdb.DATE:
  120. return 'Date'
  121. else:
  122. return 'Data'
  123. def build_description_simple():
  124. colnames, coltypes, coloptions, colwidths = [], [], [], []
  125. for m in webnotes.conn.get_description():
  126. colnames.append(m[0])
  127. coltypes.append(guess_type[m[0]])
  128. coloptions.append('')
  129. colwidths.append('100')
  130. return colnames, coltypes, coloptions, colwidths
  131. def build_description_standard(meta, tl):
  132. desc = webnotes.conn.get_description()
  133. colnames, coltypes, coloptions, colwidths = [], [], [], []
  134. # merged metadata - used if we are unable to
  135. # get both the table name and field name from
  136. # the description - in case of joins
  137. merged_meta = {}
  138. for d in meta:
  139. merged_meta.update(meta[d])
  140. for f in desc:
  141. fn, dt = f[0], ''
  142. if '.' in fn:
  143. dt, fn = fn.split('.')
  144. if (not dt) and merged_meta.get(fn):
  145. # no "AS" given, find type from merged description
  146. desc = merged_meta[fn]
  147. colnames.append(desc[0] or fn)
  148. coltypes.append(desc[1] or '')
  149. coloptions.append(desc[2] or '')
  150. colwidths.append(desc[3] or '100')
  151. elif meta.get(dt,{}).has_key(fn):
  152. # type specified for a multi-table join
  153. # usually from Report Builder
  154. desc = meta[dt][fn]
  155. colnames.append(desc[0] or fn)
  156. coltypes.append(desc[1] or '')
  157. coloptions.append(desc[2] or '')
  158. colwidths.append(desc[3] or '100')
  159. else:
  160. # nothing found
  161. # guess
  162. colnames.append(fn)
  163. coltypes.append(guess_type(f[1]))
  164. coloptions.append('')
  165. colwidths.append('100')
  166. return colnames, coltypes, coloptions, colwidths
  167. @webnotes.whitelist()
  168. def runquery(q='', ret=0, from_export=0):
  169. import webnotes.utils
  170. formatted = cint(webnotes.form_dict.get('formatted'))
  171. # CASE A: Simple Query
  172. # --------------------
  173. if webnotes.form_dict.get('simple_query') or webnotes.form_dict.get('is_simple'):
  174. if not q: q = webnotes.form_dict.get('simple_query') or webnotes.form_dict.get('query')
  175. if q.split()[0].lower() != 'select':
  176. raise Exception, 'Query must be a SELECT'
  177. as_dict = cint(webnotes.form_dict.get('as_dict'))
  178. res = sql(q, as_dict = as_dict, as_list = not as_dict, formatted=formatted)
  179. # build colnames etc from metadata
  180. colnames, coltypes, coloptions, colwidths = [], [], [], []
  181. # CASE B: Standard Query
  182. # -----------------------
  183. else:
  184. if not q: q = webnotes.form_dict.get('query')
  185. tl = get_sql_tables(q)
  186. meta = get_sql_meta(tl)
  187. q = add_match_conditions(q, tl)
  188. webnotes
  189. # replace special variables
  190. q = q.replace('__user', session['user'])
  191. q = q.replace('__today', webnotes.utils.nowdate())
  192. res = sql(q, as_list=1, formatted=formatted)
  193. colnames, coltypes, coloptions, colwidths = build_description_standard(meta, tl)
  194. # run server script
  195. # -----------------
  196. style, header_html, footer_html, page_template = '', '', '', ''
  197. if webnotes.form_dict.get('sc_id'):
  198. sc_id = webnotes.form_dict.get('sc_id')
  199. from webnotes.model.code import get_code
  200. sc_details = webnotes.conn.sql("select module, standard, server_script from `tabSearch Criteria` where name=%s", sc_id)[0]
  201. if sc_details[1]!='No':
  202. code = get_code(sc_details[0], 'Search Criteria', sc_id, 'py')
  203. else:
  204. code = sc_details[2]
  205. if code:
  206. filter_values = eval(webnotes.form_dict.get('filter_values','')) or {}
  207. res, style, header_html, footer_html, page_template = exec_report(code, res, colnames, colwidths, coltypes, coloptions, filter_values, q, from_export)
  208. out['colnames'] = colnames
  209. out['coltypes'] = coltypes
  210. out['coloptions'] = coloptions
  211. out['colwidths'] = colwidths
  212. out['header_html'] = header_html
  213. out['footer_html'] = footer_html
  214. out['page_template'] = page_template
  215. if style:
  216. out['style'] = style
  217. # just the data - return
  218. if ret==1:
  219. return res
  220. out['values'] = res
  221. # return num of entries
  222. qm = webnotes.form_dict.get('query_max') or ''
  223. if qm and qm.strip():
  224. if qm.split()[0].lower() != 'select':
  225. raise Exception, 'Query (Max) must be a SELECT'
  226. if not webnotes.form_dict.get('simple_query'):
  227. qm = add_match_conditions(qm, tl)
  228. out['n_values'] = webnotes.utils.cint(sql(qm)[0][0])
  229. @webnotes.whitelist()
  230. def runquery_csv():
  231. global out
  232. # run query
  233. res = runquery(from_export = 1)
  234. q = webnotes.form_dict.get('query')
  235. rep_name = webnotes.form_dict.get('report_name')
  236. if not webnotes.form_dict.get('simple_query'):
  237. # Report Name
  238. if not rep_name:
  239. rep_name = get_sql_tables(q)[0]
  240. if not rep_name: rep_name = 'DataExport'
  241. # Headings
  242. heads = []
  243. rows = [[rep_name], out['colnames']] + out['values']
  244. from cStringIO import StringIO
  245. import csv
  246. f = StringIO()
  247. writer = csv.writer(f)
  248. for r in rows:
  249. # encode only unicode type strings and not int, floats etc.
  250. writer.writerow(map(lambda v: isinstance(v, unicode) and v.encode('utf-8') or v, r))
  251. f.seek(0)
  252. out['result'] = unicode(f.read(), 'utf-8')
  253. out['type'] = 'csv'
  254. out['doctype'] = rep_name
  255. def add_limit_to_query(query, args):
  256. """
  257. Add limit condition to query
  258. can be used by methods called in listing to add limit condition
  259. """
  260. if args.get('limit_page_length'):
  261. query += """
  262. limit %(limit_start)s, %(limit_page_length)s"""
  263. import webnotes.utils
  264. args['limit_start'] = webnotes.utils.cint(args.get('limit_start'))
  265. args['limit_page_length'] = webnotes.utils.cint(args.get('limit_page_length'))
  266. return query, args