Changed frappe.conn to frappe.db

This commit is contained in:
Anand Doshi 2014-02-26 12:35:02 +05:30
parent a5b72fd258
commit edbadc18b2
127 changed files with 747 additions and 747 deletions

View file

@ -60,7 +60,7 @@ def set_user_lang(user, user_language=None):
from frappe.translate import get_lang_dict
if not user_language:
user_language = conn.get_value("Profile", user, "language")
user_language = db.get_value("Profile", user, "language")
if user_language:
lang_dict = get_lang_dict()
@ -68,7 +68,7 @@ def set_user_lang(user, user_language=None):
local.lang = lang_dict[user_language]
# local-globals
conn = local("conn")
db = local("db")
conf = local("conf")
form = form_dict = local("form_dict")
request = local("request")
@ -129,8 +129,8 @@ def get_site_config():
def destroy():
"""closes connection and releases werkzeug local"""
if conn:
conn.close()
if db:
db.close()
release_local(local)
@ -182,7 +182,7 @@ def msgprint(msg, small=0, raise_exception=0, as_table=False):
def _raise_exception():
if raise_exception:
if flags.rollback_on_exception:
conn.rollback()
db.rollback()
import inspect
if inspect.isclass(raise_exception) and issubclass(raise_exception, Exception):
raise raise_exception, msg
@ -210,10 +210,10 @@ def create_folder(path):
if not os.path.exists(path): os.makedirs(path)
def connect(site=None, db_name=None):
from db import Database
from database import Database
if 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.form_dict = _dict()
local.session = _dict()
@ -296,11 +296,11 @@ def has_permission(doctype, ptype="read", refdoc=None):
return frappe.permissions.has_permission(doctype, ptype, refdoc)
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):
clear_perms(doctype)
reload_doc(conn.get_value("DocType", doctype, "module"),
reload_doc(db.get_value("DocType", doctype, "module"),
"DocType", doctype, force=True)
def generate_hash(txt=None):
@ -413,7 +413,7 @@ def get_all_apps(with_frappe=False, with_internal_apps=True):
def get_installed_apps():
if flags.in_install_db:
return []
installed = json.loads(conn.get_global("installed_apps") or "[]")
installed = json.loads(db.get_global("installed_apps") or "[]")
return installed
def get_hooks(hook=None, app_name=None):
@ -507,14 +507,14 @@ def make_property_setter(args):
def get_application_home_page(user='Guest'):
"""get home page for user"""
hpl = conn.sql("""select home_page
hpl = db.sql("""select home_page
from `tabDefault Home Page`
where parent='Control Panel'
and role in ('%s') order by idx asc limit 1""" % "', '".join(get_roles(user)))
if hpl:
return hpl[0][0]
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):
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)
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):
bean({

View file

@ -54,7 +54,7 @@ def handle():
if not bean.has_permission("write"):
frappe.throw("No Permission", frappe.PermissionError)
bean.run_method(frappe.local.form_dict.run_method, **frappe.local.form_dict)
frappe.conn.commit()
frappe.db.commit()
else:
if name:
@ -66,12 +66,12 @@ def handle():
if frappe.local.request.method=="POST":
frappe.local.response.update({
"doclist": frappe.client.insert(frappe.local.form_dict.doclist)})
frappe.conn.commit()
frappe.db.commit()
if frappe.local.request.method=="PUT":
frappe.local.response.update({
"doclist":frappe.client.save(frappe.local.form_dict.doclist)})
frappe.conn.commit()
frappe.db.commit()
if frappe.local.request.method=="DELETE":
frappe.client.delete(doctype, name)

View file

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

View file

@ -3,7 +3,7 @@
from __future__ import unicode_literals
import frappe
import frappe.db
import frappe.database
import frappe.utils
import frappe.profile
from frappe import conf
@ -35,8 +35,8 @@ class HTTPRequest:
frappe.local.login_manager = LoginManager()
# 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')
# load profile
@ -81,7 +81,7 @@ class HTTPRequest:
def connect(self, ac_name = None):
"""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', ''))
class LoginManager:
@ -106,7 +106,7 @@ class LoginManager:
self.set_user_info()
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)
if info.user_type=="Website User":
frappe.local._response.set_cookie("system_user", "no")
@ -142,12 +142,12 @@ class LoginManager:
"""raise exception if user not enabled"""
from frappe.utils import cint
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')
def check_password(self, user, pwd):
"""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))
if not user:
self.fail('Incorrect password')
@ -165,7 +165,7 @@ class LoginManager:
def validate_ip_address(self):
"""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:
return
@ -182,8 +182,8 @@ class LoginManager:
def validate_hour(self):
"""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):
return
@ -206,7 +206,7 @@ class LoginManager:
if not user: user = frappe.session.user
self.run_trigger('on_logout')
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"))
else:
from frappe.sessions import clear_sessions
@ -241,7 +241,7 @@ class CookieManager:
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
import datetime
@ -252,7 +252,7 @@ class CookieManager:
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))
on duplicate key update `password`=password(%s)""", (user,
password, password))

View file

