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.
 
 
 
 
 
 

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