Просмотр исходного кода

Merge branch 'develop' of github.com:frappe/frappe into develop

version-14
Rushabh Mehta 11 лет назад
Родитель
Сommit
4530147af4
100 измененных файлов: 630 добавлений и 630 удалений
  1. +13
    -13
      frappe/__init__.py
  2. +3
    -3
      frappe/api.py
  3. +2
    -2
      frappe/app.py
  4. +13
    -13
      frappe/auth.py
  5. +6
    -6
      frappe/boot.py
  6. +13
    -13
      frappe/cli.py
  7. +4
    -4
      frappe/client.py
  8. +6
    -6
      frappe/core/doctype/comment/comment.py
  9. +6
    -6
      frappe/core/doctype/comment/test_comment.py
  10. +4
    -4
      frappe/core/doctype/communication/communication.py
  11. +5
    -5
      frappe/core/doctype/custom_field/custom_field.py
  12. +5
    -5
      frappe/core/doctype/customize_form/customize_form.py
  13. +6
    -6
      frappe/core/doctype/defaultvalue/defaultvalue.py
  14. +16
    -16
      frappe/core/doctype/doctype/doctype.py
  15. +2
    -2
      frappe/core/doctype/event/event.py
  16. +3
    -3
      frappe/core/doctype/event/test_event.py
  17. +3
    -3
      frappe/core/doctype/file_data/file_data.py
  18. +3
    -3
      frappe/core/doctype/letter_head/letter_head.py
  19. +6
    -6
      frappe/core/doctype/notification_count/notification_count.py
  20. +2
    -2
      frappe/core/doctype/page/page.py
  21. +4
    -4
      frappe/core/doctype/print_format/print_format.py
  22. +31
    -31
      frappe/core/doctype/profile/profile.py
  23. +13
    -13
      frappe/core/doctype/profile/test_profile.py
  24. +6
    -6
      frappe/core/doctype/property_setter/property_setter.py
  25. +1
    -1
      frappe/core/doctype/report/report.py
  26. +1
    -1
      frappe/core/doctype/todo/todo.py
  27. +1
    -1
      frappe/core/doctype/userrole/userrole.py
  28. +1
    -1
      frappe/core/doctype/version/version.py
  29. +2
    -2
      frappe/core/doctype/workflow/workflow.py
  30. +2
    -2
      frappe/core/notifications.py
  31. +11
    -11
      frappe/core/page/data_import_tool/data_import_tool.py
  32. +9
    -9
      frappe/core/page/messages/messages.py
  33. +1
    -1
      frappe/core/page/modules_setup/modules_setup.py
  34. +8
    -8
      frappe/core/page/permission_manager/permission_manager.py
  35. +4
    -4
      frappe/core/page/user_properties/user_properties.py
  36. +9
    -9
      frappe/database.py
  37. +6
    -6
      frappe/defaults.py
  38. +6
    -6
      frappe/handler.py
  39. +10
    -10
      frappe/installer.py
  40. +13
    -13
      frappe/model/__init__.py
  41. +7
    -7
      frappe/model/bean.py
  42. +1
    -1
      frappe/model/controller.py
  43. +2
    -2
      frappe/model/create_new.py
  44. +44
    -44
      frappe/model/db_schema.py
  45. +5
    -5
      frappe/model/delete_doc.py
  46. +26
    -26
      frappe/model/doc.py
  47. +10
    -10
      frappe/model/docfield.py
  48. +13
    -13
      frappe/model/doctype.py
  49. +9
    -9
      frappe/model/meta.py
  50. +27
    -27
      frappe/model/rename_doc.py
  51. +1
    -1
      frappe/model/sync.py
  52. +2
    -2
      frappe/model/utils.py
  53. +4
    -4
      frappe/model/workflow.py
  54. +2
    -2
      frappe/modules/__init__.py
  55. +1
    -1
      frappe/modules/export_file.py
  56. +4
    -4
      frappe/modules/import_file.py
  57. +16
    -16
      frappe/modules/patch_handler.py
  58. +1
    -1
      frappe/modules/utils.py
  59. +2
    -2
      frappe/patches/4_0/add_delete_permission.py
  60. +1
    -1
      frappe/patches/4_0/move_match_to_restricted.py
  61. +1
    -1
      frappe/patches/4_0/remove_index_sitemap.py
  62. +1
    -1
      frappe/patches/4_0/rename_sitemap_to_route.py
  63. +1
    -1
      frappe/patches/4_0/set_todo_checked_as_closed.py
  64. +3
    -3
      frappe/patches/4_0/set_website_route_idx.py
  65. +1
    -1
      frappe/patches/4_0/webnotes_to_frappe.py
  66. +4
    -4
      frappe/patches/4_0/website_sitemap_hierarchy.py
  67. +1
    -1
      frappe/permissions.py
  68. +7
    -7
      frappe/profile.py
  69. +13
    -13
      frappe/sessions.py
  70. +3
    -3
      frappe/templates/generators/blog_post.py
  71. +3
    -3
      frappe/templates/generators/web_page.py
  72. +5
    -5
      frappe/templates/generators/website_group.py
  73. +2
    -2
      frappe/templates/includes/comments.py
  74. +2
    -2
      frappe/templates/pages/contact.py
  75. +1
    -1
      frappe/templates/pages/rss.py
  76. +1
    -1
      frappe/templates/pages/sitemap.py
  77. +2
    -2
      frappe/templates/pages/website_script.py
  78. +2
    -2
      frappe/templates/pages/writers.py
  79. +3
    -3
      frappe/templates/website_group/forum.py
  80. +5
    -5
      frappe/templates/website_group/post.py
  81. +4
    -4
      frappe/templates/website_group/settings.py
  82. +4
    -4
      frappe/test_runner.py
  83. +8
    -8
      frappe/tests/test_db.py
  84. +5
    -5
      frappe/tests/test_email.py
  85. +6
    -6
      frappe/tests/test_fmt_money.py
  86. +6
    -6
      frappe/translate.py
  87. +15
    -15
      frappe/utils/__init__.py
  88. +5
    -5
      frappe/utils/backups.py
  89. +3
    -3
      frappe/utils/datautils.py
  90. +2
    -2
      frappe/utils/email_lib/__init__.py
  91. +10
    -10
      frappe/utils/email_lib/bulk.py
  92. +2
    -2
      frappe/utils/email_lib/email_body.py
  93. +4
    -4
      frappe/utils/email_lib/receive.py
  94. +4
    -4
      frappe/utils/file_manager.py
  95. +3
    -3
      frappe/utils/install.py
  96. +30
    -30
      frappe/utils/nestedset.py
  97. +1
    -1
      frappe/utils/response.py
  98. +12
    -12
      frappe/utils/scheduler.py
  99. +3
    -3
      frappe/website/doctype/blog_post/blog_post.py
  100. +4
    -4
      frappe/website/doctype/blog_post/test_blog_post.py

+ 13
- 13
frappe/__init__.py Просмотреть файл

@@ -60,7 +60,7 @@ def set_user_lang(user, user_language=None):
from frappe.translate import get_lang_dict from frappe.translate import get_lang_dict
if not user_language: if not user_language:
user_language = conn.get_value("Profile", user, "language")
user_language = db.get_value("Profile", user, "language")
if user_language: if user_language:
lang_dict = get_lang_dict() lang_dict = get_lang_dict()
@@ -68,7 +68,7 @@ def set_user_lang(user, user_language=None):
local.lang = lang_dict[user_language] local.lang = lang_dict[user_language]


# local-globals # local-globals
conn = local("conn")
db = local("db")
conf = local("conf") conf = local("conf")
form = form_dict = local("form_dict") form = form_dict = local("form_dict")
request = local("request") request = local("request")
@@ -129,8 +129,8 @@ def get_site_config():


def destroy(): def destroy():
"""closes connection and releases werkzeug local""" """closes connection and releases werkzeug local"""
if conn:
conn.close()
if db:
db.close()
release_local(local) release_local(local)


@@ -182,7 +182,7 @@ def msgprint(msg, small=0, raise_exception=0, as_table=False):
def _raise_exception(): def _raise_exception():
if raise_exception: if raise_exception:
if flags.rollback_on_exception: if flags.rollback_on_exception:
conn.rollback()
db.rollback()
import inspect import inspect
if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception): if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
raise raise_exception, msg raise raise_exception, msg
@@ -210,10 +210,10 @@ def create_folder(path):
if not os.path.exists(path): os.makedirs(path) if not os.path.exists(path): os.makedirs(path)
def connect(site=None, db_name=None): def connect(site=None, db_name=None):
from db import Database
from database import Database
if site: if site:
init(site) init(site)
local.conn = Database(user=db_name or local.conf.db_name)
local.db = Database(user=db_name or local.conf.db_name)
local.response = _dict() local.response = _dict()
local.form_dict = _dict() local.form_dict = _dict()
local.session = _dict() local.session = _dict()
@@ -296,11 +296,11 @@ def has_permission(doctype, ptype="read", refdoc=None):
return frappe.permissions.has_permission(doctype, ptype, refdoc) return frappe.permissions.has_permission(doctype, ptype, refdoc)
def clear_perms(doctype): def clear_perms(doctype):
conn.sql("""delete from tabDocPerm where parent=%s""", doctype)
db.sql("""delete from tabDocPerm where parent=%s""", doctype)


def reset_perms(doctype): def reset_perms(doctype):
clear_perms(doctype) clear_perms(doctype)
reload_doc(conn.get_value("DocType", doctype, "module"),
reload_doc(db.get_value("DocType", doctype, "module"),
"DocType", doctype, force=True) "DocType", doctype, force=True)


def generate_hash(txt=None): def generate_hash(txt=None):
@@ -413,7 +413,7 @@ def get_all_apps(with_frappe=False, with_internal_apps=True):
def get_installed_apps(): def get_installed_apps():
if flags.in_install_db: if flags.in_install_db:
return [] return []
installed = json.loads(conn.get_global("installed_apps") or "[]")
installed = json.loads(db.get_global("installed_apps") or "[]")
return installed return installed


def get_hooks(hook=None, app_name=None): def get_hooks(hook=None, app_name=None):
@@ -507,14 +507,14 @@ def make_property_setter(args):


def get_application_home_page(user='Guest'): def get_application_home_page(user='Guest'):
"""get home page for user""" """get home page for user"""
hpl = conn.sql("""select home_page
hpl = db.sql("""select home_page
from `tabDefault Home Page` from `tabDefault Home Page`
where parent='Control Panel' where parent='Control Panel'
and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user))) and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
if hpl: if hpl:
return hpl[0][0] return hpl[0][0]
else: else:
return conn.get_value("Control Panel", None, "home_page")
return db.get_value("Control Panel", None, "home_page")


def import_doclist(path, ignore_links=False, ignore_insert=False, insert=False): def import_doclist(path, ignore_links=False, ignore_insert=False, insert=False):
from frappe.core.page.data_import_tool import data_import_tool from frappe.core.page.data_import_tool import data_import_tool
@@ -617,7 +617,7 @@ def get_template(path):
return get_jenv().get_template(path) return get_jenv().get_template(path)
def get_website_route(doctype, name): def get_website_route(doctype, name):
return conn.get_value("Website Route", {"ref_doctype": doctype, "docname": name})
return db.get_value("Website Route", {"ref_doctype": doctype, "docname": name})