@ -28,7 +28,7 @@ def get_bootinfo():
bootinfo['control_panel'] = frappe._dict(cp.copy())
bootinfo['sysdefaults'] = frappe.defaults.get_defaults()
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")
if frappe.session['user'] != 'Guest':
@ -43,10 +43,10 @@ def get_bootinfo():
except ImportError, e:
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,'')!=''"""))
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,'')!=''""")))
add_home_page(bootinfo, doclist)
@ -83,7 +83,7 @@ def load_conf_settings(bootinfo):
if key in conf: bootinfo[key] = conf.get(key)
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())))
def load_translations(bootinfo):
@ -95,7 +95,7 @@ def load_translations(bootinfo):
def get_fullnames():
"""map of user fullnames"""
ret = frappe.conn.sql("""select name,
ret = frappe.db.sql("""select name,
concat(ifnull(first_name, ''),
if(ifnull(last_name, '')!='', ' ', ''), ifnull(last_name, '')),
user_image, gender, email

View file

@ -275,7 +275,7 @@ def install_fixtures():
def add_system_manager(email, first_name=None, last_name=None):
frappe.connect()
frappe.profile.add_system_manager(email, first_name, last_name)
frappe.conn.commit()
frappe.db.commit()
frappe.destroy()
# utilities
@ -352,7 +352,7 @@ def update_all_sites(remote=None, branch=None, verbose=True):
def reload_doc(module, doctype, docname, force=False):
frappe.connect()
frappe.reload_doc(module, doctype, docname, force=force)
frappe.conn.commit()
frappe.db.commit()
frappe.destroy()
@cmd
@ -406,10 +406,10 @@ def move(dest_dir=None):
def domain(host_url=None):
frappe.connect()
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:
print frappe.conn.get_value("Website Settings", None, "subdomain")
print frappe.db.get_value("Website Settings", None, "subdomain")
frappe.destroy()
@cmd
@ -451,13 +451,13 @@ def sync_statics():
from frappe.website import statics
frappe.connect()
statics.sync_statics()
frappe.conn.commit()
frappe.db.commit()
frappe.destroy()
@cmd
def reset_perms():
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"""):
frappe.clear_cache(doctype=d)
frappe.reset_perms(d)
@ -467,7 +467,7 @@ def reset_perms():
def execute(method):
frappe.connect()
ret = frappe.get_attr(method)()
frappe.conn.commit()
frappe.db.commit()
frappe.destroy()
if ret:
print ret
@ -593,9 +593,9 @@ def checkout(branch):
def set_admin_password(admin_password):
import frappe
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,))
frappe.conn.commit()
frappe.db.commit()
frappe.destroy()
@cmd
@ -728,13 +728,13 @@ def get_site_status(verbose=False):
'active_website_users': get_active_website_users(),
'website_users': get_website_users(),
'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(),
'working_directory': frappe.local.site_path
}
# 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)
if control_panel_details:
ret.update(control_panel_details)
@ -743,7 +743,7 @@ def get_site_status(verbose=False):
for doctype in ("Company", "Customer", "Item", "Quotation", "Sales Invoice",
"Journal Voucher", "Stock Ledger Entry"):
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()

View file

@ -11,7 +11,7 @@ import json, os
@frappe.whitelist()
def get(doctype, name=None, filters=None):
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:
raise Exception, "No document found for given filters"
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("["):
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()
def set_value(doctype, name, fieldname, value):
if fieldname in frappe.model.default_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:
bean = frappe.bean(doc.parenttype, doc.parent)
child = bean.doclist.getone({"doctype": doctype, "name": name})
@ -90,7 +90,7 @@ def delete(doctype, name):
@frappe.whitelist()
def set_default(key, value, parent=None):
"""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.whitelist()

View file

@ -9,7 +9,7 @@ class DocType:
self.doc, self.doclist = d, dl
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:
frappe.msgprint("Max Comments reached!", raise_exception=True)
@ -45,13 +45,13 @@ class DocType:
raise
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 "[]"
return json.loads(_comments)
def update_comments_in_parent(self, _comments):
# 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))
def on_trash(self):
@ -63,8 +63,8 @@ class DocType:
self.update_comments_in_parent(_comments)
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" """):
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)""")

View file

@ -21,12 +21,12 @@ import frappe, unittest, json
# self.cleanup()
#
# 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):
# self.comment = frappe.bean({

View file

@ -65,7 +65,7 @@ def _make(doctype=None, name=None, content=None, subject=None, sent_or_received
d.subject = subject
d.content = content
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
# add as child
@ -94,7 +94,7 @@ def get_customer_supplier(args=None):
if not args: args = frappe.local.form_dict
if not args.get('contact'):
raise Exception, "Please specify a contact to fetch Customer/Supplier"
result = frappe.conn.sql("""\
result = frappe.db.sql("""\
select customer, supplier
from `tabContact`
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)
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:
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)
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:
print_html = scrub_urls(print_html)

View file

@ -48,7 +48,7 @@ class DocType:
def on_trash(self):
# delete property setter entries
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabProperty Setter`
WHERE doc_type = %s
AND field_name = %s""",
@ -63,7 +63,7 @@ class DocType:
if label_index==-1: return
prev_field = field_list[label_index]
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabProperty Setter`
WHERE doc_type = %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):
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 \
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({
"doctype":"Custom Field",
"dt": doctype,

View file

@ -174,7 +174,7 @@ class DocType:
if self.has_property_changed(ref_d, new_d, prop):
# using set_value not bean because validations are called
# 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:
d = self.prepare_to_set(prop, new_d, ref_d, dt_dl)
if d: diff_list.append(d)
@ -193,7 +193,7 @@ class DocType:
"""
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
FROM `tabDocField`
WHERE parent='DocField' or parent='DocType'""", as_dict=1)
@ -312,12 +312,12 @@ class DocType:
for d in ps_doclist:
# Delete existing property setter entry
if not d.fields.get("field_name"):
frappe.conn.sql("""
frappe.db.sql("""
DELETE FROM `tabProperty Setter`
WHERE doc_type = %(doc_type)s
AND property = %(property)s""", d.fields)
else:
frappe.conn.sql("""
frappe.db.sql("""
DELETE FROM `tabProperty Setter`
WHERE doc_type = %(doc_type)s
AND field_name = %(field_name)s
@ -334,7 +334,7 @@ class DocType:
and resets it to standard
"""
if self.doc.doc_type:
frappe.conn.sql("""
frappe.db.sql("""
DELETE FROM `tabProperty Setter`
WHERE doc_type = %s""", self.doc.doc_type)

View file

@ -9,14 +9,14 @@ class DocType:
self.doc, self.doclist = d, dl
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" """):
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)""")
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" """):
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)""")

View file

@ -32,10 +32,10 @@ class DocType:
def change_modified_of_parent(self):
if frappe.flags.in_import:
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)
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]))
def scrub_field_names(self):
@ -67,7 +67,7 @@ class DocType:
if autoname and (not autoname.startswith('field:')) and (not autoname.startswith('eval:')) \
and (not autoname=='Prompt') and (not autoname.startswith('naming_series:')):
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:
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):
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:"):
frappe.msgprint("link: type Select fields are getting replaced. Please check for %s" % d.label,
raise_exception=True)
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):
if merge:
@ -110,9 +110,9 @@ class DocType:
def after_rename(self, old, new, merge=False):
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:
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):
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 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):
new = self.doc.addchild('fields', 'DocField', self.doclist)
new.label = 'Amended From'
@ -153,7 +153,7 @@ class DocType:
new.idx = self.get_max_idx() + 1
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)
return max_idx and max_idx[0][0] or 0
@ -187,7 +187,7 @@ def validate_fields(fields):
raise_exception=1)
if d.options=="[Select]":
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,
raise_exception=1)
@ -231,7 +231,7 @@ def validate_permissions(permissions, for_remove=False):
doctype = permissions and permissions[0].parent
issingle = issubmittable = isimportable = False
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 = cint(values.issingle)
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"):
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.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
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.doc.role_name = role
r.insert()

View file

@ -49,7 +49,7 @@ def has_permission(doc):
def send_event_digest():
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
and user_type='System User' and name not in ('Guest', 'Administrator')""", as_dict=1):
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:
user = frappe.session.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,
monday, tuesday, wednesday, thursday, friday, saturday, sunday
from tabEvent where ((

View file

@ -43,17 +43,17 @@ class TestEvent(unittest.TestCase):
def test_allowed_public(self):
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))
def test_not_allowed_private(self):
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))
def test_allowed_private_if_in_event_user(self):
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))
def test_event_list(self):

View file

@ -20,7 +20,7 @@ class DocType():
def on_update(self):
# 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
and name!=%s
and attached_to_doctype=%s
@ -29,7 +29,7 @@ class DocType():
if len(n_records) > 0:
self.doc.duplicate_entry = n_records[0][0]
frappe.msgprint(frappe._("Same file has already been attached to the record"))
frappe.conn.rollback()
frappe.db.rollback()
raise frappe.DuplicateEntryError
def on_trash(self):
@ -44,7 +44,7 @@ class DocType():
pass
# 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]}):
if self.doc.file_name.startswith("files/"):
path = frappe.utils.get_site_path("public", self.doc.file_name)

View file

@ -19,12 +19,12 @@ class DocType:
def set_as_default(self):
from frappe.utils import set_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
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)
set_default('letter_head', self.doc.name)
# 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)

View file

@ -17,7 +17,7 @@ def get_notifications():
open_count_doctype = {}
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,)))
for d in config.for_doctype:
@ -51,7 +51,7 @@ def get_notifications():
def delete_notification_count_for(doctype):
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():
delete_notification_count_for("Event")
@ -78,7 +78,7 @@ def get_notification_info_for_boot():
can_read = frappe.user.get_can_read()
conditions = {}
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())):
if d in config.for_doctype:
@ -104,9 +104,9 @@ def get_notification_config():
return config
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" """):
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)""")

View file

@ -18,8 +18,8 @@ class DocType:
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("'",'').\
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)
if cnt:
cnt = cint(cnt[0][0].split('-')[-1]) + 1

View file

@ -17,7 +17,7 @@ class DocType:
frappe.msgprint("Standard Print Format cannot be updated.", raise_exception=1)
# 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')
def on_update(self):
@ -90,13 +90,13 @@ def get_print_format_name(doctype, format_name):
return format_name
# 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")
if os.path.exists(path):
with open(path, "r") as pffile:
return pffile.read()
else:
html = frappe.conn.get_value("Print Format", format_name, "html")
html = frappe.db.get_value("Print Format", format_name, "html")
if html:
return html
else:
@ -104,7 +104,7 @@ def get_print_format_name(doctype, format_name):
def get_print_style(style=None):
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",
style.lower() + ".css")
if not os.path.exists(path):

View file

@ -18,7 +18,7 @@ class DocType:
self.doc.email = self.doc.email.strip()
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"))
def validate(self):
@ -67,7 +67,7 @@ class DocType:
if 'max_users' in conf and self.doc.enabled and \
self.doc.name not in ["Administrator", "Guest"] and \
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
and ifnull(user_type, "System User") = "System User"
and name not in ('Administrator', 'Guest', %s)""", (self.doc.name,))[0][0]
@ -104,7 +104,7 @@ class DocType:
def on_update(self):
# 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)
def update_gravatar(self):
@ -120,11 +120,11 @@ class DocType:
from frappe.utils import random_string, get_url
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))
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
and parent not in ('Administrator', %s) and exists
(select * from `tabProfile` profile
@ -155,7 +155,7 @@ class DocType:
from frappe.utils import get_url
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'])
if full_name == "Guest":
@ -196,20 +196,20 @@ class DocType:
frappe.local.login_manager.logout(user=self.doc.name)
# 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
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,))
# 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,))
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
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))
def before_rename(self, olddn, newdn, merge=False):
@ -237,27 +237,27 @@ class DocType:
}))
def after_rename(self, olddn, newdn, merge=False):
tables = frappe.conn.sql("show tables")
tables = frappe.db.sql("show 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 = []
for d in desc:
if d.get('Field') in ['owner', 'modified_by']:
has_fields.append(d.get('Field'))
for field in has_fields:
frappe.conn.sql("""\
frappe.db.sql("""\
update `%s` set `%s`=%s
where `%s`=%s""" % \
(tab[0], field, '%s', field, '%s'), (newdn, olddn))
# set email
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabProfile` set email=%s
where name=%s""", (newdn, newdn))
# update __Auth table
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):
for role in roles:
@ -281,7 +281,7 @@ def get_languages():
@frappe.whitelist()
def get_all_roles(arg=None):
"""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""")]
@frappe.whitelist()
@ -292,7 +292,7 @@ def get_user_roles(arg=None):
@frappe.whitelist()
def get_perm_info(arg=None):
"""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
and docstatus<2 order by parent, permlevel""",
(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):
# verify old password
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:
return _("Cannot Update: Incorrect / Expired Link.")
elif old_password:
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)):
return _("Cannot Update: Incorrect 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()
@ -320,14 +320,14 @@ def update_password(new_password, key=None, old_password=None):
@frappe.whitelist(allow_guest=True)
def sign_up(email, full_name):
profile = frappe.conn.get("Profile", {"email": email})
profile = frappe.db.get("Profile", {"email": email})
if profile:
if profile.disabled:
return _("Registered but disabled.")
else:
return _("Already Registered")
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:
raise Exception, "Too Many New Profiles"
from frappe.utils import random_string
@ -349,7 +349,7 @@ def reset_password(user):
if user in ["demo@erpnext.com", "Administrator"]:
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!
frappe.session["user"] = "Administrator"
profile = frappe.bean("Profile", user)
@ -371,7 +371,7 @@ def facebook_login(data):
# garbage
raise frappe.ValidationError
if not frappe.conn.exists("Profile", user):
if not frappe.db.exists("Profile", user):
if data.get("birthday"):
b = data.get("birthday").split("/")
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):
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`
where ifnull(enabled, 0)=1
and docstatus < 2
@ -426,25 +426,25 @@ def profile_query(doctype, txt, searchfield, start, page_len, filters):
def get_total_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'
and name not in ('Administrator', 'Guest')""")[0][0]
def get_active_users():
"""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'
and name not in ('Administrator', 'Guest')
and hour(timediff(now(), last_login)) < 72""")[0][0]
def get_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]
def get_active_website_users():
"""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'
and hour(timediff(now(), last_login)) < 72""")[0][0]

