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.
 
 
 
 
 
 

729 lines
22 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. """
  23. Contains the Document class representing an object / record
  24. """
  25. import webnotes
  26. import webnotes.model.meta
  27. from webnotes.utils import *
  28. class Document:
  29. """
  30. The wn(meta-data)framework equivalent of a Database Record.
  31. Stores,Retrieves,Updates the record in the corresponding table.
  32. Runs the triggers required.
  33. The `Document` class represents the basic Object-Relational Mapper (ORM). The object type is defined by
  34. `DocType` and the object ID is represented by `name`::
  35. Please note the anamoly in the Web Notes Framework that `ID` is always called as `name`
  36. If both `doctype` and `name` are specified in the constructor, then the object is loaded from the database.
  37. If only `doctype` is given, then the object is not loaded
  38. If `fielddata` is specfied, then the object is created from the given dictionary.
  39. **Note 1:**
  40. The getter and setter of the object are overloaded to map to the fields of the object that
  41. are loaded when it is instantiated.
  42. For example: doc.name will be the `name` field and doc.owner will be the `owner` field
  43. **Note 2 - Standard Fields:**
  44. * `name`: ID / primary key
  45. * `owner`: creator of the record
  46. * `creation`: datetime of creation
  47. * `modified`: datetime of last modification
  48. * `modified_by` : last updating user
  49. * `docstatus` : Status 0 - Saved, 1 - Submitted, 2- Cancelled
  50. * `parent` : if child (table) record, this represents the parent record
  51. * `parenttype` : type of parent record (if any)
  52. * `parentfield` : table fieldname of parent record (if any)
  53. * `idx` : Index (sequence) of the child record
  54. """
  55. def __init__(self, doctype = '', name = '', fielddata = {}, prefix='tab'):
  56. self._roles = []
  57. self._perms = []
  58. self._user_defaults = {}
  59. self._prefix = prefix
  60. if fielddata:
  61. self.fields = fielddata
  62. else:
  63. self.fields = {}
  64. if not self.fields.has_key('name'):
  65. self.fields['name']='' # required on save
  66. if not self.fields.has_key('doctype'):
  67. self.fields['doctype']='' # required on save
  68. if not self.fields.has_key('owner'):
  69. self.fields['owner']='' # required on save
  70. if doctype:
  71. self.fields['doctype'] = doctype
  72. if name:
  73. self.fields['name'] = name
  74. self.__initialized = 1
  75. if (doctype and name):
  76. self._loadfromdb(doctype, name)
  77. else:
  78. if not fielddata:
  79. self.fields['__islocal'] = 1
  80. def __nonzero__(self):
  81. return True
  82. def __str__(self):
  83. return str(self.fields)
  84. # Load Document
  85. # ---------------------------------------------------------------------------
  86. def _loadfromdb(self, doctype = None, name = None):
  87. if name: self.name = name
  88. if doctype: self.doctype = doctype
  89. is_single = False
  90. try:
  91. is_single = webnotes.model.meta.is_single(self.doctype)
  92. except Exception, e:
  93. pass
  94. if is_single:
  95. self._loadsingle()
  96. else:
  97. dataset = webnotes.conn.sql('select * from `%s%s` where name="%s"' % (self._prefix, self.doctype, self.name.replace('"', '\"')))
  98. if not dataset:
  99. raise Exception, '[WNF] %s %s does not exist' % (self.doctype, self.name)
  100. self._load_values(dataset[0], webnotes.conn.get_description())
  101. # Load Fields from dataset
  102. # ---------------------------------------------------------------------------
  103. def _load_values(self, data, description):
  104. if '__islocal' in self.fields:
  105. del self.fields['__islocal']
  106. for i in range(len(description)):
  107. v = data[i]
  108. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  109. def _merge_values(self, data, description):
  110. for i in range(len(description)):
  111. v = data[i]
  112. if v: # only if value, over-write
  113. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  114. # Load Single Type
  115. # ---------------------------------------------------------------------------
  116. def _loadsingle(self):
  117. self.name = self.doctype
  118. self.fields.update(getsingle(self.doctype))
  119. # Setter
  120. # ---------------------------------------------------------------------------
  121. def __setattr__(self, name, value):
  122. # normal attribute
  123. if not self.__dict__.has_key('_Document__initialized'):
  124. self.__dict__[name] = value
  125. elif self.__dict__.has_key(name):
  126. self.__dict__[name] = value
  127. else:
  128. # field attribute
  129. f = self.__dict__['fields']
  130. f[name] = value
  131. # Getter
  132. # ---------------------------------------------------------------------------
  133. def __getattr__(self, name):
  134. if self.__dict__.has_key(name):
  135. return self.__dict__[name]
  136. elif self.fields.has_key(name):
  137. return self.fields[name]
  138. else:
  139. return ''
  140. # Get Amendement number
  141. # ---------------------------------------------------------------------------
  142. def _get_amended_name(self):
  143. am_id = 1
  144. am_prefix = self.amended_from
  145. if webnotes.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
  146. am_id = cint(self.amended_from.split('-')[-1]) + 1
  147. am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
  148. self.name = am_prefix + '-' + str(am_id)
  149. # Set Name
  150. # ---------------------------------------------------------------------------
  151. def _set_name(self, autoname, istable):
  152. self.localname = self.name
  153. # get my object
  154. import webnotes.model.code
  155. so = webnotes.model.code.get_server_obj(self, [])
  156. # amendments
  157. if self.amended_from:
  158. self._get_amended_name()
  159. # by method
  160. elif so and hasattr(so, 'autoname'):
  161. r = webnotes.model.code.run_server_obj(so, 'autoname')
  162. if r: return r
  163. # based on a field
  164. elif autoname and autoname.startswith('field:'):
  165. n = self.fields[autoname[6:]]
  166. if not n:
  167. raise Exception, 'Name is required'
  168. self.name = n.strip()
  169. # based on expression
  170. elif autoname and autoname.startswith('eval:'):
  171. doc = self # for setting
  172. self.name = eval(autoname[5:])
  173. # call the method!
  174. elif autoname and autoname!='Prompt':
  175. self.name = make_autoname(autoname, self.doctype)
  176. # given
  177. elif self.fields.get('__newname',''):
  178. self.name = self.fields['__newname']
  179. # default name for table
  180. elif istable:
  181. self.name = make_autoname('#########', self.doctype)
  182. # unable to determine a name, use a serial number!
  183. if not self.name:
  184. self.name = make_autoname('#########', self.doctype)
  185. # Validate Name
  186. # ---------------------------------------------------------------------------
  187. def _validate_name(self, case):
  188. if webnotes.conn.sql('select name from `tab%s` where name=%s' % (self.doctype,'%s'), self.name):
  189. raise NameError, 'Name %s already exists' % self.name
  190. # no name
  191. if not self.name: return 'No Name Specified for %s' % self.doctype
  192. # new..
  193. if self.name.startswith('New '+self.doctype):
  194. return 'There were some errors setting the name, please contact the administrator'
  195. if case=='Title Case': self.name = self.name.title()
  196. if case=='UPPER CASE': self.name = self.name.upper()
  197. self.name = self.name.strip() # no leading and trailing blanks
  198. forbidden = ['%', "'", '"', '#', '*', '?', '`']
  199. for f in forbidden:
  200. if f in self.name:
  201. webnotes.msgprint('%s not allowed in ID (name)' % f, raise_exception =1)
  202. # Insert
  203. # ---------------------------------------------------------------------------
  204. def insert(self, autoname, istable, case='', make_autoname=1):
  205. # set name
  206. if make_autoname:
  207. self._set_name(autoname, istable)
  208. # validate name
  209. self._validate_name(case)
  210. # insert!
  211. if not self.owner: self.owner = webnotes.session['user']
  212. self.modified_by = webnotes.session['user']
  213. self.creation = self.modified = now()
  214. webnotes.conn.sql("""insert into `tab%(doctype)s` (name, owner, creation, modified, modified_by)
  215. values ('%(name)s', '%(owner)s', '%(creation)s', '%(modified)s', '%(modified_by)s')""" % self.fields)
  216. # Update Values
  217. # ---------------------------------------------------------------------------
  218. def _update_single(self, link_list):
  219. update_str = ["(%s, 'modified', %s)",]
  220. values = [self.doctype, now()]
  221. webnotes.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
  222. for f in self.fields.keys():
  223. if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
  224. and (not f.startswith('__')): # fields not saved
  225. # validate links
  226. if link_list and link_list.get(f):
  227. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  228. if self.fields[f]==None:
  229. update_str.append("(%s,%s,NULL)")
  230. values.append(self.doctype)
  231. values.append(f)
  232. else:
  233. update_str.append("(%s,%s,%s)")
  234. values.append(self.doctype)
  235. values.append(f)
  236. values.append(self.fields[f])
  237. webnotes.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
  238. # Validate Links
  239. # ---------------------------------------------------------------------------
  240. def validate_links(self, link_list):
  241. err_list = []
  242. for f in self.fields.keys():
  243. # validate links
  244. old_val = self.fields[f]
  245. if link_list and link_list.get(f):
  246. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  247. if old_val and not self.fields[f]:
  248. s = link_list[f][1] + ': ' + old_val
  249. err_list.append(s)
  250. return err_list
  251. def make_link_list(self):
  252. res = webnotes.model.meta.get_link_fields(self.doctype)
  253. link_list = {}
  254. for i in res: link_list[i[0]] = (i[1], i[2]) # options, label
  255. return link_list
  256. def _validate_link(self, dt, dn):
  257. if not dt: return dn
  258. if not dn: return None
  259. if dt.lower().startswith('link:'):
  260. dt = dt[5:]
  261. if '\n' in dt:
  262. dt = dt.split('\n')[0]
  263. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  264. WHERE name = %s""" % (dt, '%s'), dn)
  265. return tmp and tmp[0][0] or ''# match case
  266. # Update query
  267. # ---------------------------------------------------------------------------
  268. def _update_values(self, issingle, link_list, ignore_fields=0):
  269. if issingle:
  270. self._update_single(link_list)
  271. else:
  272. update_str, values = [], []
  273. # set modified timestamp
  274. self.modified = now()
  275. self.modified_by = webnotes.session['user']
  276. for f in self.fields.keys():
  277. if (not (f in ('doctype', 'name', 'perm', 'localname', 'creation','_user_tags'))) \
  278. and (not f.startswith('__')): # fields not saved
  279. # validate links
  280. if link_list and link_list.get(f):
  281. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  282. if self.fields[f]==None or self.fields[f]=='':
  283. update_str.append("`%s`=NULL" % f)
  284. if ignore_fields:
  285. try: r = webnotes.conn.sql("update `tab%s` set `%s`=NULL where name=%s" % (self.doctype, f, '%s'), self.name)
  286. except: pass
  287. else:
  288. values.append(self.fields[f])
  289. update_str.append("`%s`=%s" % (f, '%s'))
  290. if ignore_fields:
  291. try: r = webnotes.conn.sql("update `tab%s` set `%s`=%s where name=%s" % (self.doctype, f, '%s', '%s'), (self.fields[f], self.name))
  292. except: pass
  293. if values:
  294. if not ignore_fields:
  295. # update all in one query
  296. r = webnotes.conn.sql("update `tab%s` set %s where name='%s'" % (self.doctype, ', '.join(update_str), self.name), values)
  297. # Save values
  298. # ---------------------------------------------------------------------------
  299. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname = 1):
  300. """
  301. Saves the current record in the database. If new = 1, creates a new instance of the record.
  302. Also clears temperory fields starting with `__`
  303. * if check_links is set, it validates all `Link` fields
  304. * if ignore_fields is sets, it does not throw an exception for any field that does not exist in the
  305. database table
  306. """
  307. res = webnotes.model.meta.get_dt_values(self.doctype, 'autoname, issingle, istable, name_case', as_dict=1)
  308. res = res and res[0] or {}
  309. # add missing parentinfo (if reqd)
  310. if self.parent and not (self.parenttype and self.parentfield):
  311. self.update_parentinfo()
  312. if self.parent and not self.idx:
  313. self.set_idx()
  314. # if required, make new
  315. if new or (not new and self.fields.get('__islocal')) and (not res.get('issingle')):
  316. r = self.insert(res.get('autoname'), res.get('istable'), res.get('name_case'), \
  317. make_autoname)
  318. if r:
  319. return r
  320. # save the values
  321. self._update_values(res.get('issingle'), check_links and self.make_link_list() or {}, ignore_fields)
  322. self._clear_temp_fields()
  323. def update_parentinfo(self):
  324. """update parent type and parent field, if not explicitly specified"""
  325. tmp = webnotes.conn.sql("""select parent, fieldname from tabDocField
  326. where fieldtype='Table' and options=%s""", self.doctype)
  327. if len(tmp)==0:
  328. raise Exception, 'Incomplete parent info in child table (%s, %s)' \
  329. % (self.doctype, self.fields.get('name', '[new]'))
  330. elif len(tmp)>1:
  331. raise Exception, 'Ambiguous parent info (%s, %s)' \
  332. % (self.doctype, self.fields.get('name', '[new]'))
  333. else:
  334. self.parenttype = tmp[0][0]
  335. self.parentfield = tmp[0][1]
  336. def set_idx(self):
  337. """set idx"""
  338. self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
  339. where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
  340. (self.parent, self.parentfield))[0][0] or 0) + 1
  341. # check permissions
  342. # ---------------------------------------------------------------------------
  343. def _get_perms(self):
  344. if not self._perms:
  345. self._perms = webnotes.conn.sql("""select role, `match` from tabDocPerm
  346. where parent=%s and ifnull(`read`,0) = 1
  347. and ifnull(permlevel,0)=0""", self.doctype)
  348. def _get_roles(self):
  349. # check if roles match/
  350. if not self._roles:
  351. if webnotes.user:
  352. self._roles = webnotes.user.get_roles()
  353. else:
  354. self._roles = ['Guest']
  355. def _get_user_defaults(self):
  356. if not self._user_defaults:
  357. if webnotes.user:
  358. self._user_defaults = webnotes.user.get_defaults()
  359. else:
  360. self.defaults = {}
  361. def check_perm(self, verbose=0):
  362. import webnotes
  363. # Admin has all permissions
  364. if webnotes.session['user']=='Administrator':
  365. return 1
  366. # find roles with read access for this record at 0
  367. self._get_perms()
  368. self._get_roles()
  369. self._get_user_defaults()
  370. has_perm, match = 0, []
  371. # loop through everything to find if there is a match
  372. for r in self._perms:
  373. if r[0] in self._roles:
  374. has_perm = 1
  375. if r[1] and match != -1:
  376. match.append(r[1]) # add to match check
  377. else:
  378. match = -1 # has permission and no match, so match not required!
  379. if has_perm and match and match != -1:
  380. for m in match:
  381. if self.fields.get(m, 'no value') in self._user_defaults.get(m, 'no default'):
  382. has_perm = 1
  383. break # permission found! break
  384. else:
  385. has_perm = 0
  386. if verbose:
  387. webnotes.msgprint("Value not allowed: '%s' for '%s'" % (self.fields.get(m, 'no value'), m))
  388. return has_perm
  389. # Cleanup
  390. # ---------------------------------------------------------------------------
  391. def _clear_temp_fields(self):
  392. # clear temp stuff
  393. keys = self.fields.keys()
  394. for f in keys:
  395. if f.startswith('__'):
  396. del self.fields[f]
  397. # Table methods
  398. # ---------------------------------------------------------------------------
  399. def clear_table(self, doclist, tablefield, save=0):
  400. """
  401. Clears the child records from the given `doclist` for a particular `tablefield`
  402. """
  403. from webnotes.model.utils import getlist
  404. table_list = getlist(doclist, tablefield)
  405. delete_list = [d.name for d in table_list]
  406. if delete_list:
  407. #filter doclist
  408. doclist = filter(lambda d: d.name not in delete_list, doclist)
  409. # delete from db
  410. webnotes.conn.sql("""\
  411. delete from `tab%s`
  412. where parent=%s and parenttype=%s"""
  413. % (table_list[0].doctype, '%s', '%s'),
  414. (self.name, self.doctype))
  415. self.fields['__unsaved'] = 1
  416. return doclist
  417. def addchild(self, fieldname, childtype = '', local=0, doclist=None):
  418. """
  419. Returns a child record of the give `childtype`.
  420. * if local is set, it does not save the record
  421. * if doclist is passed, it append the record to the doclist
  422. """
  423. d = Document()
  424. d.parent = self.name
  425. d.parenttype = self.doctype
  426. d.parentfield = fieldname
  427. d.doctype = childtype
  428. d.docstatus = 0;
  429. d.name = ''
  430. d.owner = webnotes.session['user']
  431. if local:
  432. d.fields['__islocal'] = '1' # for Client to identify unsaved doc
  433. else:
  434. d.save(new=1)
  435. if doclist != None:
  436. doclist.append(d)
  437. return d
  438. def addchild(parent, fieldname, childtype = '', local=0, doclist=None):
  439. """
  440. Create a child record to the parent doc.
  441. Example::
  442. c = Document('Contact','ABC')
  443. d = addchild(c, 'contact_updates', 'Contact Update', local = 1)
  444. d.last_updated = 'Phone call'
  445. d.save(1)
  446. """
  447. return parent.addchild(fieldname, childtype, local, doclist)
  448. # Naming
  449. # ------
  450. def make_autoname(key, doctype=''):
  451. """
  452. Creates an autoname from the given key:
  453. **Autoname rules:**
  454. * The key is separated by '.'
  455. * '####' represents a series. The string before this part becomes the prefix:
  456. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  457. * 'MM' represents the current month
  458. * 'YY' and 'YYYY' represent the current year
  459. *Example:*
  460. * DE/./.YY./.MM./.##### will create a series like
  461. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  462. """
  463. n = ''
  464. l = key.split('.')
  465. for e in l:
  466. en = ''
  467. if e.startswith('#'):
  468. digits = len(e)
  469. en = getseries(n, digits, doctype)
  470. elif e=='YY':
  471. import time
  472. en = time.strftime('%y')
  473. elif e=='MM':
  474. import time
  475. en = time.strftime('%m')
  476. elif e=='YYYY':
  477. import time
  478. en = time.strftime('%Y')
  479. else: en = e
  480. n+=en
  481. return n
  482. # Get Series for Autoname
  483. # -----------------------
  484. def getseries(key, digits, doctype=''):
  485. # series created ?
  486. if webnotes.conn.sql("select name from tabSeries where name='%s'" % key):
  487. # yes, update it
  488. webnotes.conn.sql("update tabSeries set current = current+1 where name='%s'" % key)
  489. # find the series counter
  490. r = webnotes.conn.sql("select current from tabSeries where name='%s'" % key)
  491. n = r[0][0]
  492. else:
  493. # no, create it
  494. webnotes.conn.sql("insert into tabSeries (name, current) values ('%s', 1)" % key)
  495. n = 1
  496. return ('%0'+str(digits)+'d') % n
  497. # Get Children
  498. # ------------
  499. def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'):
  500. import webnotes
  501. tmp = ''
  502. if field:
  503. tmp = ' and parentfield="%s" ' % field
  504. if parenttype:
  505. tmp = ' and parenttype="%s" ' % parenttype
  506. try:
  507. dataset = webnotes.conn.sql("select * from `%s%s` where parent='%s' %s order by idx" \
  508. % (prefix, childtype, name, tmp))
  509. desc = webnotes.conn.get_description()
  510. except Exception, e:
  511. if prefix=='arc' and e.args[0]==1146:
  512. return []
  513. else:
  514. raise e
  515. l = []
  516. for i in dataset:
  517. d = Document()
  518. d.doctype = childtype
  519. d._load_values(i, desc)
  520. l.append(d)
  521. return l
  522. # Check if "Guest" is allowed to view this page
  523. # ---------------------------------------------
  524. def check_page_perm(doc):
  525. if doc.name=='Login Page':
  526. return
  527. if doc.publish:
  528. return
  529. if not webnotes.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", doc.name):
  530. webnotes.response['403'] = 1
  531. raise webnotes.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)
  532. def get_report_builder_code(doc):
  533. if doc.doctype=='Search Criteria':
  534. from webnotes.model.code import get_code
  535. if doc.standard != 'No':
  536. doc.report_script = get_code(doc.module, 'Search Criteria', doc.name, 'js')
  537. doc.custom_query = get_code(doc.module, 'Search Criteria', doc.name, 'sql')
  538. # called from everywhere
  539. # load a record and its child records and bundle it in a list - doclist
  540. # ---------------------------------------------------------------------
  541. def get(dt, dn='', with_children = 1, from_get_obj = 0, prefix = 'tab'):
  542. """
  543. Returns a doclist containing the main record and all child records
  544. """
  545. import webnotes
  546. import webnotes.model
  547. dn = dn or dt
  548. # load the main doc
  549. doc = Document(dt, dn, prefix=prefix)
  550. # check permission - for doctypes, pages
  551. if (dt in ('DocType', 'Page', 'Control Panel', 'Search Criteria')) or (from_get_obj and webnotes.session.get('user') != 'Guest'):
  552. if dt=='Page' and webnotes.session['user'] == 'Guest':
  553. check_page_perm(doc)
  554. else:
  555. if not doc.check_perm():
  556. webnotes.response['403'] = 1
  557. raise webnotes.ValidationError, '[WNF] No read permission for %s %s' % (dt, dn)
  558. if not with_children:
  559. # done
  560. return [doc,]
  561. # get all children types
  562. tablefields = webnotes.model.meta.get_table_fields(dt)
  563. # load chilren
  564. doclist = [doc,]
  565. for t in tablefields:
  566. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  567. # import report_builder code
  568. if not from_get_obj:
  569. get_report_builder_code(doc)
  570. return doclist
  571. def getsingle(doctype):
  572. """get single doc as dict"""
  573. dataset = webnotes.conn.sql("select field, value from tabSingles where doctype=%s", doctype)
  574. return dict(dataset)