def add_version(doclist): def add_version(doclist):
bean({ bean({


+ 3
- 3
frappe/api.py Просмотреть файл

@@ -54,7 +54,7 @@ def handle():
if not bean.has_permission("write"): if not bean.has_permission("write"):
frappe.throw("No Permission", frappe.PermissionError) frappe.throw("No Permission", frappe.PermissionError)
bean.run_method(frappe.local.form_dict.run_method, **frappe.local.form_dict) bean.run_method(frappe.local.form_dict.run_method, **frappe.local.form_dict)
frappe.conn.commit()
frappe.db.commit()


else: else:
if name: if name:
@@ -66,12 +66,12 @@ def handle():
if frappe.local.request.method=="POST": if frappe.local.request.method=="POST":
frappe.local.response.update({ frappe.local.response.update({
"doclist": frappe.client.insert(frappe.local.form_dict.doclist)}) "doclist": frappe.client.insert(frappe.local.form_dict.doclist)})
frappe.conn.commit()
frappe.db.commit()
if frappe.local.request.method=="PUT": if frappe.local.request.method=="PUT":
frappe.local.response.update({ frappe.local.response.update({
"doclist":frappe.client.save(frappe.local.form_dict.doclist)}) "doclist":frappe.client.save(frappe.local.form_dict.doclist)})
frappe.conn.commit()
frappe.db.commit()
if frappe.local.request.method=="DELETE": if frappe.local.request.method=="DELETE":
frappe.client.delete(doctype, name) frappe.client.delete(doctype, name)


+ 2
- 2
frappe/app.py Просмотреть файл

@@ -73,8 +73,8 @@ def application(request):
frappe.local._response = handle_session_stopped() frappe.local._response = handle_session_stopped()
finally: finally:
if frappe.conn:
frappe.conn.close()
if frappe.db:
frappe.db.close()
return frappe.local._response return frappe.local._response




+ 13
- 13
frappe/auth.py Просмотреть файл

@@ -3,7 +3,7 @@


from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
import frappe.db
import frappe.database
import frappe.utils import frappe.utils
import frappe.profile import frappe.profile
from frappe import conf from frappe import conf
@@ -35,8 +35,8 @@ class HTTPRequest:
frappe.local.login_manager = LoginManager() frappe.local.login_manager = LoginManager()


# check status # check status
if frappe.conn.get_global("__session_status")=='stop':
frappe.msgprint(frappe.conn.get_global("__session_status_message"))
if frappe.db.get_global("__session_status")=='stop':
frappe.msgprint(frappe.db.get_global("__session_status_message"))
raise frappe.SessionStopped('Session Stopped') raise frappe.SessionStopped('Session Stopped')


# load profile # load profile
@@ -81,7 +81,7 @@ class HTTPRequest:


def connect(self, ac_name = None): def connect(self, ac_name = None):
"""connect to db, from ac_name or db_name""" """connect to db, from ac_name or db_name"""
frappe.local.conn = frappe.db.Database(user = self.get_db_name(), \
frappe.local.db = frappe.db.Database(user = self.get_db_name(), \
password = getattr(conf,'db_password', '')) password = getattr(conf,'db_password', ''))


class LoginManager: class LoginManager:
@@ -106,7 +106,7 @@ class LoginManager:
self.set_user_info() self.set_user_info()
def set_user_info(self): def set_user_info(self):
info = frappe.conn.get_value("Profile", self.user,
info = frappe.db.get_value("Profile", self.user,
["user_type", "first_name", "last_name", "user_image"], as_dict=1) ["user_type", "first_name", "last_name", "user_image"], as_dict=1)
if info.user_type=="Website User": if info.user_type=="Website User":
frappe.local._response.set_cookie("system_user", "no") frappe.local._response.set_cookie("system_user", "no")
@@ -142,12 +142,12 @@ class LoginManager:
"""raise exception if user not enabled""" """raise exception if user not enabled"""
from frappe.utils import cint from frappe.utils import cint
if user=='Administrator': return if user=='Administrator': return
if not cint(frappe.conn.get_value('Profile', user, 'enabled')):
if not cint(frappe.db.get_value('Profile', user, 'enabled')):
self.fail('User disabled or missing') self.fail('User disabled or missing')


def check_password(self, user, pwd): def check_password(self, user, pwd):
"""check password""" """check password"""
user = frappe.conn.sql("""select `user` from __Auth where `user`=%s
user = frappe.db.sql("""select `user` from __Auth where `user`=%s
and `password`=password(%s)""", (user, pwd)) and `password`=password(%s)""", (user, pwd))
if not user: if not user:
self.fail('Incorrect password') self.fail('Incorrect password')
@@ -165,7 +165,7 @@ class LoginManager:
def validate_ip_address(self): def validate_ip_address(self):
"""check if IP Address is valid""" """check if IP Address is valid"""
ip_list = frappe.conn.get_value('Profile', self.user, 'restrict_ip', ignore=True)
ip_list = frappe.db.get_value('Profile', self.user, 'restrict_ip', ignore=True)
if not ip_list: if not ip_list:
return return
@@ -182,8 +182,8 @@ class LoginManager:


def validate_hour(self): def validate_hour(self):
"""check if user is logging in during restricted hours""" """check if user is logging in during restricted hours"""
login_before = int(frappe.conn.get_value('Profile', self.user, 'login_before', ignore=True) or 0)
login_after = int(frappe.conn.get_value('Profile', self.user, 'login_after', ignore=True) or 0)
login_before = int(frappe.db.get_value('Profile', self.user, 'login_before', ignore=True) or 0)
login_after = int(frappe.db.get_value('Profile', self.user, 'login_after', ignore=True) or 0)
if not (login_before or login_after): if not (login_before or login_after):
return return
@@ -206,7 +206,7 @@ class LoginManager:
if not user: user = frappe.session.user if not user: user = frappe.session.user
self.run_trigger('on_logout') self.run_trigger('on_logout')
if user in ['demo@erpnext.com', 'Administrator']: if user in ['demo@erpnext.com', 'Administrator']:
frappe.conn.sql('delete from tabSessions where sid=%s', frappe.session.get('sid'))
frappe.db.sql('delete from tabSessions where sid=%s', frappe.session.get('sid'))
frappe.cache().delete_value("session:" + frappe.session.get("sid")) frappe.cache().delete_value("session:" + frappe.session.get("sid"))
else: else:
from frappe.sessions import clear_sessions from frappe.sessions import clear_sessions
@@ -241,7 +241,7 @@ class CookieManager:
if not cint(frappe.form_dict.get('remember_me')): return if not cint(frappe.form_dict.get('remember_me')): return
remember_days = frappe.conn.get_value('Control Panel', None,
remember_days = frappe.db.get_value('Control Panel', None,
'remember_for_days') or 7 'remember_for_days') or 7
import datetime import datetime
@@ -252,7 +252,7 @@ class CookieManager:




def _update_password(user, password): def _update_password(user, password):
frappe.conn.sql("""insert into __Auth (user, `password`)
frappe.db.sql("""insert into __Auth (user, `password`)
values (%s, password(%s)) values (%s, password(%s))
on duplicate key update `password`=password(%s)""", (user, on duplicate key update `password`=password(%s)""", (user,
password, password)) password, password))


+ 6
- 6
frappe/boot.py Просмотреть файл

@@ -28,7 +28,7 @@ def get_bootinfo():
bootinfo['control_panel'] = frappe._dict(cp.copy()) bootinfo['control_panel'] = frappe._dict(cp.copy())
bootinfo['sysdefaults'] = frappe.defaults.get_defaults() bootinfo['sysdefaults'] = frappe.defaults.get_defaults()
bootinfo['server_date'] = frappe.utils.nowdate() bootinfo['server_date'] = frappe.utils.nowdate()
bootinfo["send_print_in_body_and_attachment"] = frappe.conn.get_value("Email Settings",
bootinfo["send_print_in_body_and_attachment"] = frappe.db.get_value("Email Settings",
None, "send_print_in_body_and_attachment") None, "send_print_in_body_and_attachment")


if frappe.session['user'] != 'Guest': if frappe.session['user'] != 'Guest':
@@ -43,10 +43,10 @@ def get_bootinfo():
except ImportError, e: except ImportError, e:
pass pass


bootinfo.hidden_modules = frappe.conn.get_global("hidden_modules")
bootinfo.doctype_icons = dict(frappe.conn.sql("""select name, icon from
bootinfo.hidden_modules = frappe.db.get_global("hidden_modules")
bootinfo.doctype_icons = dict(frappe.db.sql("""select name, icon from
tabDocType where ifnull(icon,'')!=''""")) tabDocType where ifnull(icon,'')!=''"""))
bootinfo.doctype_icons.update(dict(frappe.conn.sql("""select name, icon from
bootinfo.doctype_icons.update(dict(frappe.db.sql("""select name, icon from
tabPage where ifnull(icon,'')!=''"""))) tabPage where ifnull(icon,'')!=''""")))
add_home_page(bootinfo, doclist) add_home_page(bootinfo, doclist)
@@ -83,7 +83,7 @@ def load_conf_settings(bootinfo):
if key in conf: bootinfo[key] = conf.get(key) if key in conf: bootinfo[key] = conf.get(key)


def add_allowed_pages(bootinfo): def add_allowed_pages(bootinfo):
bootinfo.page_info = dict(frappe.conn.sql("""select distinct parent, modified from `tabPage Role`
bootinfo.page_info = dict(frappe.db.sql("""select distinct parent, modified from `tabPage Role`
where role in ('%s')""" % "', '".join(frappe.get_roles()))) where role in ('%s')""" % "', '".join(frappe.get_roles())))


def load_translations(bootinfo): def load_translations(bootinfo):
@@ -95,7 +95,7 @@ def load_translations(bootinfo):


def get_fullnames(): def get_fullnames():
"""map of user fullnames""" """map of user fullnames"""
ret = frappe.conn.sql("""select name,
ret = frappe.db.sql("""select name,
concat(ifnull(first_name, ''), concat(ifnull(first_name, ''),
if(ifnull(last_name, '')!='', ' ', ''), ifnull(last_name, '')), if(ifnull(last_name, '')!='', ' ', ''), ifnull(last_name, '')),
user_image, gender, email user_image, gender, email


+ 13
- 13
frappe/cli.py Просмотреть файл

@@ -275,7 +275,7 @@ def install_fixtures():
def add_system_manager(email, first_name=None, last_name=None): def add_system_manager(email, first_name=None, last_name=None):
frappe.connect() frappe.connect()
frappe.profile.add_system_manager(email, first_name, last_name) frappe.profile.add_system_manager(email, first_name, last_name)
frappe.conn.commit()
frappe.db.commit()
frappe.destroy() frappe.destroy()
# utilities # utilities
@@ -355,7 +355,7 @@ def update_all_sites(remote=None, branch=None, verbose=True):
def reload_doc(module, doctype, docname, force=False): def reload_doc(module, doctype, docname, force=False):
frappe.connect() frappe.connect()
frappe.reload_doc(module, doctype, docname, force=force) frappe.reload_doc(module, doctype, docname, force=force)
frappe.conn.commit()
frappe.db.commit()
frappe.destroy() frappe.destroy()


@cmd @cmd
@@ -409,10 +409,10 @@ def move(dest_dir=None):
def domain(host_url=None): def domain(host_url=None):
frappe.connect() frappe.connect()
if host_url: if host_url:
frappe.conn.set_value("Website Settings", None, "subdomain", host_url)
frappe.conn.commit()
frappe.db.set_value("Website Settings", None, "subdomain", host_url)
frappe.db.commit()
else: else:
print frappe.conn.get_value("Website Settings", None, "subdomain")
print frappe.db.get_value("Website Settings", None, "subdomain")
frappe.destroy() frappe.destroy()


@cmd @cmd
@@ -454,13 +454,13 @@ def sync_statics():
from frappe.website import statics from frappe.website import statics
frappe.connect() frappe.connect()
statics.sync_statics() statics.sync_statics()
frappe.conn.commit()
frappe.db.commit()
frappe.destroy() frappe.destroy()
@cmd @cmd
def reset_perms(): def reset_perms():
frappe.connect() frappe.connect()
for d in frappe.conn.sql_list("""select name from `tabDocType`
for d in frappe.db.sql_list("""select name from `tabDocType`
where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""): where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
frappe.clear_cache(doctype=d) frappe.clear_cache(doctype=d)
frappe.reset_perms(d) frappe.reset_perms(d)
@@ -470,7 +470,7 @@ def reset_perms():
def execute(method): def execute(method):
frappe.connect() frappe.connect()
ret = frappe.get_attr(method)() ret = frappe.get_attr(method)()
frappe.conn.commit()
frappe.db.commit()
frappe.destroy() frappe.destroy()
if ret: if ret:
print ret print ret
@@ -596,9 +596,9 @@ def checkout(branch):
def set_admin_password(admin_password): def set_admin_password(admin_password):
import frappe import frappe
frappe.connect() frappe.connect()
frappe.conn.sql("""update __Auth set `password`=password(%s)
frappe.db.sql("""update __Auth set `password`=password(%s)
where user='Administrator'""", (admin_password,)) where user='Administrator'""", (admin_password,))
frappe.conn.commit()
frappe.db.commit()
frappe.destroy() frappe.destroy()


@cmd @cmd
@@ -731,13 +731,13 @@ def get_site_status(verbose=False):
'active_website_users': get_active_website_users(), 'active_website_users': get_active_website_users(),
'website_users': get_website_users(), 'website_users': get_website_users(),
'system_managers': "\n".join(get_system_managers()), 'system_managers': "\n".join(get_system_managers()),
'default_company': frappe.conn.get_default("company"),
'default_company': frappe.db.get_default("company"),
'disk_usage': frappe.utils.get_disk_usage(), 'disk_usage': frappe.utils.get_disk_usage(),
'working_directory': frappe.local.site_path 'working_directory': frappe.local.site_path
} }
# country, timezone, industry # country, timezone, industry
control_panel_details = frappe.conn.get_value("Control Panel", "Control Panel",
control_panel_details = frappe.db.get_value("Control Panel", "Control Panel",
["country", "time_zone", "industry"], as_dict=True) ["country", "time_zone", "industry"], as_dict=True)
if control_panel_details: if control_panel_details:
ret.update(control_panel_details) ret.update(control_panel_details)
@@ -746,7 +746,7 @@ def get_site_status(verbose=False):
for doctype in ("Company", "Customer", "Item", "Quotation", "Sales Invoice", for doctype in ("Company", "Customer", "Item", "Quotation", "Sales Invoice",
"Journal Voucher", "Stock Ledger Entry"): "Journal Voucher", "Stock Ledger Entry"):
key = doctype.lower().replace(" ", "_") + "_exists" key = doctype.lower().replace(" ", "_") + "_exists"
ret[key] = 1 if frappe.conn.count(doctype) else 0
ret[key] = 1 if frappe.db.count(doctype) else 0
frappe.destroy() frappe.destroy()


+ 4
- 4
frappe/client.py Просмотреть файл

@@ -11,7 +11,7 @@ import json, os
@frappe.whitelist() @frappe.whitelist()
def get(doctype, name=None, filters=None): def get(doctype, name=None, filters=None):
if filters and not name: if filters and not name:
name = frappe.conn.get_value(doctype, json.loads(filters))
name = frappe.db.get_value(doctype, json.loads(filters))
if not name: if not name:
raise Exception, "No document found for given filters" raise Exception, "No document found for given filters"
return [d.fields for d in frappe.bean(doctype, name).doclist] return [d.fields for d in frappe.bean(doctype, name).doclist]
@@ -23,14 +23,14 @@ def get_value(doctype, fieldname, filters=None, as_dict=True, debug=False):
if fieldname and fieldname.startswith("["): if fieldname and fieldname.startswith("["):
fieldname = json.loads(fieldname) fieldname = json.loads(fieldname)
return frappe.conn.get_value(doctype, json.loads(filters), fieldname, as_dict=as_dict, debug=debug)
return frappe.db.get_value(doctype, json.loads(filters), fieldname, as_dict=as_dict, debug=debug)


@frappe.whitelist() @frappe.whitelist()
def set_value(doctype, name, fieldname, value): def set_value(doctype, name, fieldname, value):
if fieldname in frappe.model.default_fields: if fieldname in frappe.model.default_fields:
frappe.throw(_("Cannot edit standard fields")) frappe.throw(_("Cannot edit standard fields"))
doc = frappe.conn.get_value(doctype, name, ["parenttype", "parent"], as_dict=True)
doc = frappe.db.get_value(doctype, name, ["parenttype", "parent"], as_dict=True)
if doc and doc.parent: if doc and doc.parent:
bean = frappe.bean(doc.parenttype, doc.parent) bean = frappe.bean(doc.parenttype, doc.parent)
child = bean.doclist.getone({"doctype": doctype, "name": name}) child = bean.doclist.getone({"doctype": doctype, "name": name})
@@ -90,7 +90,7 @@ def delete(doctype, name):
@frappe.whitelist() @frappe.whitelist()
def set_default(key, value, parent=None): def set_default(key, value, parent=None):
"""set a user default value""" """set a user default value"""
frappe.conn.set_default(key, value, parent or frappe.session.user)
frappe.db.set_default(key, value, parent or frappe.session.user)
frappe.clear_cache(user=frappe.session.user) frappe.clear_cache(user=frappe.session.user)


@frappe.whitelist() @frappe.whitelist()


+ 6
- 6
frappe/core/doctype/comment/comment.py Просмотреть файл

@@ -9,7 +9,7 @@ class DocType:
self.doc, self.doclist = d, dl self.doc, self.doclist = d, dl
def validate(self): def validate(self):
if frappe.conn.sql("""select count(*) from tabComment where comment_doctype=%s
if frappe.db.sql("""select count(*) from tabComment where comment_doctype=%s
and comment_docname=%s""", (self.doc.doctype, self.doc.name))[0][0] >= 50: and comment_docname=%s""", (self.doc.doctype, self.doc.name))[0][0] >= 50:
frappe.msgprint("Max Comments reached!", raise_exception=True) frappe.msgprint("Max Comments reached!", raise_exception=True)
@@ -45,13 +45,13 @@ class DocType:
raise raise
def get_comments_from_parent(self): def get_comments_from_parent(self):
_comments = frappe.conn.get_value(self.doc.comment_doctype,
_comments = frappe.db.get_value(self.doc.comment_doctype,
self.doc.comment_docname, "_comments") or "[]" self.doc.comment_docname, "_comments") or "[]"
return json.loads(_comments) return json.loads(_comments)
def update_comments_in_parent(self, _comments): def update_comments_in_parent(self, _comments):
# use sql, so that we do not mess with the timestamp # use sql, so that we do not mess with the timestamp
frappe.conn.sql("""update `tab%s` set `_comments`=%s where name=%s""" % (self.doc.comment_doctype,
frappe.db.sql("""update `tab%s` set `_comments`=%s where name=%s""" % (self.doc.comment_doctype,
"%s", "%s"), (json.dumps(_comments), self.doc.comment_docname)) "%s", "%s"), (json.dumps(_comments), self.doc.comment_docname))
def on_trash(self): def on_trash(self):
@@ -63,8 +63,8 @@ class DocType:
self.update_comments_in_parent(_comments) self.update_comments_in_parent(_comments)
def on_doctype_update(): def on_doctype_update():
if not frappe.conn.sql("""show index from `tabComment`
if not frappe.db.sql("""show index from `tabComment`
where Key_name="comment_doctype_docname_index" """): where Key_name="comment_doctype_docname_index" """):
frappe.conn.commit()
frappe.conn.sql("""alter table `tabComment`
frappe.db.commit()
frappe.db.sql("""alter table `tabComment`
add index comment_doctype_docname_index(comment_doctype, comment_docname)""") add index comment_doctype_docname_index(comment_doctype, comment_docname)""")

+ 6
- 6
frappe/core/doctype/comment/test_comment.py Просмотреть файл

@@ -21,12 +21,12 @@ import frappe, unittest, json
# self.cleanup() # self.cleanup()
# #
# def cleanup(self): # def cleanup(self):
# frappe.conn.sql("""delete from tabEvent where subject='__Comment Test Event'""")
# frappe.conn.sql("""delete from tabComment where comment='__Test Comment'""")
# frappe.conn.commit()
# if "_comments" in frappe.conn.get_table_columns("Event"):
# frappe.conn.commit()
# frappe.conn.sql("""alter table `tabEvent` drop column `_comments`""")
# frappe.db.sql("""delete from tabEvent where subject='__Comment Test Event'""")
# frappe.db.sql("""delete from tabComment where comment='__Test Comment'""")
# frappe.db.commit()
# if "_comments" in frappe.db.get_table_columns("Event"):
# frappe.db.commit()
# frappe.db.sql("""alter table `tabEvent` drop column `_comments`""")
# #
# def test_add_comment(self): # def test_add_comment(self):
# self.comment = frappe.bean({ # self.comment = frappe.bean({


+ 4
- 4
frappe/core/doctype/communication/communication.py Просмотреть файл

@@ -65,7 +65,7 @@ def _make(doctype=None, name=None, content=None, subject=None, sent_or_received
d.subject = subject d.subject = subject
d.content = content d.content = content
d.sent_or_received = sent_or_received d.sent_or_received = sent_or_received
d.sender = sender or frappe.conn.get_value("Profile", frappe.session.user, "email")
d.sender = sender or frappe.db.get_value("Profile", frappe.session.user, "email")
d.recipients = recipients d.recipients = recipients
# add as child # add as child
@@ -94,7 +94,7 @@ def get_customer_supplier(args=None):
if not args: args = frappe.local.form_dict if not args: args = frappe.local.form_dict
if not args.get('contact'): if not args.get('contact'):
raise Exception, "Please specify a contact to fetch Customer/Supplier" raise Exception, "Please specify a contact to fetch Customer/Supplier"
result = frappe.conn.sql("""\
result = frappe.db.sql("""\
select customer, supplier select customer, supplier
from `tabContact` from `tabContact`
where name = %s""", args.get('contact'), as_dict=1) where name = %s""", args.get('contact'), as_dict=1)
@@ -118,7 +118,7 @@ def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', s
footer = set_portal_link(sent_via, d) footer = set_portal_link(sent_via, d)
send_print_in_body = frappe.conn.get_value("Email Settings", None, "send_print_in_body_and_attachment")
send_print_in_body = frappe.db.get_value("Email Settings", None, "send_print_in_body_and_attachment")
if not send_print_in_body: if not send_print_in_body:
d.content += "<p>Please see attachment for document details.</p>" d.content += "<p>Please see attachment for document details.</p>"
@@ -126,7 +126,7 @@ def send_comm_email(d, name, sent_via=None, print_html=None, attachments='[]', s
msg=d.content, footer=footer, print_html=print_html if send_print_in_body else None) msg=d.content, footer=footer, print_html=print_html if send_print_in_body else None)
if send_me_a_copy: if send_me_a_copy:
mail.cc.append(frappe.conn.get_value("Profile", frappe.session.user, "email"))
mail.cc.append(frappe.db.get_value("Profile", frappe.session.user, "email"))
if print_html: if print_html:
print_html = scrub_urls(print_html) print_html = scrub_urls(print_html)


+ 5
- 5
frappe/core/doctype/custom_field/custom_field.py Просмотреть файл

@@ -48,7 +48,7 @@ class DocType:


def on_trash(self): def on_trash(self):
# delete property setter entries # delete property setter entries
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabProperty Setter` DELETE FROM `tabProperty Setter`
WHERE doc_type = %s WHERE doc_type = %s
AND field_name = %s""", AND field_name = %s""",
@@ -63,7 +63,7 @@ class DocType:
if label_index==-1: return if label_index==-1: return


prev_field = field_list[label_index] prev_field = field_list[label_index]
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabProperty Setter` DELETE FROM `tabProperty Setter`
WHERE doc_type = %s WHERE doc_type = %s
AND field_name = %s AND field_name = %s
@@ -110,10 +110,10 @@ def get_fields_label(dt=None, form=1):


def create_custom_field_if_values_exist(doctype, df): def create_custom_field_if_values_exist(doctype, df):
df = frappe._dict(df) df = frappe._dict(df)
if df.fieldname in frappe.conn.get_table_columns(doctype) and \
frappe.conn.sql("""select count(*) from `tab{doctype}`
if df.fieldname in frappe.db.get_table_columns(doctype) and \
frappe.db.sql("""select count(*) from `tab{doctype}`
where ifnull({fieldname},'')!=''""".format(doctype=doctype, fieldname=df.fieldname))[0][0] and \ where ifnull({fieldname},'')!=''""".format(doctype=doctype, fieldname=df.fieldname))[0][0] and \
not frappe.conn.get_value("Custom Field", {"dt": doctype, "fieldname": df.fieldname}):
not frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": df.fieldname}):
frappe.bean({ frappe.bean({
"doctype":"Custom Field", "doctype":"Custom Field",
"dt": doctype, "dt": doctype,


+ 5
- 5
frappe/core/doctype/customize_form/customize_form.py Просмотреть файл

@@ -174,7 +174,7 @@ class DocType:
if self.has_property_changed(ref_d, new_d, prop): if self.has_property_changed(ref_d, new_d, prop):
# using set_value not bean because validations are called # using set_value not bean because validations are called
# in the end anyways # in the end anyways
frappe.conn.set_value("Custom Field", ref_d.name, prop, new_d.get(prop))
frappe.db.set_value("Custom Field", ref_d.name, prop, new_d.get(prop))
else: else:
d = self.prepare_to_set(prop, new_d, ref_d, dt_dl) d = self.prepare_to_set(prop, new_d, ref_d, dt_dl)
if d: diff_list.append(d) if d: diff_list.append(d)
@@ -193,7 +193,7 @@ class DocType:
""" """
Get fieldtype and default value for properties of a field Get fieldtype and default value for properties of a field
""" """
df_defaults = frappe.conn.sql("""
df_defaults = frappe.db.sql("""
SELECT fieldname, fieldtype, `default`, label SELECT fieldname, fieldtype, `default`, label
FROM `tabDocField` FROM `tabDocField`
WHERE parent='DocField' or parent='DocType'""", as_dict=1) WHERE parent='DocField' or parent='DocType'""", as_dict=1)
@@ -312,12 +312,12 @@ class DocType:
for d in ps_doclist: for d in ps_doclist:
# Delete existing property setter entry # Delete existing property setter entry
if not d.fields.get("field_name"): if not d.fields.get("field_name"):
frappe.conn.sql("""
frappe.db.sql("""
DELETE FROM `tabProperty Setter` DELETE FROM `tabProperty Setter`
WHERE doc_type = %(doc_type)s WHERE doc_type = %(doc_type)s
AND property = %(property)s""", d.fields) AND property = %(property)s""", d.fields)
else: else:
frappe.conn.sql("""
frappe.db.sql("""
DELETE FROM `tabProperty Setter` DELETE FROM `tabProperty Setter`
WHERE doc_type = %(doc_type)s WHERE doc_type = %(doc_type)s
AND field_name = %(field_name)s AND field_name = %(field_name)s
@@ -334,7 +334,7 @@ class DocType:
and resets it to standard and resets it to standard
""" """
if self.doc.doc_type: if self.doc.doc_type:
frappe.conn.sql("""
frappe.db.sql("""
DELETE FROM `tabProperty Setter` DELETE FROM `tabProperty Setter`
WHERE doc_type = %s""", self.doc.doc_type) WHERE doc_type = %s""", self.doc.doc_type)


+ 6
- 6
frappe/core/doctype/defaultvalue/defaultvalue.py Просмотреть файл

@@ -9,14 +9,14 @@ class DocType:
self.doc, self.doclist = d, dl self.doc, self.doclist = d, dl
def on_doctype_update(): def on_doctype_update():
if not frappe.conn.sql("""show index from `tabDefaultValue`
if not frappe.db.sql("""show index from `tabDefaultValue`
where Key_name="defaultvalue_parent_defkey_index" """): where Key_name="defaultvalue_parent_defkey_index" """):
frappe.conn.commit()
frappe.conn.sql("""alter table `tabDefaultValue`
frappe.db.commit()
frappe.db.sql("""alter table `tabDefaultValue`
add index defaultvalue_parent_defkey_index(parent, defkey)""") add index defaultvalue_parent_defkey_index(parent, defkey)""")


if not frappe.conn.sql("""show index from `tabDefaultValue`
if not frappe.db.sql("""show index from `tabDefaultValue`
where Key_name="defaultvalue_parent_parenttype_index" """): where Key_name="defaultvalue_parent_parenttype_index" """):
frappe.conn.commit()
frappe.conn.sql("""alter table `tabDefaultValue`
frappe.db.commit()
frappe.db.sql("""alter table `tabDefaultValue`
add index defaultvalue_parent_parenttype_index(parent, parenttype)""") add index defaultvalue_parent_parenttype_index(parent, parenttype)""")

+ 16
- 16
frappe/core/doctype/doctype/doctype.py Просмотреть файл

@@ -32,10 +32,10 @@ class DocType:
def change_modified_of_parent(self): def change_modified_of_parent(self):
if frappe.flags.in_import: if frappe.flags.in_import:
return return
parent_list = frappe.conn.sql("""SELECT parent
parent_list = frappe.db.sql("""SELECT parent
from tabDocField where fieldtype="Table" and options="%s" """ % self.doc.name) from tabDocField where fieldtype="Table" and options="%s" """ % self.doc.name)
for p in parent_list: for p in parent_list:
frappe.conn.sql('''UPDATE tabDocType SET modified="%s"
frappe.db.sql('''UPDATE tabDocType SET modified="%s"
WHERE `name`="%s"''' % (now(), p[0])) WHERE `name`="%s"''' % (now(), p[0]))


def scrub_field_names(self): def scrub_field_names(self):
@@ -67,7 +67,7 @@ class DocType:
if autoname and (not autoname.startswith('field:')) and (not autoname.startswith('eval:')) \ if autoname and (not autoname.startswith('field:')) and (not autoname.startswith('eval:')) \
and (not autoname=='Prompt') and (not autoname.startswith('naming_series:')): and (not autoname=='Prompt') and (not autoname.startswith('naming_series:')):
prefix = autoname.split('.')[0] prefix = autoname.split('.')[0]
used_in = frappe.conn.sql('select name from tabDocType where substring_index(autoname, ".", 1) = %s and name!=%s', (prefix, name))
used_in = frappe.db.sql('select name from tabDocType where substring_index(autoname, ".", 1) = %s and name!=%s', (prefix, name))
if used_in: if used_in:
msgprint('<b>Series already in use:</b> The series "%s" is already used in "%s"' % (prefix, used_in[0][0]), raise_exception=1) msgprint('<b>Series already in use:</b> The series "%s" is already used in "%s"' % (prefix, used_in[0][0]), raise_exception=1)


@@ -93,16 +93,16 @@ class DocType:


def check_link_replacement_error(self): def check_link_replacement_error(self):
for d in self.doclist.get({"doctype":"DocField", "fieldtype":"Select"}): for d in self.doclist.get({"doctype":"DocField", "fieldtype":"Select"}):
if (frappe.conn.get_value("DocField", d.name, "options") or "").startswith("link:") \
if (frappe.db.get_value("DocField", d.name, "options") or "").startswith("link:") \
and not d.options.startswith("link:"): and not d.options.startswith("link:"):
frappe.msgprint("link: type Select fields are getting replaced. Please check for %s" % d.label, frappe.msgprint("link: type Select fields are getting replaced. Please check for %s" % d.label,
raise_exception=True) raise_exception=True)


def on_trash(self): def on_trash(self):
frappe.conn.sql("delete from `tabCustom Field` where dt = %s", self.doc.name)
frappe.conn.sql("delete from `tabCustom Script` where dt = %s", self.doc.name)
frappe.conn.sql("delete from `tabProperty Setter` where doc_type = %s", self.doc.name)
frappe.conn.sql("delete from `tabReport` where ref_doctype=%s", self.doc.name)
frappe.db.sql("delete from `tabCustom Field` where dt = %s", self.doc.name)
frappe.db.sql("delete from `tabCustom Script` where dt = %s", self.doc.name)
frappe.db.sql("delete from `tabProperty Setter` where doc_type = %s", self.doc.name)
frappe.db.sql("delete from `tabReport` where ref_doctype=%s", self.doc.name)
def before_rename(self, old, new, merge=False): def before_rename(self, old, new, merge=False):
if merge: if merge:
@@ -110,9 +110,9 @@ class DocType:
def after_rename(self, old, new, merge=False): def after_rename(self, old, new, merge=False):
if self.doc.issingle: if self.doc.issingle:
frappe.conn.sql("""update tabSingles set doctype=%s where doctype=%s""", (new, old))
frappe.db.sql("""update tabSingles set doctype=%s where doctype=%s""", (new, old))
else: else:
frappe.conn.sql("rename table `tab%s` to `tab%s`" % (old, new))
frappe.db.sql("rename table `tab%s` to `tab%s`" % (old, new))
def export_doc(self): def export_doc(self):
from frappe.modules.export_file import export_to_files from frappe.modules.export_file import export_to_files
@@ -139,7 +139,7 @@ class DocType:
if is_submittable is set, add amended_from docfields if is_submittable is set, add amended_from docfields
""" """
if self.doc.is_submittable: if self.doc.is_submittable:
if not frappe.conn.sql("""select name from tabDocField
if not frappe.db.sql("""select name from tabDocField
where fieldname = 'amended_from' and parent = %s""", self.doc.name): where fieldname = 'amended_from' and parent = %s""", self.doc.name):
new = self.doc.addchild('fields', 'DocField', self.doclist) new = self.doc.addchild('fields', 'DocField', self.doclist)
new.label = 'Amended From' new.label = 'Amended From'
@@ -153,7 +153,7 @@ class DocType:
new.idx = self.get_max_idx() + 1 new.idx = self.get_max_idx() + 1
def get_max_idx(self): def get_max_idx(self):
max_idx = frappe.conn.sql("""select max(idx) from `tabDocField` where parent = %s""",
max_idx = frappe.db.sql("""select max(idx) from `tabDocField` where parent = %s""",
self.doc.name) self.doc.name)
return max_idx and max_idx[0][0] or 0 return max_idx and max_idx[0][0] or 0


@@ -187,7 +187,7 @@ def validate_fields(fields):
raise_exception=1) raise_exception=1)
if d.options=="[Select]": if d.options=="[Select]":
return return
if d.options != d.parent and not frappe.conn.exists("DocType", d.options):
if d.options != d.parent and not frappe.db.exists("DocType", d.options):
frappe.msgprint("""#%(idx)s %(label)s: Options %(options)s must be a valid "DocType" for Link and Table type fields""" % d.fields, frappe.msgprint("""#%(idx)s %(label)s: Options %(options)s must be a valid "DocType" for Link and Table type fields""" % d.fields,
raise_exception=1) raise_exception=1)


@@ -231,7 +231,7 @@ def validate_permissions(permissions, for_remove=False):
doctype = permissions and permissions[0].parent doctype = permissions and permissions[0].parent
issingle = issubmittable = isimportable = False issingle = issubmittable = isimportable = False
if doctype and not doctype.startswith("New DocType"): if doctype and not doctype.startswith("New DocType"):
values = frappe.conn.get_value("DocType", doctype,
values = frappe.db.get_value("DocType", doctype,
["issingle", "is_submittable", "allow_import"], as_dict=True) ["issingle", "is_submittable", "allow_import"], as_dict=True)
issingle = cint(values.issingle) issingle = cint(values.issingle)
issubmittable = cint(values.is_submittable) issubmittable = cint(values.is_submittable)
@@ -329,7 +329,7 @@ def validate_permissions(permissions, for_remove=False):


def make_module_and_roles(doclist, perm_doctype="DocPerm"): def make_module_and_roles(doclist, perm_doctype="DocPerm"):
try: try:
if not frappe.conn.exists("Module Def", doclist[0].module):
if not frappe.db.exists("Module Def", doclist[0].module):
m = frappe.bean({"doctype": "Module Def", "module_name": doclist[0].module}) m = frappe.bean({"doctype": "Module Def", "module_name": doclist[0].module})
m.insert() m.insert()
@@ -337,7 +337,7 @@ def make_module_and_roles(doclist, perm_doctype="DocPerm"):
roles = [p.role for p in doclist.get({"doctype": perm_doctype})] + default_roles roles = [p.role for p in doclist.get({"doctype": perm_doctype})] + default_roles
for role in list(set(roles)): for role in list(set(roles)):
if not frappe.conn.exists("Role", role):
if not frappe.db.exists("Role", role):
r = frappe.bean({"doctype": "Role", "role_name": role}) r = frappe.bean({"doctype": "Role", "role_name": role})
r.doc.role_name = role r.doc.role_name = role
r.insert() r.insert()


+ 2
- 2
frappe/core/doctype/event/event.py Просмотреть файл

@@ -49,7 +49,7 @@ def has_permission(doc):


def send_event_digest(): def send_event_digest():
today = nowdate() today = nowdate()
for user in frappe.conn.sql("""select name, email, language
for user in frappe.db.sql("""select name, email, language
from tabProfile where ifnull(enabled,0)=1 from tabProfile where ifnull(enabled,0)=1
and user_type='System User' and name not in ('Guest', 'Administrator')""", as_dict=1): and user_type='System User' and name not in ('Guest', 'Administrator')""", as_dict=1):
events = get_events(today, today, user.name, for_reminder=True) events = get_events(today, today, user.name, for_reminder=True)
@@ -75,7 +75,7 @@ def get_events(start, end, user=None, for_reminder=False):
if not user: if not user:
user = frappe.session.user user = frappe.session.user
roles = frappe.get_roles(user) roles = frappe.get_roles(user)
events = frappe.conn.sql("""select name, subject, description,
events = frappe.db.sql("""select name, subject, description,
starts_on, ends_on, owner, all_day, event_type, repeat_this_event, repeat_on, starts_on, ends_on, owner, all_day, event_type, repeat_this_event, repeat_on,
monday, tuesday, wednesday, thursday, friday, saturday, sunday monday, tuesday, wednesday, thursday, friday, saturday, sunday
from tabEvent where (( from tabEvent where ((


+ 3
- 3
frappe/core/doctype/event/test_event.py Просмотреть файл

@@ -43,17 +43,17 @@ class TestEvent(unittest.TestCase):


def test_allowed_public(self): def test_allowed_public(self):
frappe.set_user("test1@example.com") frappe.set_user("test1@example.com")
doc = frappe.doc("Event", frappe.conn.get_value("Event", {"subject":"_Test Event 1"}))
doc = frappe.doc("Event", frappe.db.get_value("Event", {"subject":"_Test Event 1"}))
self.assertTrue(frappe.has_permission("Event", refdoc=doc)) self.assertTrue(frappe.has_permission("Event", refdoc=doc))
def test_not_allowed_private(self): def test_not_allowed_private(self):
frappe.set_user("test1@example.com") frappe.set_user("test1@example.com")
doc = frappe.doc("Event", frappe.conn.get_value("Event", {"subject":"_Test Event 2"}))
doc = frappe.doc("Event", frappe.db.get_value("Event", {"subject":"_Test Event 2"}))
self.assertFalse(frappe.has_permission("Event", refdoc=doc)) self.assertFalse(frappe.has_permission("Event", refdoc=doc))


def test_allowed_private_if_in_event_user(self): def test_allowed_private_if_in_event_user(self):
frappe.set_user("test1@example.com") frappe.set_user("test1@example.com")
doc = frappe.doc("Event", frappe.conn.get_value("Event", {"subject":"_Test Event 3"}))
doc = frappe.doc("Event", frappe.db.get_value("Event", {"subject":"_Test Event 3"}))
self.assertTrue(frappe.has_permission("Event", refdoc=doc)) self.assertTrue(frappe.has_permission("Event", refdoc=doc))
def test_event_list(self): def test_event_list(self):


+ 3
- 3
frappe/core/doctype/file_data/file_data.py Просмотреть файл

@@ -20,7 +20,7 @@ class DocType():
def on_update(self): def on_update(self):
# check duplicate assignement # check duplicate assignement
n_records = frappe.conn.sql("""select name from `tabFile Data`
n_records = frappe.db.sql("""select name from `tabFile Data`
where file_name=%s where file_name=%s
and name!=%s and name!=%s
and attached_to_doctype=%s and attached_to_doctype=%s
@@ -29,7 +29,7 @@ class DocType():
if len(n_records) > 0: if len(n_records) > 0:
self.doc.duplicate_entry = n_records[0][0] self.doc.duplicate_entry = n_records[0][0]
frappe.msgprint(frappe._("Same file has already been attached to the record")) frappe.msgprint(frappe._("Same file has already been attached to the record"))
frappe.conn.rollback()
frappe.db.rollback()
raise frappe.DuplicateEntryError raise frappe.DuplicateEntryError


def on_trash(self): def on_trash(self):
@@ -44,7 +44,7 @@ class DocType():
pass pass


# if file not attached to any other record, delete it # if file not attached to any other record, delete it
if self.doc.file_name and not frappe.conn.count("File Data",
if self.doc.file_name and not frappe.db.count("File Data",
{"file_name": self.doc.file_name, "name": ["!=", self.doc.name]}): {"file_name": self.doc.file_name, "name": ["!=", self.doc.name]}):
if self.doc.file_name.startswith("files/"): if self.doc.file_name.startswith("files/"):
path = frappe.utils.get_site_path("public", self.doc.file_name) path = frappe.utils.get_site_path("public", self.doc.file_name)


+ 3
- 3
frappe/core/doctype/letter_head/letter_head.py Просмотреть файл

@@ -19,12 +19,12 @@ class DocType:
def set_as_default(self): def set_as_default(self):
from frappe.utils import set_default from frappe.utils import set_default
if not self.doc.is_default: if not self.doc.is_default:
if not frappe.conn.sql("""select count(*) from `tabLetter Head` where ifnull(is_default,0)=1"""):
if not frappe.db.sql("""select count(*) from `tabLetter Head` where ifnull(is_default,0)=1"""):
self.doc.is_default = 1 self.doc.is_default = 1
if self.doc.is_default: if self.doc.is_default:
frappe.conn.sql("update `tabLetter Head` set is_default=0 where name != %s",
frappe.db.sql("update `tabLetter Head` set is_default=0 where name != %s",
self.doc.name) self.doc.name)
set_default('letter_head', self.doc.name) set_default('letter_head', self.doc.name)


# update control panel - so it loads new letter directly # update control panel - so it loads new letter directly
frappe.conn.set_value('Control Panel', None, 'letter_head', self.doc.content)
frappe.db.set_value('Control Panel', None, 'letter_head', self.doc.content)

+ 6
- 6
frappe/core/doctype/notification_count/notification_count.py Просмотреть файл

@@ -17,7 +17,7 @@ def get_notifications():
open_count_doctype = {} open_count_doctype = {}
open_count_module = {} open_count_module = {}


notification_count = dict(frappe.conn.sql("""select for_doctype, open_count
notification_count = dict(frappe.db.sql("""select for_doctype, open_count
from `tabNotification Count` where owner=%s""", (frappe.session.user,))) from `tabNotification Count` where owner=%s""", (frappe.session.user,)))


for d in config.for_doctype: for d in config.for_doctype:
@@ -51,7 +51,7 @@ def get_notifications():


def delete_notification_count_for(doctype): def delete_notification_count_for(doctype):
if frappe.flags.in_import: return if frappe.flags.in_import: return
frappe.conn.sql("""delete from `tabNotification Count` where for_doctype = %s""", (doctype,))
frappe.db.sql("""delete from `tabNotification Count` where for_doctype = %s""", (doctype,))


def delete_event_notification_count(): def delete_event_notification_count():
delete_notification_count_for("Event") delete_notification_count_for("Event")
@@ -78,7 +78,7 @@ def get_notification_info_for_boot():
can_read = frappe.user.get_can_read() can_read = frappe.user.get_can_read()
conditions = {} conditions = {}
module_doctypes = {} module_doctypes = {}
doctype_info = dict(frappe.conn.sql("""select name, module from tabDocType"""))
doctype_info = dict(frappe.db.sql("""select name, module from tabDocType"""))
for d in list(set(can_read + config.for_doctype.keys())): for d in list(set(can_read + config.for_doctype.keys())):
if d in config.for_doctype: if d in config.for_doctype:
@@ -104,9 +104,9 @@ def get_notification_config():
return config return config


def on_doctype_update(): def on_doctype_update():
if not frappe.conn.sql("""show index from `tabNotification Count`
if not frappe.db.sql("""show index from `tabNotification Count`
where Key_name="notification_count_owner_index" """): where Key_name="notification_count_owner_index" """):
frappe.conn.commit()
frappe.conn.sql("""alter table `tabNotification Count`
frappe.db.commit()
frappe.db.sql("""alter table `tabNotification Count`
add index notification_count_owner_index(owner)""") add index notification_count_owner_index(owner)""")

+ 2
- 2
frappe/core/doctype/page/page.py Просмотреть файл

@@ -18,8 +18,8 @@ class DocType:
if (self.doc.name and self.doc.name.startswith('New Page')) or not self.doc.name: if (self.doc.name and self.doc.name.startswith('New Page')) or not self.doc.name:
self.doc.name = self.doc.page_name.lower().replace('"','').replace("'",'').\ self.doc.name = self.doc.page_name.lower().replace('"','').replace("'",'').\
replace(' ', '-')[:20] replace(' ', '-')[:20]
if frappe.conn.exists('Page',self.doc.name):
cnt = frappe.conn.sql("""select name from tabPage
if frappe.db.exists('Page',self.doc.name):
cnt = frappe.db.sql("""select name from tabPage
where name like "%s-%%" order by name desc limit 1""" % self.doc.name) where name like "%s-%%" order by name desc limit 1""" % self.doc.name)
if cnt: if cnt:
cnt = cint(cnt[0][0].split('-')[-1]) + 1 cnt = cint(cnt[0][0].split('-')[-1]) + 1


+ 4
- 4
frappe/core/doctype/print_format/print_format.py Просмотреть файл

@@ -17,7 +17,7 @@ class DocType:
frappe.msgprint("Standard Print Format cannot be updated.", raise_exception=1) frappe.msgprint("Standard Print Format cannot be updated.", raise_exception=1)
# old_doc_type is required for clearing item cache # old_doc_type is required for clearing item cache
self.old_doc_type = frappe.conn.get_value('Print Format',
self.old_doc_type = frappe.db.get_value('Print Format',
self.doc.name, 'doc_type') self.doc.name, 'doc_type')


def on_update(self): def on_update(self):
@@ -90,13 +90,13 @@ def get_print_format_name(doctype, format_name):
return format_name return format_name
# server, find template # server, find template
path = os.path.join(get_doc_path(frappe.conn.get_value("DocType", doctype, "module"),
path = os.path.join(get_doc_path(frappe.db.get_value("DocType", doctype, "module"),
"Print Format", format_name), format_name + ".html") "Print Format", format_name), format_name + ".html")
if os.path.exists(path): if os.path.exists(path):
with open(path, "r") as pffile: with open(path, "r") as pffile:
return pffile.read() return pffile.read()
else: else:
html = frappe.conn.get_value("Print Format", format_name, "html")
html = frappe.db.get_value("Print Format", format_name, "html")
if html: if html:
return html return html
else: else:
@@ -104,7 +104,7 @@ def get_print_format_name(doctype, format_name):


def get_print_style(style=None): def get_print_style(style=None):
if not style: if not style:
style = frappe.conn.get_default("print_style") or "Standard"
style = frappe.db.get_default("print_style") or "Standard"
path = os.path.join(get_doc_path("Core", "DocType", "Print Format"), "styles", path = os.path.join(get_doc_path("Core", "DocType", "Print Format"), "styles",
style.lower() + ".css") style.lower() + ".css")
if not os.path.exists(path): if not os.path.exists(path):


+ 31
- 31
frappe/core/doctype/profile/profile.py Просмотреть файл

@@ -18,7 +18,7 @@ class DocType:
self.doc.email = self.doc.email.strip() self.doc.email = self.doc.email.strip()
self.doc.name = self.doc.email self.doc.name = self.doc.email
if frappe.conn.exists("Profile", self.doc.name):
if frappe.db.exists("Profile", self.doc.name):
throw(_("Name Exists")) throw(_("Name Exists"))


def validate(self): def validate(self):
@@ -67,7 +67,7 @@ class DocType:
if 'max_users' in conf and self.doc.enabled and \ if 'max_users' in conf and self.doc.enabled and \
self.doc.name not in ["Administrator", "Guest"] and \ self.doc.name not in ["Administrator", "Guest"] and \
cstr(self.doc.user_type).strip() in ("", "System User"): cstr(self.doc.user_type).strip() in ("", "System User"):
active_users = frappe.conn.sql("""select count(*) from tabProfile
active_users = frappe.db.sql("""select count(*) from tabProfile
where ifnull(enabled, 0)=1 and docstatus<2 where ifnull(enabled, 0)=1 and docstatus<2
and ifnull(user_type, "System User") = "System User" and ifnull(user_type, "System User") = "System User"
and name not in ('Administrator', 'Guest', %s)""", (self.doc.name,))[0][0] and name not in ('Administrator', 'Guest', %s)""", (self.doc.name,))[0][0]
@@ -104,7 +104,7 @@ class DocType:
def on_update(self): def on_update(self):
# owner is always name # owner is always name
frappe.conn.set(self.doc, 'owner', self.doc.name)
frappe.db.set(self.doc, 'owner', self.doc.name)
frappe.clear_cache(user=self.doc.name) frappe.clear_cache(user=self.doc.name)
def update_gravatar(self): def update_gravatar(self):
@@ -120,11 +120,11 @@ class DocType:
from frappe.utils import random_string, get_url from frappe.utils import random_string, get_url


key = random_string(32) key = random_string(32)
frappe.conn.set_value("Profile", self.doc.name, "reset_password_key", key)
frappe.db.set_value("Profile", self.doc.name, "reset_password_key", key)
self.password_reset_mail(get_url("/update-password?key=" + key)) self.password_reset_mail(get_url("/update-password?key=" + key))
def get_other_system_managers(self): def get_other_system_managers(self):
return frappe.conn.sql("""select distinct parent from tabUserRole user_role
return frappe.db.sql("""select distinct parent from tabUserRole user_role
where role='System Manager' and docstatus<2 where role='System Manager' and docstatus<2
and parent not in ('Administrator', %s) and exists and parent not in ('Administrator', %s) and exists
(select * from `tabProfile` profile (select * from `tabProfile` profile
@@ -155,7 +155,7 @@ class DocType:
from frappe.utils import get_url from frappe.utils import get_url
mail_titles = frappe.get_hooks().get("login_mail_title", []) mail_titles = frappe.get_hooks().get("login_mail_title", [])
title = frappe.conn.get_default('company') or (mail_titles and mail_titles[0]) or ""
title = frappe.db.get_default('company') or (mail_titles and mail_titles[0]) or ""
full_name = get_user_fullname(frappe.session['user']) full_name = get_user_fullname(frappe.session['user'])
if full_name == "Guest": if full_name == "Guest":
@@ -196,20 +196,20 @@ class DocType:
frappe.local.login_manager.logout(user=self.doc.name) frappe.local.login_manager.logout(user=self.doc.name)
# delete their password # delete their password
frappe.conn.sql("""delete from __Auth where user=%s""", (self.doc.name,))
frappe.db.sql("""delete from __Auth where user=%s""", (self.doc.name,))
# delete todos # delete todos
frappe.conn.sql("""delete from `tabToDo` where owner=%s""", (self.doc.name,))
frappe.conn.sql("""update tabToDo set assigned_by=null where assigned_by=%s""",
frappe.db.sql("""delete from `tabToDo` where owner=%s""", (self.doc.name,))
frappe.db.sql("""update tabToDo set assigned_by=null where assigned_by=%s""",
(self.doc.name,)) (self.doc.name,))
# delete events # delete events
frappe.conn.sql("""delete from `tabEvent` where owner=%s
frappe.db.sql("""delete from `tabEvent` where owner=%s
and event_type='Private'""", (self.doc.name,)) and event_type='Private'""", (self.doc.name,))
frappe.conn.sql("""delete from `tabEvent User` where person=%s""", (self.doc.name,))
frappe.db.sql("""delete from `tabEvent User` where person=%s""", (self.doc.name,))
# delete messages # delete messages
frappe.conn.sql("""delete from `tabComment` where comment_doctype='Message'
frappe.db.sql("""delete from `tabComment` where comment_doctype='Message'
and (comment_docname=%s or owner=%s)""", (self.doc.name, self.doc.name)) and (comment_docname=%s or owner=%s)""", (self.doc.name, self.doc.name))
def before_rename(self, olddn, newdn, merge=False): def before_rename(self, olddn, newdn, merge=False):
@@ -237,27 +237,27 @@ class DocType:
})) }))
def after_rename(self, olddn, newdn, merge=False): def after_rename(self, olddn, newdn, merge=False):
tables = frappe.conn.sql("show tables")
tables = frappe.db.sql("show tables")
for tab in tables: for tab in tables:
desc = frappe.conn.sql("desc `%s`" % tab[0], as_dict=1)
desc = frappe.db.sql("desc `%s`" % tab[0], as_dict=1)
has_fields = [] has_fields = []
for d in desc: for d in desc:
if d.get('Field') in ['owner', 'modified_by']: if d.get('Field') in ['owner', 'modified_by']:
has_fields.append(d.get('Field')) has_fields.append(d.get('Field'))
for field in has_fields: for field in has_fields:
frappe.conn.sql("""\
frappe.db.sql("""\
update `%s` set `%s`=%s update `%s` set `%s`=%s
where `%s`=%s""" % \ where `%s`=%s""" % \
(tab[0], field, '%s', field, '%s'), (newdn, olddn)) (tab[0], field, '%s', field, '%s'), (newdn, olddn))
# set email # set email
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabProfile` set email=%s update `tabProfile` set email=%s
where name=%s""", (newdn, newdn)) where name=%s""", (newdn, newdn))
# update __Auth table # update __Auth table
if not merge: if not merge:
frappe.conn.sql("""update __Auth set user=%s where user=%s""", (newdn, olddn))
frappe.db.sql("""update __Auth set user=%s where user=%s""", (newdn, olddn))
def add_roles(self, *roles): def add_roles(self, *roles):
for role in roles: for role in roles:
@@ -281,7 +281,7 @@ def get_languages():
@frappe.whitelist() @frappe.whitelist()
def get_all_roles(arg=None): def get_all_roles(arg=None):
"""return all roles""" """return all roles"""
return [r[0] for r in frappe.conn.sql("""select name from tabRole
return [r[0] for r in frappe.db.sql("""select name from tabRole
where name not in ('Administrator', 'Guest', 'All') order by name""")] where name not in ('Administrator', 'Guest', 'All') order by name""")]
@frappe.whitelist() @frappe.whitelist()
@@ -292,7 +292,7 @@ def get_user_roles(arg=None):
@frappe.whitelist() @frappe.whitelist()
def get_perm_info(arg=None): def get_perm_info(arg=None):
"""get permission info""" """get permission info"""
return frappe.conn.sql("""select parent, permlevel, `read`, `write`, submit,
return frappe.db.sql("""select parent, permlevel, `read`, `write`, submit,
cancel, amend from tabDocPerm where role=%s cancel, amend from tabDocPerm where role=%s
and docstatus<2 order by parent, permlevel""", and docstatus<2 order by parent, permlevel""",
(frappe.form_dict['role'],), as_dict=1) (frappe.form_dict['role'],), as_dict=1)
@@ -301,18 +301,18 @@ def get_perm_info(arg=None):
def update_password(new_password, key=None, old_password=None): def update_password(new_password, key=None, old_password=None):
# verify old password # verify old password
if key: if key:
user = frappe.conn.get_value("Profile", {"reset_password_key":key})
user = frappe.db.get_value("Profile", {"reset_password_key":key})
if not user: if not user:
return _("Cannot Update: Incorrect / Expired Link.") return _("Cannot Update: Incorrect / Expired Link.")
elif old_password: elif old_password:
user = frappe.session.user user = frappe.session.user
if not frappe.conn.sql("""select user from __Auth where password=password(%s)
if not frappe.db.sql("""select user from __Auth where password=password(%s)
and user=%s""", (old_password, user)): and user=%s""", (old_password, user)):
return _("Cannot Update: Incorrect Password") return _("Cannot Update: Incorrect Password")
_update_password(user, new_password) _update_password(user, new_password)
frappe.conn.set_value("Profile", user, "reset_password_key", "")
frappe.db.set_value("Profile", user, "reset_password_key", "")
frappe.local.login_manager.logout() frappe.local.login_manager.logout()
@@ -320,14 +320,14 @@ def update_password(new_password, key=None, old_password=None):
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def sign_up(email, full_name): def sign_up(email, full_name):
profile = frappe.conn.get("Profile", {"email": email})
profile = frappe.db.get("Profile", {"email": email})
if profile: if profile:
if profile.disabled: if profile.disabled:
return _("Registered but disabled.") return _("Registered but disabled.")
else: else:
return _("Already Registered") return _("Already Registered")
else: else:
if frappe.conn.sql("""select count(*) from tabProfile where
if frappe.db.sql("""select count(*) from tabProfile where
TIMEDIFF(%s, modified) > '1:00:00' """, now())[0][0] > 200: TIMEDIFF(%s, modified) > '1:00:00' """, now())[0][0] > 200:
raise Exception, "Too Many New Profiles" raise Exception, "Too Many New Profiles"
from frappe.utils import random_string from frappe.utils import random_string
@@ -349,7 +349,7 @@ def reset_password(user):
if user in ["demo@erpnext.com", "Administrator"]: if user in ["demo@erpnext.com", "Administrator"]:
return "Not allowed" return "Not allowed"
if frappe.conn.sql("""select name from tabProfile where name=%s""", (user,)):
if frappe.db.sql("""select name from tabProfile where name=%s""", (user,)):
# Hack! # Hack!
frappe.session["user"] = "Administrator" frappe.session["user"] = "Administrator"
profile = frappe.bean("Profile", user) profile = frappe.bean("Profile", user)
@@ -371,7 +371,7 @@ def facebook_login(data):
# garbage # garbage
raise frappe.ValidationError raise frappe.ValidationError
if not frappe.conn.exists("Profile", user):
if not frappe.db.exists("Profile", user):
if data.get("birthday"): if data.get("birthday"):
b = data.get("birthday").split("/") b = data.get("birthday").split("/")
data["birthday"] = b[2] + "-" + b[0] + "-" + b[1] data["birthday"] = b[2] + "-" + b[0] + "-" + b[1]
@@ -407,7 +407,7 @@ def get_fb_userid(fb_access_token):
def profile_query(doctype, txt, searchfield, start, page_len, filters): def profile_query(doctype, txt, searchfield, start, page_len, filters):
from frappe.widgets.reportview import get_match_cond from frappe.widgets.reportview import get_match_cond
return frappe.conn.sql("""select name, concat_ws(' ', first_name, middle_name, last_name)
return frappe.db.sql("""select name, concat_ws(' ', first_name, middle_name, last_name)
from `tabProfile` from `tabProfile`
where ifnull(enabled, 0)=1 where ifnull(enabled, 0)=1
and docstatus < 2 and docstatus < 2
@@ -426,25 +426,25 @@ def profile_query(doctype, txt, searchfield, start, page_len, filters):


def get_total_users(): def get_total_users():
"""Returns total no. of system users""" """Returns total no. of system users"""
return frappe.conn.sql("""select count(*) from `tabProfile`
return frappe.db.sql("""select count(*) from `tabProfile`
where enabled = 1 and user_type != 'Website User' where enabled = 1 and user_type != 'Website User'
and name not in ('Administrator', 'Guest')""")[0][0] and name not in ('Administrator', 'Guest')""")[0][0]


def get_active_users(): def get_active_users():
"""Returns No. of system users who logged in, in the last 3 days""" """Returns No. of system users who logged in, in the last 3 days"""
return frappe.conn.sql("""select count(*) from `tabProfile`
return frappe.db.sql("""select count(*) from `tabProfile`
where enabled = 1 and user_type != 'Website User' where enabled = 1 and user_type != 'Website User'
and name not in ('Administrator', 'Guest') and name not in ('Administrator', 'Guest')
and hour(timediff(now(), last_login)) < 72""")[0][0] and hour(timediff(now(), last_login)) < 72""")[0][0]


def get_website_users(): def get_website_users():
"""Returns total no. of website users""" """Returns total no. of website users"""
return frappe.conn.sql("""select count(*) from `tabProfile`
return frappe.db.sql("""select count(*) from `tabProfile`
where enabled = 1 and user_type = 'Website User'""")[0][0] where enabled = 1 and user_type = 'Website User'""")[0][0]
def get_active_website_users(): def get_active_website_users():
"""Returns No. of website users who logged in, in the last 3 days""" """Returns No. of website users who logged in, in the last 3 days"""
return frappe.conn.sql("""select count(*) from `tabProfile`
return frappe.db.sql("""select count(*) from `tabProfile`
where enabled = 1 and user_type = 'Website User' where enabled = 1 and user_type = 'Website User'
and hour(timediff(now(), last_login)) < 72""")[0][0] and hour(timediff(now(), last_login)) < 72""")[0][0]



+ 13
- 13
frappe/core/doctype/profile/test_profile.py Просмотреть файл

@@ -8,7 +8,7 @@ from frappe.model.delete_doc import delete_doc, LinkExistsError
class TestProfile(unittest.TestCase): class TestProfile(unittest.TestCase):
def test_delete(self): def test_delete(self):
self.assertRaises(LinkExistsError, delete_doc, "Role", "_Test Role 2") self.assertRaises(LinkExistsError, delete_doc, "Role", "_Test Role 2")
frappe.conn.sql("""delete from tabUserRole where role='_Test Role 2'""")
frappe.db.sql("""delete from tabUserRole where role='_Test Role 2'""")
delete_doc("Role","_Test Role 2") delete_doc("Role","_Test Role 2")
profile = frappe.bean(copy=test_records[1]) profile = frappe.bean(copy=test_records[1])
@@ -19,33 +19,33 @@ class TestProfile(unittest.TestCase):
delete_doc("Profile", "_test@example.com") delete_doc("Profile", "_test@example.com")
self.assertTrue(not frappe.conn.sql("""select * from `tabToDo` where owner=%s""",
self.assertTrue(not frappe.db.sql("""select * from `tabToDo` where owner=%s""",
("_test@example.com",))) ("_test@example.com",)))
from frappe.core.doctype.role.test_role import test_records as role_records from frappe.core.doctype.role.test_role import test_records as role_records
frappe.bean(copy=role_records[1]).insert() frappe.bean(copy=role_records[1]).insert()
def test_get_value(self): def test_get_value(self):
self.assertEquals(frappe.conn.get_value("Profile", "test@example.com"), "test@example.com")
self.assertEquals(frappe.conn.get_value("Profile", {"email":"test@example.com"}), "test@example.com")
self.assertEquals(frappe.conn.get_value("Profile", {"email":"test@example.com"}, "email"), "test@example.com")
self.assertEquals(frappe.conn.get_value("Profile", {"email":"test@example.com"}, ["first_name", "email"]),
self.assertEquals(frappe.db.get_value("Profile", "test@example.com"), "test@example.com")
self.assertEquals(frappe.db.get_value("Profile", {"email":"test@example.com"}), "test@example.com")
self.assertEquals(frappe.db.get_value("Profile", {"email":"test@example.com"}, "email"), "test@example.com")
self.assertEquals(frappe.db.get_value("Profile", {"email":"test@example.com"}, ["first_name", "email"]),
("_Test", "test@example.com")) ("_Test", "test@example.com"))
self.assertEquals(frappe.conn.get_value("Profile",
self.assertEquals(frappe.db.get_value("Profile",
{"email":"test@example.com", "first_name": "_Test"}, {"email":"test@example.com", "first_name": "_Test"},
["first_name", "email"]), ["first_name", "email"]),
("_Test", "test@example.com")) ("_Test", "test@example.com"))
test_profile = frappe.conn.sql("select * from tabProfile where name='test@example.com'",
test_profile = frappe.db.sql("select * from tabProfile where name='test@example.com'",
as_dict=True)[0] as_dict=True)[0]
self.assertEquals(frappe.conn.get_value("Profile", {"email":"test@example.com"}, "*", as_dict=True),
self.assertEquals(frappe.db.get_value("Profile", {"email":"test@example.com"}, "*", as_dict=True),
test_profile) test_profile)


self.assertEquals(frappe.conn.get_value("Profile", "xxxtest@example.com"), None)
self.assertEquals(frappe.db.get_value("Profile", "xxxtest@example.com"), None)
frappe.conn.set_value("Control Panel", "Control Panel", "_test", "_test_val")
self.assertEquals(frappe.conn.get_value("Control Panel", None, "_test"), "_test_val")
self.assertEquals(frappe.conn.get_value("Control Panel", "Control Panel", "_test"), "_test_val")
frappe.db.set_value("Control Panel", "Control Panel", "_test", "_test_val")
self.assertEquals(frappe.db.get_value("Control Panel", None, "_test"), "_test_val")
self.assertEquals(frappe.db.get_value("Control Panel", "Control Panel", "_test"), "_test_val")
def test_doclist(self): def test_doclist(self):
p_meta = frappe.get_doctype("Profile") p_meta = frappe.get_doctype("Profile")


+ 6
- 6
frappe/core/doctype/property_setter/property_setter.py Просмотреть файл

@@ -16,7 +16,7 @@ class DocType:
def validate(self): def validate(self):
"""delete other property setters on this, if this is new""" """delete other property setters on this, if this is new"""
if self.doc.fields['__islocal']: if self.doc.fields['__islocal']:
frappe.conn.sql("""delete from `tabProperty Setter` where
frappe.db.sql("""delete from `tabProperty Setter` where
doctype_or_field = %(doctype_or_field)s doctype_or_field = %(doctype_or_field)s
and doc_type = %(doc_type)s and doc_type = %(doc_type)s
and ifnull(field_name,'') = ifnull(%(field_name)s, '') and ifnull(field_name,'') = ifnull(%(field_name)s, '')
@@ -26,7 +26,7 @@ class DocType:
frappe.clear_cache(doctype = self.doc.doc_type) frappe.clear_cache(doctype = self.doc.doc_type)
def get_property_list(self, dt): def get_property_list(self, dt):
return frappe.conn.sql("""select fieldname, label, fieldtype
return frappe.db.sql("""select fieldname, label, fieldtype
from tabDocField from tabDocField
where parent=%s where parent=%s
and fieldtype not in ('Section Break', 'Column Break', 'HTML', 'Read Only', 'Table') and fieldtype not in ('Section Break', 'Column Break', 'HTML', 'Read Only', 'Table')
@@ -35,19 +35,19 @@ class DocType:
def get_setup_data(self): def get_setup_data(self):
return { return {
'doctypes': [d[0] for d in frappe.conn.sql("select name from tabDocType")],
'doctypes': [d[0] for d in frappe.db.sql("select name from tabDocType")],
'dt_properties': self.get_property_list('DocType'), 'dt_properties': self.get_property_list('DocType'),
'df_properties': self.get_property_list('DocField') 'df_properties': self.get_property_list('DocField')
} }
def get_field_ids(self): def get_field_ids(self):
return frappe.conn.sql("select name, fieldtype, label, fieldname from tabDocField where parent=%s", self.doc.doc_type, as_dict = 1)
return frappe.db.sql("select name, fieldtype, label, fieldname from tabDocField where parent=%s", self.doc.doc_type, as_dict = 1)
def get_defaults(self): def get_defaults(self):
if not self.doc.field_name: if not self.doc.field_name:
return frappe.conn.sql("select * from `tabDocType` where name=%s", self.doc.doc_type, as_dict = 1)[0]
return frappe.db.sql("select * from `tabDocType` where name=%s", self.doc.doc_type, as_dict = 1)[0]
else: else:
return frappe.conn.sql("select * from `tabDocField` where fieldname=%s and parent=%s",
return frappe.db.sql("select * from `tabDocField` where fieldname=%s and parent=%s",
(self.doc.field_name, self.doc.doc_type), as_dict = 1)[0] (self.doc.field_name, self.doc.doc_type), as_dict = 1)[0]
def on_update(self): def on_update(self):


+ 1
- 1
frappe/core/doctype/report/report.py Просмотреть файл

@@ -32,4 +32,4 @@ class DocType:
from frappe.modules.export_file import export_to_files from frappe.modules.export_file import export_to_files
if self.doc.is_standard == 'Yes' and (conf.get('developer_mode') or 0) == 1: if self.doc.is_standard == 'Yes' and (conf.get('developer_mode') or 0) == 1:
export_to_files(record_list=[['Report', self.doc.name]], export_to_files(record_list=[['Report', self.doc.name]],
record_module=frappe.conn.get_value("DocType", self.doc.ref_doctype, "module"))
record_module=frappe.db.get_value("DocType", self.doc.ref_doctype, "module"))

+ 1
- 1
frappe/core/doctype/todo/todo.py Просмотреть файл

@@ -12,7 +12,7 @@ class DocType:
if self.doc.is_new(): if self.doc.is_new():
self.add_comment(frappe._("Assignment Added")) self.add_comment(frappe._("Assignment Added"))
else: else:
cur_status = frappe.conn.get_value("ToDo", self.doc.name, "status")
cur_status = frappe.db.get_value("ToDo", self.doc.name, "status")
if cur_status != self.doc.status: if cur_status != self.doc.status:
self.add_comment(frappe._("Assignment Status Changed")) self.add_comment(frappe._("Assignment Status Changed"))


+ 1
- 1
frappe/core/doctype/userrole/userrole.py Просмотреть файл

@@ -10,7 +10,7 @@ class DocType:
self.doc, self.doclist = d, dl self.doc, self.doclist = d, dl
def validate(self): def validate(self):
if cint(self.doc.fields.get("__islocal")) and frappe.conn.exists("UserRole", {
if cint(self.doc.fields.get("__islocal")) and frappe.db.exists("UserRole", {
"parent": self.doc.parent, "role": self.doc.role}): "parent": self.doc.parent, "role": self.doc.role}):
frappe.msgprint("Role Already Exists", raise_exception=True) frappe.msgprint("Role Already Exists", raise_exception=True)

+ 1
- 1
frappe/core/doctype/version/version.py Просмотреть файл

@@ -24,7 +24,7 @@ def restore(version):
for d in doclist[1:]: for d in doclist[1:]:
d["parent"] = version.docname d["parent"] = version.docname
doclist[0]["modified"] = frappe.conn.get_value(version.ref_doctype, version.docname, "modified")
doclist[0]["modified"] = frappe.db.get_value(version.ref_doctype, version.docname, "modified")
# overwrite # overwrite
frappe.bean(doclist).save() frappe.bean(doclist).save()

+ 2
- 2
frappe/core/doctype/workflow/workflow.py Просмотреть файл

@@ -44,7 +44,7 @@ class DocType:
states.sort(lambda x, y: x.idx - y.idx) states.sort(lambda x, y: x.idx - y.idx)
for d in self.doclist.get({"doctype": "Workflow Document State"}): for d in self.doclist.get({"doctype": "Workflow Document State"}):
if not d.doc_status in docstatus_map: if not d.doc_status in docstatus_map:
frappe.conn.sql("""update `tab%s` set `%s` = %s where \
frappe.db.sql("""update `tab%s` set `%s` = %s where \
ifnull(`%s`, '')='' and docstatus=%s""" % (self.doc.document_type, self.doc.workflow_state_field, ifnull(`%s`, '')='' and docstatus=%s""" % (self.doc.document_type, self.doc.workflow_state_field,
'%s', self.doc.workflow_state_field, "%s"), (d.state, d.doc_status)) '%s', self.doc.workflow_state_field, "%s"), (d.state, d.doc_status))
docstatus_map[d.doc_status] = d.state docstatus_map[d.doc_status] = d.state
@@ -52,6 +52,6 @@ class DocType:
def set_active(self): def set_active(self):
if int(self.doc.is_active or 0): if int(self.doc.is_active or 0):
# clear all other # clear all other
frappe.conn.sql("""update tabWorkflow set is_active=0
frappe.db.sql("""update tabWorkflow set is_active=0
where document_type=%s""", where document_type=%s""",
self.doc.document_type) self.doc.document_type)

+ 2
- 2
frappe/core/notifications.py Просмотреть файл

@@ -20,7 +20,7 @@ def get_notification_config():


def get_things_todo(): def get_things_todo():
"""Returns a count of incomplete todos""" """Returns a count of incomplete todos"""
incomplete_todos = frappe.conn.sql("""\
incomplete_todos = frappe.db.sql("""\
SELECT COUNT(*) FROM `tabToDo` SELECT COUNT(*) FROM `tabToDo`
WHERE status="Open" WHERE status="Open"
AND (owner = %s or assigned_by=%s)""", (frappe.session.user, frappe.session.user)) AND (owner = %s or assigned_by=%s)""", (frappe.session.user, frappe.session.user))
@@ -35,7 +35,7 @@ def get_todays_events():


def get_unread_messages(): def get_unread_messages():
"returns unread (docstatus-0 messages for a user)" "returns unread (docstatus-0 messages for a user)"
return frappe.conn.sql("""\
return frappe.db.sql("""\
SELECT count(*) SELECT count(*)
FROM `tabComment` FROM `tabComment`
WHERE comment_doctype IN ('My Company', 'Message') WHERE comment_doctype IN ('My Company', 'Message')


+ 11
- 11
frappe/core/page/data_import_tool/data_import_tool.py Просмотреть файл

@@ -23,7 +23,7 @@ data_keys = frappe._dict({
@frappe.whitelist() @frappe.whitelist()
def get_doctypes(): def get_doctypes():
if "System Manager" in frappe.get_roles(): if "System Manager" in frappe.get_roles():
return [r[0] for r in frappe.conn.sql("""select name from `tabDocType`
return [r[0] for r in frappe.db.sql("""select name from `tabDocType`
where allow_import = 1""")] where allow_import = 1""")]
else: else:
return frappe.user._get("can_import") return frappe.user._get("can_import")
@@ -77,7 +77,7 @@ def get_template(doctype=None, parent_doctype=None, all_doctypes="No", with_data
doctype_dl = frappe.model.doctype.get(dt) doctype_dl = frappe.model.doctype.get(dt)


tablecolumns = filter(None, tablecolumns = filter(None,
[doctype_dl.get_field(f[0]) for f in frappe.conn.sql('desc `tab%s`' % dt)])
[doctype_dl.get_field(f[0]) for f in frappe.db.sql('desc `tab%s`' % dt)])


tablecolumns.sort(lambda a, b: a.idx - b.idx) tablecolumns.sort(lambda a, b: a.idx - b.idx)


@@ -184,7 +184,7 @@ def get_template(doctype=None, parent_doctype=None, all_doctypes="No", with_data
if all_doctypes: if all_doctypes:
# add child tables # add child tables
for child_doctype in child_doctypes: for child_doctype in child_doctypes:
for ci, child in enumerate(frappe.conn.sql("""select * from `tab%s`
for ci, child in enumerate(frappe.db.sql("""select * from `tab%s`
where parent=%s order by idx""" % (child_doctype, "%s"), doc.name, as_dict=1)): where parent=%s order by idx""" % (child_doctype, "%s"), doc.name, as_dict=1)):
add_data_row(row_group, child_doctype, child, ci) add_data_row(row_group, child_doctype, child, ci)
@@ -351,7 +351,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
column_idx_to_fieldname = {} column_idx_to_fieldname = {}
column_idx_to_fieldtype = {} column_idx_to_fieldtype = {}
if submit_after_import and not cint(frappe.conn.get_value("DocType",
if submit_after_import and not cint(frappe.db.get_value("DocType",
doctype, "is_submittable")): doctype, "is_submittable")):
submit_after_import = False submit_after_import = False


@@ -370,7 +370,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
check_data_length() check_data_length()
make_column_map() make_column_map()
frappe.conn.begin()
frappe.db.begin()
if not overwrite: if not overwrite:
overwrite = params.get('overwrite') overwrite = params.get('overwrite')
doctype_dl = frappe.model.doctype.get(doctype) doctype_dl = frappe.model.doctype.get(doctype)
@@ -398,7 +398,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
# ignoring parent check as it will be automatically added # ignoring parent check as it will be automatically added
check_record(d, None, doctype_dl) check_record(d, None, doctype_dl)
if overwrite and frappe.conn.exists(doctype, doclist[0]["name"]):
if overwrite and frappe.db.exists(doctype, doclist[0]["name"]):
bean = frappe.bean(doctype, doclist[0]["name"]) bean = frappe.bean(doctype, doclist[0]["name"])
bean.ignore_links = ignore_links bean.ignore_links = ignore_links
bean.doclist.update(doclist) bean.doclist.update(doclist)
@@ -441,9 +441,9 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
ret, error = validate_parent(parent_list, parenttype, ret, error) ret, error = validate_parent(parent_list, parenttype, ret, error)
if error: if error:
frappe.conn.rollback()
frappe.db.rollback()
else: else:
frappe.conn.commit()
frappe.db.commit()
frappe.flags.mute_emails = False frappe.flags.mute_emails = False
@@ -484,7 +484,7 @@ def get_parent_field(doctype, parenttype):
def delete_child_rows(rows, doctype): def delete_child_rows(rows, doctype):
"""delete child rows for all parents""" """delete child rows for all parents"""
for p in list(set([r[1] for r in rows])): for p in list(set([r[1] for r in rows])):
frappe.conn.sql("""delete from `tab%s` where parent=%s""" % (doctype, '%s'), p)
frappe.db.sql("""delete from `tab%s` where parent=%s""" % (doctype, '%s'), p)
import csv import csv
def import_file_by_path(path, ignore_links=False, overwrite=False): def import_file_by_path(path, ignore_links=False, overwrite=False):
@@ -551,7 +551,7 @@ def import_doclist(path, overwrite=False, ignore_links=False, ignore_insert=Fals
_import_doclist(doc) _import_doclist(doc)
else: else:
_import_doclist(data) _import_doclist(data)
frappe.conn.commit()
frappe.db.commit()
if f.endswith(".csv"): if f.endswith(".csv"):
import_file_by_path(f, ignore_links=True, overwrite=overwrite) import_file_by_path(f, ignore_links=True, overwrite=overwrite)
frappe.conn.commit()
frappe.db.commit()

+ 9
- 9
frappe/core/page/messages/messages.py Просмотреть файл

@@ -14,19 +14,19 @@ def get_list(arg=None):
frappe.form_dict['user'] = frappe.session['user'] frappe.form_dict['user'] = frappe.session['user']


# set all messages as read # set all messages as read
frappe.conn.begin()
frappe.conn.sql("""UPDATE `tabComment`
frappe.db.begin()
frappe.db.sql("""UPDATE `tabComment`
set docstatus = 1 where comment_doctype in ('My Company', 'Message') set docstatus = 1 where comment_doctype in ('My Company', 'Message')
and comment_docname = %s and comment_docname = %s
""", frappe.user.name) """, frappe.user.name)
delete_notification_count_for("Messages") delete_notification_count_for("Messages")
frappe.conn.commit()
frappe.db.commit()


if frappe.form_dict['contact'] == frappe.session['user']: if frappe.form_dict['contact'] == frappe.session['user']:
# return messages # return messages
return frappe.conn.sql("""select * from `tabComment`
return frappe.db.sql("""select * from `tabComment`
where (owner=%(contact)s where (owner=%(contact)s
or comment_docname=%(user)s or comment_docname=%(user)s
or (owner=comment_docname and ifnull(parenttype, "")!="Assignment")) or (owner=comment_docname and ifnull(parenttype, "")!="Assignment"))
@@ -34,7 +34,7 @@ def get_list(arg=None):
order by creation desc order by creation desc
limit %(limit_start)s, %(limit_page_length)s""", frappe.local.form_dict, as_dict=1) limit %(limit_start)s, %(limit_page_length)s""", frappe.local.form_dict, as_dict=1)
else: else:
return frappe.conn.sql("""select * from `tabComment`
return frappe.db.sql("""select * from `tabComment`
where (owner=%(contact)s and comment_docname=%(user)s) where (owner=%(contact)s and comment_docname=%(user)s)
or (owner=%(user)s and comment_docname=%(contact)s) or (owner=%(user)s and comment_docname=%(contact)s)
or (owner=%(contact)s and comment_docname=%(contact)s) or (owner=%(contact)s and comment_docname=%(contact)s)
@@ -45,7 +45,7 @@ def get_list(arg=None):


@frappe.whitelist() @frappe.whitelist()
def get_active_users(arg=None): def get_active_users(arg=None):
return frappe.conn.sql("""select name,
return frappe.db.sql("""select name,
(select count(*) from tabSessions where user=tabProfile.name (select count(*) from tabSessions where user=tabProfile.name
and timediff(now(), lastupdate) < time("01:00:00")) as has_session and timediff(now(), lastupdate) < time("01:00:00")) as has_session
from tabProfile from tabProfile
@@ -83,15 +83,15 @@ def post(arg=None):
@frappe.whitelist() @frappe.whitelist()
def delete(arg=None): def delete(arg=None):
frappe.conn.sql("""delete from `tabComment` where name=%s""",
frappe.db.sql("""delete from `tabComment` where name=%s""",
frappe.form_dict['name']); frappe.form_dict['name']);


def notify(arg=None): def notify(arg=None):
from frappe.utils import cstr, get_fullname, get_url from frappe.utils import cstr, get_fullname, get_url
frappe.sendmail(\ frappe.sendmail(\
recipients=[frappe.conn.get_value("Profile", arg["contact"], "email") or arg["contact"]],
sender= frappe.conn.get_value("Profile", frappe.session.user, "email"),
recipients=[frappe.db.get_value("Profile", arg["contact"], "email") or arg["contact"]],
sender= frappe.db.get_value("Profile", frappe.session.user, "email"),
subject="New Message from " + get_fullname(frappe.user.name), subject="New Message from " + get_fullname(frappe.user.name),
message=frappe.get_template("templates/emails/new_message.html").render({ message=frappe.get_template("templates/emails/new_message.html").render({
"from": get_fullname(frappe.user.name), "from": get_fullname(frappe.user.name),


+ 1
- 1
frappe/core/page/modules_setup/modules_setup.py Просмотреть файл

@@ -7,6 +7,6 @@ import frappe
@frappe.whitelist() @frappe.whitelist()
def update(ml): def update(ml):
"""update modules""" """update modules"""
frappe.conn.set_global('hidden_modules', ml)
frappe.db.set_global('hidden_modules', ml)
frappe.msgprint('Updated') frappe.msgprint('Updated')
frappe.clear_cache() frappe.clear_cache()

+ 8
- 8
frappe/core/page/permission_manager/permission_manager.py Просмотреть файл

@@ -10,18 +10,18 @@ from frappe.modules.import_file import get_file_path, read_doclist_from_file
def get_roles_and_doctypes(): def get_roles_and_doctypes():
frappe.only_for("System Manager") frappe.only_for("System Manager")
return { return {
"doctypes": [d[0] for d in frappe.conn.sql("""select name from `tabDocType` dt where
"doctypes": [d[0] for d in frappe.db.sql("""select name from `tabDocType` dt where
ifnull(istable,0)=0 and ifnull(istable,0)=0 and
name not in ('DocType', 'Control Panel') and name not in ('DocType', 'Control Panel') and
exists(select * from `tabDocField` where parent=dt.name)""")], exists(select * from `tabDocField` where parent=dt.name)""")],
"roles": [d[0] for d in frappe.conn.sql("""select name from tabRole where name not in
"roles": [d[0] for d in frappe.db.sql("""select name from tabRole where name not in
('Guest', 'Administrator')""")] ('Guest', 'Administrator')""")]
} }


@frappe.whitelist() @frappe.whitelist()
def get_permissions(doctype=None, role=None): def get_permissions(doctype=None, role=None):
frappe.only_for("System Manager") frappe.only_for("System Manager")
return frappe.conn.sql("""select * from tabDocPerm
return frappe.db.sql("""select * from tabDocPerm
where %s%s order by parent, permlevel, role""" % (\ where %s%s order by parent, permlevel, role""" % (\
doctype and (" parent='%s'" % doctype) or "", doctype and (" parent='%s'" % doctype) or "",
role and ((doctype and " and " or "") + " role='%s'" % role) or "", role and ((doctype and " and " or "") + " role='%s'" % role) or "",
@@ -30,7 +30,7 @@ def get_permissions(doctype=None, role=None):
@frappe.whitelist() @frappe.whitelist()
def remove(doctype, name): def remove(doctype, name):
frappe.only_for("System Manager") frappe.only_for("System Manager")
frappe.conn.sql("""delete from tabDocPerm where name=%s""", name)
frappe.db.sql("""delete from tabDocPerm where name=%s""", name)
validate_and_reset(doctype, for_remove=True) validate_and_reset(doctype, for_remove=True)
@frappe.whitelist() @frappe.whitelist()
@@ -52,7 +52,7 @@ def add(parent, role, permlevel):
@frappe.whitelist() @frappe.whitelist()
def update(name, doctype, ptype, value=0): def update(name, doctype, ptype, value=0):
frappe.only_for("System Manager") frappe.only_for("System Manager")
frappe.conn.sql("""update tabDocPerm set `%s`=%s where name=%s"""\
frappe.db.sql("""update tabDocPerm set `%s`=%s where name=%s"""\
% (ptype, '%s', '%s'), (value, name)) % (ptype, '%s', '%s'), (value, name))
validate_and_reset(doctype) validate_and_reset(doctype)
@@ -69,7 +69,7 @@ def reset(doctype):


def clear_doctype_cache(doctype): def clear_doctype_cache(doctype):
frappe.clear_cache(doctype=doctype) frappe.clear_cache(doctype=doctype)
for user in frappe.conn.sql_list("""select distinct tabUserRole.parent from tabUserRole, tabDocPerm
for user in frappe.db.sql_list("""select distinct tabUserRole.parent from tabUserRole, tabDocPerm
where tabDocPerm.parent = %s where tabDocPerm.parent = %s
and tabDocPerm.role = tabUserRole.role""", doctype): and tabDocPerm.role = tabUserRole.role""", doctype):
frappe.clear_cache(user=user) frappe.clear_cache(user=user)
@@ -77,7 +77,7 @@ def clear_doctype_cache(doctype):
@frappe.whitelist() @frappe.whitelist()
def get_users_with_role(role): def get_users_with_role(role):
frappe.only_for("System Manager") frappe.only_for("System Manager")
return [p[0] for p in frappe.conn.sql("""select distinct tabProfile.name
return [p[0] for p in frappe.db.sql("""select distinct tabProfile.name
from tabUserRole, tabProfile where from tabUserRole, tabProfile where
tabUserRole.role=%s tabUserRole.role=%s
and tabProfile.name != "Administrator" and tabProfile.name != "Administrator"
@@ -86,6 +86,6 @@ def get_users_with_role(role):


@frappe.whitelist() @frappe.whitelist()
def get_standard_permissions(doctype): def get_standard_permissions(doctype):
module = frappe.conn.get_value("DocType", doctype, "module")
module = frappe.db.get_value("DocType", doctype, "module")
path = get_file_path(module, "DocType", doctype) path = get_file_path(module, "DocType", doctype)
return [d for d in read_doclist_from_file(path) if d.get("doctype")=="DocPerm"] return [d for d in read_doclist_from_file(path) if d.get("doctype")=="DocPerm"]

+ 4
- 4
frappe/core/page/user_properties/user_properties.py Просмотреть файл

@@ -9,7 +9,7 @@ import frappe.permissions
@frappe.whitelist() @frappe.whitelist()
def get_users_and_links(): def get_users_and_links():
return { return {
"users": frappe.conn.sql_list("""select name from tabProfile where
"users": frappe.db.sql_list("""select name from tabProfile where
ifnull(enabled,0)=1 and ifnull(enabled,0)=1 and
name not in ("Administrator", "Guest")"""), name not in ("Administrator", "Guest")"""),
"link_fields": get_restrictable_doctypes() "link_fields": get_restrictable_doctypes()
@@ -22,7 +22,7 @@ def get_properties(parent=None, defkey=None, defvalue=None):
conditions, values = _build_conditions(locals()) conditions, values = _build_conditions(locals())
properties = frappe.conn.sql("""select name, parent, defkey, defvalue
properties = frappe.db.sql("""select name, parent, defkey, defvalue
from tabDefaultValue from tabDefaultValue
where parent not in ('Control Panel', '__global') where parent not in ('Control Panel', '__global')
and substr(defkey,1,1)!='_' and substr(defkey,1,1)!='_'
@@ -68,7 +68,7 @@ def add(user, defkey, defvalue):
user=user, doctype=defkey, name=defvalue)) user=user, doctype=defkey, name=defvalue))
# check if already exists # check if already exists
d = frappe.conn.sql("""select name from tabDefaultValue
d = frappe.db.sql("""select name from tabDefaultValue
where parent=%s and parenttype='Restriction' and defkey=%s and defvalue=%s""", (user, defkey, defvalue)) where parent=%s and parenttype='Restriction' and defkey=%s and defvalue=%s""", (user, defkey, defvalue))
if not d: if not d:
@@ -84,6 +84,6 @@ def get_restrictable_doctypes():
and `tabDocPerm`.name in ({roles}))""".format(roles=", ".join(["%s"]*len(user_roles))) and `tabDocPerm`.name in ({roles}))""".format(roles=", ".join(["%s"]*len(user_roles)))
values = user_roles values = user_roles
return frappe.conn.sql_list("""select name from tabDocType
return frappe.db.sql_list("""select name from tabDocType
where ifnull(issingle,0)=0 and ifnull(istable,0)=0 {condition}""".format(condition=condition), where ifnull(issingle,0)=0 and ifnull(istable,0)=0 {condition}""".format(condition=condition),
values) values)

frappe/db.py → frappe/database.py Просмотреть файл

@@ -14,7 +14,7 @@ class Database:
""" """
Open a database connection with the given parmeters, if use_default is True, use the Open a database connection with the given parmeters, if use_default is True, use the
login details from `conf.py`. This is called by the request handler and is accessible using login details from `conf.py`. This is called by the request handler and is accessible using
the `conn` global variable. the `sql` method is also global to run queries
the `db` global variable. the `sql` method is also global to run queries
""" """
def __init__(self, host=None, user=None, password=None, ac_name=None, use_default = 0): def __init__(self, host=None, user=None, password=None, ac_name=None, use_default = 0):
self.host = host or frappe.conf.db_host or 'localhost' self.host = host or frappe.conf.db_host or 'localhost'
@@ -164,7 +164,7 @@ class Database:
self.transaction_writes += 1 self.transaction_writes += 1
if not frappe.flags.in_test and self.transaction_writes > 10000: if not frappe.flags.in_test and self.transaction_writes > 10000:
if self.auto_commit_on_many_writes: if self.auto_commit_on_many_writes:
frappe.conn.commit()
frappe.db.commit()
else: else:
frappe.msgprint('A very long query was encountered. If you are trying to import data, please do so using smaller files') frappe.msgprint('A very long query was encountered. If you are trying to import data, please do so using smaller files')
raise Exception, 'Bad Query!!! Too many writes' raise Exception, 'Bad Query!!! Too many writes'
@@ -402,7 +402,7 @@ class Database:
def touch(self, doctype, docname): def touch(self, doctype, docname):
from frappe.utils import now from frappe.utils import now
modified = now() modified = now()
frappe.conn.sql("""update `tab{doctype}` set `modified`=%s
frappe.db.sql("""update `tab{doctype}` set `modified`=%s
where name=%s""".format(doctype=doctype), (modified, docname)) where name=%s""".format(doctype=doctype), (modified, docname))
return modified return modified


@@ -483,10 +483,10 @@ class Database:
def count(self, dt, filters=None, debug=False): def count(self, dt, filters=None, debug=False):
if filters: if filters:
conditions, filters = self.build_conditions(filters) conditions, filters = self.build_conditions(filters)
return frappe.conn.sql("""select count(*)
return frappe.db.sql("""select count(*)
from `tab%s` where %s""" % (dt, conditions), filters, debug=debug)[0][0] from `tab%s` where %s""" % (dt, conditions), filters, debug=debug)[0][0]
else: else:
return frappe.conn.sql("""select count(*)
return frappe.db.sql("""select count(*)
from `tab%s`""" % (dt,))[0][0] from `tab%s`""" % (dt,))[0][0]
@@ -495,7 +495,7 @@ class Database:
from frappe.utils import now_datetime from frappe.utils import now_datetime
from dateutil.relativedelta import relativedelta from dateutil.relativedelta import relativedelta
return frappe.conn.sql("""select count(name) from `tab{doctype}`
return frappe.db.sql("""select count(name) from `tab{doctype}`
where creation >= %s""".format(doctype=doctype), where creation >= %s""".format(doctype=doctype),
now_datetime() - relativedelta(minutes=minutes))[0][0] now_datetime() - relativedelta(minutes=minutes))[0][0]
@@ -505,9 +505,9 @@ class Database:
def add_index(self, doctype, fields, index_name=None): def add_index(self, doctype, fields, index_name=None):
if not index_name: if not index_name:
index_name = "_".join(fields) + "_index" index_name = "_".join(fields) + "_index"
if not frappe.conn.sql("""show index from `tab%s` where Key_name="%s" """ % (doctype, index_name)):
frappe.conn.commit()
frappe.conn.sql("""alter table `tab%s`
if not frappe.db.sql("""show index from `tab%s` where Key_name="%s" """ % (doctype, index_name)):
frappe.db.commit()
frappe.db.sql("""alter table `tab%s`
add index %s(%s)""" % (doctype, index_name, ", ".join(fields))) add index %s(%s)""" % (doctype, index_name, ", ".join(fields)))


def close(self): def close(self):

+ 6
- 6
frappe/defaults.py Просмотреть файл

@@ -33,7 +33,7 @@ def get_restrictions(user=None):
def build_restrictions(user): def build_restrictions(user):
out = {} out = {}
for key, value in frappe.conn.sql("""select defkey, defvalue
for key, value in frappe.db.sql("""select defkey, defvalue
from tabDefaultValue where parent=%s and parenttype='Restriction'""", (user,)): from tabDefaultValue where parent=%s and parenttype='Restriction'""", (user,)):
out.setdefault(key, []) out.setdefault(key, [])
out[key].append(value) out[key].append(value)
@@ -69,10 +69,10 @@ def get_global_default(key):
# Common # Common


def set_default(key, value, parent, parenttype="Control Panel"): def set_default(key, value, parent, parenttype="Control Panel"):
if frappe.conn.sql("""select defkey from `tabDefaultValue` where
if frappe.db.sql("""select defkey from `tabDefaultValue` where
defkey=%s and parent=%s """, (key, parent)): defkey=%s and parent=%s """, (key, parent)):
# update # update
frappe.conn.sql("""update `tabDefaultValue` set defvalue=%s, parenttype=%s
frappe.db.sql("""update `tabDefaultValue` set defvalue=%s, parenttype=%s
where parent=%s and defkey=%s""", (value, parenttype, parent, key)) where parent=%s and defkey=%s""", (value, parenttype, parent, key))
_clear_cache(parent) _clear_cache(parent)
else: else:
@@ -125,14 +125,14 @@ def clear_default(key=None, value=None, parent=None, name=None, parenttype=None)
if not conditions: if not conditions:
raise Exception, "[clear_default] No key specified." raise Exception, "[clear_default] No key specified."
frappe.conn.sql("""delete from tabDefaultValue where %s""" % " and ".join(conditions), values)
frappe.db.sql("""delete from tabDefaultValue where %s""" % " and ".join(conditions), values)
_clear_cache(parent) _clear_cache(parent)
def get_defaults_for(parent="Control Panel"): def get_defaults_for(parent="Control Panel"):
"""get all defaults""" """get all defaults"""
defaults = frappe.cache().get_value("__defaults:" + parent) defaults = frappe.cache().get_value("__defaults:" + parent)
if not defaults: if not defaults:
res = frappe.conn.sql("""select defkey, defvalue from `tabDefaultValue`
res = frappe.db.sql("""select defkey, defvalue from `tabDefaultValue`
where parent = %s order by creation""", (parent,), as_dict=1) where parent = %s order by creation""", (parent,), as_dict=1)


defaults = frappe._dict({}) defaults = frappe._dict({})
@@ -162,6 +162,6 @@ def clear_cache(user=None):
if user: if user:
to_clear = [user] to_clear = [user]
elif frappe.flags.in_install_app!="frappe": elif frappe.flags.in_install_app!="frappe":
to_clear = frappe.conn.sql_list("select name from tabProfile")
to_clear = frappe.db.sql_list("select name from tabProfile")
for p in to_clear + common_keys: for p in to_clear + common_keys:
frappe.cache().delete_value("__defaults:" + p) frappe.cache().delete_value("__defaults:" + p)

+ 6
- 6
frappe/handler.py Просмотреть файл

@@ -25,7 +25,7 @@ def logout():
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def web_logout(): def web_logout():
frappe.local.login_manager.logout() frappe.local.login_manager.logout()
frappe.conn.commit()
frappe.db.commit()
frappe.repsond_as_web_page("Logged Out", """<p>You have been logged out.</p> frappe.repsond_as_web_page("Logged Out", """<p>You have been logged out.</p>
<p><a href='index'>Back to Home</a></p>""") <p><a href='index'>Back to Home</a></p>""")


@@ -48,7 +48,7 @@ def uploadfile():
except frappe.DuplicateEntryError, e: except frappe.DuplicateEntryError, e:
# ignore pass # ignore pass
ret = None ret = None
frappe.conn.rollback()
frappe.db.rollback()
else: else:
if frappe.form_dict.get('method'): if frappe.form_dict.get('method'):
ret = frappe.get_attr(frappe.form_dict.method)() ret = frappe.get_attr(frappe.form_dict.method)()
@@ -77,13 +77,13 @@ def handle():
except Exception, e: except Exception, e:
report_error(status_codes.get(e.__class__, 500)) report_error(status_codes.get(e.__class__, 500))
else: else:
if frappe.local.request.method in ("POST", "PUT") and frappe.conn:
frappe.conn.commit()
if frappe.local.request.method in ("POST", "PUT") and frappe.db:
frappe.db.commit()
build_response() build_response()


if frappe.conn:
frappe.conn.close()
if frappe.db:
frappe.db.close()
if frappe._memc: if frappe._memc:
frappe._memc.disconnect_all() frappe._memc.disconnect_all()




+ 10
- 10
frappe/installer.py Просмотреть файл

@@ -8,7 +8,7 @@ from __future__ import unicode_literals


import os, sys, json import os, sys, json
import frappe import frappe
import frappe.db
import frappe.database
import getpass import getpass


from frappe.model.db_schema import DbManager from frappe.model.db_schema import DbManager
@@ -21,11 +21,11 @@ def install_db(root_login="root", root_password=None, db_name=None, source_sql=N
make_conf(db_name, site_config=site_config) make_conf(db_name, site_config=site_config)
if reinstall: if reinstall:
frappe.connect(db_name=db_name) frappe.connect(db_name=db_name)
dbman = DbManager(frappe.local.conn)
dbman = DbManager(frappe.local.db)
dbman.create_database(db_name) dbman.create_database(db_name)


else: else:
frappe.local.conn = make_connection(root_login, root_password)
frappe.local.db = make_connection(root_login, root_password)
frappe.local.session = frappe._dict({'user':'Administrator'}) frappe.local.session = frappe._dict({'user':'Administrator'})
create_database_and_user(force, verbose) create_database_and_user(force, verbose)


@@ -39,7 +39,7 @@ def install_db(root_login="root", root_password=None, db_name=None, source_sql=N


def create_database_and_user(force, verbose): def create_database_and_user(force, verbose):
db_name = frappe.local.conf.db_name db_name = frappe.local.conf.db_name
dbman = DbManager(frappe.local.conn)
dbman = DbManager(frappe.local.db)
if force or (db_name not in dbman.get_database_list()): if force or (db_name not in dbman.get_database_list()):
dbman.delete_user(db_name) dbman.delete_user(db_name)
dbman.drop_database(db_name) dbman.drop_database(db_name)
@@ -57,10 +57,10 @@ def create_database_and_user(force, verbose):
if verbose: print "Granted privileges to user %s and database %s" % (db_name, db_name) if verbose: print "Granted privileges to user %s and database %s" % (db_name, db_name)
# close root connection # close root connection
frappe.conn.close()
frappe.db.close()


def create_auth_table(): def create_auth_table():
frappe.conn.sql_ddl("""create table if not exists __Auth (
frappe.db.sql_ddl("""create table if not exists __Auth (
`user` VARCHAR(180) NOT NULL PRIMARY KEY, `user` VARCHAR(180) NOT NULL PRIMARY KEY,
`password` VARCHAR(180) NOT NULL `password` VARCHAR(180) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8""") ) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
@@ -70,7 +70,7 @@ def import_db_from_sql(source_sql, verbose):
db_name = frappe.conf.db_name db_name = frappe.conf.db_name
if not source_sql: if not source_sql:
source_sql = os.path.join(os.path.dirname(frappe.__file__), 'data', 'Framework.sql') source_sql = os.path.join(os.path.dirname(frappe.__file__), 'data', 'Framework.sql')
DbManager(frappe.local.conn).restore_database(db_name, source_sql, db_name, frappe.conf.db_password)
DbManager(frappe.local.db).restore_database(db_name, source_sql, db_name, frappe.conf.db_password)
if verbose: print "Imported from database %s" % source_sql if verbose: print "Imported from database %s" % source_sql


def make_connection(root_login, root_password): def make_connection(root_login, root_password):
@@ -116,8 +116,8 @@ def add_to_installed_apps(app_name, rebuild_sitemap=True):
installed_apps = frappe.get_installed_apps() installed_apps = frappe.get_installed_apps()
if not app_name in installed_apps: if not app_name in installed_apps:
installed_apps.append(app_name) installed_apps.append(app_name)
frappe.conn.set_global("installed_apps", json.dumps(installed_apps))
frappe.conn.commit()
frappe.db.set_global("installed_apps", json.dumps(installed_apps))
frappe.db.commit()


if rebuild_sitemap: if rebuild_sitemap:
from frappe.website.doctype.website_template.website_template import rebuild_website_template from frappe.website.doctype.website_template.website_template import rebuild_website_template
@@ -133,7 +133,7 @@ def set_all_patches_as_completed(app):
"doctype": "Patch Log", "doctype": "Patch Log",
"patch": patch "patch": patch
}).insert() }).insert()
frappe.conn.commit()
frappe.db.commit()
def make_conf(db_name=None, db_password=None, site_config=None): def make_conf(db_name=None, db_password=None, site_config=None):
site = frappe.local.site site = frappe.local.site


+ 13
- 13
frappe/model/__init__.py Просмотреть файл

@@ -46,7 +46,7 @@ def copytables(srctype, src, srcfield, tartype, tar, tarfield, srcfields, tarfie


def db_exists(dt, dn): def db_exists(dt, dn):
import frappe import frappe
return frappe.conn.exists(dt, dn)
return frappe.db.exists(dt, dn)


def delete_fields(args_dict, delete=0): def delete_fields(args_dict, delete=0):
""" """
@@ -62,7 +62,7 @@ def delete_fields(args_dict, delete=0):
fields = args_dict[dt] fields = args_dict[dt]
if not fields: continue if not fields: continue
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabDocField` DELETE FROM `tabDocField`
WHERE parent=%s AND fieldname IN (%s) WHERE parent=%s AND fieldname IN (%s)
""" % ('%s', ", ".join(['"' + f + '"' for f in fields])), dt) """ % ('%s', ", ".join(['"' + f + '"' for f in fields])), dt)
@@ -70,20 +70,20 @@ def delete_fields(args_dict, delete=0):
# Delete the data / column only if delete is specified # Delete the data / column only if delete is specified
if not delete: continue if not delete: continue
is_single = frappe.conn.sql("select issingle from tabDocType where name = '%s'" % dt)
is_single = frappe.db.sql("select issingle from tabDocType where name = '%s'" % dt)
is_single = is_single and frappe.utils.cint(is_single[0][0]) or 0 is_single = is_single and frappe.utils.cint(is_single[0][0]) or 0
if is_single: if is_single:
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabSingles` DELETE FROM `tabSingles`
WHERE doctype=%s AND field IN (%s) WHERE doctype=%s AND field IN (%s)
""" % ('%s', ", ".join(['"' + f + '"' for f in fields])), dt) """ % ('%s', ", ".join(['"' + f + '"' for f in fields])), dt)
else: else:
existing_fields = frappe.conn.sql("desc `tab%s`" % dt)
existing_fields = frappe.db.sql("desc `tab%s`" % dt)
existing_fields = existing_fields and [e[0] for e in existing_fields] or [] existing_fields = existing_fields and [e[0] for e in existing_fields] or []
query = "ALTER TABLE `tab%s` " % dt + \ query = "ALTER TABLE `tab%s` " % dt + \
", ".join(["DROP COLUMN `%s`" % f for f in fields if f in existing_fields]) ", ".join(["DROP COLUMN `%s`" % f for f in fields if f in existing_fields])
frappe.conn.commit()
frappe.conn.sql(query)
frappe.db.commit()
frappe.db.sql(query)


def rename_field(doctype, old_fieldname, new_fieldname): def rename_field(doctype, old_fieldname, new_fieldname):
"""This functions assumes that doctype is already synced""" """This functions assumes that doctype is already synced"""
@@ -96,28 +96,28 @@ def rename_field(doctype, old_fieldname, new_fieldname):
if new_field.fieldtype == "Table": if new_field.fieldtype == "Table":
# change parentfield of table mentioned in options # change parentfield of table mentioned in options
frappe.conn.sql("""update `tab%s` set parentfield=%s
frappe.db.sql("""update `tab%s` set parentfield=%s
where parentfield=%s""" % (new_field.options.split("\n")[0], "%s", "%s"), where parentfield=%s""" % (new_field.options.split("\n")[0], "%s", "%s"),
(new_fieldname, old_fieldname)) (new_fieldname, old_fieldname))
elif new_field.fieldtype not in no_value_fields: elif new_field.fieldtype not in no_value_fields:
if doctype_list[0].issingle: if doctype_list[0].issingle:
frappe.conn.sql("""update `tabSingles` set field=%s
frappe.db.sql("""update `tabSingles` set field=%s
where doctype=%s and field=%s""", where doctype=%s and field=%s""",
(new_fieldname, doctype, old_fieldname)) (new_fieldname, doctype, old_fieldname))
else: else:
# copy field value # copy field value
frappe.conn.sql("""update `tab%s` set `%s`=`%s`""" % \
frappe.db.sql("""update `tab%s` set `%s`=`%s`""" % \
(doctype, new_fieldname, old_fieldname)) (doctype, new_fieldname, old_fieldname))
# update in property setter # update in property setter
frappe.conn.sql("""update `tabProperty Setter` set field_name = %s
frappe.db.sql("""update `tabProperty Setter` set field_name = %s
where doc_type=%s and field_name=%s""", (new_fieldname, doctype, old_fieldname)) where doc_type=%s and field_name=%s""", (new_fieldname, doctype, old_fieldname))
update_users_report_view_settings(doctype, old_fieldname) update_users_report_view_settings(doctype, old_fieldname)
def update_users_report_view_settings(doctype, ref_fieldname): def update_users_report_view_settings(doctype, ref_fieldname):
import json import json
user_report_cols = frappe.conn.sql("""select defkey, defvalue from `tabDefaultValue` where
user_report_cols = frappe.db.sql("""select defkey, defvalue from `tabDefaultValue` where
defkey like '_list_settings:%'""") defkey like '_list_settings:%'""")
for key, value in user_report_cols: for key, value in user_report_cols:
new_columns = [] new_columns = []
@@ -127,5 +127,5 @@ def update_users_report_view_settings(doctype, ref_fieldname):
new_columns.append([field, field_doctype]) new_columns.append([field, field_doctype])
columns_modified=True columns_modified=True
if columns_modified: if columns_modified:
frappe.conn.sql("""update `tabDefaultValue` set defvalue=%s
frappe.db.sql("""update `tabDefaultValue` set defvalue=%s
where defkey=%s""" % ('%s', '%s'), (json.dumps(new_columns), key)) where defkey=%s""" % ('%s', '%s'), (json.dumps(new_columns), key))

+ 7
- 7
frappe/model/bean.py Просмотреть файл

@@ -37,7 +37,7 @@ class Bean:
dn = dt dn = dt
if dt and dn: if dt and dn:
if isinstance(dn, dict): if isinstance(dn, dict):
dn = frappe.conn.get_value(dt, dn, "name")
dn = frappe.db.get_value(dt, dn, "name")
if dn is None: if dn is None:
raise frappe.DoesNotExistError raise frappe.DoesNotExistError
@@ -120,13 +120,13 @@ class Bean:
conflict = False conflict = False
if not cint(self.doc.fields.get('__islocal')): if not cint(self.doc.fields.get('__islocal')):
if is_single(self.doc.doctype): if is_single(self.doc.doctype):
modified = frappe.conn.get_value(self.doc.doctype, self.doc.name, "modified")
modified = frappe.db.get_value(self.doc.doctype, self.doc.name, "modified")
if isinstance(modified, list): if isinstance(modified, list):
modified = modified[0] modified = modified[0]
if cstr(modified) and cstr(modified) != cstr(self.doc.modified): if cstr(modified) and cstr(modified) != cstr(self.doc.modified):
conflict = True conflict = True
else: else:
tmp = frappe.conn.sql("""select modified, docstatus from `tab%s`
tmp = frappe.db.sql("""select modified, docstatus from `tab%s`
where name="%s" for update""" where name="%s" for update"""
% (self.doc.doctype, self.doc.name), as_dict=True) % (self.doc.doctype, self.doc.name), as_dict=True)


@@ -265,7 +265,7 @@ class Bean:
return self.save() return self.save()
def insert_or_update(self): def insert_or_update(self):
if self.doc.name and frappe.conn.exists(self.doc.doctype, self.doc.name):
if self.doc.name and frappe.db.exists(self.doc.doctype, self.doc.name):
return self.save() return self.save()
else: else:
return self.insert() return self.insert()
@@ -371,7 +371,7 @@ class Bean:
frappe.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name)) frappe.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))


# prompt if cancelled # prompt if cancelled
if frappe.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
if frappe.db.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
frappe.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name)) frappe.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
frappe.errprint(frappe.utils.get_traceback()) frappe.errprint(frappe.utils.get_traceback())
raise raise
@@ -396,11 +396,11 @@ class Bean:
if dt[0] not in self.ignore_children_type: if dt[0] not in self.ignore_children_type:
cnames = child_map.get(dt[0]) or [] cnames = child_map.get(dt[0]) or []
if cnames: if cnames:
frappe.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
frappe.db.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))), name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
tuple([self.doc.name, self.doc.doctype] + cnames)) tuple([self.doc.name, self.doc.doctype] + cnames))
else: else:
frappe.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
frappe.db.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
% (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype)) % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
def delete(self): def delete(self):


+ 1
- 1
frappe/model/controller.py Просмотреть файл

@@ -95,7 +95,7 @@ class DocListController(object):
if not hasattr(self, "_precision"): if not hasattr(self, "_precision"):
self._precision = frappe._dict({ self._precision = frappe._dict({
"default": cint(frappe.conn.get_default("float_precision")) or 3,
"default": cint(frappe.db.get_default("float_precision")) or 3,
"options": {} "options": {}
}) })


+ 2
- 2
frappe/model/create_new.py Просмотреть файл

@@ -48,8 +48,8 @@ def get_new_doc(doctype, parent_doc = None, parentfield = None):
if parent_doc: if parent_doc:
ref_docname = parent_doc.fields[ref_fieldname] ref_docname = parent_doc.fields[ref_fieldname]
else: else:
ref_docname = frappe.conn.get_default(ref_fieldname)
doc.fields[d.fieldname] = frappe.conn.get_value(d.default[1:],
ref_docname = frappe.db.get_default(ref_fieldname)
doc.fields[d.fieldname] = frappe.db.get_value(d.default[1:],
ref_docname, d.fieldname) ref_docname, d.fieldname)


else: else:


+ 44
- 44
frappe/model/db_schema.py Просмотреть файл

@@ -76,7 +76,7 @@ class DbTable:
if t: add_text += ',\n'.join(self.get_index_definitions()) + ',\n' if t: add_text += ',\n'.join(self.get_index_definitions()) + ',\n'
# create table # create table
frappe.conn.sql("""create table `%s` (
frappe.db.sql("""create table `%s` (
name varchar(120) not null primary key, name varchar(120) not null primary key,
creation datetime, creation datetime,
modified datetime, modified datetime,
@@ -95,10 +95,10 @@ class DbTable:
""" """
get columns from docfields and custom fields get columns from docfields and custom fields
""" """
fl = frappe.conn.sql("SELECT * FROM tabDocField WHERE parent = '%s'" % self.doctype, as_dict = 1)
fl = frappe.db.sql("SELECT * FROM tabDocField WHERE parent = '%s'" % self.doctype, as_dict = 1)
try: try:
custom_fl = frappe.conn.sql("""\
custom_fl = frappe.db.sql("""\
SELECT * FROM `tabCustom Field` SELECT * FROM `tabCustom Field`
WHERE dt = %s AND docstatus < 2""", (self.doctype,), as_dict=1) WHERE dt = %s AND docstatus < 2""", (self.doctype,), as_dict=1)
if custom_fl: fl += custom_fl if custom_fl: fl += custom_fl
@@ -112,7 +112,7 @@ class DbTable:
f.get('search_index'), f.get('options')) f.get('search_index'), f.get('options'))
def get_columns_from_db(self): def get_columns_from_db(self):
self.show_columns = frappe.conn.sql("desc `%s`" % self.name)
self.show_columns = frappe.db.sql("desc `%s`" % self.name)
for c in self.show_columns: for c in self.show_columns:
self.current_columns[c[0]] = {'name': c[0], 'type':c[1], 'index':c[3], 'default':c[4]} self.current_columns[c[0]] = {'name': c[0], 'type':c[1], 'index':c[3], 'default':c[4]}
@@ -138,7 +138,7 @@ class DbTable:
# GET foreign keys # GET foreign keys
def get_foreign_keys(self): def get_foreign_keys(self):
fk_list = [] fk_list = []
txt = frappe.conn.sql("show create table `%s`" % self.name)[0][1]
txt = frappe.db.sql("show create table `%s`" % self.name)[0][1]
for line in txt.split('\n'): for line in txt.split('\n'):
if line.strip().startswith('CONSTRAINT') and line.find('FOREIGN')!=-1: if line.strip().startswith('CONSTRAINT') and line.find('FOREIGN')!=-1:
try: try:
@@ -162,12 +162,12 @@ class DbTable:
# drop # drop
for col in self.drop_foreign_key: for col in self.drop_foreign_key:
frappe.conn.sql("set foreign_key_checks=0")
frappe.conn.sql("alter table `%s` drop foreign key `%s`" % (self.name, fk_dict[col.fieldname]))
frappe.conn.sql("set foreign_key_checks=1")
frappe.db.sql("set foreign_key_checks=0")
frappe.db.sql("alter table `%s` drop foreign key `%s`" % (self.name, fk_dict[col.fieldname]))
frappe.db.sql("set foreign_key_checks=1")
def sync(self): def sync(self):
if not self.name in DbManager(frappe.conn).get_tables_list(frappe.conn.cur_db_name):
if not self.name in DbManager(frappe.db).get_tables_list(frappe.db.cur_db_name):
self.create() self.create()
else: else:
self.alter() self.alter()
@@ -178,24 +178,24 @@ class DbTable:
col.check(self.current_columns.get(col.fieldname, None)) col.check(self.current_columns.get(col.fieldname, None))


for col in self.add_column: for col in self.add_column:
frappe.conn.sql("alter table `%s` add column `%s` %s" % (self.name, col.fieldname, col.get_definition()))
frappe.db.sql("alter table `%s` add column `%s` %s" % (self.name, col.fieldname, col.get_definition()))


for col in self.change_type: for col in self.change_type:
frappe.conn.sql("alter table `%s` change `%s` `%s` %s" % (self.name, col.fieldname, col.fieldname, col.get_definition()))
frappe.db.sql("alter table `%s` change `%s` `%s` %s" % (self.name, col.fieldname, col.fieldname, col.get_definition()))


for col in self.add_index: for col in self.add_index:
# if index key not exists # if index key not exists
if not frappe.conn.sql("show index from `%s` where key_name = '%s'" % (self.name, col.fieldname)):
frappe.conn.sql("alter table `%s` add index `%s`(`%s`)" % (self.name, col.fieldname, col.fieldname))
if not frappe.db.sql("show index from `%s` where key_name = '%s'" % (self.name, col.fieldname)):
frappe.db.sql("alter table `%s` add index `%s`(`%s`)" % (self.name, col.fieldname, col.fieldname))


for col in self.drop_index: for col in self.drop_index:
if col.fieldname != 'name': # primary key if col.fieldname != 'name': # primary key
# if index key exists # if index key exists
if frappe.conn.sql("show index from `%s` where key_name = '%s'" % (self.name, col.fieldname)):
frappe.conn.sql("alter table `%s` drop index `%s`" % (self.name, col.fieldname))
if frappe.db.sql("show index from `%s` where key_name = '%s'" % (self.name, col.fieldname)):
frappe.db.sql("alter table `%s` drop index `%s`" % (self.name, col.fieldname))


for col in self.set_default: for col in self.set_default:
frappe.conn.sql("alter table `%s` alter column `%s` set default %s" % (self.name, col.fieldname, '%s'), (col.default,))
frappe.db.sql("alter table `%s` alter column `%s` set default %s" % (self.name, col.fieldname, '%s'), (col.default,))


class DbColumn: class DbColumn:
def __init__(self, table, fieldname, fieldtype, length, default, set_index, options): def __init__(self, table, fieldname, fieldtype, length, default, set_index, options):
@@ -265,48 +265,48 @@ class DbManager:
1. Setter and getter for different mysql variables. 1. Setter and getter for different mysql variables.
2. Setter and getter for mysql variables at global level?? 2. Setter and getter for mysql variables at global level??
""" """
def __init__(self,conn):
def __init__(self,db):
""" """
Pass root_conn here for access to all databases. Pass root_conn here for access to all databases.
""" """
if conn:
self.conn = conn
if db:
self.db = db


def get_variables(self,regex): def get_variables(self,regex):
""" """
Get variables that match the passed pattern regex Get variables that match the passed pattern regex
""" """
return list(self.conn.sql("SHOW VARIABLES LIKE '%s'"%regex))
return list(self.db.sql("SHOW VARIABLES LIKE '%s'"%regex))
def get_table_schema(self,table): def get_table_schema(self,table):
""" """
Just returns the output of Desc tables. Just returns the output of Desc tables.
""" """
return list(self.conn.sql("DESC `%s`"%table))
return list(self.db.sql("DESC `%s`"%table))
def get_tables_list(self,target=None): def get_tables_list(self,target=None):
"""get list of tables""" """get list of tables"""
if target: if target:
self.conn.use(target)
self.db.use(target)
return [t[0] for t in self.conn.sql("SHOW TABLES")]
return [t[0] for t in self.db.sql("SHOW TABLES")]


def create_user(self,user,password): def create_user(self,user,password):
#Create user if it doesn't exist. #Create user if it doesn't exist.
try: try:
if password: if password:
self.conn.sql("CREATE USER '%s'@'localhost' IDENTIFIED BY '%s';" % (user[:16], password))
self.db.sql("CREATE USER '%s'@'localhost' IDENTIFIED BY '%s';" % (user[:16], password))
else: else:
self.conn.sql("CREATE USER '%s'@'localhost';"%user[:16])
self.db.sql("CREATE USER '%s'@'localhost';"%user[:16])
except Exception, e: except Exception, e:
raise raise


def delete_user(self,target): def delete_user(self,target):
# delete user if exists # delete user if exists
try: try:
self.conn.sql("DROP USER '%s'@'localhost';" % target)
self.db.sql("DROP USER '%s'@'localhost';" % target)
except Exception, e: except Exception, e:
if e.args[0]==1396: if e.args[0]==1396:
pass pass
@@ -317,39 +317,39 @@ class DbManager:
if target in self.get_database_list(): if target in self.get_database_list():
self.drop_database(target) self.drop_database(target)


self.conn.sql("CREATE DATABASE IF NOT EXISTS `%s` ;" % target)
self.db.sql("CREATE DATABASE IF NOT EXISTS `%s` ;" % target)


def drop_database(self,target): def drop_database(self,target):
try: try:
self.conn.sql("DROP DATABASE IF EXISTS `%s`;"%target)
self.db.sql("DROP DATABASE IF EXISTS `%s`;"%target)
except Exception,e: except Exception,e:
raise raise


def grant_all_privileges(self,target,user): def grant_all_privileges(self,target,user):
try: try:
self.conn.sql("GRANT ALL PRIVILEGES ON `%s`.* TO '%s'@'localhost';" % (target, user))
self.db.sql("GRANT ALL PRIVILEGES ON `%s`.* TO '%s'@'localhost';" % (target, user))
except Exception,e: except Exception,e:
raise raise


def grant_select_privilges(self,db,table,user): def grant_select_privilges(self,db,table,user):
try: try:
if table: if table:
self.conn.sql("GRANT SELECT ON %s.%s to '%s'@'localhost';" % (db,table,user))
self.db.sql("GRANT SELECT ON %s.%s to '%s'@'localhost';" % (db,table,user))
else: else:
self.conn.sql("GRANT SELECT ON %s.* to '%s'@'localhost';" % (db,user))
self.db.sql("GRANT SELECT ON %s.* to '%s'@'localhost';" % (db,user))
except Exception,e: except Exception,e:
raise raise


def flush_privileges(self): def flush_privileges(self):
try: try:
self.conn.sql("FLUSH PRIVILEGES")
self.db.sql("FLUSH PRIVILEGES")
except Exception,e: except Exception,e:
raise raise




def get_database_list(self): def get_database_list(self):
"""get list of databases""" """get list of databases"""
return [d[0] for d in self.conn.sql("SHOW DATABASES")]
return [d[0] for d in self.db.sql("SHOW DATABASES")]


def restore_database(self,target,source,user,password): def restore_database(self,target,source,user,password):
from frappe.utils import make_esc from frappe.utils import make_esc
@@ -366,14 +366,14 @@ class DbManager:
if not table_name in self.get_tables_list(): if not table_name in self.get_tables_list():
return return
try: try:
self.conn.sql("DROP TABLE IF EXISTS %s "%(table_name))
self.db.sql("DROP TABLE IF EXISTS %s "%(table_name))
except Exception,e: except Exception,e:
raise raise


def set_transaction_isolation_level(self,scope='SESSION',level='READ COMMITTED'): def set_transaction_isolation_level(self,scope='SESSION',level='READ COMMITTED'):
#Sets the transaction isolation level. scope = global/session #Sets the transaction isolation level. scope = global/session
try: try:
self.conn.sql("SET %s TRANSACTION ISOLATION LEVEL %s"%(scope,level))
self.db.sql("SET %s TRANSACTION ISOLATION LEVEL %s"%(scope,level))
except Exception,e: except Exception,e:
raise raise


@@ -393,20 +393,20 @@ def updatedb(dt):
* updates columns * updates columns
* updates indices * updates indices
""" """
res = frappe.conn.sql("select ifnull(issingle, 0) from tabDocType where name=%s", (dt,))
res = frappe.db.sql("select ifnull(issingle, 0) from tabDocType where name=%s", (dt,))
if not res: if not res:
raise Exception, 'Wrong doctype "%s" in updatedb' % dt raise Exception, 'Wrong doctype "%s" in updatedb' % dt
if not res[0][0]: if not res[0][0]:
frappe.conn.commit()
frappe.db.commit()
tab = DbTable(dt, 'tab') tab = DbTable(dt, 'tab')
tab.sync() tab.sync()
frappe.conn.begin()
frappe.db.begin()


def remove_all_foreign_keys(): def remove_all_foreign_keys():
frappe.conn.sql("set foreign_key_checks = 0")
frappe.conn.commit()
for t in frappe.conn.sql("select name from tabDocType where ifnull(issingle,0)=0"):
frappe.db.sql("set foreign_key_checks = 0")
frappe.db.commit()
for t in frappe.db.sql("select name from tabDocType where ifnull(issingle,0)=0"):
dbtab = frappe.model.db_schema.DbTable(t[0]) dbtab = frappe.model.db_schema.DbTable(t[0])
try: try:
fklist = dbtab.get_foreign_keys() fklist = dbtab.get_foreign_keys()
@@ -417,7 +417,7 @@ def remove_all_foreign_keys():
raise raise
for f in fklist: for f in fklist:
frappe.conn.sql("alter table `tab%s` drop foreign key `%s`" % (t[0], f[1]))
frappe.db.sql("alter table `tab%s` drop foreign key `%s`" % (t[0], f[1]))


def get_definition(fieldtype): def get_definition(fieldtype):
d = type_map.get(fieldtype.lower()) d = type_map.get(fieldtype.lower())
@@ -432,7 +432,7 @@ def get_definition(fieldtype):




def add_column(doctype, column_name, fieldtype): def add_column(doctype, column_name, fieldtype):
frappe.conn.commit()
frappe.conn.sql("alter table `tab%s` add column %s %s" % (doctype,
frappe.db.commit()
frappe.db.sql("alter table `tab%s` add column %s %s" % (doctype,
column_name, get_definition(fieldtype))) column_name, get_definition(fieldtype)))

+ 5
- 5
frappe/model/delete_doc.py Просмотреть файл

@@ -24,7 +24,7 @@ def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes
frappe.msgprint('Nothing to delete!', raise_exception =1) frappe.msgprint('Nothing to delete!', raise_exception =1)


# already deleted..? # already deleted..?
if not frappe.conn.exists(doctype, name):
if not frappe.db.exists(doctype, name):
return return


if not for_reload: if not for_reload:
@@ -37,10 +37,10 @@ def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes
try: try:
tablefields = frappe.model.meta.get_table_fields(doctype) tablefields = frappe.model.meta.get_table_fields(doctype)
frappe.conn.sql("delete from `tab%s` where name=%s" % (doctype, "%s"), (name,))
frappe.db.sql("delete from `tab%s` where name=%s" % (doctype, "%s"), (name,))
for t in tablefields: for t in tablefields:
if t[0] not in ignore_doctypes: if t[0] not in ignore_doctypes:
frappe.conn.sql("delete from `tab%s` where parent = %s" % (t[0], '%s'), (name,))
frappe.db.sql("delete from `tab%s` where parent = %s" % (t[0], '%s'), (name,))
except Exception, e: except Exception, e:
if e.args[0]==1451: if e.args[0]==1451:
frappe.msgprint("Cannot delete %s '%s' as it is referenced in another record. You must delete the referred record first" % (doctype, name)) frappe.msgprint("Cannot delete %s '%s' as it is referenced in another record. You must delete the referred record first" % (doctype, name))
@@ -61,7 +61,7 @@ def check_permission_and_not_submitted(doctype, name, ignore_permissions=False):
frappe.msgprint(_("User not allowed to delete."), raise_exception=True) frappe.msgprint(_("User not allowed to delete."), raise_exception=True)


# check if submitted # check if submitted
if frappe.conn.get_value(doctype, name, "docstatus") == 1:
if frappe.db.get_value(doctype, name, "docstatus") == 1:
frappe.msgprint(_("Submitted Record cannot be deleted")+": "+name+"("+doctype+")", frappe.msgprint(_("Submitted Record cannot be deleted")+": "+name+"("+doctype+")",
raise_exception=True) raise_exception=True)


@@ -86,7 +86,7 @@ def check_if_doc_is_linked(dt, dn, method="Delete"):


for link_dt, link_field, issingle in link_fields: for link_dt, link_field, issingle in link_fields:
if not issingle: if not issingle:
item = frappe.conn.get_value(link_dt, {link_field:dn},
item = frappe.db.get_value(link_dt, {link_field:dn},
["name", "parent", "parenttype", "docstatus"], as_dict=True) ["name", "parent", "parenttype", "docstatus"], as_dict=True)
if item and item.parent != dn and (method=="Delete" or if item and item.parent != dn and (method=="Delete" or


+ 26
- 26
frappe/model/doc.py Просмотреть файл

@@ -59,7 +59,7 @@ class Document:
fielddata = doctype fielddata = doctype
doctype = None doctype = None
if doctype and isinstance(name, dict): if doctype and isinstance(name, dict):
name = frappe.conn.get_value(doctype, name, "name") or None
name = frappe.db.get_value(doctype, name, "name") or None
if fielddata: if fielddata:
self.fields = frappe._dict(fielddata) self.fields = frappe._dict(fielddata)
@@ -131,7 +131,7 @@ class Document:
self._loadsingle() self._loadsingle()
else: else:
try: try:
dataset = frappe.conn.sql('select * from `tab%s` where name="%s"' % (self.doctype, self.name.replace('"', '\"')))
dataset = frappe.db.sql('select * from `tab%s` where name="%s"' % (self.doctype, self.name.replace('"', '\"')))
except frappe.SQLError, e: except frappe.SQLError, e:
if e.args[0]==1146: if e.args[0]==1146:
dataset = None dataset = None
@@ -140,7 +140,7 @@ class Document:


if not dataset: if not dataset:
raise frappe.DoesNotExistError, '[WNF] %s %s does not exist' % (self.doctype, self.name) raise frappe.DoesNotExistError, '[WNF] %s %s does not exist' % (self.doctype, self.name)
self._load_values(dataset[0], frappe.conn.get_description())
self._load_values(dataset[0], frappe.db.get_description())


def is_new(self): def is_new(self):
return self.fields.get("__islocal") return self.fields.get("__islocal")
@@ -150,13 +150,13 @@ class Document:
del self.fields['__islocal'] del self.fields['__islocal']
for i in range(len(description)): for i in range(len(description)):
v = data[i] v = data[i]
self.fields[description[i][0]] = frappe.conn.convert_to_simple_type(v)
self.fields[description[i][0]] = frappe.db.convert_to_simple_type(v)


def _merge_values(self, data, description): def _merge_values(self, data, description):
for i in range(len(description)): for i in range(len(description)):
v = data[i] v = data[i]
if v: # only if value, over-write if v: # only if value, over-write
self.fields[description[i][0]] = frappe.conn.convert_to_simple_type(v)
self.fields[description[i][0]] = frappe.db.convert_to_simple_type(v)
def _loadsingle(self): def _loadsingle(self):
self.name = self.doctype self.name = self.doctype
@@ -223,7 +223,7 @@ class Document:
if r: if r:
return r return r
else: else:
if not frappe.conn.exists(self.doctype, self.name):
if not frappe.db.exists(self.doctype, self.name):
frappe.msgprint(frappe._("Cannot update a non-exiting record, try inserting.") + ": " + self.doctype + " / " + self.name, frappe.msgprint(frappe._("Cannot update a non-exiting record, try inserting.") + ": " + self.doctype + " / " + self.name,
raise_exception=1) raise_exception=1)
@@ -238,7 +238,7 @@ class Document:
def _get_amended_name(self): def _get_amended_name(self):
am_id = 1 am_id = 1
am_prefix = self.amended_from am_prefix = self.amended_from
if frappe.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
if frappe.db.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
am_id = cint(self.amended_from.split('-')[-1]) + 1 am_id = cint(self.amended_from.split('-')[-1]) + 1
am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
@@ -307,7 +307,7 @@ class Document:
def set(self, key, value): def set(self, key, value):
self.modified = now() self.modified = now()
self.modified_by = frappe.session["user"] self.modified_by = frappe.session["user"]
frappe.conn.set_value(self.doctype, self.name, key, value, self.modified, self.modified_by)
frappe.db.set_value(self.doctype, self.name, key, value, self.modified, self.modified_by)
self.fields[key] = value self.fields[key] = value
def _insert(self, make_autoname=True, keep_timestamps=False): def _insert(self, make_autoname=True, keep_timestamps=False):
@@ -328,7 +328,7 @@ class Document:
else: else:
self.modified = now() self.modified = now()
frappe.conn.sql("insert into `tab%(doctype)s`" % self.fields \
frappe.db.sql("insert into `tab%(doctype)s`" % self.fields \
+ """ (name, owner, creation, modified, modified_by) + """ (name, owner, creation, modified, modified_by)
values (%(name)s, %(owner)s, %(creation)s, %(modified)s, values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
%(modified_by)s)""", self.fields) %(modified_by)s)""", self.fields)
@@ -337,7 +337,7 @@ class Document:
self.modified = now() self.modified = now()
update_str, values = [], [] update_str, values = [], []
frappe.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
frappe.db.sql("delete from tabSingles where doctype='%s'" % self.doctype)
for f in self.fields.keys(): for f in self.fields.keys():
if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\ if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
and (not f.startswith('__')): # fields not saved and (not f.startswith('__')): # fields not saved
@@ -355,7 +355,7 @@ class Document:
values.append(self.doctype) values.append(self.doctype)
values.append(f) values.append(f)
values.append(self.fields[f]) values.append(self.fields[f])
frappe.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
frappe.db.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)


def validate_links(self, link_list): def validate_links(self, link_list):
err_list = [] err_list = []
@@ -391,7 +391,7 @@ class Document:
dt = dt[5:] dt = dt[5:]
if '\n' in dt: if '\n' in dt:
dt = dt.split('\n')[0] dt = dt.split('\n')[0]
tmp = frappe.conn.sql("""SELECT name FROM `tab%s`
tmp = frappe.db.sql("""SELECT name FROM `tab%s`
WHERE name = %s""" % (dt, '%s'), (dn,)) WHERE name = %s""" % (dt, '%s'), (dn,))
return tmp and tmp[0][0] or ''# match case return tmp and tmp[0][0] or ''# match case
@@ -423,7 +423,7 @@ class Document:
update_str.append("`%s`=%s" % (f, '%s')) update_str.append("`%s`=%s" % (f, '%s'))
if values: if values:
values.append(self.name) values.append(self.name)
r = frappe.conn.sql("update `tab%s` set %s where name=%s" % \
r = frappe.db.sql("update `tab%s` set %s where name=%s" % \
(self.doctype, ', '.join(update_str), "%s"), values) (self.doctype, ', '.join(update_str), "%s"), values)
def get_valid_fields(self): def get_valid_fields(self):
@@ -443,13 +443,13 @@ class Document:
"fieldtype": ["not in", frappe.model.no_value_fields]}) "fieldtype": ["not in", frappe.model.no_value_fields]})
else: else:
valid_fields_map[self.doctype] = \ valid_fields_map[self.doctype] = \
frappe.conn.get_table_columns(self.doctype)
frappe.db.get_table_columns(self.doctype)
return valid_fields_map.get(self.doctype) return valid_fields_map.get(self.doctype)


def get_meta(self): def get_meta(self):
if not self._meta: if not self._meta:
self._meta = frappe.conn.get_value("DocType", self.doctype, ["autoname", "issingle",
self._meta = frappe.db.get_value("DocType", self.doctype, ["autoname", "issingle",
"istable", "name_case"], as_dict=True) or frappe._dict() "istable", "name_case"], as_dict=True) or frappe._dict()
return self._meta return self._meta


@@ -457,7 +457,7 @@ class Document:
def update_parentinfo(self): def update_parentinfo(self):
"""update parent type and parent field, if not explicitly specified""" """update parent type and parent field, if not explicitly specified"""


tmp = frappe.conn.sql("""select parent, fieldname from tabDocField
tmp = frappe.db.sql("""select parent, fieldname from tabDocField
where fieldtype='Table' and options=%s""", (self.doctype,)) where fieldtype='Table' and options=%s""", (self.doctype,))
if len(tmp)==0: if len(tmp)==0:
@@ -474,7 +474,7 @@ class Document:


def set_idx(self): def set_idx(self):
"""set idx""" """set idx"""
self.idx = (frappe.conn.sql("""select max(idx) from `tab%s`
self.idx = (frappe.db.sql("""select max(idx) from `tab%s`
where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'), where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
(self.parent, self.parentfield))[0][0] or 0) + 1 (self.parent, self.parentfield))[0][0] or 0) + 1
@@ -500,7 +500,7 @@ class Document:
doclist = filter(lambda d: d.name not in delete_list, doclist) doclist = filter(lambda d: d.name not in delete_list, doclist)
# delete from db # delete from db
frappe.conn.sql("""\
frappe.db.sql("""\
delete from `tab%s` delete from `tab%s`
where parent=%s and parenttype=%s""" where parent=%s and parenttype=%s"""
% (table_list[0].doctype, '%s', '%s'), % (table_list[0].doctype, '%s', '%s'),
@@ -604,15 +604,15 @@ def make_autoname(key, doctype=''):


def getseries(key, digits, doctype=''): def getseries(key, digits, doctype=''):
# series created ? # series created ?
current = frappe.conn.sql("select `current` from `tabSeries` where name=%s for update", (key,))
current = frappe.db.sql("select `current` from `tabSeries` where name=%s for update", (key,))
if current and current[0][0] is not None: if current and current[0][0] is not None:
current = current[0][0] current = current[0][0]
# yes, update it # yes, update it
frappe.conn.sql("update tabSeries set current = current+1 where name=%s", (key,))
frappe.db.sql("update tabSeries set current = current+1 where name=%s", (key,))
current = cint(current) + 1 current = cint(current) + 1
else: else:
# no, create it # no, create it
frappe.conn.sql("insert into tabSeries (name, current) values (%s, 1)", (key,))
frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (key,))
current = 1 current = 1
return ('%0'+str(digits)+'d') % current return ('%0'+str(digits)+'d') % current


@@ -630,9 +630,9 @@ def getchildren(name, childtype, field='', parenttype='', from_doctype=0):
condition += ' and parenttype=%s ' condition += ' and parenttype=%s '
values.append(parenttype) values.append(parenttype)


dataset = frappe.conn.sql("""select * from `tab%s` where parent=%s %s order by idx""" \
dataset = frappe.db.sql("""select * from `tab%s` where parent=%s %s order by idx""" \
% (childtype, "%s", condition), tuple([name]+values)) % (childtype, "%s", condition), tuple([name]+values))
desc = frappe.conn.get_description()
desc = frappe.db.get_description()


l = DocList() l = DocList()
@@ -650,7 +650,7 @@ def check_page_perm(doc):
if doc.publish: if doc.publish:
return return


if not frappe.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", (doc.name,)):
if not frappe.db.sql("select name from `tabPage Role` where parent=%s and role='Guest'", (doc.name,)):
frappe.response['403'] = 1 frappe.response['403'] = 1
raise frappe.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name) raise frappe.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)


@@ -686,7 +686,7 @@ def get(dt, dn='', with_children = 1, from_controller = 0):


def getsingle(doctype): def getsingle(doctype):
"""get single doc as dict""" """get single doc as dict"""
dataset = frappe.conn.sql("select field, value from tabSingles where doctype=%s", (doctype,))
dataset = frappe.db.sql("select field, value from tabSingles where doctype=%s", (doctype,))
return dict(dataset) return dict(dataset)
def copy_common_fields(from_doc, to_doc): def copy_common_fields(from_doc, to_doc):
@@ -702,7 +702,7 @@ def copy_common_fields(from_doc, to_doc):
def validate_name(doctype, name, case=None, merge=False): def validate_name(doctype, name, case=None, merge=False):
if not merge: if not merge:
if frappe.conn.sql('select name from `tab%s` where name=%s' % (doctype,'%s'), (name,)):
if frappe.db.sql('select name from `tab%s` where name=%s' % (doctype,'%s'), (name,)):
raise NameError, 'Name %s already exists' % name raise NameError, 'Name %s already exists' % name
# no name # no name


+ 10
- 10
frappe/model/docfield.py Просмотреть файл

@@ -8,14 +8,14 @@ import frappe


def rename(doctype, fieldname, newname): def rename(doctype, fieldname, newname):
"""rename docfield""" """rename docfield"""
df = frappe.conn.sql("""select * from tabDocField where parent=%s and fieldname=%s""",
df = frappe.db.sql("""select * from tabDocField where parent=%s and fieldname=%s""",
(doctype, fieldname), as_dict=1) (doctype, fieldname), as_dict=1)
if not df: if not df:
return return
df = df[0] df = df[0]
if frappe.conn.get_value('DocType', doctype, 'issingle'):
if frappe.db.get_value('DocType', doctype, 'issingle'):
update_single(df, newname) update_single(df, newname)
else: else:
update_table(df, newname) update_table(df, newname)
@@ -23,28 +23,28 @@ def rename(doctype, fieldname, newname):


def update_single(f, new): def update_single(f, new):
"""update in tabSingles""" """update in tabSingles"""
frappe.conn.begin()
frappe.conn.sql("""update tabSingles set field=%s where doctype=%s and field=%s""",
frappe.db.begin()
frappe.db.sql("""update tabSingles set field=%s where doctype=%s and field=%s""",
(new, f['parent'], f['fieldname'])) (new, f['parent'], f['fieldname']))
frappe.conn.commit()
frappe.db.commit()


def update_table(f, new): def update_table(f, new):
"""update table""" """update table"""
query = get_change_column_query(f, new) query = get_change_column_query(f, new)
if query: if query:
frappe.conn.sql(query)
frappe.db.sql(query)
def update_parent_field(f, new): def update_parent_field(f, new):
"""update 'parentfield' in tables""" """update 'parentfield' in tables"""
if f['fieldtype']=='Table': if f['fieldtype']=='Table':
frappe.conn.begin()
frappe.conn.sql("""update `tab%s` set parentfield=%s where parentfield=%s""" \
frappe.db.begin()
frappe.db.sql("""update `tab%s` set parentfield=%s where parentfield=%s""" \
% (f['options'], '%s', '%s'), (new, f['fieldname'])) % (f['options'], '%s', '%s'), (new, f['fieldname']))
frappe.conn.commit()
frappe.db.commit()
def get_change_column_query(f, new): def get_change_column_query(f, new):
"""generate change fieldname query""" """generate change fieldname query"""
desc = frappe.conn.sql("desc `tab%s`" % f['parent'])
desc = frappe.db.sql("desc `tab%s`" % f['parent'])
for d in desc: for d in desc:
if d[0]== f['fieldname']: if d[0]== f['fieldname']:
return 'alter table `tab%s` change `%s` `%s` %s' % \ return 'alter table `tab%s` change `%s` `%s` %s' % \

+ 13
- 13
frappe/model/doctype.py Просмотреть файл

@@ -64,7 +64,7 @@ def get(doctype, processed=False, cached=True):
return DocTypeDocList(doclist) return DocTypeDocList(doclist)


def load_docfield_types(): def load_docfield_types():
frappe.local.doctype_docfield_types = dict(frappe.conn.sql("""select fieldname, fieldtype from tabDocField
frappe.local.doctype_docfield_types = dict(frappe.db.sql("""select fieldname, fieldtype from tabDocField
where parent='DocField'""")) where parent='DocField'"""))


def add_workflows(doclist): def add_workflows(doclist):
@@ -74,7 +74,7 @@ def add_workflows(doclist):
# get active workflow # get active workflow
workflow_name = get_workflow_name(doctype) workflow_name = get_workflow_name(doctype)


if workflow_name and frappe.conn.exists("Workflow", workflow_name):
if workflow_name and frappe.db.exists("Workflow", workflow_name):
doclist += frappe.get_doclist("Workflow", workflow_name) doclist += frappe.get_doclist("Workflow", workflow_name)
# add workflow states (for icons and style) # add workflow states (for icons and style)
@@ -131,7 +131,7 @@ def sort_fields(doclist):
doclist.get({"doctype":["!=", "DocField"]}).extend(newlist) doclist.get({"doctype":["!=", "DocField"]}).extend(newlist)
def apply_property_setters(doctype, doclist): def apply_property_setters(doctype, doclist):
for ps in frappe.conn.sql("""select * from `tabProperty Setter` where
for ps in frappe.db.sql("""select * from `tabProperty Setter` where
doc_type=%s""", (doctype,), as_dict=1): doc_type=%s""", (doctype,), as_dict=1):
if ps['doctype_or_field']=='DocType': if ps['doctype_or_field']=='DocType':
if ps.get('property_type', None) in ('Int', 'Check'): if ps.get('property_type', None) in ('Int', 'Check'):
@@ -148,7 +148,7 @@ def apply_property_setters(doctype, doclist):


def add_custom_fields(doctype, doclist): def add_custom_fields(doctype, doclist):
try: try:
res = frappe.conn.sql("""SELECT * FROM `tabCustom Field`
res = frappe.db.sql("""SELECT * FROM `tabCustom Field`
WHERE dt = %s AND docstatus < 2""", (doctype,), as_dict=1) WHERE dt = %s AND docstatus < 2""", (doctype,), as_dict=1)
except Exception, e: except Exception, e:
if e.args[0]==1146: if e.args[0]==1146:
@@ -174,10 +174,10 @@ def add_custom_fields(doctype, doclist):
def add_linked_with(doclist): def add_linked_with(doclist):
"""add list of doctypes this doctype is 'linked' with""" """add list of doctypes this doctype is 'linked' with"""
doctype = doclist[0].name doctype = doclist[0].name
links = frappe.conn.sql("""select parent, fieldname from tabDocField
links = frappe.db.sql("""select parent, fieldname from tabDocField
where (fieldtype="Link" and options=%s) where (fieldtype="Link" and options=%s)
or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype)) or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
links += frappe.conn.sql("""select dt as parent, fieldname from `tabCustom Field`
links += frappe.db.sql("""select dt as parent, fieldname from `tabCustom Field`
where (fieldtype="Link" and options=%s) where (fieldtype="Link" and options=%s)
or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype)) or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))


@@ -191,7 +191,7 @@ def add_linked_with(doclist):
for dt in links: for dt in links:
ret[dt] = { "fieldname": links[dt] } ret[dt] = { "fieldname": links[dt] }


for grand_parent, options in frappe.conn.sql("""select parent, options from tabDocField
for grand_parent, options in frappe.db.sql("""select parent, options from tabDocField
where fieldtype="Table" where fieldtype="Table"
and options in (select name from tabDocType and options in (select name from tabDocType
where istable=1 and name in (%s))""" % ", ".join(["%s"] * len(links)) ,tuple(links)): where istable=1 and name in (%s))""" % ", ".join(["%s"] * len(links)) ,tuple(links)):
@@ -250,7 +250,7 @@ def clear_cache(doctype=None):
clear_single(doctype) clear_single(doctype)
# clear all parent doctypes # clear all parent doctypes
for dt in frappe.conn.sql("""select parent from tabDocField
for dt in frappe.db.sql("""select parent from tabDocField
where fieldtype="Table" and options=%s""", (doctype,)): where fieldtype="Table" and options=%s""", (doctype,)):
clear_single(dt[0]) clear_single(dt[0])
@@ -260,7 +260,7 @@ def clear_cache(doctype=None):
else: else:
# clear all # clear all
for dt in frappe.conn.sql("""select name from tabDocType"""):
for dt in frappe.db.sql("""select name from tabDocType"""):
clear_single(dt[0]) clear_single(dt[0])


def add_code(doctype, doclist): def add_code(doctype, doclist):
@@ -293,7 +293,7 @@ def add_embedded_js(doc):
js = doc.fields.get('__js') or '' js = doc.fields.get('__js') or ''


# custom script # custom script
custom = frappe.conn.get_value("Custom Script", {"dt": doc.name,
custom = frappe.db.get_value("Custom Script", {"dt": doc.name,
"script_type": "Client"}, "script") or "" "script_type": "Client"}, "script") or ""
js = (js + '\n' + custom).encode("utf-8") js = (js + '\n' + custom).encode("utf-8")


@@ -307,11 +307,11 @@ def expand_selects(doclist):
and (d.options or '').startswith('link:'), doclist): and (d.options or '').startswith('link:'), doclist):
doctype = d.options.split("\n")[0][5:] doctype = d.options.split("\n")[0][5:]
d.link_doctype = doctype d.link_doctype = doctype
d.options = '\n'.join([''] + [o.name for o in frappe.conn.sql("""select
d.options = '\n'.join([''] + [o.name for o in frappe.db.sql("""select
name from `tab%s` where docstatus<2 order by name asc""" % doctype, as_dict=1)]) name from `tab%s` where docstatus<2 order by name asc""" % doctype, as_dict=1)])


def add_print_formats(doclist): def add_print_formats(doclist):
print_formats = frappe.conn.sql("""select * FROM `tabPrint Format`
print_formats = frappe.db.sql("""select * FROM `tabPrint Format`
WHERE doc_type=%s AND docstatus<2""", (doclist[0].name,), as_dict=1) WHERE doc_type=%s AND docstatus<2""", (doclist[0].name,), as_dict=1)
for pf in print_formats: for pf in print_formats:
doclist.append(frappe.model.doc.Document('Print Format', fielddata=pf)) doclist.append(frappe.model.doc.Document('Print Format', fielddata=pf))
@@ -333,7 +333,7 @@ def get_link_fields(doctype):
"options": "^link:"})) "options": "^link:"}))
def add_validators(doctype, doclist): def add_validators(doctype, doclist):
for validator in frappe.conn.sql("""select name from `tabDocType Validator` where
for validator in frappe.db.sql("""select name from `tabDocType Validator` where
for_doctype=%s""", (doctype,), as_dict=1): for_doctype=%s""", (doctype,), as_dict=1):
doclist.extend(frappe.get_doclist('DocType Validator', validator.name)) doclist.extend(frappe.get_doclist('DocType Validator', validator.name))


+ 9
- 9
frappe/model/meta.py Просмотреть файл

@@ -9,18 +9,18 @@ from frappe.utils import cstr, cint
def is_single(doctype): def is_single(doctype):
try: try:
return frappe.conn.get_value("DocType", doctype, "issingle")
return frappe.db.get_value("DocType", doctype, "issingle")
except IndexError, e: except IndexError, e:
raise Exception, 'Cannot determine whether %s is single' % doctype raise Exception, 'Cannot determine whether %s is single' % doctype


def get_parent_dt(dt): def get_parent_dt(dt):
parent_dt = frappe.conn.sql("""select parent from tabDocField
parent_dt = frappe.db.sql("""select parent from tabDocField
where fieldtype="Table" and options="%s" and (parent not like "old_parent:%%") where fieldtype="Table" and options="%s" and (parent not like "old_parent:%%")
limit 1""" % dt) limit 1""" % dt)
return parent_dt and parent_dt[0][0] or '' return parent_dt and parent_dt[0][0] or ''


def set_fieldname(field_id, fieldname): def set_fieldname(field_id, fieldname):
frappe.conn.set_value('DocField', field_id, 'fieldname', fieldname)
frappe.db.set_value('DocField', field_id, 'fieldname', fieldname)


def get_link_fields(doctype): def get_link_fields(doctype):
""" """
@@ -40,11 +40,11 @@ def get_link_fields(doctype):
] ]


def get_table_fields(doctype): def get_table_fields(doctype):
child_tables = [[d[0], d[1]] for d in frappe.conn.sql("select options, fieldname from tabDocField \
child_tables = [[d[0], d[1]] for d in frappe.db.sql("select options, fieldname from tabDocField \
where parent='%s' and fieldtype='Table'" % doctype, as_list=1)] where parent='%s' and fieldtype='Table'" % doctype, as_list=1)]
try: try:
custom_child_tables = [[d[0], d[1]] for d in frappe.conn.sql("select options, fieldname from `tabCustom Field` \
custom_child_tables = [[d[0], d[1]] for d in frappe.db.sql("select options, fieldname from `tabCustom Field` \
where dt='%s' and fieldtype='Table'" % doctype, as_list=1)] where dt='%s' and fieldtype='Table'" % doctype, as_list=1)]
except Exception, e: except Exception, e:
if e.args[0]!=1146: if e.args[0]!=1146:
@@ -67,7 +67,7 @@ def get_field_currency(df, doc):
if ":" in cstr(df.options): if ":" in cstr(df.options):
split_opts = df.options.split(":") split_opts = df.options.split(":")
if len(split_opts)==3: if len(split_opts)==3:
currency = frappe.conn.get_value(split_opts[0], doc.fields.get(split_opts[1]),
currency = frappe.db.get_value(split_opts[0], doc.fields.get(split_opts[1]),
split_opts[2]) split_opts[2])
else: else:
currency = doc.fields.get(df.options) currency = doc.fields.get(df.options)
@@ -82,14 +82,14 @@ def get_field_precision(df, doc):
if df.fieldtype == "Currency": if df.fieldtype == "Currency":
currency = get_field_currency(df, doc) currency = get_field_currency(df, doc)
if currency: if currency:
number_format = frappe.conn.get_value("Currency", currency, "number_format")
number_format = frappe.db.get_value("Currency", currency, "number_format")
if not number_format: if not number_format:
number_format = frappe.conn.get_default("number_format") or "#,###.##"
number_format = frappe.db.get_default("number_format") or "#,###.##"
decimal_str, comma_str, precision = get_number_format_info(number_format) decimal_str, comma_str, precision = get_number_format_info(number_format)


if df.fieldtype == "Float": if df.fieldtype == "Float":
precision = cint(frappe.conn.get_default("float_precision")) or 3
precision = cint(frappe.db.get_default("float_precision")) or 3


return precision return precision

+ 27
- 27
frappe/model/rename_doc.py Просмотреть файл

@@ -13,7 +13,7 @@ def rename_doc(doctype, old, new, force=False, merge=False, ignore_permissions=F
Renames a doc(dt, old) to doc(dt, new) and Renames a doc(dt, old) to doc(dt, new) and
updates all linked fields of type "Link" or "Select" with "link:" updates all linked fields of type "Link" or "Select" with "link:"
""" """
if not frappe.conn.exists(doctype, old):
if not frappe.db.exists(doctype, old):
return return
force = cint(force) force = cint(force)
@@ -48,7 +48,7 @@ def rename_doc(doctype, old, new, force=False, merge=False, ignore_permissions=F
rename_versions(doctype, old, new) rename_versions(doctype, old, new)
# update restrictions # update restrictions
frappe.conn.sql("""update tabDefaultValue set defvalue=%s where parenttype='Restriction'
frappe.db.sql("""update tabDefaultValue set defvalue=%s where parenttype='Restriction'
and defkey=%s and defvalue=%s""", (new, doctype, old)) and defkey=%s and defvalue=%s""", (new, doctype, old))
frappe.clear_cache() frappe.clear_cache()
@@ -56,25 +56,25 @@ def rename_doc(doctype, old, new, force=False, merge=False, ignore_permissions=F


def update_attachments(doctype, old, new): def update_attachments(doctype, old, new):
try: try:
frappe.conn.sql("""update `tabFile Data` set attached_to_name=%s
frappe.db.sql("""update `tabFile Data` set attached_to_name=%s
where attached_to_name=%s and attached_to_doctype=%s""", (new, old, doctype)) where attached_to_name=%s and attached_to_doctype=%s""", (new, old, doctype))
except Exception, e: except Exception, e:
if e.args[0]!=1054: # in patch? if e.args[0]!=1054: # in patch?
raise raise


def rename_versions(doctype, old, new): def rename_versions(doctype, old, new):
frappe.conn.sql("""update tabVersion set docname=%s where ref_doctype=%s and docname=%s""",
frappe.db.sql("""update tabVersion set docname=%s where ref_doctype=%s and docname=%s""",
(new, doctype, old)) (new, doctype, old))


def rename_parent_and_child(doctype, old, new, doclist): def rename_parent_and_child(doctype, old, new, doclist):
# rename the doc # rename the doc
frappe.conn.sql("update `tab%s` set name=%s where name=%s" \
frappe.db.sql("update `tab%s` set name=%s where name=%s" \
% (doctype, '%s', '%s'), (new, old)) % (doctype, '%s', '%s'), (new, old))


update_child_docs(old, new, doclist) update_child_docs(old, new, doclist)


def validate_rename(doctype, new, doclist, merge, force, ignore_permissions): def validate_rename(doctype, new, doclist, merge, force, ignore_permissions):
exists = frappe.conn.exists(doctype, new)
exists = frappe.db.exists(doctype, new)


if merge and not exists: if merge and not exists:
frappe.msgprint("%s: %s does not exist, select a new target to merge." % (doctype, new), raise_exception=1) frappe.msgprint("%s: %s does not exist, select a new target to merge." % (doctype, new), raise_exception=1)
@@ -106,7 +106,7 @@ def rename_doctype(doctype, old, new, force=False):
update_parenttype_values(old, new) update_parenttype_values(old, new)
# rename comments # rename comments
frappe.conn.sql("""update tabComment set comment_doctype=%s where comment_doctype=%s""",
frappe.db.sql("""update tabComment set comment_doctype=%s where comment_doctype=%s""",
(new, old)) (new, old))


def update_child_docs(old, new, doclist): def update_child_docs(old, new, doclist):
@@ -115,7 +115,7 @@ def update_child_docs(old, new, doclist):
if d.doctype=='DocField' and d.fieldtype=='Table') if d.doctype=='DocField' and d.fieldtype=='Table')
for child in child_doctypes: for child in child_doctypes:
frappe.conn.sql("update `tab%s` set parent=%s where parent=%s" \
frappe.db.sql("update `tab%s` set parent=%s where parent=%s" \
% (child, '%s', '%s'), (new, old)) % (child, '%s', '%s'), (new, old))


def update_link_field_values(link_fields, old, new, doctype): def update_link_field_values(link_fields, old, new, doctype):
@@ -128,22 +128,22 @@ def update_link_field_values(link_fields, old, new, doctype):
continue continue
update_list.append([field['parent'], field['fieldname']]) update_list.append([field['parent'], field['fieldname']])
if field['issingle']: if field['issingle']:
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabSingles` set value=%s update `tabSingles` set value=%s
where doctype=%s and field=%s and value=%s""", where doctype=%s and field=%s and value=%s""",
(new, field['parent'], field['fieldname'], old)) (new, field['parent'], field['fieldname'], old))
else: else:
if doctype!='DocType' and field['parent']!=new: if doctype!='DocType' and field['parent']!=new:
frappe.conn.sql("""\
frappe.db.sql("""\
update `tab%s` set `%s`=%s update `tab%s` set `%s`=%s
where `%s`=%s""" \ where `%s`=%s""" \
% (field['parent'], field['fieldname'], '%s', % (field['parent'], field['fieldname'], '%s',
field['fieldname'], '%s'), field['fieldname'], '%s'),
(new, old), debug=1)
(new, old))
def get_link_fields(doctype): def get_link_fields(doctype):
# get link fields from tabDocField # get link fields from tabDocField
link_fields = frappe.conn.sql("""\
link_fields = frappe.db.sql("""\
select parent, fieldname, select parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt (select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.parent) as issingle where dt.name = df.parent) as issingle
@@ -155,7 +155,7 @@ def get_link_fields(doctype):
% ('%s', doctype), (doctype,), as_dict=1) % ('%s', doctype), (doctype,), as_dict=1)
# get link fields from tabCustom Field # get link fields from tabCustom Field
custom_link_fields = frappe.conn.sql("""\
custom_link_fields = frappe.db.sql("""\
select dt as parent, fieldname, select dt as parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt (select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.dt) as issingle where dt.name = df.dt) as issingle
@@ -170,7 +170,7 @@ def get_link_fields(doctype):
link_fields += custom_link_fields link_fields += custom_link_fields
# remove fields whose options have been changed using property setter # remove fields whose options have been changed using property setter
property_setter_link_fields = frappe.conn.sql("""\
property_setter_link_fields = frappe.db.sql("""\
select ps.doc_type as parent, ps.field_name as fieldname, select ps.doc_type as parent, ps.field_name as fieldname,
(select ifnull(issingle, 0) from tabDocType dt (select ifnull(issingle, 0) from tabDocType dt
where dt.name = ps.doc_type) as issingle where dt.name = ps.doc_type) as issingle
@@ -186,15 +186,15 @@ def get_link_fields(doctype):
return link_fields return link_fields
def update_parent_of_fieldtype_table(old, new): def update_parent_of_fieldtype_table(old, new):
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabDocField` set options=%s update `tabDocField` set options=%s
where fieldtype='Table' and options=%s""", (new, old)) where fieldtype='Table' and options=%s""", (new, old))
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabCustom Field` set options=%s update `tabCustom Field` set options=%s
where fieldtype='Table' and options=%s""", (new, old)) where fieldtype='Table' and options=%s""", (new, old))
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabProperty Setter` set value=%s update `tabProperty Setter` set value=%s
where property='options' and value=%s""", (new, old)) where property='options' and value=%s""", (new, old))
@@ -204,7 +204,7 @@ def get_select_fields(old, new):
new line separated list new line separated list
""" """
# get link fields from tabDocField # get link fields from tabDocField
select_fields = frappe.conn.sql("""\
select_fields = frappe.db.sql("""\
select parent, fieldname, select parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt (select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.parent) as issingle where dt.name = df.parent) as issingle
@@ -217,7 +217,7 @@ def get_select_fields(old, new):
% ('%s', old), (new,), as_dict=1) % ('%s', old), (new,), as_dict=1)
# get link fields from tabCustom Field # get link fields from tabCustom Field
custom_select_fields = frappe.conn.sql("""\
custom_select_fields = frappe.db.sql("""\
select dt as parent, fieldname, select dt as parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt (select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.dt) as issingle where dt.name = df.dt) as issingle
@@ -233,7 +233,7 @@ def get_select_fields(old, new):
select_fields += custom_select_fields select_fields += custom_select_fields
# remove fields whose options have been changed using property setter # remove fields whose options have been changed using property setter
property_setter_select_fields = frappe.conn.sql("""\
property_setter_select_fields = frappe.db.sql("""\
select ps.doc_type as parent, ps.field_name as fieldname, select ps.doc_type as parent, ps.field_name as fieldname,
(select ifnull(issingle, 0) from tabDocType dt (select ifnull(issingle, 0) from tabDocType dt
where dt.name = ps.doc_type) as issingle where dt.name = ps.doc_type) as issingle
@@ -251,7 +251,7 @@ def get_select_fields(old, new):
return select_fields return select_fields
def update_select_field_values(old, new): def update_select_field_values(old, new):
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabDocField` set options=replace(options, %s, %s) update `tabDocField` set options=replace(options, %s, %s)
where where
parent != %s and parent not like "old%%%%" and parent != %s and parent not like "old%%%%" and
@@ -259,7 +259,7 @@ def update_select_field_values(old, new):
(options like "%%%%\\n%s%%%%" or options like "%%%%%s\\n%%%%")""" % \ (options like "%%%%\\n%s%%%%" or options like "%%%%%s\\n%%%%")""" % \
('%s', '%s', '%s', old, old), (old, new, new)) ('%s', '%s', '%s', old, old), (old, new, new))