View file

@ -8,7 +8,7 @@ from frappe.model.delete_doc import delete_doc, LinkExistsError
class TestProfile(unittest.TestCase):
def test_delete(self):
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")
profile = frappe.bean(copy=test_records[1])
@ -19,33 +19,33 @@ class TestProfile(unittest.TestCase):
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",)))
from frappe.core.doctype.role.test_role import test_records as role_records
frappe.bean(copy=role_records[1]).insert()
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"))
self.assertEquals(frappe.conn.get_value("Profile",
self.assertEquals(frappe.db.get_value("Profile",
{"email":"test@example.com", "first_name": "_Test"},
["first_name", "email"]),
("_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]
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)
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):
p_meta = frappe.get_doctype("Profile")

View file

@ -16,7 +16,7 @@ class DocType:
def validate(self):
"""delete other property setters on this, if this is new"""
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
and doc_type = %(doc_type)s
and ifnull(field_name,'') = ifnull(%(field_name)s, '')
@ -26,7 +26,7 @@ class DocType:
frappe.clear_cache(doctype = self.doc.doc_type)
def get_property_list(self, dt):
return frappe.conn.sql("""select fieldname, label, fieldtype
return frappe.db.sql("""select fieldname, label, fieldtype
from tabDocField
where parent=%s
and fieldtype not in ('Section Break', 'Column Break', 'HTML', 'Read Only', 'Table')
@ -35,19 +35,19 @@ class DocType:
def get_setup_data(self):
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'),
'df_properties': self.get_property_list('DocField')
}
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):
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:
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]
def on_update(self):

View file

@ -32,4 +32,4 @@ class DocType:
from frappe.modules.export_file import export_to_files
if self.doc.is_standard == 'Yes' and (conf.get('developer_mode') or 0) == 1:
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"))

View file

@ -12,7 +12,7 @@ class DocType:
if self.doc.is_new():
self.add_comment(frappe._("Assignment Added"))
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:
self.add_comment(frappe._("Assignment Status Changed"))

View file

@ -10,7 +10,7 @@ class DocType:
self.doc, self.doclist = d, dl
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}):
frappe.msgprint("Role Already Exists", raise_exception=True)

View file

@ -24,7 +24,7 @@ def restore(version):
for d in doclist[1:]:
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
frappe.bean(doclist).save()

View file

@ -44,7 +44,7 @@ class DocType:
states.sort(lambda x, y: x.idx - y.idx)
for d in self.doclist.get({"doctype": "Workflow Document State"}):
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,
'%s', self.doc.workflow_state_field, "%s"), (d.state, d.doc_status))
docstatus_map[d.doc_status] = d.state
@ -52,6 +52,6 @@ class DocType:
def set_active(self):
if int(self.doc.is_active or 0):
# 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""",
self.doc.document_type)

View file

@ -20,7 +20,7 @@ def get_notification_config():
def get_things_todo():
"""Returns a count of incomplete todos"""
incomplete_todos = frappe.conn.sql("""\
incomplete_todos = frappe.db.sql("""\
SELECT COUNT(*) FROM `tabToDo`
WHERE status="Open"
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():
"returns unread (docstatus-0 messages for a user)"
return frappe.conn.sql("""\
return frappe.db.sql("""\
SELECT count(*)
FROM `tabComment`
WHERE comment_doctype IN ('My Company', 'Message')

View file

@ -25,7 +25,7 @@ data_keys = frappe._dict({
@frappe.whitelist()
def get_doctypes():
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""")]
else:
return frappe.user._get("can_import")
@ -79,7 +79,7 @@ def get_template(doctype=None, parent_doctype=None, all_doctypes="No", with_data
doctype_dl = frappe.model.doctype.get(dt)
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)
@ -186,7 +186,7 @@ def get_template(doctype=None, parent_doctype=None, all_doctypes="No", with_data
if all_doctypes:
# add child tables
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)):
add_data_row(row_group, child_doctype, child, ci)
@ -354,7 +354,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
column_idx_to_fieldname = {}
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")):
submit_after_import = False
@ -373,7 +373,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
check_data_length()
make_column_map()
frappe.conn.begin()
frappe.db.begin()
if not overwrite:
overwrite = params.get('overwrite')
doctype_dl = frappe.model.doctype.get(doctype)
@ -401,7 +401,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
# ignoring parent check as it will be automatically added
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.ignore_links = ignore_links
bean.doclist.update(doclist)
@ -444,9 +444,9 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,
ret, error = validate_parent(parent_list, parenttype, ret, error)
if error:
frappe.conn.rollback()
frappe.db.rollback()
else:
frappe.conn.commit()
frappe.db.commit()
frappe.flags.mute_emails = False
@ -487,7 +487,7 @@ def get_parent_field(doctype, parenttype):
def delete_child_rows(rows, doctype):
"""delete child rows for all parents"""
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
def import_file_by_path(path, ignore_links=False, overwrite=False):
@ -544,7 +544,7 @@ def import_doclist(path, overwrite=False, ignore_links=False, ignore_insert=Fals
_import_doclist(doc)
else:
_import_doclist(data)
frappe.conn.commit()
frappe.db.commit()
if f.endswith(".csv"):
import_file_by_path(f, ignore_links=True, overwrite=overwrite)
frappe.conn.commit()
frappe.db.commit()

View file

@ -14,19 +14,19 @@ def get_list(arg=None):
frappe.form_dict['user'] = frappe.session['user']
# 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')
and comment_docname = %s
""", frappe.user.name)
delete_notification_count_for("Messages")
frappe.conn.commit()
frappe.db.commit()
if frappe.form_dict['contact'] == frappe.session['user']:
# return messages
return frappe.conn.sql("""select * from `tabComment`
return frappe.db.sql("""select * from `tabComment`
where (owner=%(contact)s
or comment_docname=%(user)s
or (owner=comment_docname and ifnull(parenttype, "")!="Assignment"))
@ -34,7 +34,7 @@ def get_list(arg=None):
order by creation desc
limit %(limit_start)s, %(limit_page_length)s""", frappe.local.form_dict, as_dict=1)
else:
return frappe.conn.sql("""select * from `tabComment`
return frappe.db.sql("""select * from `tabComment`
where (owner=%(contact)s and comment_docname=%(user)s)
or (owner=%(user)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()
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
and timediff(now(), lastupdate) < time("01:00:00")) as has_session
from tabProfile
@ -83,15 +83,15 @@ def post(arg=None):
@frappe.whitelist()
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']);
def notify(arg=None):
from frappe.utils import cstr, get_fullname, get_url
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),
message=frappe.get_template("templates/emails/new_message.html").render({
"from": get_fullname(frappe.user.name),

View file

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

View file

@ -10,18 +10,18 @@ from frappe.modules.import_file import get_file_path, read_doclist_from_file
def get_roles_and_doctypes():
frappe.only_for("System Manager")
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
name not in ('DocType', 'Control Panel') and
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')""")]
}
@frappe.whitelist()
def get_permissions(doctype=None, role=None):
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""" % (\
doctype and (" parent='%s'" % doctype) or "",
role and ((doctype and " and " or "") + " role='%s'" % role) or "",
@ -30,7 +30,7 @@ def get_permissions(doctype=None, role=None):
@frappe.whitelist()
def remove(doctype, name):
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)
@frappe.whitelist()
@ -52,7 +52,7 @@ def add(parent, role, permlevel):
@frappe.whitelist()
def update(name, doctype, ptype, value=0):
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))
validate_and_reset(doctype)
@ -69,7 +69,7 @@ def reset(doctype):
def clear_doctype_cache(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
and tabDocPerm.role = tabUserRole.role""", doctype):
frappe.clear_cache(user=user)
@ -77,7 +77,7 @@ def clear_doctype_cache(doctype):
@frappe.whitelist()
def get_users_with_role(role):
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
tabUserRole.role=%s
and tabProfile.name != "Administrator"
@ -86,6 +86,6 @@ def get_users_with_role(role):
@frappe.whitelist()
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)
return [d for d in read_doclist_from_file(path) if d.get("doctype")=="DocPerm"]