frappe.conn.sql("""\
frappe.db.sql("""\
update `tabCustom Field` set options=replace(options, %s, %s) update `tabCustom Field` set options=replace(options, %s, %s)
where where
dt != %s and dt not like "old%%%%" and dt != %s and dt not like "old%%%%" and
@@ -267,7 +267,7 @@ def update_select_field_values(old, new):
(options like "%%%%\\n%s%%%%" or options like "%%%%%s\\n%%%%")""" % \ (options like "%%%%\\n%s%%%%" or options like "%%%%%s\\n%%%%")""" % \
('%s', '%s', '%s', old, old), (old, new, new)) ('%s', '%s', '%s', old, old), (old, new, new))


frappe.conn.sql("""\
frappe.db.sql("""\
update `tabProperty Setter` set value=replace(value, %s, %s) update `tabProperty Setter` set value=replace(value, %s, %s)
where where
doc_type != %s and field_name is not null and doc_type != %s and field_name is not null and
@@ -276,18 +276,18 @@ def update_select_field_values(old, new):
('%s', '%s', '%s', old, old), (old, new, new)) ('%s', '%s', '%s', old, old), (old, new, new))
def update_parenttype_values(old, new): def update_parenttype_values(old, new):
child_doctypes = frappe.conn.sql("""\
child_doctypes = frappe.db.sql("""\
select options, fieldname from `tabDocField` select options, fieldname from `tabDocField`
where parent=%s and fieldtype='Table'""", (new,), as_dict=1) where parent=%s and fieldtype='Table'""", (new,), as_dict=1)