View file

@ -9,7 +9,7 @@ import frappe.permissions
@frappe.whitelist()
def get_users_and_links():
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
name not in ("Administrator", "Guest")"""),
"link_fields": get_restrictable_doctypes()
@ -22,7 +22,7 @@ def get_properties(parent=None, defkey=None, defvalue=None):
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
where parent not in ('Control Panel', '__global')
and substr(defkey,1,1)!='_'
@ -68,7 +68,7 @@ def add(user, defkey, defvalue):
user=user, doctype=defkey, name=defvalue))
# 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))
if not d:
@ -84,6 +84,6 @@ def get_restrictable_doctypes():
and `tabDocPerm`.name in ({roles}))""".format(roles=", ".join(["%s"]*len(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),
values)

View file

@ -14,7 +14,7 @@ class Database:
"""
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
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):
self.host = host or frappe.conf.db_host or 'localhost'
@ -164,7 +164,7 @@ class Database:
self.transaction_writes += 1
if not frappe.flags.in_test and self.transaction_writes > 10000:
if self.auto_commit_on_many_writes:
frappe.conn.commit()
frappe.db.commit()
else:
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'
@ -402,7 +402,7 @@ class Database:
def touch(self, doctype, docname):
from frappe.utils import 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))
return modified
@ -483,10 +483,10 @@ class Database:
def count(self, dt, filters=None, debug=False):
if 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]
else:
return frappe.conn.sql("""select count(*)
return frappe.db.sql("""select count(*)
from `tab%s`""" % (dt,))[0][0]
@ -495,7 +495,7 @@ class Database:
from frappe.utils import now_datetime
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),
now_datetime() - relativedelta(minutes=minutes))[0][0]
@ -505,9 +505,9 @@ class Database:
def add_index(self, doctype, fields, index_name=None):
if not index_name:
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)))
def close(self):

View file

@ -33,7 +33,7 @@ def get_restrictions(user=None):
def build_restrictions(user):
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,)):
out.setdefault(key, [])
out[key].append(value)
@ -69,10 +69,10 @@ def get_global_default(key):
# Common
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)):
# 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))
_clear_cache(parent)
else:
@ -125,14 +125,14 @@ def clear_default(key=None, value=None, parent=None, name=None, parenttype=None)
if not conditions:
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)
def get_defaults_for(parent="Control Panel"):
"""get all defaults"""
defaults = frappe.cache().get_value("__defaults:" + parent)
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)
defaults = frappe._dict({})
@ -162,6 +162,6 @@ def clear_cache(user=None):
if user:
to_clear = [user]
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:
frappe.cache().delete_value("__defaults:" + p)

View file