custom_child_doctypes = frappe.conn.sql("""\
custom_child_doctypes = frappe.db.sql("""\
select options, fieldname from `tabCustom Field` select options, fieldname from `tabCustom Field`
where dt=%s and fieldtype='Table'""", (new,), as_dict=1) where dt=%s and fieldtype='Table'""", (new,), as_dict=1)


child_doctypes += custom_child_doctypes child_doctypes += custom_child_doctypes
fields = [d['fieldname'] for d in child_doctypes] fields = [d['fieldname'] for d in child_doctypes]
property_setter_child_doctypes = frappe.conn.sql("""\
property_setter_child_doctypes = frappe.db.sql("""\
select value as options from `tabProperty Setter` select value as options from `tabProperty Setter`
where doc_type=%s and property='options' and where doc_type=%s and property='options' and
field_name in ("%s")""" % ('%s', '", "'.join(fields)), field_name in ("%s")""" % ('%s', '", "'.join(fields)),
@@ -297,7 +297,7 @@ def update_parenttype_values(old, new):
child_doctypes = (d['options'] for d in child_doctypes) child_doctypes = (d['options'] for d in child_doctypes)
for doctype in child_doctypes: for doctype in child_doctypes:
frappe.conn.sql("""\
frappe.db.sql("""\
update `tab%s` set parenttype=%s update `tab%s` set parenttype=%s
where parenttype=%s""" % (doctype, '%s', '%s'), where parenttype=%s""" % (doctype, '%s', '%s'),
(new, old)) (new, old))