@ -25,7 +25,7 @@ def logout():
@frappe.whitelist(allow_guest=True)
def web_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>
<p><a href='index'>Back to Home</a></p>""")
@ -48,7 +48,7 @@ def uploadfile():
except frappe.DuplicateEntryError, e:
# ignore pass
ret = None
frappe.conn.rollback()
frappe.db.rollback()
else:
if frappe.form_dict.get('method'):
ret = frappe.get_attr(frappe.form_dict.method)()
@ -77,13 +77,13 @@ def handle():
except Exception, e:
report_error(status_codes.get(e.__class__, 500))
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()
if frappe.conn:
frappe.conn.close()
if frappe.db:
frappe.db.close()
if frappe._memc:
frappe._memc.disconnect_all()

View file

@ -8,7 +8,7 @@ from __future__ import unicode_literals
import os, sys, json
import frappe
import frappe.db
import frappe.database
import getpass
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)
if reinstall:
frappe.connect(db_name=db_name)
dbman = DbManager(frappe.local.conn)
dbman = DbManager(frappe.local.db)
dbman.create_database(db_name)
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'})
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):
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()):
dbman.delete_user(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)
# close root connection
frappe.conn.close()
frappe.db.close()
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,
`password` VARCHAR(180) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
@ -70,7 +70,7 @@ def import_db_from_sql(source_sql, verbose):
db_name = frappe.conf.db_name
if not source_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
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()
if not app_name in installed_apps:
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:
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",
"patch": patch
}).insert()
frappe.conn.commit()
frappe.db.commit()
def make_conf(db_name=None, db_password=None, site_config=None):
site = frappe.local.site

View file

@ -46,7 +46,7 @@ def copytables(srctype, src, srcfield, tartype, tar, tarfield, srcfields, tarfie
def db_exists(dt, dn):
import frappe
return frappe.conn.exists(dt, dn)
return frappe.db.exists(dt, dn)
def delete_fields(args_dict, delete=0):
"""
@ -62,7 +62,7 @@ def delete_fields(args_dict, delete=0):
fields = args_dict[dt]
if not fields: continue
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabDocField`
WHERE parent=%s AND fieldname IN (%s)
""" % ('%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
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
if is_single:
frappe.conn.sql("""\
frappe.db.sql("""\
DELETE FROM `tabSingles`
WHERE doctype=%s AND field IN (%s)
""" % ('%s', ", ".join(['"' + f + '"' for f in fields])), dt)
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 []
query = "ALTER TABLE `tab%s` " % dt + \
", ".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):
"""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":
# 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"),
(new_fieldname, old_fieldname))
elif new_field.fieldtype not in no_value_fields:
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""",
(new_fieldname, doctype, old_fieldname))
else:
# 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))
# 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))
update_users_report_view_settings(doctype, old_fieldname)
def update_users_report_view_settings(doctype, ref_fieldname):
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:%'""")
for key, value in user_report_cols:
new_columns = []
@ -127,5 +127,5 @@ def update_users_report_view_settings(doctype, ref_fieldname):
new_columns.append([field, field_doctype])
columns_modified=True
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))

View file

@ -37,7 +37,7 @@ class Bean:
dn = dt
if dt and dn:
if isinstance(dn, dict):
dn = frappe.conn.get_value(dt, dn, "name")
dn = frappe.db.get_value(dt, dn, "name")
if dn is None:
raise frappe.DoesNotExistError
@ -120,13 +120,13 @@ class Bean:
conflict = False
if not cint(self.doc.fields.get('__islocal')):
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):
modified = modified[0]
if cstr(modified) and cstr(modified) != cstr(self.doc.modified):
conflict = True
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"""
% (self.doc.doctype, self.doc.name), as_dict=True)
@ -265,7 +265,7 @@ class Bean:
return self.save()
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()
else:
return self.insert()
@ -371,7 +371,7 @@ class Bean:
frappe.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
# 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.errprint(frappe.utils.get_traceback())
raise
@ -396,11 +396,11 @@ class Bean:
if dt[0] not in self.ignore_children_type:
cnames = child_map.get(dt[0]) or []
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))),
tuple([self.doc.name, self.doc.doctype] + cnames))
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))
def delete(self):

View file

@ -95,7 +95,7 @@ class DocListController(object):
if not hasattr(self, "_precision"):
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": {}
})

View file

@ -48,8 +48,8 @@ def get_new_doc(doctype, parent_doc = None, parentfield = None):
if parent_doc:
ref_docname = parent_doc.fields[ref_fieldname]
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)
else:

View file

@ -76,7 +76,7 @@ class DbTable:
if t: add_text += ',\n'.join(self.get_index_definitions()) + ',\n'
# create table
frappe.conn.sql("""create table `%s` (
frappe.db.sql("""create table `%s` (
name varchar(120) not null primary key,
creation datetime,
modified datetime,
@ -95,10 +95,10 @@ class DbTable:
"""
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:
custom_fl = frappe.conn.sql("""\
custom_fl = frappe.db.sql("""\
SELECT * FROM `tabCustom Field`
WHERE dt = %s AND docstatus < 2""", (self.doctype,), as_dict=1)
if custom_fl: fl += custom_fl
@ -112,7 +112,7 @@ class DbTable:
f.get('search_index'), f.get('options'))
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:
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
def get_foreign_keys(self):
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'):
if line.strip().startswith('CONSTRAINT') and line.find('FOREIGN')!=-1:
try:
@ -162,12 +162,12 @@ class DbTable:
# drop
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):
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()
else:
self.alter()
@ -178,24 +178,24 @@ class DbTable:
col.check(self.current_columns.get(col.fieldname, None))
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:
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:
# 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:
if col.fieldname != 'name': # primary key
# 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:
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:
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.
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.
"""
if conn:
self.conn = conn
if db:
self.db = db
def get_variables(self,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):
"""
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):
"""get list of tables"""
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):
#Create user if it doesn't exist.
try:
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:
self.conn.sql("CREATE USER '%s'@'localhost';"%user[:16])
self.db.sql("CREATE USER '%s'@'localhost';"%user[:16])
except Exception, e:
raise
def delete_user(self,target):
# delete user if exists
try:
self.conn.sql("DROP USER '%s'@'localhost';" % target)
self.db.sql("DROP USER '%s'@'localhost';" % target)
except Exception, e:
if e.args[0]==1396:
pass
@ -317,39 +317,39 @@ class DbManager:
if target in self.get_database_list():
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):
try:
self.conn.sql("DROP DATABASE IF EXISTS `%s`;"%target)
self.db.sql("DROP DATABASE IF EXISTS `%s`;"%target)
except Exception,e:
raise
def grant_all_privileges(self,target,user):
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:
raise
def grant_select_privilges(self,db,table,user):
try:
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:
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:
raise
def flush_privileges(self):
try:
self.conn.sql("FLUSH PRIVILEGES")
self.db.sql("FLUSH PRIVILEGES")
except Exception,e:
raise
def get_database_list(self):
"""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):
from frappe.utils import make_esc
@ -366,14 +366,14 @@ class DbManager:
if not table_name in self.get_tables_list():
return
try:
self.conn.sql("DROP TABLE IF EXISTS %s "%(table_name))
self.db.sql("DROP TABLE IF EXISTS %s "%(table_name))
except Exception,e:
raise
def set_transaction_isolation_level(self,scope='SESSION',level='READ COMMITTED'):
#Sets the transaction isolation level. scope = global/session
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:
raise
@ -393,20 +393,20 @@ def updatedb(dt):
* updates columns
* 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:
raise Exception, 'Wrong doctype "%s" in updatedb' % dt
if not res[0][0]:
frappe.conn.commit()
frappe.db.commit()
tab = DbTable(dt, 'tab')
tab.sync()
frappe.conn.begin()
frappe.db.begin()
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])
try:
fklist = dbtab.get_foreign_keys()
@ -417,7 +417,7 @@ def remove_all_foreign_keys():
raise
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):
d = type_map.get(fieldtype.lower())
@ -432,7 +432,7 @@ def get_definition(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)))

View file

@ -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)
# already deleted..?
if not frappe.conn.exists(doctype, name):
if not frappe.db.exists(doctype, name):
return
if not for_reload:
@ -37,10 +37,10 @@ def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes
try:
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:
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:
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))
@ -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)
# 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+")",
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:
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)
if item and item.parent != dn and (method=="Delete" or

View file

@ -59,7 +59,7 @@ class Document:
fielddata = doctype
doctype = None
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:
self.fields = frappe._dict(fielddata)
@ -131,7 +131,7 @@ class Document:
self._loadsingle()
else:
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:
if e.args[0]==1146:
dataset = None
@ -140,7 +140,7 @@ class Document:
if not dataset:
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):
return self.fields.get("__islocal")
@ -150,13 +150,13 @@ class Document:
del self.fields['__islocal']
for i in range(len(description)):
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):
for i in range(len(description)):
v = data[i]
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):
self.name = self.doctype
@ -223,7 +223,7 @@ class Document:
if r:
return r
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,
raise_exception=1)
@ -238,7 +238,7 @@ class Document:
def _get_amended_name(self):
am_id = 1
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_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
@ -307,7 +307,7 @@ class Document:
def set(self, key, value):
self.modified = now()
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
def _insert(self, make_autoname=True, keep_timestamps=False):
@ -328,7 +328,7 @@ class Document:
else:
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)
values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
%(modified_by)s)""", self.fields)
@ -337,7 +337,7 @@ class Document:
self.modified = now()
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():
if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
and (not f.startswith('__')): # fields not saved
@ -355,7 +355,7 @@ class Document:
values.append(self.doctype)
values.append(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):
err_list = []
@ -391,7 +391,7 @@ class Document:
dt = dt[5:]
if '\n' in dt:
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,))
return tmp and tmp[0][0] or ''# match case
@ -423,7 +423,7 @@ class Document:
update_str.append("`%s`=%s" % (f, '%s'))
if values:
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)
def get_valid_fields(self):
@ -443,13 +443,13 @@ class Document:
"fieldtype": ["not in", frappe.model.no_value_fields]})
else:
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)
def get_meta(self):
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()
return self._meta
@ -457,7 +457,7 @@ class Document:
def update_parentinfo(self):
"""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,))
if len(tmp)==0:
@ -474,7 +474,7 @@ class Document:
def set_idx(self):
"""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'),
(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)
# delete from db
frappe.conn.sql("""\
frappe.db.sql("""\
delete from `tab%s`
where parent=%s and parenttype=%s"""
% (table_list[0].doctype, '%s', '%s'),
@ -604,15 +604,15 @@ def make_autoname(key, doctype=''):
def getseries(key, digits, doctype=''):
# 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:
current = current[0][0]
# 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
else:
# 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
return ('%0'+str(digits)+'d') % current
@ -630,9 +630,9 @@ def getchildren(name, childtype, field='', parenttype='', from_doctype=0):
condition += ' and parenttype=%s '
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))
desc = frappe.conn.get_description()
desc = frappe.db.get_description()
l = DocList()
@ -650,7 +650,7 @@ def check_page_perm(doc):
if doc.publish:
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
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):
"""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)
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):
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
# no name

View file

@ -8,14 +8,14 @@ import frappe
def rename(doctype, fieldname, newname):
"""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)
if not df:
return
df = df[0]
if frappe.conn.get_value('DocType', doctype, 'issingle'):
if frappe.db.get_value('DocType', doctype, 'issingle'):
update_single(df, newname)
else:
update_table(df, newname)
@ -23,28 +23,28 @@ def rename(doctype, fieldname, newname):
def update_single(f, new):
"""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']))
frappe.conn.commit()
frappe.db.commit()
def update_table(f, new):
"""update table"""
query = get_change_column_query(f, new)
if query:
frappe.conn.sql(query)
frappe.db.sql(query)
def update_parent_field(f, new):
"""update 'parentfield' in tables"""
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']))
frappe.conn.commit()
frappe.db.commit()
def get_change_column_query(f, new):
"""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:
if d[0]== f['fieldname']:
return 'alter table `tab%s` change `%s` `%s` %s' % \

View file

@ -64,7 +64,7 @@ def get(doctype, processed=False, cached=True):
return DocTypeDocList(doclist)
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'"""))
def add_workflows(doclist):
@ -74,7 +74,7 @@ def add_workflows(doclist):
# get active workflow
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)
# add workflow states (for icons and style)
@ -131,7 +131,7 @@ def sort_fields(doclist):
doclist.get({"doctype":["!=", "DocField"]}).extend(newlist)
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):
if ps['doctype_or_field']=='DocType':
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):
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)
except Exception, e:
if e.args[0]==1146:
@ -174,10 +174,10 @@ def add_custom_fields(doctype, doclist):
def add_linked_with(doclist):
"""add list of doctypes this doctype is 'linked' with"""
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)
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)
or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
@ -191,7 +191,7 @@ def add_linked_with(doclist):
for dt in links:
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"
and options in (select name from tabDocType
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 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,)):
clear_single(dt[0])
@ -260,7 +260,7 @@ def clear_cache(doctype=None):
else:
# 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])
def add_code(doctype, doclist):
@ -293,7 +293,7 @@ def add_embedded_js(doc):
js = doc.fields.get('__js') or ''
# 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 ""
js = (js + '\n' + custom).encode("utf-8")
@ -307,11 +307,11 @@ def expand_selects(doclist):
and (d.options or '').startswith('link:'), doclist):
doctype = d.options.split("\n")[0][5:]
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)])
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)
for pf in print_formats:
doclist.append(frappe.model.doc.Document('Print Format', fielddata=pf))
@ -333,7 +333,7 @@ def get_link_fields(doctype):
"options": "^link:"}))
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):
doclist.extend(frappe.get_doclist('DocType Validator', validator.name))

View file

@ -9,18 +9,18 @@ from frappe.utils import cstr, cint
def is_single(doctype):
try:
return frappe.conn.get_value("DocType", doctype, "issingle")
return frappe.db.get_value("DocType", doctype, "issingle")
except IndexError, e:
raise Exception, 'Cannot determine whether %s is single' % doctype
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:%%")
limit 1""" % dt)
return parent_dt and parent_dt[0][0] or ''
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):
"""
@ -40,11 +40,11 @@ def get_link_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)]
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)]
except Exception, e:
if e.args[0]!=1146:
@ -67,7 +67,7 @@ def get_field_currency(df, doc):
if ":" in cstr(df.options):
split_opts = df.options.split(":")
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])
else:
currency = doc.fields.get(df.options)
@ -82,14 +82,14 @@ def get_field_precision(df, doc):
if df.fieldtype == "Currency":
currency = get_field_currency(df, doc)
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:
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)
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

View file

@ -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
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
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)
# 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))
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):
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))
except Exception, e:
if e.args[0]!=1054: # in patch?
raise
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))
def rename_parent_and_child(doctype, old, new, doclist):
# 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))
update_child_docs(old, new, doclist)
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:
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)
# 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))
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')
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))
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
update_list.append([field['parent'], field['fieldname']])
if field['issingle']:
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabSingles` set value=%s
where doctype=%s and field=%s and value=%s""",
(new, field['parent'], field['fieldname'], old))
else:
if doctype!='DocType' and field['parent']!=new:
frappe.conn.sql("""\
frappe.db.sql("""\
update `tab%s` set `%s`=%s
where `%s`=%s""" \
% (field['parent'], field['fieldname'], '%s',
field['fieldname'], '%s'),
(new, old), debug=1)
(new, old))
def get_link_fields(doctype):
# get link fields from tabDocField
link_fields = frappe.conn.sql("""\
link_fields = frappe.db.sql("""\
select parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.parent) as issingle
@ -155,7 +155,7 @@ def get_link_fields(doctype):
% ('%s', doctype), (doctype,), as_dict=1)
# get link fields from tabCustom Field
custom_link_fields = frappe.conn.sql("""\
custom_link_fields = frappe.db.sql("""\
select dt as parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.dt) as issingle
@ -170,7 +170,7 @@ def get_link_fields(doctype):
link_fields += custom_link_fields
# 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 ifnull(issingle, 0) from tabDocType dt
where dt.name = ps.doc_type) as issingle
@ -186,15 +186,15 @@ def get_link_fields(doctype):
return link_fields
def update_parent_of_fieldtype_table(old, new):
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabDocField` set options=%s
where fieldtype='Table' and options=%s""", (new, old))
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabCustom Field` set options=%s
where fieldtype='Table' and options=%s""", (new, old))
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabProperty Setter` set value=%s
where property='options' and value=%s""", (new, old))
@ -204,7 +204,7 @@ def get_select_fields(old, new):
new line separated list
"""
# get link fields from tabDocField
select_fields = frappe.conn.sql("""\
select_fields = frappe.db.sql("""\
select parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.parent) as issingle
@ -217,7 +217,7 @@ def get_select_fields(old, new):
% ('%s', old), (new,), as_dict=1)
# get link fields from tabCustom Field
custom_select_fields = frappe.conn.sql("""\
custom_select_fields = frappe.db.sql("""\
select dt as parent, fieldname,
(select ifnull(issingle, 0) from tabDocType dt
where dt.name = df.dt) as issingle
@ -233,7 +233,7 @@ def get_select_fields(old, new):
select_fields += custom_select_fields
# 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 ifnull(issingle, 0) from tabDocType dt
where dt.name = ps.doc_type) as issingle
@ -251,7 +251,7 @@ def get_select_fields(old, new):
return select_fields
def update_select_field_values(old, new):
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabDocField` set options=replace(options, %s, %s)
where
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%%%%")""" % \
('%s', '%s', '%s', old, old), (old, new, new))
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabCustom Field` set options=replace(options, %s, %s)
where
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%%%%")""" % \
('%s', '%s', '%s', old, old), (old, new, new))
frappe.conn.sql("""\
frappe.db.sql("""\
update `tabProperty Setter` set value=replace(value, %s, %s)
where
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))
def update_parenttype_values(old, new):
child_doctypes = frappe.conn.sql("""\
child_doctypes = frappe.db.sql("""\
select options, fieldname from `tabDocField`
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`
where dt=%s and fieldtype='Table'""", (new,), as_dict=1)
child_doctypes += custom_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`
where doc_type=%s and property='options' and
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)
for doctype in child_doctypes:
frappe.conn.sql("""\
frappe.db.sql("""\
update `tab%s` set parenttype=%s
where parenttype=%s""" % (doctype, '%s', '%s'),
(new, old))

View file

@ -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:
print module_name + ' | ' + doctype + ' | ' + name
frappe.conn.commit()
frappe.db.commit()
return modules

View file

@ -113,8 +113,8 @@ def copy_doclist(doclist, no_copy = []):
def set_default(doc, key):
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"),
(doc.fields.get(key), doc.name))