+ 1
- 1
frappe/model/sync.py Просмотреть файл

@@ -51,6 +51,6 @@ def walk_and_sync(start_path, force=0, sync_everything = False, verbose=False):
if import_file_by_path(os.path.join(path, f), force=force) and verbose: if import_file_by_path(os.path.join(path, f), force=force) and verbose:
print module_name + ' | ' + doctype + ' | ' + name print module_name + ' | ' + doctype + ' | ' + name


frappe.conn.commit()
frappe.db.commit()
return modules return modules

+ 2
- 2
frappe/model/utils.py Просмотреть файл

@@ -113,8 +113,8 @@ def copy_doclist(doclist, no_copy = []):


def set_default(doc, key): def set_default(doc, key):
if not doc.is_default: if not doc.is_default:
frappe.conn.set(doc, "is_default", 1)
frappe.db.set(doc, "is_default", 1)
frappe.conn.sql("""update `tab%s` set `is_default`=0
frappe.db.sql("""update `tab%s` set `is_default`=0
where `%s`=%s and name!=%s""" % (doc.doctype, key, "%s", "%s"), where `%s`=%s and name!=%s""" % (doc.doctype, key, "%s", "%s"),
(doc.fields.get(key), doc.name)) (doc.fields.get(key), doc.name))

+ 4
- 4
frappe/model/workflow.py Просмотреть файл