View file

@ -9,12 +9,12 @@ def get_workflow_name(doctype):
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")
# no active? get default workflow
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")
frappe.local.workflow_names[doctype] = workflow_name
@ -23,9 +23,9 @@ def get_workflow_name(doctype):
def get_default_state(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")
def get_state_fieldname(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")

View file

@ -39,8 +39,8 @@ def export_doc(doctype, name, module=None):
from frappe.modules.export_file import write_document_file
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)
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"

View file

@ -66,7 +66,7 @@ def get_module_name(doclist):
elif doclist[0]['doctype']=='Control Panel':
module = 'Core'
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:
module = doclist[0]['module']

View file

@ -38,7 +38,7 @@ def import_file_by_path(path, force=False):
if not force:
# 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
original_modified = doc["modified"]
@ -46,7 +46,7 @@ def import_file_by_path(path, force=False):
import_doclist(doclist)
# 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'),
(original_modified, doc['name']))
@ -80,7 +80,7 @@ def import_doclist(doclist):
ignore = list(doctypes.intersection(set(ignore_doctypes)))
if doctype in ignore_values:
if frappe.conn.exists(doctype, name):
if frappe.db.exists(doctype, name):
old_doc = frappe.doc(doctype, name)
# delete old
@ -112,7 +112,7 @@ def remove_ignored_docs_if_they_already_exist(doclist, ignore, name):
if ignore:
has_records = []
for d in ignore:
if frappe.conn.get_value(d, {"parent":name}):
if frappe.db.get_value(d, {"parent":name}):
has_records.append(d)
if has_records:

View file

@ -18,7 +18,7 @@ class PatchError(Exception): pass
def run_all():
"""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():
if patch and (patch not in executed):
@ -55,9 +55,9 @@ def execute_patch(patchmodule, method=None, methodargs=None):
"""execute the patch"""
success = False
block_user(True)
frappe.conn.begin()
frappe.db.begin()
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.startswith("execute:"):
exec patchmodule.split("execute:")[1] in globals()
@ -67,10 +67,10 @@ def execute_patch(patchmodule, method=None, methodargs=None):
elif method:
method(**methodargs)
frappe.conn.commit()
frappe.db.commit()
success = True
except Exception, e:
frappe.conn.rollback()
frappe.db.rollback()
tb = frappe.get_traceback()
log(tb)
import os
@ -91,32 +91,32 @@ def add_to_patch_log(tb):
def update_patch_log(patchmodule):
"""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)
else:
frappe.doc({"doctype": "Patch Log", "patch": patchmodule}).insert()
def executed(patchmodule):
"""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:
done = frappe.conn.get_value("Patch Log", {"patch": patchmodule})
done = frappe.db.get_value("Patch Log", {"patch": patchmodule})
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
def block_user(block):
"""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."
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():
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""")
def log(msg):

View file

@ -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
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:
export_doc(dt, dn)

View file

@ -4,9 +4,9 @@ def execute():
frappe.reload_doc("core", "doctype", "docperm")
# 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
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()

View file

@ -6,4 +6,4 @@ import frappe
def execute():
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'""")

View file

@ -1,6 +1,6 @@
import frappe
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)

View file

@ -3,7 +3,7 @@ import frappe
from frappe.model import rename_field
def execute():
tables = frappe.conn.sql_list("show tables")
tables = frappe.db.sql_list("show tables")
if "tabWebsite Route" not in tables:
frappe.rename_doc("DocType", "Website Sitemap", "Website Route", force=True)

View file

@ -3,6 +3,6 @@ import frappe
def execute():
frappe.reload_doc("core", "doctype", "todo")
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:
pass

View file

@ -11,12 +11,12 @@ def execute():
pages, generators = get_pages_and_generators(app)
for g in generators:
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.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"]:
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
rebuild_website_template()

View file

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

View file

@ -12,11 +12,11 @@ def execute():
frappe.reload_doc("website", "doctype", "post")
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)
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)

View file

@ -16,7 +16,7 @@ def check_admin_or_system_manager():
def has_permission(doctype, ptype="read", refdoc=None, verbose=True):
"""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
meta = frappe.get_doctype(doctype)

View file

@ -41,14 +41,14 @@ class Profile:
"""build map of special doctype properties"""
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):
self.doctype_map[r['name']] = r
def build_perm_map(self):
"""build map of permissions at level 0"""
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`
from tabDocPerm where docstatus=0
and ifnull(permlevel,0)=0
@ -150,7 +150,7 @@ class Profile:
return self.can_read
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
from tabProfile where name = %s""", (self.name,), as_dict=1)[0]
@ -173,13 +173,13 @@ class Profile:
return d
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 ''
def get_system_managers(only_name=False):
"""returns all system manager's profile details"""
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))
as fullname from tabProfile p
where docstatus < 2 and enabled = 1
@ -209,7 +209,7 @@ def add_system_manager(email, first_name=None, last_name=None):
profile.insert()
# 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")""")
profile.get_controller().add_roles(*roles)
@ -221,7 +221,7 @@ def get_roles(username=None, with_standard=True):
if username=='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']
# filter standard if required

View file

@ -19,7 +19,7 @@ import frappe.translate
@frappe.whitelist()
def clear(user=None):
frappe.local.session_obj.update(force=True)
frappe.local.conn.commit()
frappe.local.db.commit()
clear_cache(frappe.session.user)
frappe.response['message'] = "Cache Cleared"
@ -36,19 +36,19 @@ def clear_cache(user=None):
# clear notifications
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 user==frappe.session.user and frappe.session.sid:
cache.delete_value("session:" + frappe.session.sid)
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,)):
cache.delete_value("session:" + sid)
frappe.defaults.clear_cache(user)
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("session:" + sess.sid)
cache.delete_value("bootinfo:" + sess.user)
@ -57,12 +57,12 @@ def clear_cache(user=None):
def clear_sessions(user=None, keep_current=False):
if not 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]:
pass
else:
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():
"""get session boot info"""
@ -125,16 +125,16 @@ class Session:
# insert session
if self.user!="Guest":
frappe.conn.begin()
frappe.db.begin()
self.insert_session_record()
# 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']))
frappe.conn.commit()
frappe.db.commit()
def insert_session_record(self):
frappe.conn.sql("""insert into tabSessions
frappe.db.sql("""insert into tabSessions
(sessiondata, user, lastupdate, sid, status)
values (%s , %s, NOW(), %s, 'Active')""",
(str(self.data['data']), self.data['user'], self.data['sid']))
@ -189,7 +189,7 @@ class Session:
return data and data.data
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
TIMEDIFF(NOW(), lastupdate) < TIME(%s)""", (self.sid,
self.get_expiry_period()))
@ -209,7 +209,7 @@ class Session:
def delete_session(self):
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):
"""all guests share the same 'Guest' session"""
@ -233,7 +233,7 @@ class Session:
if force or (frappe.session['user'] != 'Guest' and \
((time_diff==None) or (time_diff > 1800))):
# 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']),
self.data['sid']))

View file

@ -29,9 +29,9 @@ def get_context(context):
blog_post.description = blog_post.blog_intro or blog_post.content[:140]
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
from `tabComment` where comment_doctype="Blog Post"
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
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
for res in result:

View file

@ -23,7 +23,7 @@ def get_context(context):
web_page.doc.links = get_navigation_links(web_page)
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
from `tabComment` where comment_doctype="Web Page"
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 = []
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 `tabTable of Contents`.parent=`tabWeb Page`.name
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"})
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)""" % \
(", ".join(["%s"]*len(toc_list))),
tuple([d.web_page for d in toc_list]),

View file

@ -74,7 +74,7 @@ def build_view_context(context):
context.profile = frappe.doc("Profile", context.post.assigned_to)
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
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):
from frappe.templates.website_group.post import clear_post_cache
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:
website_groups = [website_group]
else:
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()
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))
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)
def clear_cache_on_bean_event(bean, method, *args, **kwargs):
clear_cache(path=bean.doc.website_route, website_group=bean.doc.website_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})
views = {

View file

@ -38,11 +38,11 @@ def add_comment(args=None):
clear_cache(page_name)
# 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
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
send(recipients=list(set(commentors + [owner])),

View file

@ -34,13 +34,13 @@ def send_message(subject="Website Query", message="", sender=""):
return
# 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:
frappe.response["message"] = "Sorry: we believe we have received an unreasonably high number of requests of this kind. Please try later"
return
# 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:
from frappe.utils.email_lib import sendmail
sendmail(forward_to_email, sender, message, subject)

View file

@ -14,7 +14,7 @@ def get_context(context):
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`
where ifnull(published,0)=1
order by published_on desc limit 20""", as_dict=1)

View file