@@ -9,12 +9,12 @@ def get_workflow_name(doctype):
frappe.local.workflow_names = {} frappe.local.workflow_names = {}
if doctype not in frappe.local.workflow_names: if doctype not in frappe.local.workflow_names:
workflow_name = frappe.conn.get_value("Workflow", {"document_type": doctype,
workflow_name = frappe.db.get_value("Workflow", {"document_type": doctype,
"is_active": "1"}, "name") "is_active": "1"}, "name")
# no active? get default workflow # no active? get default workflow
if not workflow_name: if not workflow_name:
workflow_name = frappe.conn.get_value("Workflow", {"document_type": doctype},
workflow_name = frappe.db.get_value("Workflow", {"document_type": doctype},
"name") "name")
frappe.local.workflow_names[doctype] = workflow_name frappe.local.workflow_names[doctype] = workflow_name
@@ -23,9 +23,9 @@ def get_workflow_name(doctype):
def get_default_state(doctype): def get_default_state(doctype):
workflow_name = get_workflow_name(doctype) workflow_name = get_workflow_name(doctype)
return frappe.conn.get_value("Workflow Document State", {"parent": workflow_name,
return frappe.db.get_value("Workflow Document State", {"parent": workflow_name,
"idx":1}, "state") "idx":1}, "state")
def get_state_fieldname(doctype): def get_state_fieldname(doctype):
workflow_name = get_workflow_name(doctype) workflow_name = get_workflow_name(doctype)
return frappe.conn.get_value("Workflow", workflow_name, "workflow_state_field")
return frappe.db.get_value("Workflow", workflow_name, "workflow_state_field")

+ 2
- 2
frappe/modules/__init__.py Просмотреть файл

@@ -39,8 +39,8 @@ def export_doc(doctype, name, module=None):
from frappe.modules.export_file import write_document_file from frappe.modules.export_file import write_document_file
import frappe.model.doc import frappe.model.doc


if not module: module = frappe.conn.get_value(doctype, name, 'module')
if not module: module = frappe.db.get_value(doctype, name, 'module')
write_document_file(frappe.model.doc.get(doctype, name), module) write_document_file(frappe.model.doc.get(doctype, name), module)


def get_doctype_module(doctype): def get_doctype_module(doctype):
return frappe.conn.get_value('DocType', doctype, 'module') or "core"
return frappe.db.get_value('DocType', doctype, 'module') or "core"

+ 1
- 1
frappe/modules/export_file.py Просмотреть файл

@@ -66,7 +66,7 @@ def get_module_name(doclist):
elif doclist[0]['doctype']=='Control Panel': elif doclist[0]['doctype']=='Control Panel':
module = 'Core' module = 'Core'
elif doclist[0]['doctype']=="Workflow": elif doclist[0]['doctype']=="Workflow":
module = frappe.conn.get_value("DocType", doclist[0]["document_type"], "module")
module = frappe.db.get_value("DocType", doclist[0]["document_type"], "module")
else: else:
module = doclist[0]['module'] module = doclist[0]['module']




+ 4
- 4
frappe/modules/import_file.py Просмотреть файл

@@ -38,7 +38,7 @@ def import_file_by_path(path, force=False):
if not force: if not force:
# check if timestamps match # check if timestamps match
if doc['modified']==str(frappe.conn.get_value(doc['doctype'], doc['name'], 'modified')):
if doc['modified']==str(frappe.db.get_value(doc['doctype'], doc['name'], 'modified')):
return False return False
original_modified = doc["modified"] original_modified = doc["modified"]
@@ -46,7 +46,7 @@ def import_file_by_path(path, force=False):
import_doclist(doclist) import_doclist(doclist)


# since there is a new timestamp on the file, update timestamp in # since there is a new timestamp on the file, update timestamp in
frappe.conn.sql("update `tab%s` set modified=%s where name=%s" % \
frappe.db.sql("update `tab%s` set modified=%s where name=%s" % \
(doc['doctype'], '%s', '%s'), (doc['doctype'], '%s', '%s'),
(original_modified, doc['name'])) (original_modified, doc['name']))
@@ -80,7 +80,7 @@ def import_doclist(doclist):
ignore = list(doctypes.intersection(set(ignore_doctypes))) ignore = list(doctypes.intersection(set(ignore_doctypes)))
if doctype in ignore_values: if doctype in ignore_values:
if frappe.conn.exists(doctype, name):
if frappe.db.exists(doctype, name):
old_doc = frappe.doc(doctype, name) old_doc = frappe.doc(doctype, name)


# delete old # delete old
@@ -112,7 +112,7 @@ def remove_ignored_docs_if_they_already_exist(doclist, ignore, name):
if ignore: if ignore:
has_records = [] has_records = []
for d in ignore: for d in ignore:
if frappe.conn.get_value(d, {"parent":name}):
if frappe.db.get_value(d, {"parent":name}):
has_records.append(d) has_records.append(d)
if has_records: if has_records:


+ 16
- 16
frappe/modules/patch_handler.py Просмотреть файл

@@ -18,7 +18,7 @@ class PatchError(Exception): pass


def run_all(): def run_all():
"""run all pending patches""" """run all pending patches"""
executed = [p[0] for p in frappe.conn.sql("""select patch from `tabPatch Log`""")]
executed = [p[0] for p in frappe.db.sql("""select patch from `tabPatch Log`""")]
for patch in get_all_patches(): for patch in get_all_patches():
if patch and (patch not in executed): if patch and (patch not in executed):
@@ -55,9 +55,9 @@ def execute_patch(patchmodule, method=None, methodargs=None):
"""execute the patch""" """execute the patch"""
success = False success = False
block_user(True) block_user(True)
frappe.conn.begin()
frappe.db.begin()
try: try:
log('Executing %s in %s' % (patchmodule or str(methodargs), frappe.conn.cur_db_name))
log('Executing %s in %s' % (patchmodule or str(methodargs), frappe.db.cur_db_name))
if patchmodule: if patchmodule:
if patchmodule.startswith("execute:"): if patchmodule.startswith("execute:"):
exec patchmodule.split("execute:")[1] in globals() exec patchmodule.split("execute:")[1] in globals()
@@ -67,10 +67,10 @@ def execute_patch(patchmodule, method=None, methodargs=None):
elif method: elif method:
method(**methodargs) method(**methodargs)
frappe.conn.commit()
frappe.db.commit()
success = True success = True
except Exception, e: except Exception, e:
frappe.conn.rollback()
frappe.db.rollback()
tb = frappe.get_traceback() tb = frappe.get_traceback()
log(tb) log(tb)
import os import os
@@ -91,32 +91,32 @@ def add_to_patch_log(tb):
def update_patch_log(patchmodule): def update_patch_log(patchmodule):
"""update patch_file in patch log""" """update patch_file in patch log"""
if frappe.conn.table_exists("__PatchLog"):
frappe.conn.sql("""INSERT INTO `__PatchLog` VALUES (%s, now())""", \
if frappe.db.table_exists("__PatchLog"):
frappe.db.sql("""INSERT INTO `__PatchLog` VALUES (%s, now())""", \
patchmodule) patchmodule)
else: else:
frappe.doc({"doctype": "Patch Log", "patch": patchmodule}).insert() frappe.doc({"doctype": "Patch Log", "patch": patchmodule}).insert()


def executed(patchmodule): def executed(patchmodule):
"""return True if is executed""" """return True if is executed"""
if frappe.conn.table_exists("__PatchLog"):
done = frappe.conn.sql("""select patch from __PatchLog where patch=%s""", patchmodule)
if frappe.db.table_exists("__PatchLog"):
done = frappe.db.sql("""select patch from __PatchLog where patch=%s""", patchmodule)
else: else:
done = frappe.conn.get_value("Patch Log", {"patch": patchmodule})
done = frappe.db.get_value("Patch Log", {"patch": patchmodule})
if done: if done:
print "Patch %s executed in %s" % (patchmodule, frappe.conn.cur_db_name)
print "Patch %s executed in %s" % (patchmodule, frappe.db.cur_db_name)
return done return done
def block_user(block): def block_user(block):
"""stop/start execution till patch is run""" """stop/start execution till patch is run"""
frappe.conn.begin()
frappe.db.begin()
msg = "Patches are being executed in the system. Please try again in a few moments." msg = "Patches are being executed in the system. Please try again in a few moments."
frappe.conn.set_global('__session_status', block and 'stop' or None)
frappe.conn.set_global('__session_status_message', block and msg or None)
frappe.conn.commit()
frappe.db.set_global('__session_status', block and 'stop' or None)
frappe.db.set_global('__session_status_message', block and msg or None)
frappe.db.commit()


def setup(): def setup():
frappe.conn.sql("""CREATE TABLE IF NOT EXISTS `__PatchLog` (
frappe.db.sql("""CREATE TABLE IF NOT EXISTS `__PatchLog` (
patch TEXT, applied_on DATETIME) engine=InnoDB""") patch TEXT, applied_on DATETIME) engine=InnoDB""")
def log(msg): def log(msg):


+ 1
- 1
frappe/modules/utils.py Просмотреть файл

@@ -29,7 +29,7 @@ def switch_module(dt, dn, to, frm=None, export=None):
Change the module of the given doctype, if export is true, then also export txt and copy Change the module of the given doctype, if export is true, then also export txt and copy
code files from src code files from src
""" """
frappe.conn.sql("update `tab"+dt+"` set module=%s where name=%s", (to, dn))
frappe.db.sql("update `tab"+dt+"` set module=%s where name=%s", (to, dn))


if export: if export:
export_doc(dt, dn) export_doc(dt, dn)


+ 2
- 2
frappe/patches/4_0/add_delete_permission.py Просмотреть файл

@@ -4,9 +4,9 @@ def execute():
frappe.reload_doc("core", "doctype", "docperm") frappe.reload_doc("core", "doctype", "docperm")
# delete same as cancel (map old permissions) # delete same as cancel (map old permissions)
frappe.conn.sql("""update tabDocPerm set `delete`=ifnull(`cancel`,0)""")
frappe.db.sql("""update tabDocPerm set `delete`=ifnull(`cancel`,0)""")
# can't cancel if can't submit # can't cancel if can't submit
frappe.conn.sql("""update tabDocPerm set `cancel`=0 where ifnull(`submit`,0)=0""")
frappe.db.sql("""update tabDocPerm set `cancel`=0 where ifnull(`submit`,0)=0""")
frappe.clear_cache() frappe.clear_cache()

+ 1
- 1
frappe/patches/4_0/move_match_to_restricted.py Просмотреть файл

@@ -6,4 +6,4 @@ import frappe


def execute(): def execute():
frappe.reload_doc("core", "doctype", "docperm") frappe.reload_doc("core", "doctype", "docperm")
frappe.conn.sql("""update `tabDocPerm` set restricted=1 where `match`='owner'""")
frappe.db.sql("""update `tabDocPerm` set restricted=1 where `match`='owner'""")

+ 1
- 1
frappe/patches/4_0/remove_index_sitemap.py Просмотреть файл

@@ -1,6 +1,6 @@
import frappe import frappe


def execute(): def execute():
if frappe.conn.exists("Website Route", "index"):
if frappe.db.exists("Website Route", "index"):
frappe.delete_doc("Website Route", "index", ignore_permissions=True) frappe.delete_doc("Website Route", "index", ignore_permissions=True)

+ 1
- 1
frappe/patches/4_0/rename_sitemap_to_route.py Просмотреть файл

@@ -3,7 +3,7 @@ import frappe
from frappe.model import rename_field from frappe.model import rename_field


def execute(): def execute():
tables = frappe.conn.sql_list("show tables")
tables = frappe.db.sql_list("show tables")
if "tabWebsite Route" not in tables: if "tabWebsite Route" not in tables:
frappe.rename_doc("DocType", "Website Sitemap", "Website Route", force=True) frappe.rename_doc("DocType", "Website Sitemap", "Website Route", force=True)




+ 1
- 1
frappe/patches/4_0/set_todo_checked_as_closed.py Просмотреть файл

@@ -3,6 +3,6 @@ import frappe
def execute(): def execute():
frappe.reload_doc("core", "doctype", "todo") frappe.reload_doc("core", "doctype", "todo")
try: try:
frappe.conn.sql("""update tabToDo set status = if(ifnull(checked,0)=0, 'Open', 'Closed')""")
frappe.db.sql("""update tabToDo set status = if(ifnull(checked,0)=0, 'Open', 'Closed')""")
except: except:
pass pass

+ 3
- 3
frappe/patches/4_0/set_website_route_idx.py Просмотреть файл

@@ -11,12 +11,12 @@ def execute():
pages, generators = get_pages_and_generators(app) pages, generators = get_pages_and_generators(app)
for g in generators: for g in generators:
doctype = frappe.get_attr(get_template_controller(app, g["path"], g["fname"]) + ".doctype") doctype = frappe.get_attr(get_template_controller(app, g["path"], g["fname"]) + ".doctype")
module = frappe.conn.get_value("DocType", doctype, "module")
module = frappe.db.get_value("DocType", doctype, "module")
frappe.reload_doc(module, "doctype", doctype) frappe.reload_doc(module, "doctype", doctype)
frappe.conn.sql("""update `tabWebsite Route` set idx=null""")
frappe.db.sql("""update `tabWebsite Route` set idx=null""")
for doctype in ["Blog Category", "Blog Post", "Web Page", "Website Group"]: for doctype in ["Blog Category", "Blog Post", "Web Page", "Website Group"]:
frappe.conn.sql("""update `tab{}` set idx=null""".format(doctype))
frappe.db.sql("""update `tab{}` set idx=null""".format(doctype))


from frappe.website.doctype.website_template.website_template import rebuild_website_template from frappe.website.doctype.website_template.website_template import rebuild_website_template
rebuild_website_template() rebuild_website_template()

+ 1
- 1
frappe/patches/4_0/webnotes_to_frappe.py Просмотреть файл

@@ -5,5 +5,5 @@ def execute():
if "webnotes" in installed: if "webnotes" in installed:
installed.remove("webnotes") installed.remove("webnotes")
installed = ["frappe"] + installed installed = ["frappe"] + installed
frappe.conn.set_global("installed_apps", json.dumps(installed))
frappe.db.set_global("installed_apps", json.dumps(installed))
frappe.clear_cache() frappe.clear_cache()

+ 4
- 4
frappe/patches/4_0/website_sitemap_hierarchy.py Просмотреть файл

@@ -12,11 +12,11 @@ def execute():
frappe.reload_doc("website", "doctype", "post") frappe.reload_doc("website", "doctype", "post")
frappe.reload_doc("website", "doctype", "user_vote") frappe.reload_doc("website", "doctype", "user_vote")
frappe.conn.sql("""update `tabWebsite Route` ws set ref_doctype=(select wsc.ref_doctype
frappe.db.sql("""update `tabWebsite Route` ws set ref_doctype=(select wsc.ref_doctype
from `tabWebsite Template` wsc where wsc.name=ws.website_template) from `tabWebsite Template` wsc where wsc.name=ws.website_template)
where ifnull(page_or_generator, '')!='Page'""") where ifnull(page_or_generator, '')!='Page'""")
home_page = frappe.conn.get_value("Website Settings", "Website Settings", "home_page")
home_page = frappe.conn.get_value("Website Route", {"docname": home_page}) or home_page
frappe.conn.set_value("Website Settings", "Website Settings", "home_page",
home_page = frappe.db.get_value("Website Settings", "Website Settings", "home_page")
home_page = frappe.db.get_value("Website Route", {"docname": home_page}) or home_page
frappe.db.set_value("Website Settings", "Website Settings", "home_page",
home_page) home_page)

+ 1
- 1
frappe/permissions.py Просмотреть файл

@@ -16,7 +16,7 @@ def check_admin_or_system_manager():
def has_permission(doctype, ptype="read", refdoc=None, verbose=True): def has_permission(doctype, ptype="read", refdoc=None, verbose=True):
"""check if user has permission""" """check if user has permission"""
if frappe.conn.get_value("DocType", doctype, "istable")==1:
if frappe.db.get_value("DocType", doctype, "istable")==1:
return True return True
meta = frappe.get_doctype(doctype) meta = frappe.get_doctype(doctype)


+ 7
- 7
frappe/profile.py Просмотреть файл

@@ -41,14 +41,14 @@ class Profile:
"""build map of special doctype properties""" """build map of special doctype properties"""
self.doctype_map = {} self.doctype_map = {}
for r in frappe.conn.sql("""select name, in_create, issingle, istable,
for r in frappe.db.sql("""select name, in_create, issingle, istable,
read_only, module from tabDocType""", as_dict=1): read_only, module from tabDocType""", as_dict=1):
self.doctype_map[r['name']] = r self.doctype_map[r['name']] = r
def build_perm_map(self): def build_perm_map(self):
"""build map of permissions at level 0""" """build map of permissions at level 0"""
self.perm_map = {} self.perm_map = {}
for r in frappe.conn.sql("""select parent, `read`, `write`, `create`, `delete`, `submit`,
for r in frappe.db.sql("""select parent, `read`, `write`, `create`, `delete`, `submit`,
`cancel`,`report`, `import`, `export`, `print`, `email`, `restrict` `cancel`,`report`, `import`, `export`, `print`, `email`, `restrict`
from tabDocPerm where docstatus=0 from tabDocPerm where docstatus=0
and ifnull(permlevel,0)=0 and ifnull(permlevel,0)=0
@@ -150,7 +150,7 @@ class Profile:
return self.can_read return self.can_read
def load_profile(self): def load_profile(self):
d = frappe.conn.sql("""select email, first_name, last_name,
d = frappe.db.sql("""select email, first_name, last_name,
email_signature, background_image, user_type, language email_signature, background_image, user_type, language
from tabProfile where name = %s""", (self.name,), as_dict=1)[0] from tabProfile where name = %s""", (self.name,), as_dict=1)[0]


@@ -173,13 +173,13 @@ class Profile:
return d return d
def get_user_fullname(user): def get_user_fullname(user):
fullname = frappe.conn.sql("SELECT CONCAT_WS(' ', first_name, last_name) FROM `tabProfile` WHERE name=%s", (user,))
fullname = frappe.db.sql("SELECT CONCAT_WS(' ', first_name, last_name) FROM `tabProfile` WHERE name=%s", (user,))
return fullname and fullname[0][0] or '' return fullname and fullname[0][0] or ''


def get_system_managers(only_name=False): def get_system_managers(only_name=False):
"""returns all system manager's profile details""" """returns all system manager's profile details"""
import email.utils import email.utils
system_managers = frappe.conn.sql("""select distinct name,
system_managers = frappe.db.sql("""select distinct name,
concat_ws(" ", if(first_name="", null, first_name), if(last_name="", null, last_name)) concat_ws(" ", if(first_name="", null, first_name), if(last_name="", null, last_name))
as fullname from tabProfile p as fullname from tabProfile p
where docstatus < 2 and enabled = 1 where docstatus < 2 and enabled = 1
@@ -209,7 +209,7 @@ def add_system_manager(email, first_name=None, last_name=None):
profile.insert() profile.insert()
# add roles # add roles
roles = frappe.conn.sql_list("""select name from `tabRole`
roles = frappe.db.sql_list("""select name from `tabRole`
where name not in ("Administrator", "Guest", "All")""") where name not in ("Administrator", "Guest", "All")""")
profile.get_controller().add_roles(*roles) profile.get_controller().add_roles(*roles)
@@ -221,7 +221,7 @@ def get_roles(username=None, with_standard=True):
if username=='Guest': if username=='Guest':
return ['Guest'] return ['Guest']
roles = [r[0] for r in frappe.conn.sql("""select role from tabUserRole
roles = [r[0] for r in frappe.db.sql("""select role from tabUserRole
where parent=%s and role!='All'""", (username,))] + ['All'] where parent=%s and role!='All'""", (username,))] + ['All']
# filter standard if required # filter standard if required


+ 13
- 13
frappe/sessions.py Просмотреть файл

@@ -19,7 +19,7 @@ import frappe.translate
@frappe.whitelist() @frappe.whitelist()
def clear(user=None): def clear(user=None):
frappe.local.session_obj.update(force=True) frappe.local.session_obj.update(force=True)
frappe.local.conn.commit()
frappe.local.db.commit()
clear_cache(frappe.session.user) clear_cache(frappe.session.user)
frappe.response['message'] = "Cache Cleared" frappe.response['message'] = "Cache Cleared"


@@ -36,19 +36,19 @@ def clear_cache(user=None):
# clear notifications # clear notifications
if frappe.flags.in_install_app!="frappe": if frappe.flags.in_install_app!="frappe":
frappe.conn.sql("""delete from `tabNotification Count` where owner=%s""", (user,))
frappe.db.sql("""delete from `tabNotification Count` where owner=%s""", (user,))
if frappe.session: if frappe.session:
if user==frappe.session.user and frappe.session.sid: if user==frappe.session.user and frappe.session.sid:
cache.delete_value("session:" + frappe.session.sid) cache.delete_value("session:" + frappe.session.sid)
else: else:
for sid in frappe.conn.sql_list("""select sid from tabSessions
for sid in frappe.db.sql_list("""select sid from tabSessions
where user=%s""", (user,)): where user=%s""", (user,)):
cache.delete_value("session:" + sid) cache.delete_value("session:" + sid)


frappe.defaults.clear_cache(user) frappe.defaults.clear_cache(user)
else: else:
for sess in frappe.conn.sql("""select user, sid from tabSessions""", as_dict=1):
for sess in frappe.db.sql("""select user, sid from tabSessions""", as_dict=1):
cache.delete_value("lang:" + sess.user) cache.delete_value("lang:" + sess.user)
cache.delete_value("session:" + sess.sid) cache.delete_value("session:" + sess.sid)
cache.delete_value("bootinfo:" + sess.user) cache.delete_value("bootinfo:" + sess.user)
@@ -57,12 +57,12 @@ def clear_cache(user=None):
def clear_sessions(user=None, keep_current=False): def clear_sessions(user=None, keep_current=False):
if not user: if not user:
user = frappe.session.user user = frappe.session.user
for sid in frappe.conn.sql("""select sid from tabSessions where user=%s""", (user,)):
for sid in frappe.db.sql("""select sid from tabSessions where user=%s""", (user,)):
if keep_current and frappe.session.sid==sid[0]: if keep_current and frappe.session.sid==sid[0]:
pass pass
else: else:
frappe.cache().delete_value("session:" + sid[0]) frappe.cache().delete_value("session:" + sid[0])
frappe.conn.sql("""delete from tabSessions where sid=%s""", (sid[0],))
frappe.db.sql("""delete from tabSessions where sid=%s""", (sid[0],))


def get(): def get():
"""get session boot info""" """get session boot info"""
@@ -125,16 +125,16 @@ class Session:
# insert session # insert session
if self.user!="Guest": if self.user!="Guest":
frappe.conn.begin()
frappe.db.begin()
self.insert_session_record() self.insert_session_record()


# update profile # update profile
frappe.conn.sql("""UPDATE tabProfile SET last_login = '%s', last_ip = '%s'
frappe.db.sql("""UPDATE tabProfile SET last_login = '%s', last_ip = '%s'
where name='%s'""" % (frappe.utils.now(), frappe.get_request_header('REMOTE_ADDR'), self.data['user'])) where name='%s'""" % (frappe.utils.now(), frappe.get_request_header('REMOTE_ADDR'), self.data['user']))
frappe.conn.commit()
frappe.db.commit()


def insert_session_record(self): def insert_session_record(self):
frappe.conn.sql("""insert into tabSessions
frappe.db.sql("""insert into tabSessions
(sessiondata, user, lastupdate, sid, status) (sessiondata, user, lastupdate, sid, status)
values (%s , %s, NOW(), %s, 'Active')""", values (%s , %s, NOW(), %s, 'Active')""",
(str(self.data['data']), self.data['user'], self.data['sid'])) (str(self.data['data']), self.data['user'], self.data['sid']))
@@ -189,7 +189,7 @@ class Session:
return data and data.data return data and data.data


def get_session_data_from_db(self): def get_session_data_from_db(self):
rec = frappe.conn.sql("""select user, sessiondata
rec = frappe.db.sql("""select user, sessiondata
from tabSessions where sid=%s and from tabSessions where sid=%s and
TIMEDIFF(NOW(), lastupdate) < TIME(%s)""", (self.sid, TIMEDIFF(NOW(), lastupdate) < TIME(%s)""", (self.sid,
self.get_expiry_period())) self.get_expiry_period()))
@@ -209,7 +209,7 @@ class Session:


def delete_session(self): def delete_session(self):
frappe.cache().delete_value("session:" + self.sid) frappe.cache().delete_value("session:" + self.sid)
r = frappe.conn.sql("""delete from tabSessions where sid=%s""", (self.sid,))
r = frappe.db.sql("""delete from tabSessions where sid=%s""", (self.sid,))


def start_as_guest(self): def start_as_guest(self):
"""all guests share the same 'Guest' session""" """all guests share the same 'Guest' session"""
@@ -233,7 +233,7 @@ class Session:
if force or (frappe.session['user'] != 'Guest' and \ if force or (frappe.session['user'] != 'Guest' and \
((time_diff==None) or (time_diff > 1800))): ((time_diff==None) or (time_diff > 1800))):
# database persistence is secondary, don't update it too often # database persistence is secondary, don't update it too often
frappe.conn.sql("""update tabSessions set sessiondata=%s,
frappe.db.sql("""update tabSessions set sessiondata=%s,
lastupdate=NOW() where sid=%s""" , (str(self.data['data']), lastupdate=NOW() where sid=%s""" , (str(self.data['data']),
self.data['sid'])) self.data['sid']))




+ 3
- 3
frappe/templates/generators/blog_post.py Просмотреть файл

@@ -29,9 +29,9 @@ def get_context(context):
blog_post.description = blog_post.blog_intro or blog_post.content[:140] blog_post.description = blog_post.blog_intro or blog_post.content[:140]
blog_post.meta_description = blog_post.description blog_post.meta_description = blog_post.description
blog_post.categories = frappe.conn.sql_list("select name from `tabBlog Category` order by name")
blog_post.categories = frappe.db.sql_list("select name from `tabBlog Category` order by name")
blog_post.comment_list = frappe.conn.sql("""\
blog_post.comment_list = frappe.db.sql("""\
select comment, comment_by_fullname, creation select comment, comment_by_fullname, creation
from `tabComment` where comment_doctype="Blog Post" from `tabComment` where comment_doctype="Blog Post"
and comment_docname=%s order by creation""", (blog_post.name,), as_dict=1) or [] and comment_docname=%s order by creation""", (blog_post.name,), as_dict=1) or []
@@ -62,7 +62,7 @@ def get_blog_list(start=0, by=None, category=None):
order by published_on desc, name asc order by published_on desc, name asc
limit %(start)s, 20""" % {"start": start, "condition": condition} limit %(start)s, 20""" % {"start": start, "condition": condition}
result = frappe.conn.sql(query, as_dict=1)
result = frappe.db.sql(query, as_dict=1)


# strip html tags from content # strip html tags from content
for res in result: for res in result:


+ 3
- 3
frappe/templates/generators/web_page.py Просмотреть файл

@@ -23,7 +23,7 @@ def get_context(context):
web_page.doc.links = get_navigation_links(web_page) web_page.doc.links = get_navigation_links(web_page)
if web_page.doc.enable_comments: if web_page.doc.enable_comments:
web_page.doc.comment_list = frappe.conn.sql("""select
web_page.doc.comment_list = frappe.db.sql("""select
comment, comment_by_fullname, creation comment, comment_by_fullname, creation
from `tabComment` where comment_doctype="Web Page" from `tabComment` where comment_doctype="Web Page"
and comment_docname=%s order by creation""", web_page.doc.name, as_dict=1) or [] and comment_docname=%s order by creation""", web_page.doc.name, as_dict=1) or []
@@ -41,7 +41,7 @@ def get_breadcrumbs(web_page):
breadcrumbs = [] breadcrumbs = []
def add_parent_of(web_page): def add_parent_of(web_page):
parent = frappe.conn.sql("""select name, page_name, title from `tabWeb Page`
parent = frappe.db.sql("""select name, page_name, title from `tabWeb Page`
where exists (select parent from `tabTable of Contents` where exists (select parent from `tabTable of Contents`
where `tabTable of Contents`.parent=`tabWeb Page`.name where `tabTable of Contents`.parent=`tabWeb Page`.name
and web_page=%s)""", web_page, as_dict=True) and web_page=%s)""", web_page, as_dict=True)
@@ -58,7 +58,7 @@ def get_toc_list(web_page):
toc_list = web_page.doclist.get({"parentfield": "toc"}) toc_list = web_page.doclist.get({"parentfield": "toc"})
if not toc_list: return [] if not toc_list: return []


out = frappe.conn.sql("""select name, page_name, title
out = frappe.db.sql("""select name, page_name, title
from `tabWeb Page` where name in (%s)""" % \ from `tabWeb Page` where name in (%s)""" % \
(", ".join(["%s"]*len(toc_list))), (", ".join(["%s"]*len(toc_list))),
tuple([d.web_page for d in toc_list]), tuple([d.web_page for d in toc_list]),


+ 5
- 5
frappe/templates/generators/website_group.py Просмотреть файл

@@ -74,7 +74,7 @@ def build_view_context(context):
context.profile = frappe.doc("Profile", context.post.assigned_to) context.profile = frappe.doc("Profile", context.post.assigned_to)


elif context.view.name == "settings": elif context.view.name == "settings":
context.profiles = frappe.conn.sql("""select p.*, wsp.`read`, wsp.`write`, wsp.`admin`
context.profiles = frappe.db.sql("""select p.*, wsp.`read`, wsp.`write`, wsp.`admin`
from `tabProfile` p, `tabWebsite Route Permission` wsp from `tabProfile` p, `tabWebsite Route Permission` wsp
where wsp.website_route=%s and wsp.profile=p.name""", context.pathname, as_dict=True) where wsp.website_route=%s and wsp.profile=p.name""", context.pathname, as_dict=True)
@@ -119,12 +119,12 @@ def has_access(access, view):
def clear_cache(path=None, website_group=None): def clear_cache(path=None, website_group=None):
from frappe.templates.website_group.post import clear_post_cache from frappe.templates.website_group.post import clear_post_cache
if path: if path:
website_groups = [frappe.conn.get_value("Website Route", path, "docname")]
website_groups = [frappe.db.get_value("Website Route", path, "docname")]
elif website_group: elif website_group:
website_groups = [website_group] website_groups = [website_group]
else: else:
clear_post_cache() clear_post_cache()
website_groups = frappe.conn.sql_list("""select name from `tabWebsite Group`""")
website_groups = frappe.db.sql_list("""select name from `tabWebsite Group`""")
cache = frappe.cache() cache = frappe.cache()
all_views = get_views() all_views = get_views()
@@ -133,14 +133,14 @@ def clear_cache(path=None, website_group=None):
cache.delete_value("website_group_context:{}:{}".format(group, view)) cache.delete_value("website_group_context:{}:{}".format(group, view))


def clear_event_cache(): def clear_event_cache():
for group in frappe.conn.sql_list("""select name from `tabWebsite Group` where group_type='Event'"""):
for group in frappe.db.sql_list("""select name from `tabWebsite Group` where group_type='Event'"""):
clear_unit_views(website_group=group) clear_unit_views(website_group=group)
def clear_cache_on_bean_event(bean, method, *args, **kwargs): def clear_cache_on_bean_event(bean, method, *args, **kwargs):
clear_cache(path=bean.doc.website_route, website_group=bean.doc.website_group) clear_cache(path=bean.doc.website_route, website_group=bean.doc.website_group)
def get_pathname(group): def get_pathname(group):
return frappe.conn.get_value("Website Route", {"ref_doctype": "Website Group",
return frappe.db.get_value("Website Route", {"ref_doctype": "Website Group",
"docname": group}) "docname": group})


views = { views = {


+ 2
- 2
frappe/templates/includes/comments.py Просмотреть файл

@@ -38,11 +38,11 @@ def add_comment(args=None):
clear_cache(page_name) clear_cache(page_name)


# notify commentors # notify commentors
commentors = [d[0] for d in frappe.conn.sql("""select comment_by from tabComment where
commentors = [d[0] for d in frappe.db.sql("""select comment_by from tabComment where
comment_doctype=%s and comment_docname=%s and comment_doctype=%s and comment_docname=%s and
ifnull(unsubscribed, 0)=0""", (comment.doc.comment_doctype, comment.doc.comment_docname))] ifnull(unsubscribed, 0)=0""", (comment.doc.comment_doctype, comment.doc.comment_docname))]
owner = frappe.conn.get_value(comment.doc.comment_doctype, comment.doc.comment_docname, "owner")
owner = frappe.db.get_value(comment.doc.comment_doctype, comment.doc.comment_docname, "owner")
from frappe.utils.email_lib.bulk import send from frappe.utils.email_lib.bulk import send
send(recipients=list(set(commentors + [owner])), send(recipients=list(set(commentors + [owner])),


+ 2
- 2
frappe/templates/pages/contact.py Просмотреть файл

@@ -34,13 +34,13 @@ def send_message(subject="Website Query", message="", sender=""):
return return
# guest method, cap max writes per hour # guest method, cap max writes per hour
if frappe.conn.sql("""select count(*) from `tabCommunication`
if frappe.db.sql("""select count(*) from `tabCommunication`
where TIMEDIFF(%s, modified) < '01:00:00'""", now())[0][0] > max_communications_per_hour: where TIMEDIFF(%s, modified) < '01:00:00'""", now())[0][0] > max_communications_per_hour:
frappe.response["message"] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later" frappe.response["message"] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
return return
# send email # send email
forward_to_email = frappe.conn.get_value("Contact Us Settings", None, "forward_to_email")
forward_to_email = frappe.db.get_value("Contact Us Settings", None, "forward_to_email")
if forward_to_email: if forward_to_email:
from frappe.utils.email_lib import sendmail from frappe.utils.email_lib import sendmail
sendmail(forward_to_email, sender, message, subject) sendmail(forward_to_email, sender, message, subject)


+ 1
- 1
frappe/templates/pages/rss.py Просмотреть файл

@@ -14,7 +14,7 @@ def get_context(context):
host = get_request_site_address() host = get_request_site_address()
blog_list = frappe.conn.sql("""\
blog_list = frappe.db.sql("""\
select page_name as name, published_on, modified, title, content from `tabBlog Post` select page_name as name, published_on, modified, title, content from `tabBlog Post`
where ifnull(published,0)=1 where ifnull(published,0)=1
order by published_on desc limit 20""", as_dict=1) order by published_on desc limit 20""", as_dict=1)


+ 1
- 1
frappe/templates/pages/sitemap.py Просмотреть файл

@@ -15,7 +15,7 @@ def get_context(context):
"""generate the sitemap XML""" """generate the sitemap XML"""
host = get_request_site_address() host = get_request_site_address()
links = [] links = []
for l in frappe.conn.sql("""select `tabWebsite Route`.page_name, `tabWebsite Route`.lastmod
for l in frappe.db.sql("""select `tabWebsite Route`.page_name, `tabWebsite Route`.lastmod
from `tabWebsite Route`, `tabWebsite Template` from `tabWebsite Route`, `tabWebsite Template`
where where
`tabWebsite Route`.website_template = `tabWebsite Template`.name `tabWebsite Route`.website_template = `tabWebsite Template`.name


+ 2
- 2
frappe/templates/pages/website_script.py Просмотреть файл

@@ -8,10 +8,10 @@ no_sitemap = 1
base_template_path = "templates/pages/website_script.js" base_template_path = "templates/pages/website_script.js"


def get_context(context): def get_context(context):
script_context = { "javascript": frappe.conn.get_value('Website Script', None, 'javascript') }
script_context = { "javascript": frappe.db.get_value('Website Script', None, 'javascript') }
if not frappe.conf.developer_mode: if not frappe.conf.developer_mode:
script_context["google_analytics_id"] = frappe.conn.get_value("Website Settings", "Website Settings",
script_context["google_analytics_id"] = frappe.db.get_value("Website Settings", "Website Settings",
"google_analytics_id") "google_analytics_id")
return script_context return script_context

+ 2
- 2
frappe/templates/pages/writers.py Просмотреть файл

@@ -5,7 +5,7 @@ from __future__ import unicode_literals
import frappe import frappe


def get_context(context): def get_context(context):
bloggers = frappe.conn.sql("""select * from `tabBlogger`
bloggers = frappe.db.sql("""select * from `tabBlogger`
where ifnull(posts,0) > 0 and ifnull(disabled,0)=0 where ifnull(posts,0) > 0 and ifnull(disabled,0)=0
order by posts desc""", as_dict=1) order by posts desc""", as_dict=1)
@@ -14,7 +14,7 @@ def get_context(context):
"texts": { "texts": {
"all_posts_by": "All posts by" "all_posts_by": "All posts by"
}, },
"categories": frappe.conn.sql_list("select name from `tabBlog Category` order by name")
"categories": frappe.db.sql_list("select name from `tabBlog Category` order by name")
} }
writers_context.update(frappe.doc("Blog Settings", "Blog Settings").fields) writers_context.update(frappe.doc("Blog Settings", "Blog Settings").fields)


+ 3
- 3
frappe/templates/website_group/forum.py Просмотреть файл

@@ -12,7 +12,7 @@ def get_post_list_html(group, view, limit_start=0, limit_length=20):
# verify permission for paging # verify permission for paging
if frappe.local.form_dict.cmd == "get_post_list_html": if frappe.local.form_dict.cmd == "get_post_list_html":
pathname = frappe.conn.get_value("Website Route",
pathname = frappe.db.get_value("Website Route",
{"ref_doctype": "Website Group", "docname": group}) {"ref_doctype": "Website Group", "docname": group})
access = get_access(pathname) access = get_access(pathname)
@@ -22,7 +22,7 @@ def get_post_list_html(group, view, limit_start=0, limit_length=20):
conditions = "" conditions = ""
values = [group] values = [group]
group_type = frappe.conn.get_value("Website Group", group, "group_type")
group_type = frappe.db.get_value("Website Group", group, "group_type")
if group_type == "Events": if group_type == "Events":
# should show based on time upto precision of hour # should show based on time upto precision of hour
# because the current hour should also be in upcoming # because the current hour should also be in upcoming
@@ -52,7 +52,7 @@ def get_post_list_html(group, view, limit_start=0, limit_length=20):
values += [int(limit_start), int(limit_length)] values += [int(limit_start), int(limit_length)]
posts = frappe.conn.sql("""select p.*, pr.user_image, pr.first_name, pr.last_name,
posts = frappe.db.sql("""select p.*, pr.user_image, pr.first_name, pr.last_name,
(select count(pc.name) from `tabPost` pc where pc.parent_post=p.name) as post_reply_count (select count(pc.name) from `tabPost` pc where pc.parent_post=p.name) as post_reply_count
from `tabPost` p, `tabProfile` pr from `tabPost` p, `tabProfile` pr
where p.website_group = %s and pr.name = p.owner and ifnull(p.parent_post, '')='' where p.website_group = %s and pr.name = p.owner and ifnull(p.parent_post, '')=''


+ 5
- 5
frappe/templates/website_group/post.py Просмотреть файл

@@ -34,7 +34,7 @@ def get_parent_post_html(post, context):
.render({"post": post.fields, "view": context.view}) .render({"post": post.fields, "view": context.view})


def get_child_posts_html(post, context): def get_child_posts_html(post, context):
posts = frappe.conn.sql("""select p.*, pr.user_image, pr.first_name, pr.last_name
posts = frappe.db.sql("""select p.*, pr.user_image, pr.first_name, pr.last_name
from tabPost p, tabProfile pr from tabPost p, tabProfile pr
where p.parent_post=%s and pr.name = p.owner where p.parent_post=%s and pr.name = p.owner
order by p.creation asc""", (post.name,), as_dict=True) order by p.creation asc""", (post.name,), as_dict=True)
@@ -48,7 +48,7 @@ def get_child_posts_html(post, context):
def clear_post_cache(post=None): def clear_post_cache(post=None):
cache = frappe.cache() cache = frappe.cache()
posts = [post] if post else frappe.conn.sql_list("select name from `tabPost`")
posts = [post] if post else frappe.db.sql_list("select name from `tabPost`")


for post in posts: for post in posts:
cache.delete_value("website_group_post:{}".format(post)) cache.delete_value("website_group_post:{}".format(post))
@@ -62,7 +62,7 @@ def add_post(group, content, picture, picture_name, title=None, parent_post=None
raise frappe.PermissionError raise frappe.PermissionError


if parent_post: if parent_post:
if frappe.conn.get_value("Post", parent_post, "parent_post"):
if frappe.db.get_value("Post", parent_post, "parent_post"):
frappe.throw("Cannot reply to a reply") frappe.throw("Cannot reply to a reply")
group = frappe.doc("Website Group", group) group = frappe.doc("Website Group", group)
@@ -133,13 +133,13 @@ def process_picture(post, picture_name, picture):
file_data = save_file(picture_name, picture, "Post", post.doc.name, decode=True) file_data = save_file(picture_name, picture, "Post", post.doc.name, decode=True)
post.doc.picture_url = file_data.file_name or file_data.file_url post.doc.picture_url = file_data.file_name or file_data.file_url
frappe.conn.set_value("Post", post.doc.name, "picture_url", post.doc.picture_url)
frappe.db.set_value("Post", post.doc.name, "picture_url", post.doc.picture_url)
clear_cache(website_group=post.doc.website_group) clear_cache(website_group=post.doc.website_group)
@frappe.whitelist() @frappe.whitelist()
def suggest_user(group, term): def suggest_user(group, term):
"""suggest a user that has read permission in this group tree""" """suggest a user that has read permission in this group tree"""
profiles = frappe.conn.sql("""select
profiles = frappe.db.sql("""select
pr.name, pr.first_name, pr.last_name, pr.name, pr.first_name, pr.last_name,
pr.user_image, pr.location pr.user_image, pr.location
from `tabProfile` pr from `tabProfile` pr


+ 4
- 4
frappe/templates/website_group/settings.py Просмотреть файл

@@ -13,7 +13,7 @@ def suggest_user(term, group):
if not get_access(pathname).get("admin"): if not get_access(pathname).get("admin"):
raise frappe.PermissionError raise frappe.PermissionError
profiles = frappe.conn.sql("""select pr.name, pr.first_name, pr.last_name,
profiles = frappe.db.sql("""select pr.name, pr.first_name, pr.last_name,
pr.user_image, pr.location pr.user_image, pr.location
from `tabProfile` pr from `tabProfile` pr
where (pr.first_name like %(term)s or pr.last_name like %(term)s) where (pr.first_name like %(term)s or pr.last_name like %(term)s)
@@ -45,7 +45,7 @@ def add_sitemap_permission(group, profile):
permission.insert(ignore_permissions=True) permission.insert(ignore_permissions=True)
profile = permission.doc.fields profile = permission.doc.fields
profile.update(frappe.conn.get_value("Profile", profile.profile,
profile.update(frappe.db.get_value("Profile", profile.profile,
["name", "first_name", "last_name", "user_image", "location"], as_dict=True)) ["name", "first_name", "last_name", "user_image", "location"], as_dict=True))
return frappe.get_template("templates/includes/sitemap_permission.html").render({ return frappe.get_template("templates/includes/sitemap_permission.html").render({
@@ -64,7 +64,7 @@ def update_permission(group, profile, perm, value):
# send email # send email
if perm=="admin" and int(value): if perm=="admin" and int(value):
group_title = frappe.conn.get_value("Website Route", pathname, "page_title")
group_title = frappe.db.get_value("Website Route", pathname, "page_title")
subject = "You have been made Administrator of Group " + group_title subject = "You have been made Administrator of Group " + group_title
@@ -88,7 +88,7 @@ def add_website_group(group, new_group, public_read, public_write, group_type="F
if not get_access(get_pathname(group)).get("admin"): if not get_access(get_pathname(group)).get("admin"):
raise frappe.PermissionError raise frappe.PermissionError
parent_website_route = frappe.conn.get_value("Website Route",
parent_website_route = frappe.db.get_value("Website Route",
{"ref_doctype": "Website Group", "docname": group}) {"ref_doctype": "Website Group", "docname": group})
frappe.bean({ frappe.bean({


+ 4
- 4
frappe/test_runner.py Просмотреть файл

@@ -16,7 +16,7 @@ def main(app=None, module=None, doctype=None, verbose=False):
frappe.flags.print_messages = verbose frappe.flags.print_messages = verbose
frappe.flags.in_test = True frappe.flags.in_test = True
if not frappe.conn:
if not frappe.db:
frappe.connect() frappe.connect()
if doctype: if doctype:
@@ -80,7 +80,7 @@ def _run_test(path, filename, verbose, test_suite=None, run=True):
def make_test_records(doctype, verbose=0): def make_test_records(doctype, verbose=0):
frappe.flags.mute_emails = True frappe.flags.mute_emails = True
if not frappe.conn:
if not frappe.db:
frappe.connect() frappe.connect()
for options in get_dependencies(doctype): for options in get_dependencies(doctype):
@@ -95,7 +95,7 @@ def make_test_records(doctype, verbose=0):
make_test_records_for_doctype(options, verbose) make_test_records_for_doctype(options, verbose)


def get_modules(doctype): def get_modules(doctype):
module = frappe.conn.get_value("DocType", doctype, "module")
module = frappe.db.get_value("DocType", doctype, "module")
try: try:
test_module = load_doctype_module(doctype, module, "test_") test_module = load_doctype_module(doctype, module, "test_")
if test_module: if test_module:
@@ -173,7 +173,7 @@ def print_mandatory_fields(doctype):
print print


def run_unittest(doctype, verbose=False): def run_unittest(doctype, verbose=False):
module = frappe.conn.get_value("DocType", doctype, "module")
module = frappe.db.get_value("DocType", doctype, "module")
test_module = get_module_name(doctype, module, "test_") test_module = get_module_name(doctype, module, "test_")
make_test_records(doctype, verbose=verbose) make_test_records(doctype, verbose=verbose)
test_suite = unittest.TestSuite() test_suite = unittest.TestSuite()


+ 8
- 8
frappe/tests/test_db.py Просмотреть файл

@@ -10,21 +10,21 @@ class TestDB(unittest.TestCase):
def test_get_value(self): def test_get_value(self):
from frappe.utils import now_datetime from frappe.utils import now_datetime
import time import time
frappe.conn.sql("""delete from `tabProfile` where name not in ('Administrator', 'Guest')""")
frappe.db.sql("""delete from `tabProfile` where name not in ('Administrator', 'Guest')""")
now = now_datetime() now = now_datetime()
self.assertEquals(frappe.conn.get_value("Profile", {"name": ["=", "Administrator"]}), "Administrator")
self.assertEquals(frappe.conn.get_value("Profile", {"name": ["like", "Admin%"]}), "Administrator")
self.assertEquals(frappe.conn.get_value("Profile", {"name": ["!=", "Guest"]}), "Administrator")
self.assertEquals(frappe.conn.get_value("Profile", {"modified": ["<", now]}), "Administrator")
self.assertEquals(frappe.conn.get_value("Profile", {"modified": ["<=", now]}), "Administrator")
self.assertEquals(frappe.db.get_value("Profile", {"name": ["=", "Administrator"]}), "Administrator")
self.assertEquals(frappe.db.get_value("Profile", {"name": ["like", "Admin%"]}), "Administrator")
self.assertEquals(frappe.db.get_value("Profile", {"name": ["!=", "Guest"]}), "Administrator")
self.assertEquals(frappe.db.get_value("Profile", {"modified": ["<", now]}), "Administrator")
self.assertEquals(frappe.db.get_value("Profile", {"modified": ["<=", now]}), "Administrator")


time.sleep(2) time.sleep(2)
if "Profile" in frappe.local.test_objects: if "Profile" in frappe.local.test_objects:
del frappe.local.test_objects["Profile"] del frappe.local.test_objects["Profile"]
make_test_records("Profile") make_test_records("Profile")
self.assertEquals("test1@example.com", frappe.conn.get_value("Profile", {"modified": [">", now]}))
self.assertEquals("test1@example.com", frappe.conn.get_value("Profile", {"modified": [">=", now]}))
self.assertEquals("test1@example.com", frappe.db.get_value("Profile", {"modified": [">", now]}))
self.assertEquals("test1@example.com", frappe.db.get_value("Profile", {"modified": [">=", now]}))

+ 5
- 5
frappe/tests/test_email.py Просмотреть файл

@@ -11,8 +11,8 @@ make_test_records("Profile")


class TestEmail(unittest.TestCase): class TestEmail(unittest.TestCase):
def setUp(self): def setUp(self):
frappe.conn.sql("""update tabProfile set unsubscribed=0""")
frappe.conn.sql("""delete from `tabBulk Email`""")
frappe.db.sql("""update tabProfile set unsubscribed=0""")
frappe.db.sql("""delete from `tabBulk Email`""")
def test_send(self): def test_send(self):
from frappe.utils.email_lib import sendmail from frappe.utils.email_lib import sendmail
@@ -25,7 +25,7 @@ class TestEmail(unittest.TestCase):
doctype='Profile', email_field='email', doctype='Profile', email_field='email',
subject='Testing Bulk', message='This is a bulk mail!') subject='Testing Bulk', message='This is a bulk mail!')
bulk = frappe.conn.sql("""select * from `tabBulk Email` where status='Not Sent'""", as_dict=1)
bulk = frappe.db.sql("""select * from `tabBulk Email` where status='Not Sent'""", as_dict=1)
self.assertEquals(len(bulk), 2) self.assertEquals(len(bulk), 2)
self.assertTrue('test@example.com' in [d['recipient'] for d in bulk]) self.assertTrue('test@example.com' in [d['recipient'] for d in bulk])
self.assertTrue('test1@example.com' in [d['recipient'] for d in bulk]) self.assertTrue('test1@example.com' in [d['recipient'] for d in bulk])
@@ -35,7 +35,7 @@ class TestEmail(unittest.TestCase):
self.test_bulk() self.test_bulk()
from frappe.utils.email_lib.bulk import flush from frappe.utils.email_lib.bulk import flush
flush(from_test=True) flush(from_test=True)
bulk = frappe.conn.sql("""select * from `tabBulk Email` where status='Sent'""", as_dict=1)
bulk = frappe.db.sql("""select * from `tabBulk Email` where status='Sent'""", as_dict=1)
self.assertEquals(len(bulk), 2) self.assertEquals(len(bulk), 2)
self.assertTrue('test@example.com' in [d['recipient'] for d in bulk]) self.assertTrue('test@example.com' in [d['recipient'] for d in bulk])
self.assertTrue('test1@example.com' in [d['recipient'] for d in bulk]) self.assertTrue('test1@example.com' in [d['recipient'] for d in bulk])
@@ -55,7 +55,7 @@ class TestEmail(unittest.TestCase):
doctype='Profile', email_field='email', doctype='Profile', email_field='email',
subject='Testing Bulk', message='This is a bulk mail!') subject='Testing Bulk', message='This is a bulk mail!')
bulk = frappe.conn.sql("""select * from `tabBulk Email` where status='Not Sent'""",
bulk = frappe.db.sql("""select * from `tabBulk Email` where status='Not Sent'""",
as_dict=1) as_dict=1)
self.assertEquals(len(bulk), 1) self.assertEquals(len(bulk), 1)
self.assertFalse('test@example.com' in [d['recipient'] for d in bulk]) self.assertFalse('test@example.com' in [d['recipient'] for d in bulk])


+ 6
- 6
frappe/tests/test_fmt_money.py Просмотреть файл

@@ -10,7 +10,7 @@ def fmt_money(amount, precision=None):
Convert to string with commas for thousands, millions etc Convert to string with commas for thousands, millions etc
""" """
number_format = frappe.conn.get_default("number_format") or "#,###.##"
number_format = frappe.db.get_default("number_format") or "#,###.##"
decimal_str, comma_str, precision = get_number_format_info(number_format) decimal_str, comma_str, precision = get_number_format_info(number_format)
@@ -64,7 +64,7 @@ import unittest


class TestFmtMoney(unittest.TestCase): class TestFmtMoney(unittest.TestCase):
def test_standard(self): def test_standard(self):
frappe.conn.set_default("number_format", "#,###.##")
frappe.db.set_default("number_format", "#,###.##")
self.assertEquals(fmt_money(100), "100.00") self.assertEquals(fmt_money(100), "100.00")
self.assertEquals(fmt_money(1000), "1,000.00") self.assertEquals(fmt_money(1000), "1,000.00")
self.assertEquals(fmt_money(10000), "10,000.00") self.assertEquals(fmt_money(10000), "10,000.00")
@@ -75,7 +75,7 @@ class TestFmtMoney(unittest.TestCase):
self.assertEquals(fmt_money(1000000000), "1,000,000,000.00") self.assertEquals(fmt_money(1000000000), "1,000,000,000.00")


def test_negative(self): def test_negative(self):
frappe.conn.set_default("number_format", "#,###.##")
frappe.db.set_default("number_format", "#,###.##")
self.assertEquals(fmt_money(-100), "-100.00") self.assertEquals(fmt_money(-100), "-100.00")
self.assertEquals(fmt_money(-1000), "-1,000.00") self.assertEquals(fmt_money(-1000), "-1,000.00")
self.assertEquals(fmt_money(-10000), "-10,000.00") self.assertEquals(fmt_money(-10000), "-10,000.00")
@@ -86,7 +86,7 @@ class TestFmtMoney(unittest.TestCase):
self.assertEquals(fmt_money(-1000000000), "-1,000,000,000.00") self.assertEquals(fmt_money(-1000000000), "-1,000,000,000.00")


def test_decimal(self): def test_decimal(self):
frappe.conn.set_default("number_format", "#.###,##")
frappe.db.set_default("number_format", "#.###,##")
self.assertEquals(fmt_money(-100), "-100,00") self.assertEquals(fmt_money(-100), "-100,00")
self.assertEquals(fmt_money(-1000), "-1.000,00") self.assertEquals(fmt_money(-1000), "-1.000,00")
self.assertEquals(fmt_money(-10000), "-10.000,00") self.assertEquals(fmt_money(-10000), "-10.000,00")
@@ -98,7 +98,7 @@ class TestFmtMoney(unittest.TestCase):




def test_lacs(self): def test_lacs(self):
frappe.conn.set_default("number_format", "#,##,###.##")
frappe.db.set_default("number_format", "#,##,###.##")
self.assertEquals(fmt_money(100), "100.00") self.assertEquals(fmt_money(100), "100.00")
self.assertEquals(fmt_money(1000), "1,000.00") self.assertEquals(fmt_money(1000), "1,000.00")
self.assertEquals(fmt_money(10000), "10,000.00") self.assertEquals(fmt_money(10000), "10,000.00")
@@ -109,7 +109,7 @@ class TestFmtMoney(unittest.TestCase):
self.assertEquals(fmt_money(1000000000), "1,00,00,00,000.00") self.assertEquals(fmt_money(1000000000), "1,00,00,00,000.00")


def test_no_precision(self): def test_no_precision(self):
frappe.conn.set_default("number_format", "#,###")
frappe.db.set_default("number_format", "#,###")
self.assertEquals(fmt_money(0.3), "0") self.assertEquals(fmt_money(0.3), "0")
self.assertEquals(fmt_money(100.3), "100") self.assertEquals(fmt_money(100.3), "100")
self.assertEquals(fmt_money(1000.3), "1,000") self.assertEquals(fmt_money(1000.3), "1,000")


+ 6
- 6
frappe/translate.py Просмотреть файл

@@ -21,7 +21,7 @@ import frappe, os, re, codecs, json
def get_user_lang(user=None): def get_user_lang(user=None):
if not user: if not user:
user = frappe.session.user user = frappe.session.user
user_lang = frappe.conn.get_value("Profile", user, "language")
user_lang = frappe.db.get_value("Profile", user, "language")
return get_lang_dict().get(user_lang!="Loading..." and user_lang or "english") return get_lang_dict().get(user_lang!="Loading..." and user_lang or "english")


def get_all_languages(): def get_all_languages():
@@ -115,17 +115,17 @@ def get_messages_for_app(app):
for m in frappe.local.app_modules[app]]) for m in frappe.local.app_modules[app]])
# doctypes # doctypes
for name in frappe.conn.sql_list("""select name from tabDocType
for name in frappe.db.sql_list("""select name from tabDocType
where module in ({})""".format(modules)): where module in ({})""".format(modules)):
messages.extend(get_messages_from_doctype(name)) messages.extend(get_messages_from_doctype(name))


# pages # pages
for name in frappe.conn.sql_list("""select name from tabPage
for name in frappe.db.sql_list("""select name from tabPage
where module in ({})""".format(modules)): where module in ({})""".format(modules)):
messages.extend(get_messages_from_page(name)) messages.extend(get_messages_from_page(name))
# reports # reports
for name in frappe.conn.sql_list("""select tabReport.name from tabDocType, tabReport
for name in frappe.db.sql_list("""select tabReport.name from tabDocType, tabReport
where tabReport.ref_doctype = tabDocType.name where tabReport.ref_doctype = tabDocType.name
and tabDocType.module in ({})""".format(modules)): and tabDocType.module in ({})""".format(modules)):
messages.extend(get_messages_from_report(name)) messages.extend(get_messages_from_report(name))
@@ -166,7 +166,7 @@ def get_messages_from_page(name):
def get_messages_from_report(name): def get_messages_from_report(name):
report = frappe.doc("Report", name) report = frappe.doc("Report", name)
messages = get_messages_from_page_or_report("Report", name, messages = get_messages_from_page_or_report("Report", name,
frappe.conn.get_value("DocType", report.ref_doctype, "module"))
frappe.db.get_value("DocType", report.ref_doctype, "module"))
if report.query: if report.query:
messages.extend(re.findall('"([^:,^"]*):', report.query)) messages.extend(re.findall('"([^:,^"]*):', report.query))
messages.append(report.report_name) messages.append(report.report_name)
@@ -174,7 +174,7 @@ def get_messages_from_report(name):


def get_messages_from_page_or_report(doctype, name, module=None): def get_messages_from_page_or_report(doctype, name, module=None):
if not module: if not module:
module = frappe.conn.get_value(doctype, name, "module")
module = frappe.db.get_value(doctype, name, "module")
file_path = frappe.get_module_path(module, doctype, name, name) file_path = frappe.get_module_path(module, doctype, name, name)
messages = get_messages_from_file(file_path + ".js") messages = get_messages_from_file(file_path + ".js")


+ 15
- 15
frappe/utils/__init__.py Просмотреть файл

@@ -38,7 +38,7 @@ def get_fullname(profile):
frappe.local.fullnames = {} frappe.local.fullnames = {}
if not frappe.local.fullnames.get(profile): if not frappe.local.fullnames.get(profile):
p = frappe.conn.get_value("Profile", profile, ["first_name", "last_name"], as_dict=True)
p = frappe.db.get_value("Profile", profile, ["first_name", "last_name"], as_dict=True)
if p: if p:
frappe.local.fullnames[profile] = " ".join(filter(None, frappe.local.fullnames[profile] = " ".join(filter(None,
[p.get('first_name'), p.get('last_name')])) or profile [p.get('first_name'), p.get('last_name')])) or profile
@@ -105,7 +105,7 @@ def get_traceback():
(unicode((b"").join(trace_list[:-1]), 'utf-8'), unicode(trace_list[-1], 'utf-8')) (unicode((b"").join(trace_list[:-1]), 'utf-8'), unicode(trace_list[-1], 'utf-8'))
if frappe.logger: if frappe.logger:
frappe.logger.error('Db:'+(frappe.conn and frappe.conn.cur_db_name or '') \
frappe.logger.error('Db:'+(frappe.db and frappe.db.cur_db_name or '') \
+ ' - ' + body) + ' - ' + body)
return body return body
@@ -176,7 +176,7 @@ def get_user_time_zone():
frappe.local.user_time_zone = frappe.cache().get_value("time_zone") frappe.local.user_time_zone = frappe.cache().get_value("time_zone")
if not frappe.local.user_time_zone: if not frappe.local.user_time_zone:
frappe.local.user_time_zone = frappe.conn.get_value('Control Panel', None, 'time_zone') \
frappe.local.user_time_zone = frappe.db.get_value('Control Panel', None, 'time_zone') \
or 'Asia/Calcutta' or 'Asia/Calcutta'
frappe.cache().set_value("time_zone", frappe.local.user_time_zone) frappe.cache().set_value("time_zone", frappe.local.user_time_zone)


@@ -261,7 +261,7 @@ def formatdate(string_date=None):
string_date = now_datetime().date() string_date = now_datetime().date()
if getattr(frappe.local, "user_format", None) is None: if getattr(frappe.local, "user_format", None) is None:
frappe.local.user_format = frappe.conn.get_default("date_format")
frappe.local.user_format = frappe.db.get_default("date_format")
out = frappe.local.user_format out = frappe.local.user_format
@@ -378,7 +378,7 @@ def fmt_money(amount, precision=None, currency=None):
""" """
Convert to string with commas for thousands, millions etc Convert to string with commas for thousands, millions etc
""" """
number_format = frappe.conn.get_default("number_format") or "#,###.##"
number_format = frappe.db.get_default("number_format") or "#,###.##"
decimal_str, comma_str, precision = get_number_format_info(number_format) decimal_str, comma_str, precision = get_number_format_info(number_format)
@@ -413,7 +413,7 @@ def fmt_money(amount, precision=None, currency=None):
amount = minus + amount amount = minus + amount
if currency: if currency:
symbol = frappe.conn.get_value("Currency", currency, "symbol")
symbol = frappe.db.get_value("Currency", currency, "symbol")
if symbol: if symbol:
amount = symbol + " " + amount amount = symbol + " " + amount


@@ -444,15 +444,15 @@ def money_in_words(number, main_currency = None, fraction_currency=None):
if not main_currency: if not main_currency:
main_currency = d.get('currency', 'INR') main_currency = d.get('currency', 'INR')
if not fraction_currency: if not fraction_currency:
fraction_currency = frappe.conn.get_value("Currency", main_currency, "fraction") or "Cent"
fraction_currency = frappe.db.get_value("Currency", main_currency, "fraction") or "Cent"


n = "%.2f" % flt(number) n = "%.2f" % flt(number)
main, fraction = n.split('.') main, fraction = n.split('.')
if len(fraction)==1: fraction += '0' if len(fraction)==1: fraction += '0'
number_format = frappe.conn.get_value("Currency", main_currency, "number_format") or \
frappe.conn.get_default("number_format") or "#,###.##"
number_format = frappe.db.get_value("Currency", main_currency, "number_format") or \
frappe.db.get_default("number_format") or "#,###.##"
in_million = True in_million = True
if number_format == "#,##,###.##": in_million = False if number_format == "#,##,###.##": in_million = False
@@ -530,13 +530,13 @@ def get_defaults(key=None):
""" """
Get dictionary of default values from the :term:`Control Panel`, or a value if key is passed Get dictionary of default values from the :term:`Control Panel`, or a value if key is passed
""" """
return frappe.conn.get_defaults(key)
return frappe.db.get_defaults(key)


def set_default(key, val): def set_default(key, val):
""" """
Set / add a default value to :term:`Control Panel` Set / add a default value to :term:`Control Panel`
""" """
return frappe.conn.set_default(key, val)
return frappe.db.set_default(key, val)


def remove_blanks(d): def remove_blanks(d):
""" """
@@ -688,12 +688,12 @@ def get_doctype_label(dt=None):
Gets label of a doctype Gets label of a doctype
""" """
if dt: if dt:
res = frappe.conn.sql("""\
res = frappe.db.sql("""\
SELECT name, dt_label FROM `tabDocType Label` SELECT name, dt_label FROM `tabDocType Label`
WHERE name=%s""", dt) WHERE name=%s""", dt)
return res and res[0][0] or dt return res and res[0][0] or dt
else: else:
res = frappe.conn.sql("SELECT name, dt_label FROM `tabDocType Label`")
res = frappe.db.sql("SELECT name, dt_label FROM `tabDocType Label`")
dt_label_dict = {} dt_label_dict = {}
for r in res: for r in res:
dt_label_dict[r[0]] = r[1] dt_label_dict[r[0]] = r[1]
@@ -705,7 +705,7 @@ def get_label_doctype(label):
""" """
Gets doctype from its label Gets doctype from its label
""" """
res = frappe.conn.sql("""\
res = frappe.db.sql("""\
SELECT name FROM `tabDocType Label` SELECT name FROM `tabDocType Label`
WHERE dt_label=%s""", label) WHERE dt_label=%s""", label)


@@ -823,7 +823,7 @@ def get_backups_path():
def get_url(uri=None): def get_url(uri=None):
url = get_request_site_address() url = get_request_site_address()
if not url or "localhost" in url: if not url or "localhost" in url:
subdomain = frappe.conn.get_value("Website Settings", "Website Settings",
subdomain = frappe.db.get_value("Website Settings", "Website Settings",
"subdomain") "subdomain")
if subdomain: if subdomain:
if "http" not in subdomain: if "http" not in subdomain:


+ 5
- 5
frappe/utils/backups.py Просмотреть файл

@@ -131,10 +131,10 @@ def get_backup():
This function is executed when the user clicks on This function is executed when the user clicks on
Toos > Download Backup Toos > Download Backup
""" """
#if verbose: print frappe.conn.cur_db_name + " " + conf.db_password
#if verbose: print frappe.db.cur_db_name + " " + conf.db_password
delete_temp_backups() delete_temp_backups()
odb = BackupGenerator(frappe.conn.cur_db_name, frappe.conn.cur_db_name,\
frappe.conf.db_password, db_host = frappe.conn.host)
odb = BackupGenerator(frappe.db.cur_db_name, frappe.db.cur_db_name,\
frappe.conf.db_password, db_host = frappe.db.host)
odb.get_backup() odb.get_backup()
recipient_list = odb.send_email() recipient_list = odb.send_email()
frappe.msgprint("""A download link to your backup will be emailed \ frappe.msgprint("""A download link to your backup will be emailed \
@@ -150,9 +150,9 @@ def scheduled_backup(older_than=6, ignore_files=False, backup_path_db=None, back


def new_backup(older_than=6, ignore_files=False, backup_path_db=None, backup_path_files=None): def new_backup(older_than=6, ignore_files=False, backup_path_db=None, backup_path_files=None):
delete_temp_backups(older_than=168) delete_temp_backups(older_than=168)
odb = BackupGenerator(frappe.conn.cur_db_name, frappe.conn.cur_db_name,\
odb = BackupGenerator(frappe.db.cur_db_name, frappe.db.cur_db_name,\
frappe.conf.db_password, frappe.conf.db_password,
backup_path_db=backup_path_db, backup_path_files=backup_path_files, db_host = frappe.conn.host)
backup_path_db=backup_path_db, backup_path_files=backup_path_files, db_host = frappe.db.host)
odb.get_backup(older_than, ignore_files) odb.get_backup(older_than, ignore_files)
return odb return odb




+ 3
- 3
frappe/utils/datautils.py Просмотреть файл

@@ -18,7 +18,7 @@ def read_csv_content_from_uploaded_file(ignore_encoding=False):
return read_csv_content(fcontent, ignore_encoding) return read_csv_content(fcontent, ignore_encoding)


def read_csv_content_from_attached_file(doc): def read_csv_content_from_attached_file(doc):
fileid = frappe.conn.get_value("File Data", {"attached_to_doctype": doc.doctype,
fileid = frappe.db.get_value("File Data", {"attached_to_doctype": doc.doctype,
"attached_to_name":doc.name}, "name") "attached_to_name":doc.name}, "name")
if not fileid: if not fileid:
msgprint("File not attached!") msgprint("File not attached!")
@@ -111,7 +111,7 @@ def check_record(d, parenttype=None, doctype_dl=None):
if docfield.fieldtype=='Select' and val and docfield.options: if docfield.fieldtype=='Select' and val and docfield.options:
if docfield.options.startswith('link:'): if docfield.options.startswith('link:'):
link_doctype = docfield.options.split(':')[1] link_doctype = docfield.options.split(':')[1]
if not frappe.conn.exists(link_doctype, val):
if not frappe.db.exists(link_doctype, val):
frappe.msgprint("%s: %s must be a valid %s" % (docfield.label, val, link_doctype), frappe.msgprint("%s: %s must be a valid %s" % (docfield.label, val, link_doctype),
raise_exception=1) raise_exception=1)
elif docfield.options == "attach_files:": elif docfield.options == "attach_files:":
@@ -130,7 +130,7 @@ def check_record(d, parenttype=None, doctype_dl=None):


def import_doc(d, doctype, overwrite, row_idx, submit=False, ignore_links=False): def import_doc(d, doctype, overwrite, row_idx, submit=False, ignore_links=False):
"""import main (non child) document""" """import main (non child) document"""
if d.get("name") and frappe.conn.exists(doctype, d['name']):
if d.get("name") and frappe.db.exists(doctype, d['name']):
if overwrite: if overwrite:
bean = frappe.bean(doctype, d['name']) bean = frappe.bean(doctype, d['name'])
bean.ignore_links = ignore_links bean.ignore_links = ignore_links


+ 2
- 2
frappe/utils/email_lib/__init__.py Просмотреть файл

@@ -26,7 +26,7 @@ def get_contact_list():
"""Returns contacts (from autosuggest)""" """Returns contacts (from autosuggest)"""
cond = ['`%s` like "%s%%"' % (f, cond = ['`%s` like "%s%%"' % (f,
frappe.form_dict.get('txt')) for f in frappe.form_dict.get('where').split(',')] frappe.form_dict.get('txt')) for f in frappe.form_dict.get('where').split(',')]
cl = frappe.conn.sql("select `%s` from `tab%s` where %s" % (
cl = frappe.db.sql("select `%s` from `tab%s` where %s" % (
frappe.form_dict.get('select') frappe.form_dict.get('select')
,frappe.form_dict.get('from') ,frappe.form_dict.get('from')
,' OR '.join(cond) ,' OR '.join(cond)
@@ -35,7 +35,7 @@ def get_contact_list():
frappe.response['cl'] = filter(None, [c[0] for c in cl]) frappe.response['cl'] = filter(None, [c[0] for c in cl])


def get_system_managers(): def get_system_managers():
return frappe.conn.sql_list("""select parent FROM tabUserRole
return frappe.db.sql_list("""select parent FROM tabUserRole
WHERE role='System Manager' WHERE role='System Manager'
AND parent!='Administrator' AND parent!='Administrator'
AND parent IN AND parent IN

+ 10
- 10
frappe/utils/email_lib/bulk.py Просмотреть файл

@@ -22,7 +22,7 @@ def send(recipients=None, sender=None, doctype='Profile', email_field='email',
return cint(rdata.unsubscribed) return cint(rdata.unsubscribed)


def check_bulk_limit(new_mails): def check_bulk_limit(new_mails):
this_month = frappe.conn.sql("""select count(*) from `tabBulk Email` where
this_month = frappe.db.sql("""select count(*) from `tabBulk Email` where
month(creation)=month(%s)""" % nowdate())[0][0] month(creation)=month(%s)""" % nowdate())[0][0]


monthly_bulk_mail_limit = frappe.conf.get('monthly_bulk_mail_limit') or 500 monthly_bulk_mail_limit = frappe.conf.get('monthly_bulk_mail_limit') or 500
@@ -54,13 +54,13 @@ def send(recipients=None, sender=None, doctype='Profile', email_field='email',
if not recipients: recipients = [] if not recipients: recipients = []
if not sender or sender == "Administrator": if not sender or sender == "Administrator":
sender = frappe.conn.get_value('Email Settings', None, 'auto_email_id')
sender = frappe.db.get_value('Email Settings', None, 'auto_email_id')
check_bulk_limit(len(recipients)) check_bulk_limit(len(recipients))
formatted = get_formatted_html(subject, message) formatted = get_formatted_html(subject, message)


for r in filter(None, list(set(recipients))): for r in filter(None, list(set(recipients))):
rdata = frappe.conn.sql("""select * from `tab%s` where %s=%s""" % (doctype,
rdata = frappe.db.sql("""select * from `tab%s` where %s=%s""" % (doctype,
email_field, '%s'), (r,), as_dict=1) email_field, '%s'), (r,), as_dict=1)


doc = rdata and rdata[0] or {} doc = rdata and rdata[0] or {}
@@ -99,11 +99,11 @@ def unsubscribe():
field = frappe.form_dict.get('email_field') field = frappe.form_dict.get('email_field')
email = frappe.form_dict.get('email') email = frappe.form_dict.get('email')


frappe.conn.sql("""update `tab%s` set unsubscribed=1
frappe.db.sql("""update `tab%s` set unsubscribed=1
where `%s`=%s""" % (doctype, field, '%s'), (email,)) where `%s`=%s""" % (doctype, field, '%s'), (email,))
if not frappe.form_dict.get("from_test"): if not frappe.form_dict.get("from_test"):
frappe.conn.commit()
frappe.db.commit()


frappe.local.message_title = "Unsubscribe" frappe.local.message_title = "Unsubscribe"
frappe.local.message = "<h3>Unsubscribed</h3><p>%s has been successfully unsubscribed.</p>" % email frappe.local.message = "<h3>Unsubscribed</h3><p>%s has been successfully unsubscribed.</p>" % email
@@ -122,27 +122,27 @@ def flush(from_test=False):
from_test = True from_test = True
for i in xrange(500): for i in xrange(500):
email = frappe.conn.sql("""select * from `tabBulk Email` where
email = frappe.db.sql("""select * from `tabBulk Email` where
status='Not Sent' limit 1 for update""", as_dict=1) status='Not Sent' limit 1 for update""", as_dict=1)
if email: if email:
email = email[0] email = email[0]
else: else:
break break
frappe.conn.sql("""update `tabBulk Email` set status='Sending' where name=%s""",
frappe.db.sql("""update `tabBulk Email` set status='Sending' where name=%s""",
(email["name"],), auto_commit=auto_commit) (email["name"],), auto_commit=auto_commit)
try: try:
if not from_test: if not from_test:
smtpserver.sess.sendmail(email["sender"], email["recipient"], email["message"]) smtpserver.sess.sendmail(email["sender"], email["recipient"], email["message"])


frappe.conn.sql("""update `tabBulk Email` set status='Sent' where name=%s""",
frappe.db.sql("""update `tabBulk Email` set status='Sent' where name=%s""",
(email["name"],), auto_commit=auto_commit) (email["name"],), auto_commit=auto_commit)


except Exception, e: except Exception, e:
frappe.conn.sql("""update `tabBulk Email` set status='Error', error=%s
frappe.db.sql("""update `tabBulk Email` set status='Error', error=%s
where name=%s""", (unicode(e), email["name"]), auto_commit=auto_commit) where name=%s""", (unicode(e), email["name"]), auto_commit=auto_commit)


def clear_outbox(): def clear_outbox():
"""remove mails older than 30 days in Outbox""" """remove mails older than 30 days in Outbox"""
frappe.conn.sql("""delete from `tabBulk Email` where
frappe.db.sql("""delete from `tabBulk Email` where
datediff(now(), creation) > 30""") datediff(now(), creation) > 30""")

+ 2
- 2
frappe/utils/email_lib/email_body.py Просмотреть файл

@@ -159,7 +159,7 @@ class EMail:
return email return email
if not self.sender: if not self.sender:
self.sender = frappe.conn.get_value('Email Settings', None,
self.sender = frappe.db.get_value('Email Settings', None,
'auto_email_id') or frappe.conf.get('auto_email_id') or None 'auto_email_id') or frappe.conf.get('auto_email_id') or None
if not self.sender: if not self.sender:
msgprint(_("Please specify 'Auto Email Id' in Setup > Email Settings")) msgprint(_("Please specify 'Auto Email Id' in Setup > Email Settings"))
@@ -211,7 +211,7 @@ def get_footer(footer=None):
footer = footer or "" footer = footer or ""
# control panel # control panel
footer += frappe.conn.get_value('Control Panel', None, 'mail_footer') or ''
footer += frappe.db.get_value('Control Panel', None, 'mail_footer') or ''
# hooks # hooks
for f in frappe.get_hooks("mail_footer"): for f in frappe.get_hooks("mail_footer"):


+ 4
- 4
frappe/utils/email_lib/receive.py Просмотреть файл

@@ -149,7 +149,7 @@ class POP3Mailbox:
if not self.check_mails(): if not self.check_mails():
return # nothing to do return # nothing to do
frappe.conn.commit()
frappe.db.commit()
self.connect() self.connect()
try: try:
@@ -193,9 +193,9 @@ class POP3Mailbox:
msg = self.pop.retr(msg_num) msg = self.pop.retr(msg_num)


incoming_mail = IncomingMail(b'\n'.join(msg[1])) incoming_mail = IncomingMail(b'\n'.join(msg[1]))
frappe.conn.begin()
frappe.db.begin()
self.process_message(incoming_mail) self.process_message(incoming_mail)
frappe.conn.commit()
frappe.db.commit()
except (TotalSizeExceededError, EmailTimeoutError): except (TotalSizeExceededError, EmailTimeoutError):
# propagate this error to break the loop # propagate this error to break the loop
@@ -205,7 +205,7 @@ class POP3Mailbox:
# log performs rollback and logs error in scheduler log # log performs rollback and logs error in scheduler log
log("receive.get_messages", self.make_error_msg(msg_num, incoming_mail)) log("receive.get_messages", self.make_error_msg(msg_num, incoming_mail))
self.errors = True self.errors = True
frappe.conn.rollback()
frappe.db.rollback()
self.pop.dele(msg_num) self.pop.dele(msg_num)
else: else:


+ 4
- 4
frappe/utils/file_manager.py Просмотреть файл

@@ -11,7 +11,7 @@ from frappe import conf
class MaxFileSizeReachedError(frappe.ValidationError): pass class MaxFileSizeReachedError(frappe.ValidationError): pass


def get_file_url(file_data_name): def get_file_url(file_data_name):
data = frappe.conn.get_value("File Data", file_data_name, ["file_name", "file_url"], as_dict=True)
data = frappe.db.get_value("File Data", file_data_name, ["file_name", "file_url"], as_dict=True)
return data.file_name or data.file_url return data.file_name or data.file_url


def upload(): def upload():
@@ -96,7 +96,7 @@ def save_file(fname, content, dt, dn, decode=False):
import filecmp import filecmp
from frappe.model.code import load_doctype_module from frappe.model.code import load_doctype_module
files_path = os.path.join(frappe.local.site_path, "public", "files") files_path = os.path.join(frappe.local.site_path, "public", "files")
module = load_doctype_module(dt, frappe.conn.get_value("DocType", dt, "module"))
module = load_doctype_module(dt, frappe.db.get_value("DocType", dt, "module"))
if hasattr(module, "attachments_folder"): if hasattr(module, "attachments_folder"):
files_path = os.path.join(files_path, module.attachments_folder) files_path = os.path.join(files_path, module.attachments_folder)
@@ -211,7 +211,7 @@ def write_file(content, files_path):
def remove_all(dt, dn): def remove_all(dt, dn):
"""remove all files in a transaction""" """remove all files in a transaction"""
try: try:
for fid in frappe.conn.sql_list("""select name from `tabFile Data` where
for fid in frappe.db.sql_list("""select name from `tabFile Data` where
attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)): attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)):
remove_file(fid) remove_file(fid)
except Exception, e: except Exception, e:
@@ -222,7 +222,7 @@ def remove_file(fid):
frappe.delete_doc("File Data", fid) frappe.delete_doc("File Data", fid)
def get_file(fname): def get_file(fname):
f = frappe.conn.sql("""select file_name from `tabFile Data`
f = frappe.db.sql("""select file_name from `tabFile Data`
where name=%s or file_name=%s""", (fname, fname)) where name=%s or file_name=%s""", (fname, fname))
if f: if f:
file_name = f[0][0] file_name = f[0][0]


+ 3
- 3
frappe/utils/install.py Просмотреть файл

@@ -12,7 +12,7 @@ def before_install():


def after_install(): def after_install():
# reset installed apps for re-install # reset installed apps for re-install
frappe.conn.set_global("installed_apps", '["frappe"]')
frappe.db.set_global("installed_apps", '["frappe"]')
# core users / roles # core users / roles
install_docs = [ install_docs = [
@@ -34,11 +34,11 @@ def after_install():
pass pass


# all roles to admin # all roles to admin
frappe.bean("Profile", "Administrator").get_controller().add_roles(*frappe.conn.sql_list("""
frappe.bean("Profile", "Administrator").get_controller().add_roles(*frappe.db.sql_list("""
select name from tabRole""")) select name from tabRole"""))


# update admin password # update admin password
from frappe.auth import _update_password from frappe.auth import _update_password
_update_password("Administrator", frappe.conf.get("admin_password")) _update_password("Administrator", frappe.conf.get("admin_password"))


frappe.conn.commit()
frappe.db.commit()

+ 30
- 30
frappe/utils/nestedset.py Просмотреть файл

@@ -49,7 +49,7 @@ def update_nsm(doc_obj):


# set old parent # set old parent
d.fields[opf] = p d.fields[opf] = p
frappe.conn.set_value(d.doctype, d.name, opf, p or '')
frappe.db.set_value(d.doctype, d.name, opf, p or '')


# reload # reload
d._loadfromdb() d._loadfromdb()
@@ -66,23 +66,23 @@ def update_add_node(doc, parent, parent_field):


# get the last sibling of the parent # get the last sibling of the parent
if parent: if parent:
left, right = frappe.conn.sql("select lft, rgt from `tab%s` where name=%s" \
left, right = frappe.db.sql("select lft, rgt from `tab%s` where name=%s" \
% (doctype, "%s"), parent)[0] % (doctype, "%s"), parent)[0]
validate_loop(doc.doctype, doc.name, left, right) validate_loop(doc.doctype, doc.name, left, right)
else: # root else: # root
right = frappe.conn.sql("select ifnull(max(rgt),0)+1 from `tab%s` where ifnull(`%s`,'') =''" % (doctype, parent_field))[0][0]
right = frappe.db.sql("select ifnull(max(rgt),0)+1 from `tab%s` where ifnull(`%s`,'') =''" % (doctype, parent_field))[0][0]
right = right or 1 right = right or 1
# update all on the right # update all on the right
frappe.conn.sql("update `tab%s` set rgt = rgt+2, modified='%s' where rgt >= %s" %(doctype,n,right))
frappe.conn.sql("update `tab%s` set lft = lft+2, modified='%s' where lft >= %s" %(doctype,n,right))
frappe.db.sql("update `tab%s` set rgt = rgt+2, modified='%s' where rgt >= %s" %(doctype,n,right))
frappe.db.sql("update `tab%s` set lft = lft+2, modified='%s' where lft >= %s" %(doctype,n,right))
# update index of new node # update index of new node
if frappe.conn.sql("select * from `tab%s` where lft=%s or rgt=%s"% (doctype, right, right+1)):
if frappe.db.sql("select * from `tab%s` where lft=%s or rgt=%s"% (doctype, right, right+1)):
frappe.msgprint("Nested set error. Please send mail to support") frappe.msgprint("Nested set error. Please send mail to support")
raise Exception raise Exception


frappe.conn.sql("update `tab%s` set lft=%s, rgt=%s, modified='%s' where name='%s'" % (doctype,right,right+1,n,name))
frappe.db.sql("update `tab%s` set lft=%s, rgt=%s, modified='%s' where name='%s'" % (doctype,right,right+1,n,name))
return right return right




@@ -90,41 +90,41 @@ def update_move_node(doc, parent_field):
parent = doc.fields.get(parent_field) parent = doc.fields.get(parent_field)
if parent: if parent:
new_parent = frappe.conn.sql("""select lft, rgt from `tab%s`
new_parent = frappe.db.sql("""select lft, rgt from `tab%s`
where name = %s""" % (doc.doctype, '%s'), parent, as_dict=1)[0] where name = %s""" % (doc.doctype, '%s'), parent, as_dict=1)[0]
validate_loop(doc.doctype, doc.name, new_parent.lft, new_parent.rgt) validate_loop(doc.doctype, doc.name, new_parent.lft, new_parent.rgt)
# move to dark side # move to dark side
frappe.conn.sql("""update `tab%s` set lft = -lft, rgt = -rgt
frappe.db.sql("""update `tab%s` set lft = -lft, rgt = -rgt
where lft >= %s and rgt <= %s"""% (doc.doctype, '%s', '%s'), (doc.lft, doc.rgt)) where lft >= %s and rgt <= %s"""% (doc.doctype, '%s', '%s'), (doc.lft, doc.rgt))
# shift left # shift left
diff = doc.rgt - doc.lft + 1 diff = doc.rgt - doc.lft + 1
frappe.conn.sql("""update `tab%s` set lft = lft -%s, rgt = rgt - %s
frappe.db.sql("""update `tab%s` set lft = lft -%s, rgt = rgt - %s
where lft > %s"""% (doc.doctype, '%s', '%s', '%s'), (diff, diff, doc.rgt)) where lft > %s"""% (doc.doctype, '%s', '%s', '%s'), (diff, diff, doc.rgt))


# shift left rgts of ancestors whose only rgts must shift # shift left rgts of ancestors whose only rgts must shift
frappe.conn.sql("""update `tab%s` set rgt = rgt - %s
frappe.db.sql("""update `tab%s` set rgt = rgt - %s
where lft < %s and rgt > %s"""% (doc.doctype, '%s', '%s', '%s'), where lft < %s and rgt > %s"""% (doc.doctype, '%s', '%s', '%s'),
(diff, doc.lft, doc.rgt)) (diff, doc.lft, doc.rgt))
if parent: if parent:
new_parent = frappe.conn.sql("""select lft, rgt from `tab%s`
new_parent = frappe.db.sql("""select lft, rgt from `tab%s`
where name = %s""" % (doc.doctype, '%s'), parent, as_dict=1)[0] where name = %s""" % (doc.doctype, '%s'), parent, as_dict=1)[0]
# set parent lft, rgt # set parent lft, rgt
frappe.conn.sql("""update `tab%s` set rgt = rgt + %s
frappe.db.sql("""update `tab%s` set rgt = rgt + %s
where name = %s"""% (doc.doctype, '%s', '%s'), (diff, parent)) where name = %s"""% (doc.doctype, '%s', '%s'), (diff, parent))
# shift right at new parent # shift right at new parent
frappe.conn.sql("""update `tab%s` set lft = lft + %s, rgt = rgt + %s
frappe.db.sql("""update `tab%s` set lft = lft + %s, rgt = rgt + %s
where lft > %s""" % (doc.doctype, '%s', '%s', '%s'), where lft > %s""" % (doc.doctype, '%s', '%s', '%s'),
(diff, diff, new_parent.rgt)) (diff, diff, new_parent.rgt))


# shift right rgts of ancestors whose only rgts must shift # shift right rgts of ancestors whose only rgts must shift
frappe.conn.sql("""update `tab%s` set rgt = rgt + %s
frappe.db.sql("""update `tab%s` set rgt = rgt + %s
where lft < %s and rgt > %s""" % (doc.doctype, '%s', '%s', '%s'), where lft < %s and rgt > %s""" % (doc.doctype, '%s', '%s', '%s'),
(diff, new_parent.lft, new_parent.rgt)) (diff, new_parent.lft, new_parent.rgt))


@@ -132,11 +132,11 @@ def update_move_node(doc, parent_field):
new_diff = new_parent.rgt - doc.lft new_diff = new_parent.rgt - doc.lft
else: else:
# new root # new root
max_rgt = frappe.conn.sql("""select max(rgt) from `tab%s`""" % doc.doctype)[0][0]
max_rgt = frappe.db.sql("""select max(rgt) from `tab%s`""" % doc.doctype)[0][0]
new_diff = max_rgt + 1 - doc.lft new_diff = max_rgt + 1 - doc.lft
# bring back from dark side # bring back from dark side
frappe.conn.sql("""update `tab%s` set lft = -lft + %s, rgt = -rgt + %s
frappe.db.sql("""update `tab%s` set lft = -lft + %s, rgt = -rgt + %s
where lft < 0"""% (doc.doctype, '%s', '%s'), (new_diff, new_diff)) where lft < 0"""% (doc.doctype, '%s', '%s'), (new_diff, new_diff))
def rebuild_tree(doctype, parent_field): def rebuild_tree(doctype, parent_field):
@@ -144,14 +144,14 @@ def rebuild_tree(doctype, parent_field):
call rebuild_node for all root nodes call rebuild_node for all root nodes
""" """
# get all roots # get all roots
frappe.conn.auto_commit_on_many_writes = 1
frappe.db.auto_commit_on_many_writes = 1


right = 1 right = 1
result = frappe.conn.sql("SELECT name FROM `tab%s` WHERE `%s`='' or `%s` IS NULL ORDER BY name ASC" % (doctype, parent_field, parent_field))
result = frappe.db.sql("SELECT name FROM `tab%s` WHERE `%s`='' or `%s` IS NULL ORDER BY name ASC" % (doctype, parent_field, parent_field))
for r in result: for r in result:
right = rebuild_node(doctype, r[0], right, parent_field) right = rebuild_node(doctype, r[0], right, parent_field)


frappe.conn.auto_commit_on_many_writes = 0
frappe.db.auto_commit_on_many_writes = 0
def rebuild_node(doctype, parent, left, parent_field): def rebuild_node(doctype, parent, left, parent_field):
""" """
@@ -164,13 +164,13 @@ def rebuild_node(doctype, parent, left, parent_field):
right = left+1 right = left+1


# get all children of this node # get all children of this node
result = frappe.conn.sql("SELECT name FROM `tab%s` WHERE `%s`='%s'" % (doctype, parent_field, parent))
result = frappe.db.sql("SELECT name FROM `tab%s` WHERE `%s`='%s'" % (doctype, parent_field, parent))
for r in result: for r in result:
right = rebuild_node(doctype, r[0], right, parent_field) right = rebuild_node(doctype, r[0], right, parent_field)


# we've got the left value, and now that we've processed # we've got the left value, and now that we've processed
# the children of this node we also know the right value # the children of this node we also know the right value
frappe.conn.sql("UPDATE `tab%s` SET lft=%s, rgt=%s, modified='%s' WHERE name='%s'" % (doctype,left,right,n,parent))
frappe.db.sql("UPDATE `tab%s` SET lft=%s, rgt=%s, modified='%s' WHERE name='%s'" % (doctype,left,right,n,parent))


#return the right value of this node + 1 #return the right value of this node + 1
return right+1 return right+1
@@ -178,7 +178,7 @@ def rebuild_node(doctype, parent, left, parent_field):


def validate_loop(doctype, name, lft, rgt): def validate_loop(doctype, name, lft, rgt):
"""check if item not an ancestor (loop)""" """check if item not an ancestor (loop)"""
if name in frappe.conn.sql_list("""select name from `tab%s` where lft <= %s and rgt >= %s""" % (doctype,
if name in frappe.db.sql_list("""select name from `tab%s` where lft <= %s and rgt >= %s""" % (doctype,
"%s", "%s"), (lft, rgt)): "%s", "%s"), (lft, rgt)):
frappe.throw("""Item cannot be added to its own descendents.""", NestedSetRecursionError) frappe.throw("""Item cannot be added to its own descendents.""", NestedSetRecursionError)


@@ -196,7 +196,7 @@ class DocTypeNestedSet(object):
msgprint(_("Root ") + self.doc.doctype + _(" cannot be deleted."), raise_exception=1) msgprint(_("Root ") + self.doc.doctype + _(" cannot be deleted."), raise_exception=1)
# cannot delete non-empty group # cannot delete non-empty group
has_children = frappe.conn.sql("""select count(name) from `tab{doctype}`
has_children = frappe.db.sql("""select count(name) from `tab{doctype}`
where `{nsm_parent_field}`=%s""".format(doctype=self.doc.doctype, nsm_parent_field=self.nsm_parent_field), where `{nsm_parent_field}`=%s""".format(doctype=self.doc.doctype, nsm_parent_field=self.nsm_parent_field),
(self.doc.name,))[0][0] (self.doc.name,))[0][0]
if has_children: if has_children:
@@ -209,7 +209,7 @@ class DocTypeNestedSet(object):
def before_rename(self, olddn, newdn, merge=False, group_fname="is_group"): def before_rename(self, olddn, newdn, merge=False, group_fname="is_group"):
if merge: if merge:
is_group = frappe.conn.get_value(self.doc.doctype, newdn, group_fname)
is_group = frappe.db.get_value(self.doc.doctype, newdn, group_fname)
if self.doc.fields[group_fname] != is_group: if self.doc.fields[group_fname] != is_group:
frappe.throw(_("""Merging is only possible between Group-to-Group or frappe.throw(_("""Merging is only possible between Group-to-Group or
Ledger-to-Ledger"""), NestedSetInvalidMergeError) Ledger-to-Ledger"""), NestedSetInvalidMergeError)
@@ -221,27 +221,27 @@ class DocTypeNestedSet(object):
def validate_one_root(self): def validate_one_root(self):
if not self.doc.fields[self.nsm_parent_field]: if not self.doc.fields[self.nsm_parent_field]:
if frappe.conn.sql("""select count(*) from `tab%s` where
if frappe.db.sql("""select count(*) from `tab%s` where
ifnull(%s, '')=''""" % (self.doc.doctype, self.nsm_parent_field))[0][0] > 1: ifnull(%s, '')=''""" % (self.doc.doctype, self.nsm_parent_field))[0][0] > 1:
frappe.throw(_("""Multiple root nodes not allowed."""), NestedSetMultipleRootsError) frappe.throw(_("""Multiple root nodes not allowed."""), NestedSetMultipleRootsError)


def validate_ledger(self, group_identifier="is_group"): def validate_ledger(self, group_identifier="is_group"):
if self.doc.fields.get(group_identifier) == "No": if self.doc.fields.get(group_identifier) == "No":
if frappe.conn.sql("""select name from `tab%s` where %s=%s and docstatus!=2""" %
if frappe.db.sql("""select name from `tab%s` where %s=%s and docstatus!=2""" %
(self.doc.doctype, self.nsm_parent_field, '%s'), (self.doc.name)): (self.doc.doctype, self.nsm_parent_field, '%s'), (self.doc.name)):
frappe.throw(self.doc.doctype + ": " + self.doc.name + frappe.throw(self.doc.doctype + ": " + self.doc.name +
_(" can not be marked as a ledger as it has existing child")) _(" can not be marked as a ledger as it has existing child"))


def get_root_of(doctype): def get_root_of(doctype):
"""Get root element of a DocType with a tree structure""" """Get root element of a DocType with a tree structure"""
result = frappe.conn.sql_list("""select name from `tab%s`
result = frappe.db.sql_list("""select name from `tab%s`
where lft=1 and rgt=(select max(rgt) from `tab%s` where docstatus < 2)""" % where lft=1 and rgt=(select max(rgt) from `tab%s` where docstatus < 2)""" %
(doctype, doctype)) (doctype, doctype))
return result[0] if result else None return result[0] if result else None
def get_ancestors_of(doctype, name): def get_ancestors_of(doctype, name):
"""Get ancestor elements of a DocType with a tree structure""" """Get ancestor elements of a DocType with a tree structure"""
lft, rgt = frappe.conn.get_value(doctype, name, ["lft", "rgt"])
result = frappe.conn.sql_list("""select name from `tab%s`
lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
result = frappe.db.sql_list("""select name from `tab%s`
where lft<%s and rgt>%s order by lft desc""" % (doctype, "%s", "%s"), (lft, rgt)) where lft<%s and rgt>%s order by lft desc""" % (doctype, "%s", "%s"), (lft, rgt))
return result or [] return result or []

+ 1
- 1
frappe/utils/response.py Просмотреть файл

@@ -16,7 +16,7 @@ def report_error(status_code):
frappe.errprint(frappe.utils.get_traceback()) frappe.errprint(frappe.utils.get_traceback())
frappe._response.status_code = status_code frappe._response.status_code = status_code
if frappe.request_method == "POST": if frappe.request_method == "POST":
frappe.conn.rollback()
frappe.db.rollback()


def build_response(): def build_response():
print_map = { print_map = {


+ 12
- 12
frappe/utils/scheduler.py Просмотреть файл

@@ -29,18 +29,18 @@ def execute(site=None):
format = '%Y-%m-%d %H:%M:%S' format = '%Y-%m-%d %H:%M:%S'
if not frappe.conn:
if not frappe.db:
frappe.connect(site=site) frappe.connect(site=site)
out = [] out = []


nowtime = frappe.utils.now_datetime() nowtime = frappe.utils.now_datetime()
last = frappe.conn.get_global('scheduler_last_event')
last = frappe.db.get_global('scheduler_last_event')
# set scheduler last event # set scheduler last event
frappe.conn.begin()
frappe.conn.set_global('scheduler_last_event', nowtime.strftime(format))
frappe.conn.commit()
frappe.db.begin()
frappe.db.set_global('scheduler_last_event', nowtime.strftime(format))
frappe.db.commit()
if last: if last:
last = datetime.strptime(last, format) last = datetime.strptime(last, format)
@@ -71,11 +71,11 @@ def trigger(method):
if method==event_name: if method==event_name:
try: try:
frappe.get_attr(handler)() frappe.get_attr(handler)()
frappe.conn.commit()
frappe.db.commit()
except Exception: except Exception:
traceback += log("Method: {method}, Handler: {handler}".format(method=method, handler=handler)) traceback += log("Method: {method}, Handler: {handler}".format(method=method, handler=handler))
traceback += log(frappe.get_traceback()) traceback += log(frappe.get_traceback())
frappe.conn.rollback()
frappe.db.rollback()
return traceback or 'ok' return traceback or 'ok'


@@ -84,23 +84,23 @@ def log(method, message=None):
message = frappe.utils.cstr(message) + "\n" if message else "" message = frappe.utils.cstr(message) + "\n" if message else ""
message += frappe.get_traceback() message += frappe.get_traceback()
if not (frappe.conn and frappe.conn._conn):
if not (frappe.db and frappe.db._conn):
frappe.connect() frappe.connect()
frappe.conn.rollback()
frappe.conn.begin()
frappe.db.rollback()
frappe.db.begin()


d = frappe.doc("Scheduler Log") d = frappe.doc("Scheduler Log")
d.method = method d.method = method
d.error = message d.error = message
d.save() d.save()


frappe.conn.commit()
frappe.db.commit()
return message return message
def get_errors(from_date, to_date, limit): def get_errors(from_date, to_date, limit):
errors = frappe.conn.sql("""select modified, method, error from `tabScheduler Log`
errors = frappe.db.sql("""select modified, method, error from `tabScheduler Log`
where date(modified) between %s and %s where date(modified) between %s and %s
and error not like '%%[Errno 110] Connection timed out%%' and error not like '%%[Errno 110] Connection timed out%%'
order by modified limit %s""", (from_date, to_date, limit), as_dict=True) order by modified limit %s""", (from_date, to_date, limit), as_dict=True)


+ 3
- 3
frappe/website/doctype/blog_post/blog_post.py Просмотреть файл

@@ -28,11 +28,11 @@ class DocType(WebsiteGenerator):
if self.doc.published and not self.doc.published_on: if self.doc.published and not self.doc.published_on:
self.doc.published_on = today() self.doc.published_on = today()


self.doc.parent_website_route = frappe.conn.get_value("Website Route",
self.doc.parent_website_route = frappe.db.get_value("Website Route",
{"ref_doctype": "Blog Category", "docname": self.doc.blog_category}) {"ref_doctype": "Blog Category", "docname": self.doc.blog_category})


# update posts # update posts
frappe.conn.sql("""update tabBlogger set posts=(select count(*) from `tabBlog Post`
frappe.db.sql("""update tabBlogger set posts=(select count(*) from `tabBlog Post`
where ifnull(blogger,'')=tabBlogger.name) where ifnull(blogger,'')=tabBlogger.name)
where name=%s""", (self.doc.blogger,)) where name=%s""", (self.doc.blogger,))
@@ -42,7 +42,7 @@ class DocType(WebsiteGenerator):
clear_cache("writers") clear_cache("writers")


def clear_blog_cache(): def clear_blog_cache():
for blog in frappe.conn.sql_list("""select page_name from
for blog in frappe.db.sql_list("""select page_name from
`tabBlog Post` where ifnull(published,0)=1"""): `tabBlog Post` where ifnull(published,0)=1"""):
clear_cache(blog) clear_cache(blog)


+ 4
- 4
frappe/website/doctype/blog_post/test_blog_post.py Просмотреть файл

@@ -32,9 +32,9 @@ from frappe.core.page.user_properties.user_properties import add, remove, get_pr
test_dependencies = ["Profile"] test_dependencies = ["Profile"]
class TestBlogPost(unittest.TestCase): class TestBlogPost(unittest.TestCase):
def setUp(self): def setUp(self):
frappe.conn.sql("""update tabDocPerm set `restricted`=0 where parent='Blog Post'
frappe.db.sql("""update tabDocPerm set `restricted`=0 where parent='Blog Post'
and ifnull(permlevel,0)=0""") and ifnull(permlevel,0)=0""")
frappe.conn.sql("""update `tabBlog Post` set owner='test2@example.com'
frappe.db.sql("""update `tabBlog Post` set owner='test2@example.com'
where name='_test-blog-post'""") where name='_test-blog-post'""")


frappe.clear_cache(doctype="Blog Post") frappe.clear_cache(doctype="Blog Post")
@@ -84,7 +84,7 @@ class TestBlogPost(unittest.TestCase):
self.assertEquals(doc.get("blog_category"), "_Test Blog Category 1") self.assertEquals(doc.get("blog_category"), "_Test Blog Category 1")
def add_restricted_on_blogger(self): def add_restricted_on_blogger(self):
frappe.conn.sql("""update tabDocPerm set `restricted`=1 where parent='Blog Post' and role='Blogger'
frappe.db.sql("""update tabDocPerm set `restricted`=1 where parent='Blog Post' and role='Blogger'
and ifnull(permlevel,0)=0""") and ifnull(permlevel,0)=0""")
frappe.clear_cache(doctype="Blog Post") frappe.clear_cache(doctype="Blog Post")
@@ -100,7 +100,7 @@ class TestBlogPost(unittest.TestCase):
self.assertFalse(post1.has_read_perm()) self.assertFalse(post1.has_read_perm())
def test_owner_match_report(self): def test_owner_match_report(self):
frappe.conn.sql("""update tabDocPerm set `restricted`=1 where parent='Blog Post'
frappe.db.sql("""update tabDocPerm set `restricted`=1 where parent='Blog Post'
and ifnull(permlevel,0)=0""") and ifnull(permlevel,0)=0""")
frappe.clear_cache(doctype="Blog Post") frappe.clear_cache(doctype="Blog Post")




Некоторые файлы не были показаны из-за большого количества измененных файлов

Загрузка…
Отмена
Сохранить