@ -15,7 +15,7 @@ def get_context(context):
"""generate the sitemap XML"""
host = get_request_site_address()
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`
where
`tabWebsite Route`.website_template = `tabWebsite Template`.name

View file

@ -8,10 +8,10 @@ no_sitemap = 1
base_template_path = "templates/pages/website_script.js"
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:
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")
return script_context

View file

@ -5,7 +5,7 @@ from __future__ import unicode_literals
import frappe
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
order by posts desc""", as_dict=1)
@ -14,7 +14,7 @@ def get_context(context):
"texts": {
"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)

View file

@ -12,7 +12,7 @@ def get_post_list_html(group, view, limit_start=0, limit_length=20):
# verify permission for paging
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})
access = get_access(pathname)
@ -22,7 +22,7 @@ def get_post_list_html(group, view, limit_start=0, limit_length=20):
conditions = ""
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":
# should show based on time upto precision of hour
# 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)]
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
from `tabPost` p, `tabProfile` pr
where p.website_group = %s and pr.name = p.owner and ifnull(p.parent_post, '')=''

View file

@ -34,7 +34,7 @@ def get_parent_post_html(post, context):
.render({"post": post.fields, "view": context.view})
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
where p.parent_post=%s and pr.name = p.owner
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):
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:
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
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")
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)
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)
@frappe.whitelist()
def suggest_user(group, term):
"""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.user_image, pr.location
from `tabProfile` pr

View file

@ -13,7 +13,7 @@ def suggest_user(term, group):
if not get_access(pathname).get("admin"):
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
from `tabProfile` pr
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)
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))
return frappe.get_template("templates/includes/sitemap_permission.html").render({
@ -64,7 +64,7 @@ def update_permission(group, profile, perm, value):
# send email
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
@ -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"):
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})
frappe.bean({

View file

@ -16,7 +16,7 @@ def main(app=None, module=None, doctype=None, verbose=False):
frappe.flags.print_messages = verbose
frappe.flags.in_test = True
if not frappe.conn:
if not frappe.db:
frappe.connect()
if doctype:
@ -80,7 +80,7 @@ def _run_test(path, filename, verbose, test_suite=None, run=True):
def make_test_records(doctype, verbose=0):
frappe.flags.mute_emails = True
if not frappe.conn:
if not frappe.db:
frappe.connect()
for options in get_dependencies(doctype):
@ -95,7 +95,7 @@ def make_test_records(doctype, verbose=0):
make_test_records_for_doctype(options, verbose)
def get_modules(doctype):
module = frappe.conn.get_value("DocType", doctype, "module")
module = frappe.db.get_value("DocType", doctype, "module")
try:
test_module = load_doctype_module(doctype, module, "test_")
if test_module:
@ -173,7 +173,7 @@ def print_mandatory_fields(doctype):
print
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_")
make_test_records(doctype, verbose=verbose)
test_suite = unittest.TestSuite()

View file

@ -10,21 +10,21 @@ class TestDB(unittest.TestCase):
def test_get_value(self):
from frappe.utils import now_datetime
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()
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)
if "Profile" in frappe.local.test_objects:
del frappe.local.test_objects["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]}))

View file

@ -11,8 +11,8 @@ make_test_records("Profile")
class TestEmail(unittest.TestCase):
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):
from frappe.utils.email_lib import sendmail
@ -25,7 +25,7 @@ class TestEmail(unittest.TestCase):
doctype='Profile', email_field='email',
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.assertTrue('test@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()
from frappe.utils.email_lib.bulk import flush
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.assertTrue('test@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',
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)
self.assertEquals(len(bulk), 1)
self.assertFalse('test@example.com' in [d['recipient'] for d in bulk])

View file

@ -10,7 +10,7 @@ def fmt_money(amount, precision=None):
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)
@ -64,7 +64,7 @@ import unittest
class TestFmtMoney(unittest.TestCase):
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(1000), "1,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")
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(-1000), "-1,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")
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(-1000), "-1.000,00")
self.assertEquals(fmt_money(-10000), "-10.000,00")
@ -98,7 +98,7 @@ class TestFmtMoney(unittest.TestCase):
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(1000), "1,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")
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(100.3), "100")
self.assertEquals(fmt_money(1000.3), "1,000")

View file

@ -21,7 +21,7 @@ import frappe, os, re, codecs, json
def get_user_lang(user=None):
if not 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")
def get_all_languages():
@ -115,17 +115,17 @@ def get_messages_for_app(app):
for m in frappe.local.app_modules[app]])
# 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)):
messages.extend(get_messages_from_doctype(name))
# 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)):
messages.extend(get_messages_from_page(name))
# 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
and tabDocType.module in ({})""".format(modules)):
messages.extend(get_messages_from_report(name))
@ -166,7 +166,7 @@ def get_messages_from_page(name):
def get_messages_from_report(name):
report = frappe.doc("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:
messages.extend(re.findall('"([^:,^"]*):', report.query))
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):
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)
messages = get_messages_from_file(file_path + ".js")

View file

@ -38,7 +38,7 @@ def get_fullname(profile):
frappe.local.fullnames = {}
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:
frappe.local.fullnames[profile] = " ".join(filter(None,
[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'))
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)
return body
@ -176,7 +176,7 @@ def get_user_time_zone():
frappe.local.user_time_zone = frappe.cache().get_value("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'
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()
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
@ -378,7 +378,7 @@ def fmt_money(amount, precision=None, currency=None):
"""
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)
@ -413,7 +413,7 @@ def fmt_money(amount, precision=None, currency=None):
amount = minus + amount
if currency:
symbol = frappe.conn.get_value("Currency", currency, "symbol")
symbol = frappe.db.get_value("Currency", currency, "symbol")
if symbol:
amount = symbol + " " + amount
@ -444,15 +444,15 @@ def money_in_words(number, main_currency = None, fraction_currency=None):
if not main_currency:
main_currency = d.get('currency', 'INR')
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)
main, fraction = n.split('.')
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
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
"""
return frappe.conn.get_defaults(key)
return frappe.db.get_defaults(key)
def set_default(key, val):
"""
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):
"""
@ -688,12 +688,12 @@ def get_doctype_label(dt=None):
Gets label of a doctype
"""
if dt:
res = frappe.conn.sql("""\
res = frappe.db.sql("""\
SELECT name, dt_label FROM `tabDocType Label`
WHERE name=%s""", dt)
return res and res[0][0] or dt
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 = {}
for r in res:
dt_label_dict[r[0]] = r[1]
@ -705,7 +705,7 @@ def get_label_doctype(label):
"""
Gets doctype from its label
"""
res = frappe.conn.sql("""\
res = frappe.db.sql("""\
SELECT name FROM `tabDocType Label`
WHERE dt_label=%s""", label)
@ -823,7 +823,7 @@ def get_backups_path():
def get_url(uri=None):
url = get_request_site_address()
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")
if subdomain:
if "http" not in subdomain:

View file

@ -131,10 +131,10 @@ def get_backup():
This function is executed when the user clicks on
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()
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()
recipient_list = odb.send_email()
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):
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,
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)
return odb

View file

@ -18,7 +18,7 @@ def read_csv_content_from_uploaded_file(ignore_encoding=False):
return read_csv_content(fcontent, ignore_encoding)
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")
if not fileid:
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.options.startswith('link:'):
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),
raise_exception=1)
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):
"""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:
bean = frappe.bean(doctype, d['name'])
bean.ignore_links = ignore_links

View file

@ -26,7 +26,7 @@ def get_contact_list():
"""Returns contacts (from autosuggest)"""
cond = ['`%s` like "%s%%"' % (f,
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('from')
,' OR '.join(cond)
@ -35,7 +35,7 @@ def get_contact_list():
frappe.response['cl'] = filter(None, [c[0] for c in cl])
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'
AND parent!='Administrator'
AND parent IN

View file

@ -22,7 +22,7 @@ def send(recipients=None, sender=None, doctype='Profile', email_field='email',
return cint(rdata.unsubscribed)
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]
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 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))
formatted = get_formatted_html(subject, message)
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)
doc = rdata and rdata[0] or {}
@ -99,11 +99,11 @@ def unsubscribe():
field = frappe.form_dict.get('email_field')
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,))
if not frappe.form_dict.get("from_test"):
frappe.conn.commit()
frappe.db.commit()
frappe.local.message_title = "Unsubscribe"
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
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)
if email:
email = email[0]
else:
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)
try:
if not from_test:
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)
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)
def clear_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""")

View file

@ -159,7 +159,7 @@ class EMail:
return email
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
if not self.sender:
msgprint(_("Please specify 'Auto Email Id' in Setup > Email Settings"))
@ -211,7 +211,7 @@ def get_footer(footer=None):
footer = footer or ""
# 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
for f in frappe.get_hooks("mail_footer"):

View file

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

View file

@ -11,7 +11,7 @@ from frappe import conf
class MaxFileSizeReachedError(frappe.ValidationError): pass
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
def upload():
@ -96,7 +96,7 @@ def save_file(fname, content, dt, dn, decode=False):
import filecmp
from frappe.model.code import load_doctype_module
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"):
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):
"""remove all files in a transaction"""
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)):
remove_file(fid)
except Exception, e:
@ -222,7 +222,7 @@ def remove_file(fid):
frappe.delete_doc("File Data", fid)
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))
if f:
file_name = f[0][0]

View file

@ -10,7 +10,7 @@ def before_install():
def after_install():
# reset installed apps for re-install
frappe.conn.set_global("installed_apps", '["frappe"]')
frappe.db.set_global("installed_apps", '["frappe"]')
# core users / roles
install_docs = [
@ -32,11 +32,11 @@ def after_install():
pass
# 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"""))
# update admin password
from frappe.auth import _update_password
_update_password("Administrator", frappe.conf.get("admin_password"))
frappe.conn.commit()
frappe.db.commit()

View file

@ -49,7 +49,7 @@ def update_nsm(doc_obj):
# set old parent
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
d._loadfromdb()
@ -66,23 +66,23 @@ def update_add_node(doc, parent, parent_field):
# get the last sibling of the 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]
validate_loop(doc.doctype, doc.name, left, right)
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
# 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
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")
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
@ -90,41 +90,41 @@ def update_move_node(doc, parent_field):
parent = doc.fields.get(parent_field)
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]
validate_loop(doc.doctype, doc.name, new_parent.lft, new_parent.rgt)
# 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))
# shift left
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))
# 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'),
(diff, doc.lft, doc.rgt))
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]
# 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))
# 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'),
(diff, diff, new_parent.rgt))
# 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'),
(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
else:
# 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
# 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))
def rebuild_tree(doctype, parent_field):
@ -144,14 +144,14 @@ def rebuild_tree(doctype, parent_field):
call rebuild_node for all root nodes
"""
# get all roots
frappe.conn.auto_commit_on_many_writes = 1
frappe.db.auto_commit_on_many_writes = 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:
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):
"""
@ -164,13 +164,13 @@ def rebuild_node(doctype, parent, left, parent_field):
right = left+1
# 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:
right = rebuild_node(doctype, r[0], right, parent_field)
# we've got the left value, and now that we've processed
# 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 right+1
@ -178,7 +178,7 @@ def rebuild_node(doctype, parent, left, parent_field):
def validate_loop(doctype, name, lft, rgt):
"""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)):
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)
# 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),
(self.doc.name,))[0][0]
if has_children:
@ -209,7 +209,7 @@ class DocTypeNestedSet(object):
def before_rename(self, olddn, newdn, merge=False, group_fname="is_group"):
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:
frappe.throw(_("""Merging is only possible between Group-to-Group or
Ledger-to-Ledger"""), NestedSetInvalidMergeError)
@ -221,27 +221,27 @@ class DocTypeNestedSet(object):
def validate_one_root(self):
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:
frappe.throw(_("""Multiple root nodes not allowed."""), NestedSetMultipleRootsError)
def validate_ledger(self, group_identifier="is_group"):
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)):
frappe.throw(self.doc.doctype + ": " + self.doc.name +
_(" can not be marked as a ledger as it has existing child"))
def get_root_of(doctype):
"""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)""" %
(doctype, doctype))
return result[0] if result else None
def get_ancestors_of(doctype, name):
"""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))
return result or []

View file

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

View file

@ -29,18 +29,18 @@ def execute(site=None):
format = '%Y-%m-%d %H:%M:%S'
if not frappe.conn:
if not frappe.db:
frappe.connect(site=site)
out = []
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
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:
last = datetime.strptime(last, format)
@ -71,11 +71,11 @@ def trigger(method):
if method==event_name:
try:
frappe.get_attr(handler)()
frappe.conn.commit()
frappe.db.commit()
except Exception:
traceback += log("Method: {method}, Handler: {handler}".format(method=method, handler=handler))
traceback += log(frappe.get_traceback())
frappe.conn.rollback()
frappe.db.rollback()
return traceback or 'ok'
@ -84,23 +84,23 @@ def log(method, message=None):
message = frappe.utils.cstr(message) + "\n" if message else ""
message += frappe.get_traceback()
if not (frappe.conn and frappe.conn._conn):
if not (frappe.db and frappe.db._conn):
frappe.connect()
frappe.conn.rollback()
frappe.conn.begin()
frappe.db.rollback()
frappe.db.begin()
d = frappe.doc("Scheduler Log")
d.method = method
d.error = message
d.save()
frappe.conn.commit()
frappe.db.commit()
return message
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
and error not like '%%[Errno 110] Connection timed out%%'
order by modified limit %s""", (from_date, to_date, limit), as_dict=True)

View file

@ -28,11 +28,11 @@ class DocType(WebsiteGenerator):
if self.doc.published and not self.doc.published_on:
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})
# 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 name=%s""", (self.doc.blogger,))
@ -42,7 +42,7 @@ class DocType(WebsiteGenerator):
clear_cache("writers")
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"""):
clear_cache(blog)

View file

@ -32,9 +32,9 @@ from frappe.core.page.user_properties.user_properties import add, remove, get_pr
test_dependencies = ["Profile"]
class TestBlogPost(unittest.TestCase):
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""")
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'""")
frappe.clear_cache(doctype="Blog Post")
@ -84,7 +84,7 @@ class TestBlogPost(unittest.TestCase):
self.assertEquals(doc.get("blog_category"), "_Test Blog Category 1")
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""")
frappe.clear_cache(doctype="Blog Post")
@ -100,7 +100,7 @@ class TestBlogPost(unittest.TestCase):
self.assertFalse(post1.has_read_perm())
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""")
frappe.clear_cache(doctype="Blog Post")

Some files were not shown because too many files have changed in this diff Show more