Merge branch 'master' of github.com:webnotes/erpnext into wsgi

Conflicts:
	accounts/doctype/account/account.py
	accounts/doctype/gl_entry/gl_entry.py
	accounts/doctype/period_closing_voucher/period_closing_voucher.py
	stock/doctype/delivery_note/delivery_note.py
	stock/doctype/landed_cost_wizard/landed_cost_wizard.py
	stock/doctype/purchase_receipt/purchase_receipt.py
	stock/doctype/stock_ledger/stock_ledger.py
	stock/doctype/warehouse/warehouse.py
	stock/stock_ledger.py
diff --git a/accounts/doctype/account/account.py b/accounts/doctype/account/account.py
index fba51a9..4961d72 100644
--- a/accounts/doctype/account/account.py
+++ b/accounts/doctype/account/account.py
@@ -7,7 +7,6 @@
 from webnotes.utils import flt, fmt_money, cstr, cint
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 get_value = webnotes.conn.get_value
 
 class DocType:
@@ -31,17 +30,6 @@
 		self.validate_duplicate_account()
 		self.validate_root_details()
 		self.validate_mandatory()
-		self.validate_warehouse_account()
-	
-		if not self.doc.parent_account:
-			self.doc.parent_account = ''
-		
-	def validate(self): 
-		self.validate_master_name()
-		self.validate_parent()
-		self.validate_duplicate_account()
-		self.validate_root_details()
-		self.validate_mandatory()
 		self.validate_frozen_accounts_modifier()
 	
 		if not self.doc.parent_account:
@@ -56,7 +44,7 @@
 	def validate_parent(self):
 		"""Fetch Parent Details and validation for account not to be created under ledger"""
 		if self.doc.parent_account:
-			par = sql("""select name, group_or_ledger, is_pl_account, debit_or_credit 
+			par = webnotes.conn.sql("""select name, group_or_ledger, is_pl_account, debit_or_credit 
 				from tabAccount where name =%s""", self.doc.parent_account)
 			if not par:
 				msgprint("Parent account does not exists", raise_exception=1)
@@ -84,7 +72,7 @@
 	def validate_duplicate_account(self):
 		if self.doc.fields.get('__islocal') or not self.doc.name:
 			company_abbr = webnotes.conn.get_value("Company", self.doc.company, "abbr")
-			if sql("""select name from tabAccount where name=%s""", 
+			if webnotes.conn.sql("""select name from tabAccount where name=%s""", 
 				(self.doc.account_name + " - " + company_abbr)):
 					msgprint("Account Name: %s already exists, please rename" 
 						% self.doc.account_name, raise_exception=1)
@@ -133,7 +121,7 @@
 		return webnotes.conn.get_value("GL Entry", {"account": self.doc.name})
 
 	def check_if_child_exists(self):
-		return sql("""select name from `tabAccount` where parent_account = %s 
+		return webnotes.conn.sql("""select name from `tabAccount` where parent_account = %s 
 			and docstatus != 2""", self.doc.name)
 	
 	def validate_mandatory(self):
@@ -181,7 +169,7 @@
 		# Get credit limit
 		credit_limit_from = 'Customer'
 
-		cr_limit = sql("""select t1.credit_limit from tabCustomer t1, `tabAccount` t2 
+		cr_limit = webnotes.conn.sql("""select t1.credit_limit from tabCustomer t1, `tabAccount` t2 
 			where t2.name=%s and t1.name = t2.master_name""", account)
 		credit_limit = cr_limit and flt(cr_limit[0][0]) or 0
 		if not credit_limit:
@@ -221,7 +209,7 @@
 		
 		# rename account name
 		new_account_name = " - ".join(parts[:-1])
-		sql("update `tabAccount` set account_name = %s where name = %s", (new_account_name, old))
+		webnotes.conn.sql("update `tabAccount` set account_name = %s where name = %s", (new_account_name, old))
 		
 		if merge:
 			new_name = " - ".join(parts)
diff --git a/accounts/doctype/bank_reconciliation/bank_reconciliation.py b/accounts/doctype/bank_reconciliation/bank_reconciliation.py
index 479b579..132358e 100644
--- a/accounts/doctype/bank_reconciliation/bank_reconciliation.py
+++ b/accounts/doctype/bank_reconciliation/bank_reconciliation.py
@@ -10,7 +10,6 @@
 from webnotes.model.bean import getlist, copy_doclist
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 
 
@@ -23,7 +22,7 @@
 			msgprint("Bank Account, From Date and To Date are Mandatory")
 			return
 	
-		dl = sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
+		dl = webnotes.conn.sql("select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t2.parent = t1.name and t2.account = %s and (clearance_date is null or clearance_date = '0000-00-00' or clearance_date = '') and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1", (self.doc.bank_account, self.doc.from_date, self.doc.to_date))
 		
 		self.doclist = self.doc.clear_table(self.doclist, 'entries')
 		self.doc.total_amount = 0.0
@@ -47,7 +46,7 @@
 					msgprint("Clearance Date can not be before Cheque Date (Row #%s)" % 
 						d.idx, raise_exception=1)
 					
-				sql("""update `tabJournal Voucher` 
+				webnotes.conn.sql("""update `tabJournal Voucher` 
 					set clearance_date = %s, modified = %s where name=%s""",
 					(d.clearance_date, nowdate(), d.voucher_id))
 				vouchers.append(d.voucher_id)
diff --git a/accounts/doctype/gl_entry/gl_entry.py b/accounts/doctype/gl_entry/gl_entry.py
index 8338a5b1..2243512 100644
--- a/accounts/doctype/gl_entry/gl_entry.py
+++ b/accounts/doctype/gl_entry/gl_entry.py
@@ -117,7 +117,7 @@
 				flt(balance[0][0]) or -1*flt(balance[0][0])
 		
 			if flt(balance) < 0:
-				webnotes.throw(_("Negative balance is not allowed for account ") + self.doc.account)
+				webnotes.throw(_("Negative balance is not allowed for account ") + account)
 
 def check_freezing_date(posting_date, adv_adj=False):
 	"""
@@ -161,16 +161,6 @@
 		webnotes.conn.sql("update `tab%s` set outstanding_amount=%s where name='%s'" %
 		 	(against_voucher_type, bal, against_voucher))
 			
-def validate_freezed_account(account, adv_adj=False):
-	"""Account has been freezed for other users except account manager"""
-	
-	freezed_account = webnotes.conn.get_value("Account", account, "freeze_account")
-	
-	if freezed_account == 'Yes' and not adv_adj \
-		and 'Accounts Manager' not in webnotes.user.get_roles():
-			webnotes.throw(_("Account") + ": " + account + _(" has been freezed. \
-			Only Accounts Manager can do transaction against this account"))
-
 def validate_frozen_account(account, adv_adj):
 	frozen_account = webnotes.conn.get_value("Account", account, "freeze_account")
 	if frozen_account == 'Yes' and not adv_adj:
@@ -183,4 +173,4 @@
 		elif frozen_accounts_modifier not in webnotes.user.get_roles():
 			webnotes.throw(account + _(" is a frozen account. ") + 
 				_("To create / edit transactions against this account, you need role") + ": " +  
-				frozen_accounts_modifier)
\ No newline at end of file
+				frozen_accounts_modifier)
diff --git a/accounts/doctype/mis_control/mis_control.py b/accounts/doctype/mis_control/mis_control.py
index 84350dc..f10e3d7 100644
--- a/accounts/doctype/mis_control/mis_control.py
+++ b/accounts/doctype/mis_control/mis_control.py
@@ -11,7 +11,6 @@
 
 import webnotes.defaults
 
-sql = webnotes.conn.sql
 
 from accounts.utils import get_balance_on, get_fiscal_year
 
@@ -44,7 +43,7 @@
 		ret['company'] = get_companies()
 
 		#--- to get fiscal year and start_date of that fiscal year -----
-		res = sql("select name, year_start_date from `tabFiscal Year`")
+		res = webnotes.conn.sql("select name, year_start_date from `tabFiscal Year`")
 		ret['fiscal_year'] = [r[0] for r in res]
 		ret['start_dates'] = {}
 		for r in res:
@@ -52,7 +51,7 @@
 			
 		#--- from month and to month (for MIS - Comparison Report) -------
 		month_list = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
-		fiscal_start_month = sql("select MONTH(year_start_date) from `tabFiscal Year` where name = %s",(webnotes.defaults.get_global_default("fiscal_year")))
+		fiscal_start_month = webnotes.conn.sql("select MONTH(year_start_date) from `tabFiscal Year` where name = %s",(webnotes.defaults.get_global_default("fiscal_year")))
 		fiscal_start_month = fiscal_start_month and fiscal_start_month[0][0] or 1
 		mon = ['']
 		for i in range(fiscal_start_month,13): mon.append(month_list[i-1])
@@ -107,7 +106,7 @@
 	def dates(self,fiscal_year,from_date,to_date):
 		import datetime
 		ret = ''
-		start_date = cstr(sql("select year_start_date from `tabFiscal Year` where name = %s",fiscal_year)[0][0])
+		start_date = cstr(webnotes.conn.sql("select year_start_date from `tabFiscal Year` where name = %s",fiscal_year)[0][0])
 		st_mon = cint(from_date.split('-')[1])
 		ed_mon = cint(to_date.split('-')[1])
 		st_day = cint(from_date.split('-')[2])
@@ -152,7 +151,7 @@
 	def get_totals(self, args):
 		args = eval(args)
 		#msgprint(args)
-		totals = sql("SELECT %s FROM %s WHERE %s %s %s %s" %(cstr(args['query_val']), cstr(args['tables']), cstr(args['company']), cstr(args['cond']), cstr(args['add_cond']), cstr(args['fil_cond'])), as_dict = 1)[0]
+		totals = webnotes.conn.sql("SELECT %s FROM %s WHERE %s %s %s %s" %(cstr(args['query_val']), cstr(args['tables']), cstr(args['company']), cstr(args['cond']), cstr(args['add_cond']), cstr(args['fil_cond'])), as_dict = 1)[0]
 		#msgprint(totals)
 		tot_keys = totals.keys()
 		# return in flt because JSON doesn't accept Decimal
@@ -185,7 +184,7 @@
 	# Get Children
 	# ------------
 	def get_children(self, parent_account, level, pl, company, fy):
-		cl = sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
+		cl = webnotes.conn.sql("select distinct account_name, name, debit_or_credit, lft, rgt from `tabAccount` where ifnull(parent_account, '') = %s and ifnull(is_pl_account, 'No')=%s and company=%s and docstatus != 2 order by name asc", (parent_account, pl, company))
 		level0_diff = [0 for p in self.period_list]
 		if pl=='Yes' and level==0: # switch for income & expenses
 			cl = [c for c in cl]
@@ -238,7 +237,7 @@
 	def define_periods(self, year, period):
 		
 		# get year start date		
-		ysd = sql("select year_start_date from `tabFiscal Year` where name=%s", year)
+		ysd = webnotes.conn.sql("select year_start_date from `tabFiscal Year` where name=%s", year)
 		ysd = ysd and ysd[0][0] or ''
 
 		self.ysd = ysd
diff --git a/accounts/doctype/period_closing_voucher/period_closing_voucher.py b/accounts/doctype/period_closing_voucher/period_closing_voucher.py
index 99282f5..70a4992 100644
--- a/accounts/doctype/period_closing_voucher/period_closing_voucher.py
+++ b/accounts/doctype/period_closing_voucher/period_closing_voucher.py
@@ -69,7 +69,6 @@
 		
 	def get_pl_balances(self):
 		"""Get balance for pl accounts"""
-		
 		return webnotes.conn.sql("""
 			select t1.account, sum(ifnull(t1.debit,0))-sum(ifnull(t1.credit,0)) as balance
 			from `tabGL Entry` t1, `tabAccount` t2 
@@ -101,4 +100,4 @@
 			}))
 			
 		from accounts.general_ledger import make_gl_entries
-		make_gl_entries(gl_entries)
\ No newline at end of file
+		make_gl_entries(gl_entries)
diff --git a/accounts/doctype/purchase_invoice/purchase_invoice.py b/accounts/doctype/purchase_invoice/purchase_invoice.py
index 2b84564..9a6b901 100644
--- a/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -12,7 +12,6 @@
 
 import webnotes.defaults
 
-sql = webnotes.conn.sql
 	
 from controllers.buying_controller import BuyingController
 class DocType(BuyingController):
@@ -62,7 +61,7 @@
 			"purchase_receipt_details")
 
 	def get_credit_to(self):
-		acc_head = sql("""select name, credit_days from `tabAccount` 
+		acc_head = webnotes.conn.sql("""select name, credit_days from `tabAccount` 
 			where (name = %s or (master_name = %s and master_type = 'supplier')) 
 			and docstatus != 2 and company = %s""", 
 			(cstr(self.doc.supplier) + " - " + self.company_abbr, 
@@ -89,14 +88,14 @@
 		return get_obj('Purchase Common').get_rate(arg,self)
 
 	def get_rate1(self,acc):
-		rate = sql("select tax_rate from `tabAccount` where name='%s'"%(acc))
+		rate = webnotes.conn.sql("select tax_rate from `tabAccount` where name='%s'"%(acc))
 		ret={'add_tax_rate' :rate and flt(rate[0][0]) or 0 }
 		return ret
 
 	def check_active_purchase_items(self):
 		for d in getlist(self.doclist, 'entries'):
 			if d.item_code:		# extra condn coz item_code is not mandatory in PV
-				valid_item = sql("select docstatus,is_purchase_item from tabItem where name = %s",d.item_code)
+				valid_item = webnotes.conn.sql("select docstatus,is_purchase_item from tabItem where name = %s",d.item_code)
 				if valid_item[0][0] == 2:
 					msgprint("Item : '%s' is Inactive, you can restore it from Trash" %(d.item_code))
 					raise Exception
@@ -116,7 +115,7 @@
 	def validate_bill_no(self):
 		if self.doc.bill_no and self.doc.bill_no.lower().strip() \
 				not in ['na', 'not applicable', 'none']:
-			b_no = sql("""select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice` 
+			b_no = webnotes.conn.sql("""select bill_no, name, ifnull(is_opening,'') from `tabPurchase Invoice` 
 				where bill_no = %s and credit_to = %s and docstatus = 1 and name != %s""", 
 				(self.doc.bill_no, self.doc.credit_to, self.doc.name))
 			if b_no and cstr(b_no[0][2]) == cstr(self.doc.is_opening):
@@ -132,7 +131,7 @@
 			self.doc.remarks = "No Remarks"
 
 	def validate_credit_acc(self):
-		acc = sql("select debit_or_credit, is_pl_account from tabAccount where name = %s", 
+		acc = webnotes.conn.sql("select debit_or_credit, is_pl_account from tabAccount where name = %s", 
 			self.doc.credit_to)
 		if not acc:
 			msgprint("Account: "+ self.doc.credit_to + "does not exist")
@@ -148,7 +147,7 @@
 	# ------------------------------------------------------------
 	def check_for_acc_head_of_supplier(self): 
 		if self.doc.supplier and self.doc.credit_to:
-			acc_head = sql("select master_name from `tabAccount` where name = %s", self.doc.credit_to)
+			acc_head = webnotes.conn.sql("select master_name from `tabAccount` where name = %s", self.doc.credit_to)
 			
 			if (acc_head and cstr(acc_head[0][0]) != cstr(self.doc.supplier)) or (not acc_head and (self.doc.credit_to != cstr(self.doc.supplier) + " - " + self.company_abbr)):
 				msgprint("Credit To: %s do not match with Supplier: %s for Company: %s.\n If both correctly entered, please select Master Type and Master Name in account master." %(self.doc.credit_to,self.doc.supplier,self.doc.company), raise_exception=1)
@@ -160,7 +159,7 @@
 		for d in getlist(self.doclist,'entries'):
 			if d.purchase_order and not d.purchase_order in check_list and not d.purchase_receipt:
 				check_list.append(d.purhcase_order)
-				stopped = sql("select name from `tabPurchase Order` where status = 'Stopped' and name = '%s'" % d.purchase_order)
+				stopped = webnotes.conn.sql("select name from `tabPurchase Order` where status = 'Stopped' and name = '%s'" % d.purchase_order)
 				if stopped:
 					msgprint("One cannot do any transaction against 'Purchase Order' : %s, it's status is 'Stopped'" % (d.purhcase_order))
 					raise Exception
@@ -260,11 +259,11 @@
 	def check_prev_docstatus(self):
 		for d in getlist(self.doclist,'entries'):
 			if d.purchase_order:
-				submitted = sql("select name from `tabPurchase Order` where docstatus = 1 and name = '%s'" % d.purchase_order)
+				submitted = webnotes.conn.sql("select name from `tabPurchase Order` where docstatus = 1 and name = '%s'" % d.purchase_order)
 				if not submitted:
 					webnotes.throw("Purchase Order : "+ cstr(d.purchase_order) +" is not submitted")
 			if d.purchase_receipt:
-				submitted = sql("select name from `tabPurchase Receipt` where docstatus = 1 and name = '%s'" % d.purchase_receipt)
+				submitted = webnotes.conn.sql("select name from `tabPurchase Receipt` where docstatus = 1 and name = '%s'" % d.purchase_receipt)
 				if not submitted:
 					webnotes.throw("Purchase Receipt : "+ cstr(d.purchase_receipt) +" is not submitted")
 					
diff --git a/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.py b/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.py
index a4534ae..0a32fb9 100644
--- a/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.py
+++ b/accounts/doctype/purchase_taxes_and_charges_master/purchase_taxes_and_charges_master.py
@@ -8,7 +8,6 @@
 from webnotes.model.bean import copy_doclist
 from webnotes.model.code import get_obj
 
-sql = webnotes.conn.sql
 	
 
 
diff --git a/buying/doctype/purchase_common/purchase_common.py b/buying/doctype/purchase_common/purchase_common.py
index 9b6dc6c..c05aba4 100644
--- a/buying/doctype/purchase_common/purchase_common.py
+++ b/buying/doctype/purchase_common/purchase_common.py
@@ -10,7 +10,6 @@
 
 from buying.utils import get_last_purchase_details
 
-sql = webnotes.conn.sql
 	
 from controllers.buying_controller import BuyingController
 class DocType(BuyingController):
@@ -23,14 +22,14 @@
 			msgprint(_("You need to put at least one item in the item table."), raise_exception=True)
 
 	def get_supplier_details(self, name = ''):
-		details = sql("select supplier_name,address from `tabSupplier` where name = '%s' and docstatus != 2" %(name), as_dict = 1)
+		details = webnotes.conn.sql("select supplier_name,address from `tabSupplier` where name = '%s' and docstatus != 2" %(name), as_dict = 1)
 		if details:
 			ret = {
 				'supplier_name'	:	details and details[0]['supplier_name'] or '',
 				'supplier_address'	:	details and details[0]['address'] or ''
 			}
 			# ********** get primary contact details (this is done separately coz. , in case there is no primary contact thn it would not be able to fetch customer details in case of join query)
-			contact_det = sql("select contact_name, contact_no, email_id from `tabContact` where supplier = '%s' and is_supplier = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(name), as_dict = 1)
+			contact_det = webnotes.conn.sql("select contact_name, contact_no, email_id from `tabContact` where supplier = '%s' and is_supplier = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(name), as_dict = 1)
 			ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
 			return ret
 		else:
@@ -40,7 +39,7 @@
 	# Get Available Qty at Warehouse
 	def get_bin_details( self, arg = ''):
 		arg = eval(arg)
-		bin = sql("select projected_qty from `tabBin` where item_code = %s and warehouse = %s", (arg['item_code'], arg['warehouse']), as_dict=1)
+		bin = webnotes.conn.sql("select projected_qty from `tabBin` where item_code = %s and warehouse = %s", (arg['item_code'], arg['warehouse']), as_dict=1)
 		ret = { 'projected_qty' : bin and flt(bin[0]['projected_qty']) or 0 }
 		return ret
 
@@ -70,7 +69,7 @@
 
 			# update last purchsae rate
 			if last_purchase_rate:
-				sql("update `tabItem` set last_purchase_rate = %s where name = %s",
+				webnotes.conn.sql("update `tabItem` set last_purchase_rate = %s where name = %s",
 						(flt(last_purchase_rate),d.item_code))
 	
 	def get_last_purchase_rate(self, obj):
@@ -107,7 +106,7 @@
 				raise Exception
 			
 			# udpate with latest quantities
-			bin = sql("select projected_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
+			bin = webnotes.conn.sql("select projected_qty from `tabBin` where item_code = %s and warehouse = %s", (d.item_code, d.warehouse), as_dict = 1)
 			
 			f_lst ={'projected_qty': bin and flt(bin[0]['projected_qty']) or 0, 'ordered_qty': 0, 'received_qty' : 0}
 			if d.doctype == 'Purchase Receipt Item':
@@ -116,7 +115,7 @@
 				if d.fields.has_key(x):
 					d.fields[x] = f_lst[x]
 			
-			item = sql("select is_stock_item, is_purchase_item, is_sub_contracted_item, end_of_life from tabItem where name=%s", 
+			item = webnotes.conn.sql("select is_stock_item, is_purchase_item, is_sub_contracted_item, end_of_life from tabItem where name=%s", 
 				d.item_code)
 			if not item:
 				msgprint("Item %s does not exist in Item Master." % cstr(d.item_code), raise_exception=True)
@@ -139,7 +138,7 @@
 			# if is not stock item
 			f = [d.schedule_date, d.item_code, d.description]
 			
-			ch = sql("select is_stock_item from `tabItem` where name = '%s'"%d.item_code)
+			ch = webnotes.conn.sql("select is_stock_item from `tabItem` where name = '%s'"%d.item_code)
 			
 			if ch and ch[0][0] == 'Yes':	
 				# check for same items
@@ -165,18 +164,18 @@
 		# but if in Material Request uom KG it can change in PO
 		
 		get_qty = (transaction == 'Material Request - Purchase Order') and 'qty * conversion_factor' or 'qty'
-		qty = sql("select sum(%s) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% ( get_qty, curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
+		qty = webnotes.conn.sql("select sum(%s) from `tab%s` where %s = '%s' and docstatus = 1 and parent != '%s'"% ( get_qty, curr_doctype, ref_tab_fname, ref_tab_dn, curr_parent_name))
 		qty = qty and flt(qty[0][0]) or 0 
 		
 		# get total qty of ref doctype
 		#--------------------
-		max_qty = sql("select qty from `tab%s` where name = '%s' and docstatus = 1"% (ref_doc_tname, ref_tab_dn))
+		max_qty = webnotes.conn.sql("select qty from `tab%s` where name = '%s' and docstatus = 1"% (ref_doc_tname, ref_tab_dn))
 		max_qty = max_qty and flt(max_qty[0][0]) or 0
 		
 		return cstr(qty)+'~~~'+cstr(max_qty)
 
 	def check_for_stopped_status(self, doctype, docname):
-		stopped = sql("select name from `tab%s` where name = '%s' and status = 'Stopped'" % 
+		stopped = webnotes.conn.sql("select name from `tab%s` where name = '%s' and status = 'Stopped'" % 
 			( doctype, docname))
 		if stopped:
 			msgprint("One cannot do any transaction against %s : %s, it's status is 'Stopped'" % 
@@ -184,7 +183,7 @@
 	
 	def check_docstatus(self, check, doctype, docname , detail_doctype = ''):
 		if check == 'Next':
-			submitted = sql("""select t1.name from `tab%s` t1,`tab%s` t2 
+			submitted = webnotes.conn.sql("""select t1.name from `tab%s` t1,`tab%s` t2 
 				where t1.name = t2.parent and t2.prevdoc_docname = %s and t1.docstatus = 1""" 
 				% (doctype, detail_doctype, '%s'), docname)
 			if submitted:
@@ -192,7 +191,7 @@
 					+ _(" has already been submitted."), raise_exception=1)
 
 		if check == 'Previous':
-			submitted = sql("""select name from `tab%s` 
+			submitted = webnotes.conn.sql("""select name from `tab%s` 
 				where docstatus = 1 and name = %s"""% (doctype, '%s'), docname)
 			if not submitted:
 				msgprint(cstr(doctype) + ": " + cstr(submitted[0][0]) 
@@ -200,7 +199,7 @@
 
 	def get_rate(self, arg, obj):
 		arg = eval(arg)
-		rate = sql("select account_type, tax_rate from `tabAccount` where name = %s" 
+		rate = webnotes.conn.sql("select account_type, tax_rate from `tabAccount` where name = %s" 
 			, (arg['account_head']), as_dict=1)
 		
 		return {'rate':	rate and (rate[0]['account_type'] == 'Tax' \
@@ -209,6 +208,6 @@
 	def get_prevdoc_date(self, obj):
 		for d in getlist(obj.doclist, obj.fname):
 			if d.prevdoc_doctype and d.prevdoc_docname:
-				dt = sql("select transaction_date from `tab%s` where name = %s" 
+				dt = webnotes.conn.sql("select transaction_date from `tab%s` where name = %s" 
 					% (d.prevdoc_doctype, '%s'), (d.prevdoc_docname))
 				d.prevdoc_date = dt and dt[0][0].strftime('%Y-%m-%d') or ''
\ No newline at end of file
diff --git a/buying/doctype/purchase_order/purchase_order.py b/buying/doctype/purchase_order/purchase_order.py
index 64f89e3..3389f74 100644
--- a/buying/doctype/purchase_order/purchase_order.py
+++ b/buying/doctype/purchase_order/purchase_order.py
@@ -9,7 +9,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 from controllers.buying_controller import BuyingController
 class DocType(BuyingController):
@@ -133,8 +132,8 @@
 				update_bin(args)
 				
 	def check_modified_date(self):
-		mod_db = sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
-		date_diff = sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
+		mod_db = webnotes.conn.sql("select modified from `tabPurchase Order` where name = '%s'" % self.doc.name)
+		date_diff = webnotes.conn.sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
 		
 		if date_diff and date_diff[0][0]:
 			msgprint(cstr(self.doc.doctype) +" => "+ cstr(self.doc.name) +" has been modified. Please Refresh. ")
@@ -173,7 +172,7 @@
 		pc_obj.check_docstatus(check = 'Next', doctype = 'Purchase Receipt', docname = self.doc.name, detail_doctype = 'Purchase Receipt Item')
 
 		# Check if Purchase Invoice has been submitted against current Purchase Order
-		submitted = sql("select t1.name from `tabPurchase Invoice` t1,`tabPurchase Invoice Item` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name)
+		submitted = webnotes.conn.sql("select t1.name from `tabPurchase Invoice` t1,`tabPurchase Invoice Item` t2 where t1.name = t2.parent and t2.purchase_order = '%s' and t1.docstatus = 1" % self.doc.name)
 		if submitted:
 			msgprint("Purchase Invoice : " + cstr(submitted[0][0]) + " has already been submitted !")
 			raise Exception
diff --git a/buying/doctype/supplier/supplier.py b/buying/doctype/supplier/supplier.py
index 15e1d62..3c01633 100644
--- a/buying/doctype/supplier/supplier.py
+++ b/buying/doctype/supplier/supplier.py
@@ -9,7 +9,6 @@
 from webnotes import msgprint, _
 from webnotes.model.doc import make_autoname
 
-sql = webnotes.conn.sql
 
 from utilities.transaction_base import TransactionBase
 
@@ -29,7 +28,7 @@
 			self.doc.name = make_autoname(self.doc.naming_series + '.#####')
 
 	def update_credit_days_limit(self):
-		sql("""update tabAccount set credit_days = %s where name = %s""", 
+		webnotes.conn.sql("""update tabAccount set credit_days = %s where name = %s""", 
 			(cint(self.doc.credit_days), self.doc.name + " - " + self.get_company_abbr()))
 
 	def on_update(self):
@@ -43,7 +42,7 @@
 		self.update_credit_days_limit()
 	
 	def get_payables_group(self):
-		g = sql("select payables_group from tabCompany where name=%s", self.doc.company)
+		g = webnotes.conn.sql("select payables_group from tabCompany where name=%s", self.doc.company)
 		g = g and g[0][0] or ''
 		if not g:
 			msgprint("Update Company master, assign a default group for Payables")
@@ -65,14 +64,14 @@
 		msgprint(_("Created Group ") + ac)
 	
 	def get_company_abbr(self):
-		return sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
+		return webnotes.conn.sql("select abbr from tabCompany where name=%s", self.doc.company)[0][0]
 	
 	def get_parent_account(self, abbr):
 		if (not self.doc.supplier_type):
 			msgprint("Supplier Type is mandatory")
 			raise Exception
 		
-		if not sql("select name from tabAccount where name=%s and debit_or_credit = 'Credit' and ifnull(is_pl_account, 'No') = 'No'", (self.doc.supplier_type + " - " + abbr)):
+		if not webnotes.conn.sql("select name from tabAccount where name=%s and debit_or_credit = 'Credit' and ifnull(is_pl_account, 'No') = 'No'", (self.doc.supplier_type + " - " + abbr)):
 
 			# if not group created , create it
 			self.add_account(self.doc.supplier_type, self.get_payables_group(), abbr)
@@ -90,7 +89,7 @@
 			abbr = self.get_company_abbr() 
 			parent_account = self.get_parent_account(abbr)
 						
-			if not sql("select name from tabAccount where name=%s", (self.doc.name + " - " + abbr)):
+			if not webnotes.conn.sql("select name from tabAccount where name=%s", (self.doc.name + " - " + abbr)):
 				ac_bean = webnotes.bean({
 					"doctype": "Account",
 					'account_name': self.doc.name,
@@ -121,15 +120,15 @@
 	
 	def get_contacts(self,nm):
 		if nm:
-			contact_details =webnotes.conn.convert_to_lists(sql("select name, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')),contact_no,email_id from `tabContact` where supplier = '%s'"%nm))
+			contact_details =webnotes.conn.convert_to_lists(webnotes.conn.sql("select name, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')),contact_no,email_id from `tabContact` where supplier = '%s'"%nm))
 	 
 			return contact_details
 		else:
 			return ''
 			
 	def delete_supplier_address(self):
-		for rec in sql("select * from `tabAddress` where supplier=%s", (self.doc.name,), as_dict=1):
-			sql("delete from `tabAddress` where name=%s",(rec['name']))
+		for rec in webnotes.conn.sql("select * from `tabAddress` where supplier=%s", (self.doc.name,), as_dict=1):
+			webnotes.conn.sql("delete from `tabAddress` where name=%s",(rec['name']))
 	
 	def delete_supplier_contact(self):
 		for contact in webnotes.conn.sql_list("""select name from `tabContact` 
@@ -138,7 +137,7 @@
 	
 	def delete_supplier_account(self):
 		"""delete supplier's ledger if exist and check balance before deletion"""
-		acc = sql("select name from `tabAccount` where master_type = 'Supplier' \
+		acc = webnotes.conn.sql("select name from `tabAccount` where master_type = 'Supplier' \
 			and master_name = %s and docstatus < 2", self.doc.name)
 		if acc:
 			from webnotes.model import delete_doc
@@ -161,7 +160,7 @@
 			('Purchase Receipt', 'supplier'),
 			('Serial No', 'supplier')]
 			for rec in update_fields:
-				sql("update `tab%s` set supplier_name = %s where `%s` = %s" % \
+				webnotes.conn.sql("update `tab%s` set supplier_name = %s where `%s` = %s" % \
 					(rec[0], '%s', rec[1], '%s'), (new, old))
 				
 		for account in webnotes.conn.sql("""select name, account_name from 
diff --git a/home/doctype/feed/feed.py b/home/doctype/feed/feed.py
index 25abf57..ebee5c4 100644
--- a/home/doctype/feed/feed.py
+++ b/home/doctype/feed/feed.py
@@ -7,7 +7,6 @@
 from webnotes.model import db_exists
 from webnotes.model.bean import copy_doclist
 
-sql = webnotes.conn.sql
 	
 
 
diff --git a/hr/doctype/attendance/attendance.py b/hr/doctype/attendance/attendance.py
index 7b82bc5..6d52b57 100644
--- a/hr/doctype/attendance/attendance.py
+++ b/hr/doctype/attendance/attendance.py
@@ -7,7 +7,6 @@
 from webnotes.utils import getdate, nowdate
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self, doc, doclist=[]):
@@ -15,7 +14,7 @@
 		self.doclist = doclist
 	
 	def validate_duplicate_record(self):	 
-		res = sql("""select name from `tabAttendance` where employee = %s and att_date = %s 
+		res = webnotes.conn.sql("""select name from `tabAttendance` where employee = %s and att_date = %s 
 			and name != %s and docstatus = 1""", 
 			(self.doc.employee, self.doc.att_date, self.doc.name))
 		if res:
@@ -24,7 +23,7 @@
 			
 	def check_leave_record(self):
 		if self.doc.status == 'Present':
-			leave = sql("""select name from `tabLeave Application` 
+			leave = webnotes.conn.sql("""select name from `tabLeave Application` 
 				where employee = %s and %s between from_date and to_date and status = 'Approved' 
 				and docstatus = 1""", (self.doc.employee, self.doc.att_date))
 			
@@ -42,7 +41,7 @@
 			msgprint(_("Attendance can not be marked for future dates"), raise_exception=1)
 
 	def validate_employee(self):
-		emp = sql("select name from `tabEmployee` where name = %s and status = 'Active'",
+		emp = webnotes.conn.sql("select name from `tabEmployee` where name = %s and status = 'Active'",
 		 	self.doc.employee)
 		if not emp:
 			msgprint(_("Employee: ") + self.doc.employee + 
diff --git a/hr/doctype/employee/employee.py b/hr/doctype/employee/employee.py
index e28e02d..e8396eb 100644
--- a/hr/doctype/employee/employee.py
+++ b/hr/doctype/employee/employee.py
@@ -8,7 +8,6 @@
 from webnotes.model.doc import make_autoname
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self,doc,doclist=[]):
diff --git a/hr/doctype/holiday_list/holiday_list.py b/hr/doctype/holiday_list/holiday_list.py
index 81d18f3..100c140 100644
--- a/hr/doctype/holiday_list/holiday_list.py
+++ b/hr/doctype/holiday_list/holiday_list.py
@@ -10,7 +10,6 @@
 from webnotes.model.bean import copy_doclist
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 
 import datetime
 
diff --git a/hr/doctype/leave_allocation/leave_allocation.py b/hr/doctype/leave_allocation/leave_allocation.py
index 1c856fa..a058e1d 100755
--- a/hr/doctype/leave_allocation/leave_allocation.py
+++ b/hr/doctype/leave_allocation/leave_allocation.py
@@ -5,7 +5,6 @@
 import webnotes
 from webnotes.utils import cint, flt
 from webnotes import msgprint
-sql = webnotes.conn.sql
 	
 class DocType:
 	def __init__(self, doc, doclist):
@@ -37,7 +36,7 @@
 		
 	def check_existing_leave_allocation(self):
 		"""check whether leave for same type is already allocated or not"""
-		leave_allocation = sql("""select name from `tabLeave Allocation`
+		leave_allocation = webnotes.conn.sql("""select name from `tabLeave Allocation`
 			where employee=%s and leave_type=%s and fiscal_year=%s and docstatus=1""",
 			(self.doc.employee, self.doc.leave_type, self.doc.fiscal_year))
 		if leave_allocation:
@@ -64,14 +63,14 @@
 		return self.get_leaves_allocated(prev_fyear) - self.get_leaves_applied(prev_fyear)
 		
 	def get_leaves_applied(self, fiscal_year):
-		leaves_applied = sql("""select SUM(ifnull(total_leave_days, 0))
+		leaves_applied = webnotes.conn.sql("""select SUM(ifnull(total_leave_days, 0))
 			from `tabLeave Application` where employee=%s and leave_type=%s
 			and fiscal_year=%s and docstatus=1""", 
 			(self.doc.employee, self.doc.leave_type, fiscal_year))
 		return leaves_applied and flt(leaves_applied[0][0]) or 0
 
 	def get_leaves_allocated(self, fiscal_year):
-		leaves_allocated = sql("""select SUM(ifnull(total_leaves_allocated, 0))
+		leaves_allocated = webnotes.conn.sql("""select SUM(ifnull(total_leaves_allocated, 0))
 			from `tabLeave Allocation` where employee=%s and leave_type=%s
 			and fiscal_year=%s and docstatus=1 and name!=%s""",
 			(self.doc.employee, self.doc.leave_type, fiscal_year, self.doc.name))
@@ -79,7 +78,7 @@
 	
 	def allow_carry_forward(self):
 		"""check whether carry forward is allowed or not for this leave type"""
-		cf = sql("""select is_carry_forward from `tabLeave Type` where name = %s""",
+		cf = webnotes.conn.sql("""select is_carry_forward from `tabLeave Type` where name = %s""",
 			self.doc.leave_type)
 		cf = cf and cint(cf[0][0]) or 0
 		if not cf:
@@ -110,7 +109,7 @@
 		webnotes.conn.set(self.doc,'total_leaves_allocated',flt(leave_det['total_leaves_allocated']))
 
 	def check_for_leave_application(self):
-		exists = sql("""select name from `tabLeave Application`
+		exists = webnotes.conn.sql("""select name from `tabLeave Application`
 			where employee=%s and leave_type=%s and fiscal_year=%s and docstatus=1""",
 			(self.doc.employee, self.doc.leave_type, self.doc.fiscal_year))
 		if exists:
diff --git a/hr/doctype/leave_control_panel/leave_control_panel.py b/hr/doctype/leave_control_panel/leave_control_panel.py
index 30b52ba..294701c 100644
--- a/hr/doctype/leave_control_panel/leave_control_panel.py
+++ b/hr/doctype/leave_control_panel/leave_control_panel.py
@@ -9,7 +9,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 
 
@@ -34,7 +33,7 @@
     emp_query = "select name from `tabEmployee` "
     if flag == 1:
       emp_query += condition 
-    e = sql(emp_query)
+    e = webnotes.conn.sql(emp_query)
     return e
 
   # ----------------
diff --git a/hr/doctype/salary_manager/salary_manager.py b/hr/doctype/salary_manager/salary_manager.py
index 0eadca1..48dcab1 100644
--- a/hr/doctype/salary_manager/salary_manager.py
+++ b/hr/doctype/salary_manager/salary_manager.py
@@ -11,7 +11,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 
 
@@ -30,7 +29,7 @@
 		cond = self.get_filter_condition()
 		cond += self.get_joining_releiving_condition()
 		
-		emp_list = sql("""
+		emp_list = webnotes.conn.sql("""
 			select t1.name
 			from `tabEmployee` t1, `tabSalary Structure` t2 
 			where t1.docstatus!=2 and t2.docstatus != 2 
@@ -68,7 +67,7 @@
 		
 	
 	def get_month_details(self, year, month):
-		ysd = sql("select year_start_date from `tabFiscal Year` where name ='%s'"%year)[0][0]
+		ysd = webnotes.conn.sql("select year_start_date from `tabFiscal Year` where name ='%s'"%year)[0][0]
 		if ysd:
 			from dateutil.relativedelta import relativedelta
 			import calendar, datetime
@@ -96,7 +95,7 @@
 		emp_list = self.get_emp_list()
 		ss_list = []
 		for emp in emp_list:
-			if not sql("""select name from `tabSalary Slip` 
+			if not webnotes.conn.sql("""select name from `tabSalary Slip` 
 					where docstatus!= 2 and employee = %s and month = %s and fiscal_year = %s and company = %s
 					""", (emp[0], self.doc.month, self.doc.fiscal_year, self.doc.company)):
 				ss = webnotes.bean({
@@ -127,7 +126,7 @@
 			which are not submitted
 		"""
 		cond = self.get_filter_condition()
-		ss_list = sql("""
+		ss_list = webnotes.conn.sql("""
 			select t1.name from `tabSalary Slip` t1 
 			where t1.docstatus = 0 and month = '%s' and fiscal_year = '%s' %s
 		""" % (self.doc.month, self.doc.fiscal_year, cond))
@@ -189,7 +188,7 @@
 			Get total salary amount from submitted salary slip based on selected criteria
 		"""
 		cond = self.get_filter_condition()
-		tot = sql("""
+		tot = webnotes.conn.sql("""
 			select sum(rounded_total) from `tabSalary Slip` t1 
 			where t1.docstatus = 1 and month = '%s' and fiscal_year = '%s' %s
 		""" % (self.doc.month, self.doc.fiscal_year, cond))
@@ -202,7 +201,7 @@
 			get default bank account,default salary acount from company
 		"""
 		amt = self.get_total_salary()
-		com = sql("select default_bank_account from `tabCompany` where name = '%s'" % self.doc.company)
+		com = webnotes.conn.sql("select default_bank_account from `tabCompany` where name = '%s'" % self.doc.company)
 		
 		if not com[0][0] or not com[0][1]:
 			msgprint("You can set Default Bank Account in Company master.")
diff --git a/hr/doctype/salary_manager/test_salary_manager.py b/hr/doctype/salary_manager/test_salary_manager.py
index 04000f0..13815db 100644
--- a/hr/doctype/salary_manager/test_salary_manager.py
+++ b/hr/doctype/salary_manager/test_salary_manager.py
@@ -9,7 +9,7 @@
 
 # from webnotes.model.doc import Document
 # from webnotes.model.code import get_obj
-# sql = webnotes.conn.sql
+# webnotes.conn.sql = webnotes.conn.sql
 # 
 # class TestSalaryManager(unittest.TestCase):
 # 	def setUp(self):
@@ -20,15 +20,15 @@
 # 		ss1[0].employee = emp1.name
 # 		for s in ss1: s.save(1)
 # 		for s in ss1[1:]:
-# 			sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
-# 			sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
+# 			webnotes.conn.sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
+# 			webnotes.conn.sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss1[0].name, s.name))
 # 			
 # 		
 # 		ss2[0].employee = emp2.name
 # 		for s in ss2: s.save(1)		
 # 		for s in ss2[1:]:
-# 			sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
-# 			sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
+# 			webnotes.conn.sql("update `tabSalary Structure Earning` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
+# 			webnotes.conn.sql("update `tabSalary Structure Deduction` set parent = '%s' where name = '%s'" % (ss2[0].name, s.name))
 # 			
 # 		sman.save()
 # 		self.sm = get_obj('Salary Manager')	
@@ -36,7 +36,7 @@
 # 		self.sm.create_sal_slip()
 # 		
 # 	def test_creation(self):
-# 		ssid = sql("""
+# 		ssid = webnotes.conn.sql("""
 # 			select name, department 
 # 			from `tabSalary Slip` 
 # 			where month = '08' and fiscal_year='2011-2012'""")
@@ -46,7 +46,7 @@
 # 		
 # 		
 # 	def test_lwp_calc(self):
-# 		ss = sql("""
+# 		ss = webnotes.conn.sql("""
 # 			select payment_days
 # 			from `tabSalary Slip` 
 # 			where month = '08' and fiscal_year='2011-2012' and employee = '%s'
diff --git a/hr/doctype/salary_slip/salary_slip.py b/hr/doctype/salary_slip/salary_slip.py
index 36d7ceb..dab026e 100644
--- a/hr/doctype/salary_slip/salary_slip.py
+++ b/hr/doctype/salary_slip/salary_slip.py
@@ -11,7 +11,6 @@
 from webnotes import msgprint, _
 from setup.utils import get_company_currency
 
-sql = webnotes.conn.sql
 	
 from utilities.transaction_base import TransactionBase
 
@@ -32,7 +31,7 @@
 
 
 	def check_sal_struct(self):
-		struct = sql("select name from `tabSalary Structure` where employee ='%s' and is_active = 'Yes' "%self.doc.employee)
+		struct = webnotes.conn.sql("select name from `tabSalary Structure` where employee ='%s' and is_active = 'Yes' "%self.doc.employee)
 		if not struct:
 			msgprint("Please create Salary Structure for employee '%s'"%self.doc.employee)
 			self.doc.employee = ''
@@ -100,13 +99,13 @@
 		return payment_days
 		
 	def get_holidays_for_employee(self, m):
-		holidays = sql("""select t1.holiday_date 
+		holidays = webnotes.conn.sql("""select t1.holiday_date 
 			from `tabHoliday` t1, tabEmployee t2 
 			where t1.parent = t2.holiday_list and t2.name = %s 
 			and t1.holiday_date between %s and %s""", 
 			(self.doc.employee, m['month_start_date'], m['month_end_date']))
 		if not holidays:
-			holidays = sql("""select t1.holiday_date 
+			holidays = webnotes.conn.sql("""select t1.holiday_date 
 				from `tabHoliday` t1, `tabHoliday List` t2 
 				where t1.parent = t2.name and ifnull(t2.is_default, 0) = 1 
 				and t2.fiscal_year = %s
@@ -120,7 +119,7 @@
 		for d in range(m['month_days']):
 			dt = add_days(cstr(m['month_start_date']), d)
 			if dt not in holidays:
-				leave = sql("""
+				leave = webnotes.conn.sql("""
 					select t1.name, t1.half_day
 					from `tabLeave Application` t1, `tabLeave Type` t2 
 					where t2.name = t1.leave_type 
@@ -134,7 +133,7 @@
 		return lwp
 
 	def check_existing(self):
-		ret_exist = sql("""select name from `tabSalary Slip` 
+		ret_exist = webnotes.conn.sql("""select name from `tabSalary Slip` 
 			where month = %s and fiscal_year = %s and docstatus != 2 
 			and employee = %s and name != %s""", 
 			(self.doc.month, self.doc.fiscal_year, self.doc.employee, self.doc.name))
@@ -201,9 +200,9 @@
 		receiver = webnotes.conn.get_value("Employee", self.doc.employee, "company_email")
 		if receiver:
 			subj = 'Salary Slip - ' + cstr(self.doc.month) +'/'+cstr(self.doc.fiscal_year)
-			earn_ret=sql("""select e_type, e_modified_amount from `tabSalary Slip Earning` 
+			earn_ret=webnotes.conn.sql("""select e_type, e_modified_amount from `tabSalary Slip Earning` 
 				where parent = %s""", self.doc.name)
-			ded_ret=sql("""select d_type, d_modified_amount from `tabSalary Slip Deduction` 
+			ded_ret=webnotes.conn.sql("""select d_type, d_modified_amount from `tabSalary Slip Deduction` 
 				where parent = %s""", self.doc.name)
 		 
 			earn_table = ''
diff --git a/hr/doctype/salary_structure/salary_structure.py b/hr/doctype/salary_structure/salary_structure.py
index 50b0160..bfa7850 100644
--- a/hr/doctype/salary_structure/salary_structure.py
+++ b/hr/doctype/salary_structure/salary_structure.py
@@ -8,7 +8,6 @@
 from webnotes.model.doc import addchild, make_autoname
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self,doc,doclist=[]):
@@ -20,7 +19,7 @@
 
 	def get_employee_details(self):
 		ret = {}
-		det = sql("""select employee_name, branch, designation, department, grade 
+		det = webnotes.conn.sql("""select employee_name, branch, designation, department, grade 
 			from `tabEmployee` where name = %s""", self.doc.employee)
 		if det:
 			ret = {
@@ -34,7 +33,7 @@
 		return ret
 
 	def get_ss_values(self,employee):
-		basic_info = sql("""select bank_name, bank_ac_no, esic_card_no, pf_number 
+		basic_info = webnotes.conn.sql("""select bank_name, bank_ac_no, esic_card_no, pf_number 
 			from `tabEmployee` where name =%s""", employee)
 		ret = {'bank_name': basic_info and basic_info[0][0] or '',
 			'bank_ac_no': basic_info and basic_info[0][1] or '',
@@ -43,7 +42,7 @@
 		return ret
 
 	def make_table(self, doct_name, tab_fname, tab_name):
-		list1 = sql("select name from `tab%s` where docstatus != 2" % doct_name)
+		list1 = webnotes.conn.sql("select name from `tab%s` where docstatus != 2" % doct_name)
 		for li in list1:
 			child = addchild(self.doc, tab_fname, tab_name, self.doclist)
 			if(tab_fname == 'earning_details'):
@@ -58,7 +57,7 @@
 		self.make_table('Deduction Type','deduction_details', 'Salary Structure Deduction')
 
 	def check_existing(self):
-		ret = sql("""select name from `tabSalary Structure` where is_active = 'Yes' 
+		ret = webnotes.conn.sql("""select name from `tabSalary Structure` where is_active = 'Yes' 
 			and employee = %s and name!=%s""", (self.doc.employee,self.doc.name))
 		if ret and self.doc.is_active=='Yes':
 			msgprint(_("""Another Salary Structure '%s' is active for employee '%s'. 
diff --git a/hr/doctype/upload_attendance/upload_attendance.py b/hr/doctype/upload_attendance/upload_attendance.py
index c1344b9..5e2b02e 100644
--- a/hr/doctype/upload_attendance/upload_attendance.py
+++ b/hr/doctype/upload_attendance/upload_attendance.py
@@ -9,7 +9,8 @@
 from webnotes import msgprint, _
 from webnotes.utils.datautils import UnicodeWriter
 
-doclist = None
+# doclist = None
+doclist = webnotes.local('uploadattendance_doclist')
 
 class DocType():
 	def __init__(self, doc, doclist=[]):
@@ -22,8 +23,7 @@
 		raise webnotes.PermissionError
 	
 	args = webnotes.form_dict
-	global doclist
-	doclist = webnotes.model.doctype.get("Attendance")
+	webnotes.local.uploadattendance_doclist = webnotes.model.doctype.get("Attendance")
 
 	w = UnicodeWriter()
 	w = add_header(w)
@@ -144,4 +144,4 @@
 		webnotes.conn.rollback()		
 	else:
 		webnotes.conn.commit()
-	return {"messages": ret, "error": error}
\ No newline at end of file
+	return {"messages": ret, "error": error}
diff --git a/manufacturing/doctype/bom/bom.py b/manufacturing/doctype/bom/bom.py
index 9a56612..20c1141 100644
--- a/manufacturing/doctype/bom/bom.py
+++ b/manufacturing/doctype/bom/bom.py
@@ -9,7 +9,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 
 class DocType:
@@ -18,7 +17,7 @@
 		self.doclist = doclist
 
 	def autoname(self):
-		last_name = sql("""select max(name) from `tabBOM` 
+		last_name = webnotes.conn.sql("""select max(name) from `tabBOM` 
 			where name like "BOM/%s/%%" """ % cstr(self.doc.item).replace('"', '\\"'))
 		if last_name:
 			idx = cint(cstr(last_name[0][0]).split('/')[-1].split('-')[0]) + 1
@@ -144,7 +143,7 @@
 			webnotes.bean(self.doclist).update_after_submit()
 
 	def get_bom_unitcost(self, bom_no):
-		bom = sql("""select name, total_cost/quantity as unit_cost from `tabBOM`
+		bom = webnotes.conn.sql("""select name, total_cost/quantity as unit_cost from `tabBOM`
 			where is_active = 1 and name = %s""", bom_no, as_dict=1)
 		return bom and bom[0]['unit_cost'] or 0
 
@@ -156,7 +155,7 @@
 		from stock.utils import get_incoming_rate
 		dt = self.doc.costing_date or nowdate()
 		time = self.doc.costing_date == nowdate() and now().split()[1] or '23:59'
-		warehouse = sql("select warehouse from `tabBin` where item_code = %s", args['item_code'])
+		warehouse = webnotes.conn.sql("select warehouse from `tabBin` where item_code = %s", args['item_code'])
 		rate = []
 		for wh in warehouse:
 			r = get_incoming_rate({
@@ -184,7 +183,7 @@
 			if not self.doc.is_active:
 				webnotes.conn.set(self.doc, "is_default", 0)
 			
-			sql("update `tabItem` set default_bom = null where name = %s and default_bom = %s", 
+			webnotes.conn.sql("update `tabItem` set default_bom = null where name = %s and default_bom = %s", 
 				 (self.doc.item, self.doc.name))
 
 	def clear_operations(self):
@@ -250,7 +249,7 @@
 
 	def validate_bom_no(self, item, bom_no, idx):
 		"""Validate BOM No of sub-contracted items"""
-		bom = sql("""select name from `tabBOM` where name = %s and item = %s 
+		bom = webnotes.conn.sql("""select name from `tabBOM` where name = %s and item = %s 
 			and is_active=1 and docstatus=1""", 
 			(bom_no, item), as_dict =1)
 		if not bom:
@@ -272,7 +271,7 @@
 		for d in check_list:
 			bom_list, count = [self.doc.name], 0
 			while (len(bom_list) > count ):
-				boms = sql(" select %s from `tabBOM Item` where %s = '%s' " % 
+				boms = webnotes.conn.sql(" select %s from `tabBOM Item` where %s = '%s' " % 
 					(d[0], d[1], cstr(bom_list[count])))
 				count = count + 1
 				for b in boms:
@@ -364,7 +363,7 @@
 	def get_child_exploded_items(self, bom_no, qty):
 		""" Add all items from Flat BOM of child BOM"""
 		
-		child_fb_items = sql("""select item_code, description, stock_uom, qty, rate, 
+		child_fb_items = webnotes.conn.sql("""select item_code, description, stock_uom, qty, rate, 
 			qty_consumed_per_unit from `tabBOM Explosion Item` 
 			where parent = %s and docstatus = 1""", bom_no, as_dict = 1)
 			
@@ -390,12 +389,12 @@
 			ch.save(1)
 
 	def get_parent_bom_list(self, bom_no):
-		p_bom = sql("select parent from `tabBOM Item` where bom_no = '%s'" % bom_no)
+		p_bom = webnotes.conn.sql("select parent from `tabBOM Item` where bom_no = '%s'" % bom_no)
 		return p_bom and [i[0] for i in p_bom] or []
 
 	def validate_bom_links(self):
 		if not self.doc.is_active:
-			act_pbom = sql("""select distinct bom_item.parent from `tabBOM Item` bom_item
+			act_pbom = webnotes.conn.sql("""select distinct bom_item.parent from `tabBOM Item` bom_item
 				where bom_item.bom_no = %s and bom_item.docstatus = 1
 				and exists (select * from `tabBOM` where name = bom_item.parent
 					and docstatus = 1 and is_active = 1)""", self.doc.name)
diff --git a/manufacturing/doctype/production_order/production_order.py b/manufacturing/doctype/production_order/production_order.py
index 6447c0a..a280a82 100644
--- a/manufacturing/doctype/production_order/production_order.py
+++ b/manufacturing/doctype/production_order/production_order.py
@@ -8,7 +8,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 class OverProductionError(webnotes.ValidationError): pass
 
@@ -23,14 +22,14 @@
 			"In Process", "Completed", "Cancelled"])
 
 		if self.doc.production_item :
-			item_detail = sql("select name from `tabItem` where name = '%s' and docstatus != 2"
+			item_detail = webnotes.conn.sql("select name from `tabItem` where name = '%s' and docstatus != 2"
 			 	% self.doc.production_item, as_dict = 1)
 			if not item_detail:
 				msgprint("Item '%s' does not exist or cancelled in the system." 
 					% cstr(self.doc.production_item), raise_exception=1)
 
 		if self.doc.bom_no:
-			bom = sql("""select name from `tabBOM` where name=%s and docstatus=1 
+			bom = webnotes.conn.sql("""select name from `tabBOM` where name=%s and docstatus=1 
 				and is_active=1 and item=%s"""
 				, (self.doc.bom_no, self.doc.production_item), as_dict =1)
 			if not bom:
@@ -104,7 +103,7 @@
 
 	def on_cancel(self):
 		# Check whether any stock entry exists against this Production Order
-		stock_entry = sql("""select name from `tabStock Entry` 
+		stock_entry = webnotes.conn.sql("""select name from `tabStock Entry` 
 			where production_order = %s and docstatus = 1""", self.doc.name)
 		if stock_entry:
 			msgprint("""Submitted Stock Entry %s exists against this production order. 
diff --git a/manufacturing/doctype/production_planning_tool/production_planning_tool.py b/manufacturing/doctype/production_planning_tool/production_planning_tool.py
index 766f2ac..5480f17 100644
--- a/manufacturing/doctype/production_planning_tool/production_planning_tool.py
+++ b/manufacturing/doctype/production_planning_tool/production_planning_tool.py
@@ -9,7 +9,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self, doc, doclist=[]):
@@ -19,7 +18,7 @@
 
 	def get_so_details(self, so):
 		"""Pull other details from so"""
-		so = sql("""select transaction_date, customer, grand_total 
+		so = webnotes.conn.sql("""select transaction_date, customer, grand_total 
 			from `tabSales Order` where name = %s""", so, as_dict = 1)
 		ret = {
 			'sales_order_date': so and so[0]['transaction_date'] or '',
@@ -31,7 +30,7 @@
 	def get_item_details(self, item_code):
 		""" Pull other item details from item master"""
 
-		item = sql("""select description, stock_uom, default_bom 
+		item = webnotes.conn.sql("""select description, stock_uom, default_bom 
 			from `tabItem` where name = %s""", item_code, as_dict =1)
 		ret = {
 			'description'	: item and item[0]['description'],
@@ -63,7 +62,7 @@
 		if self.doc.fg_item:
 			item_filter += ' and item.name = "' + self.doc.fg_item + '"'
 		
-		open_so = sql("""
+		open_so = webnotes.conn.sql("""
 			select distinct so.name, so.transaction_date, so.customer, so.grand_total
 			from `tabSales Order` so, `tabSales Order Item` so_item
 			where so_item.parent = so.name
@@ -108,7 +107,7 @@
 			msgprint("Please enter sales order in the above table")
 			return []
 			
-		items = sql("""select distinct parent, item_code, reserved_warehouse,
+		items = webnotes.conn.sql("""select distinct parent, item_code, reserved_warehouse,
 			(qty - ifnull(delivered_qty, 0)) as pending_qty
 			from `tabSales Order Item` so_item
 			where parent in (%s) and docstatus = 1 and ifnull(qty, 0) > ifnull(delivered_qty, 0)
@@ -117,7 +116,7 @@
 					or ifnull(item.is_sub_contracted_item, 'No') = 'Yes'))""" % \
 			(", ".join(["%s"] * len(so_list))), tuple(so_list), as_dict=1)
 		
-		dnpi_items = sql("""select distinct dnpi.parent, dnpi.item_code, dnpi.warehouse as reserved_warhouse,
+		dnpi_items = webnotes.conn.sql("""select distinct dnpi.parent, dnpi.item_code, dnpi.warehouse as reserved_warhouse,
 			(((so_item.qty - ifnull(so_item.delivered_qty, 0)) * dnpi.qty) / so_item.qty) 
 				as pending_qty
 			from `tabSales Order Item` so_item, `tabDelivery Note Packing Item` dnpi
@@ -136,7 +135,7 @@
 		self.clear_item_table()
 
 		for p in items:
-			item_details = sql("""select description, stock_uom, default_bom 
+			item_details = webnotes.conn.sql("""select description, stock_uom, default_bom 
 				from tabItem where name=%s""", p['item_code'])
 			pi = addchild(self.doc, 'pp_details', 'Production Plan Item', self.doclist)
 			pi.sales_order				= p['parent']
@@ -162,7 +161,7 @@
 			msgprint("Please enter bom no for item: %s at row no: %s" % 
 				(d.item_code, d.idx), raise_exception=1)
 		else:
-			bom = sql("""select name from `tabBOM` where name = %s and item = %s 
+			bom = webnotes.conn.sql("""select name from `tabBOM` where name = %s and item = %s 
 				and docstatus = 1 and is_active = 1""", 
 				(d.bom_no, d.item_code), as_dict = 1)
 			if not bom:
@@ -243,7 +242,7 @@
 		for bom in bom_dict:
 			if self.doc.use_multi_level_bom:
 				# get all raw materials with sub assembly childs					
-				fl_bom_items = sql("""select fb.item_code, 
+				fl_bom_items = webnotes.conn.sql("""select fb.item_code, 
 					ifnull(sum(fb.qty_consumed_per_unit), 0)*%s as qty, 
 					fb.description, fb.stock_uom, it.min_order_qty 
 					from `tabBOM Explosion Item` fb,`tabItem` it 
@@ -254,7 +253,7 @@
 			else:
 				# Get all raw materials considering SA items as raw materials, 
 				# so no childs of SA items
-				fl_bom_items = sql("""select bom_item.item_code, 
+				fl_bom_items = webnotes.conn.sql("""select bom_item.item_code, 
 						ifnull(sum(bom_item.qty_consumed_per_unit), 0) * %s, 
 						bom_item.description, bom_item.stock_uom, item.min_order_qty
 					from `tabBOM Item` bom_item, tabItem item
@@ -274,7 +273,7 @@
 		 	'Quantity Requested for Purchase', 'Ordered Qty', 'Actual Qty']]
 		for d in self.item_dict:
 			item_list.append([d, self.item_dict[d][1], self.item_dict[d][2], self.item_dict[d][0]])
-			item_qty= sql("""select warehouse, indented_qty, ordered_qty, actual_qty 
+			item_qty= webnotes.conn.sql("""select warehouse, indented_qty, ordered_qty, actual_qty 
 				from `tabBin` where item_code = %s""", d)
 			i_qty, o_qty, a_qty = 0, 0, 0
 			for w in item_qty:
diff --git a/manufacturing/doctype/workstation/workstation.py b/manufacturing/doctype/workstation/workstation.py
index 35e2c1f..cc12934 100644
--- a/manufacturing/doctype/workstation/workstation.py
+++ b/manufacturing/doctype/workstation/workstation.py
@@ -8,7 +8,6 @@
 from webnotes.model import db_exists
 from webnotes.model.bean import copy_doclist
 
-sql = webnotes.conn.sql
 	
 
 
@@ -18,9 +17,9 @@
     self.doclist = doclist
 
   def update_bom_operation(self):
-      bom_list = sql(" select DISTINCT parent from `tabBOM Operation` where workstation = '%s'" % self.doc.name)
+      bom_list = webnotes.conn.sql(" select DISTINCT parent from `tabBOM Operation` where workstation = '%s'" % self.doc.name)
       for bom_no in bom_list:
-        sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no[0], self.doc.name))
+        webnotes.conn.sql("update `tabBOM Operation` set hour_rate = '%s' where parent = '%s' and workstation = '%s'"%( self.doc.hour_rate, bom_no[0], self.doc.name))
   
   def on_update(self):
     webnotes.conn.set(self.doc, 'overhead', flt(self.doc.hour_rate_electricity) + flt(self.doc.hour_rate_consumable) + flt(self.doc.hour_rate_rent))
diff --git a/patches/april_2013/p05_update_file_data.py b/patches/april_2013/p05_update_file_data.py
index e03abc6..47d6de9 100644
--- a/patches/april_2013/p05_update_file_data.py
+++ b/patches/april_2013/p05_update_file_data.py
@@ -52,7 +52,7 @@
 		
 		exists = True
 		if not (filename.startswith("http://") or filename.startswith("https://")):
-			if not os.path.exists(webnotes.utils.get_path("public", "files", filename)):
+			if not os.path.exists(webnotes.utils.get_site_path(webnotes.conf.files_path, filename)):
 				exists = False
 
 		if exists:
diff --git a/patches/april_2013/p06_update_file_size.py b/patches/april_2013/p06_update_file_size.py
index 6879625..973cea9 100644
--- a/patches/april_2013/p06_update_file_size.py
+++ b/patches/april_2013/p06_update_file_size.py
@@ -4,7 +4,7 @@
 import webnotes, os, webnotes.utils
 
 def execute():
-	files_path = webnotes.utils.get_path("public", "files")
+	files_path = webnotes.utils.get_site_path(webnotes.conf.files_path)
 	webnotes.conn.auto_commit_on_many_writes = 1
 
 	for f in webnotes.conn.sql("""select name, file_name from 
@@ -14,4 +14,4 @@
 			if os.path.exists(filepath):
 				webnotes.conn.set_value("File Data", f.name, "file_size", os.stat(filepath).st_size)
 				
-	webnotes.conn.auto_commit_on_many_writes = 0
\ No newline at end of file
+	webnotes.conn.auto_commit_on_many_writes = 0
diff --git a/portal/templates/pages/profile.py b/portal/templates/pages/profile.py
index 8edd830..3d6a86f 100644
--- a/portal/templates/pages/profile.py
+++ b/portal/templates/pages/profile.py
@@ -33,7 +33,7 @@
 		return _("Name is required")
 		
 	webnotes.conn.set_value("Profile", webnotes.session.user, "first_name", fullname)
-	webnotes.add_cookies["full_name"] = fullname
+	webnotes._response.set_cookie("full_name", fullname)
 	
 	return _("Updated")
 	
\ No newline at end of file
diff --git a/projects/doctype/task/task.py b/projects/doctype/task/task.py
index 6cd1ba8..fb9b6ab 100644
--- a/projects/doctype/task/task.py
+++ b/projects/doctype/task/task.py
@@ -9,7 +9,6 @@
 from webnotes.model.bean import copy_doclist
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self,doc,doclist=[]):
@@ -17,13 +16,13 @@
 		self.doclist = doclist
 	
 	def get_project_details(self):
-		cust = sql("select customer, customer_name from `tabProject` where name = %s", self.doc.project)
+		cust = webnotes.conn.sql("select customer, customer_name from `tabProject` where name = %s", self.doc.project)
 		if cust:
 			ret = {'customer': cust and cust[0][0] or '', 'customer_name': cust and cust[0][1] or ''}
 			return ret
 
 	def get_customer_details(self):
-		cust = sql("select customer_name from `tabCustomer` where name=%s", self.doc.customer)
+		cust = webnotes.conn.sql("select customer_name from `tabCustomer` where name=%s", self.doc.customer)
 		if cust:
 			ret = {'customer_name': cust and cust[0][0] or ''}
 			return ret
diff --git a/selling/doctype/customer/customer.py b/selling/doctype/customer/customer.py
index 2b57da9..18c8a34 100644
--- a/selling/doctype/customer/customer.py
+++ b/selling/doctype/customer/customer.py
@@ -9,7 +9,6 @@
 from webnotes import msgprint, _
 import webnotes.defaults
 
-sql = webnotes.conn.sql
 
 from utilities.transaction_base import TransactionBase
 
@@ -31,7 +30,7 @@
 		return webnotes.conn.get_value('Company', self.doc.company, 'abbr')
 
 	def get_receivables_group(self):
-		g = sql("select receivables_group from tabCompany where name=%s", self.doc.company)
+		g = webnotes.conn.sql("select receivables_group from tabCompany where name=%s", self.doc.company)
 		g = g and g[0][0] or '' 
 		if not g:
 			msgprint("Update Company master, assign a default group for Receivables")
@@ -47,7 +46,7 @@
 
 	def update_lead_status(self):
 		if self.doc.lead_name:
-			sql("update `tabLead` set status='Converted' where name = %s", self.doc.lead_name)
+			webnotes.conn.sql("update `tabLead` set status='Converted' where name = %s", self.doc.lead_name)
 
 	def create_account_head(self):
 		if self.doc.company :
@@ -132,7 +131,7 @@
 	
 	def delete_customer_account(self):
 		"""delete customer's ledger if exist and check balance before deletion"""
-		acc = sql("select name from `tabAccount` where master_type = 'Customer' \
+		acc = webnotes.conn.sql("select name from `tabAccount` where master_type = 'Customer' \
 			and master_name = %s and docstatus < 2", self.doc.name)
 		if acc:
 			from webnotes.model import delete_doc
@@ -143,7 +142,7 @@
 		self.delete_customer_contact()
 		self.delete_customer_account()
 		if self.doc.lead_name:
-			sql("update `tabLead` set status='Interested' where name=%s",self.doc.lead_name)
+			webnotes.conn.sql("update `tabLead` set status='Interested' where name=%s",self.doc.lead_name)
 			
 	def on_rename(self, new, old, merge=False):
 		#update customer_name if not naming series
diff --git a/selling/doctype/lead/lead.py b/selling/doctype/lead/lead.py
index da11410..eb3c695 100644
--- a/selling/doctype/lead/lead.py
+++ b/selling/doctype/lead/lead.py
@@ -7,7 +7,6 @@
 from webnotes.utils import cstr, validate_email_add, cint, extract_email_id
 from webnotes import session, msgprint
 
-sql = webnotes.conn.sql
 	
 from controllers.selling_controller import SellingController
 
@@ -38,7 +37,7 @@
 		webnotes.conn.set(self.doc, 'status', status)
 
 	def check_status(self):
-		chk = sql("select status from `tabLead` where name=%s", self.doc.name)
+		chk = webnotes.conn.sql("select status from `tabLead` where name=%s", self.doc.name)
 		chk = chk and chk[0][0] or ''
 		return cstr(chk)
 	
diff --git a/selling/doctype/opportunity/opportunity.py b/selling/doctype/opportunity/opportunity.py
index b265356..284c5e0 100644
--- a/selling/doctype/opportunity/opportunity.py
+++ b/selling/doctype/opportunity/opportunity.py
@@ -8,7 +8,6 @@
 from webnotes.model.bean import getlist
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 from utilities.transaction_base import TransactionBase
 
@@ -27,7 +26,7 @@
 		})
 		
 	def get_item_details(self, item_code):
-		item = sql("""select item_name, stock_uom, description_html, description, item_group, brand
+		item = webnotes.conn.sql("""select item_name, stock_uom, description_html, description, item_group, brand
 			from `tabItem` where name = %s""", item_code, as_dict=1)
 		ret = {
 			'item_name': item and item[0]['item_name'] or '',
@@ -39,7 +38,7 @@
 		return ret
 
 	def get_cust_address(self,name):
-		details = sql("select customer_name, address, territory, customer_group from `tabCustomer` where name = '%s' and docstatus != 2" %(name), as_dict = 1)
+		details = webnotes.conn.sql("select customer_name, address, territory, customer_group from `tabCustomer` where name = '%s' and docstatus != 2" %(name), as_dict = 1)
 		if details:
 			ret = {
 				'customer_name':	details and details[0]['customer_name'] or '',
@@ -49,7 +48,7 @@
 			}
 			# ********** get primary contact details (this is done separately coz. , in case there is no primary contact thn it would not be able to fetch customer details in case of join query)
 
-			contact_det = sql("select contact_name, contact_no, email_id from `tabContact` where customer = '%s' and is_customer = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(name), as_dict = 1)
+			contact_det = webnotes.conn.sql("select contact_name, contact_no, email_id from `tabContact` where customer = '%s' and is_customer = 1 and is_primary_contact = 'Yes' and docstatus != 2" %(name), as_dict = 1)
 
 			ret['contact_person'] = contact_det and contact_det[0]['contact_name'] or ''
 			ret['contact_no']		 = contact_det and contact_det[0]['contact_no'] or ''
@@ -62,7 +61,7 @@
 			
 	def get_contact_details(self, arg):
 		arg = eval(arg)
-		contact = sql("select contact_no, email_id from `tabContact` where contact_name = '%s' and customer_name = '%s'" %(arg['contact_person'],arg['customer']), as_dict = 1)
+		contact = webnotes.conn.sql("select contact_no, email_id from `tabContact` where contact_name = '%s' and customer_name = '%s'" %(arg['contact_person'],arg['customer']), as_dict = 1)
 		ret = {
 			'contact_no' : contact and contact[0]['contact_no'] or '',
 			'email_id' : contact and contact[0]['email_id'] or ''
@@ -136,7 +135,7 @@
 		webnotes.conn.set(self.doc, 'status', 'Submitted')
 	
 	def on_cancel(self):
-		chk = sql("select t1.name from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.docstatus=1 and (t1.status!='Order Lost' and t1.status!='Cancelled') and t2.prevdoc_docname = %s",self.doc.name)
+		chk = webnotes.conn.sql("select t1.name from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.docstatus=1 and (t1.status!='Order Lost' and t1.status!='Cancelled') and t2.prevdoc_docname = %s",self.doc.name)
 		if chk:
 			msgprint("Quotation No. "+cstr(chk[0][0])+" is submitted against this Opportunity. Thus can not be cancelled.")
 			raise Exception
@@ -144,7 +143,7 @@
 			webnotes.conn.set(self.doc, 'status', 'Cancelled')
 		
 	def declare_enquiry_lost(self,arg):
-		chk = sql("select t1.name from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.docstatus=1 and (t1.status!='Order Lost' and t1.status!='Cancelled') and t2.prevdoc_docname = %s",self.doc.name)
+		chk = webnotes.conn.sql("select t1.name from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.docstatus=1 and (t1.status!='Order Lost' and t1.status!='Cancelled') and t2.prevdoc_docname = %s",self.doc.name)
 		if chk:
 			msgprint("Quotation No. "+cstr(chk[0][0])+" is submitted against this Opportunity. Thus 'Opportunity Lost' can not be declared against it.")
 			raise Exception
diff --git a/selling/doctype/quotation/quotation.py b/selling/doctype/quotation/quotation.py
index 44a67fa..8a3bef1 100644
--- a/selling/doctype/quotation/quotation.py
+++ b/selling/doctype/quotation/quotation.py
@@ -9,7 +9,6 @@
 from webnotes.model.code import get_obj
 from webnotes import _, msgprint
 
-sql = webnotes.conn.sql
 	
 
 from controllers.selling_controller import SellingController
@@ -78,7 +77,7 @@
 		
 		if self.doc.order_type in ['Maintenance', 'Service']:
 			for d in getlist(self.doclist, 'quotation_details'):
-				is_service_item = sql("select is_service_item from `tabItem` where name=%s", d.item_code)
+				is_service_item = webnotes.conn.sql("select is_service_item from `tabItem` where name=%s", d.item_code)
 				is_service_item = is_service_item and is_service_item[0][0] or 'No'
 				
 				if is_service_item == 'No':
@@ -86,7 +85,7 @@
 					raise Exception
 		else:
 			for d in getlist(self.doclist, 'quotation_details'):
-				is_sales_item = sql("select is_sales_item from `tabItem` where name=%s", d.item_code)
+				is_sales_item = webnotes.conn.sql("select is_sales_item from `tabItem` where name=%s", d.item_code)
 				is_sales_item = is_sales_item and is_sales_item[0][0] or 'No'
 				
 				if is_sales_item == 'No':
@@ -142,18 +141,18 @@
 		
 		if prevdoc:
 			if flag == 'submit': #on submit
-				sql("update `tabOpportunity` set status = 'Quotation Sent' where name = %s", prevdoc)
+				webnotes.conn.sql("update `tabOpportunity` set status = 'Quotation Sent' where name = %s", prevdoc)
 			elif flag == 'cancel': #on cancel
-				sql("update `tabOpportunity` set status = 'Open' where name = %s", prevdoc)
+				webnotes.conn.sql("update `tabOpportunity` set status = 'Open' where name = %s", prevdoc)
 			elif flag == 'order lost': #order lost
-				sql("update `tabOpportunity` set status = 'Opportunity Lost' where name=%s", prevdoc)
+				webnotes.conn.sql("update `tabOpportunity` set status = 'Opportunity Lost' where name=%s", prevdoc)
 			elif flag == 'order confirm': #order confirm
-				sql("update `tabOpportunity` set status='Order Confirmed' where name=%s", prevdoc)
+				webnotes.conn.sql("update `tabOpportunity` set status='Order Confirmed' where name=%s", prevdoc)
 	
 	# declare as order lost
 	#-------------------------
 	def declare_order_lost(self, arg):
-		chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Item` t2 where t2.parent = t1.name and t1.docstatus=1 and t2.prevdoc_docname = %s",self.doc.name)
+		chk = webnotes.conn.sql("select t1.name from `tabSales Order` t1, `tabSales Order Item` t2 where t2.parent = t1.name and t1.docstatus=1 and t2.prevdoc_docname = %s",self.doc.name)
 		if chk:
 			msgprint("Sales Order No. "+cstr(chk[0][0])+" is submitted against this Quotation. Thus 'Order Lost' can not be declared against it.")
 			raise Exception
diff --git a/selling/doctype/sales_order/sales_order.py b/selling/doctype/sales_order/sales_order.py
index 1ccccdd..4056742 100644
--- a/selling/doctype/sales_order/sales_order.py
+++ b/selling/doctype/sales_order/sales_order.py
@@ -11,7 +11,6 @@
 from webnotes import msgprint
 from webnotes.model.mapper import get_mapped_doclist
 
-sql = webnotes.conn.sql
 	
 
 from controllers.selling_controller import SellingController
@@ -88,14 +87,14 @@
 			# used for production plan
 			d.transaction_date = self.doc.transaction_date
 			
-			tot_avail_qty = sql("select projected_qty from `tabBin` \
+			tot_avail_qty = webnotes.conn.sql("select projected_qty from `tabBin` \
 				where item_code = '%s' and warehouse = '%s'" % (d.item_code,d.reserved_warehouse))
 			d.projected_qty = tot_avail_qty and flt(tot_avail_qty[0][0]) or 0
 
 	def validate_sales_mntc_quotation(self):
 		for d in getlist(self.doclist, 'sales_order_details'):
 			if d.prevdoc_docname:
-				res = sql("select name from `tabQuotation` where name=%s and order_type = %s", (d.prevdoc_docname, self.doc.order_type))
+				res = webnotes.conn.sql("select name from `tabQuotation` where name=%s and order_type = %s", (d.prevdoc_docname, self.doc.order_type))
 				if not res:
 					msgprint("""Order Type (%s) should be same in Quotation: %s \
 						and current Sales Order""" % (self.doc.order_type, d.prevdoc_docname))
@@ -112,7 +111,7 @@
 
 	def validate_proj_cust(self):
 		if self.doc.project_name and self.doc.customer_name:
-			res = sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
+			res = webnotes.conn.sql("select name from `tabProject` where name = '%s' and (customer = '%s' or ifnull(customer,'')='')"%(self.doc.project_name, self.doc.customer))
 			if not res:
 				msgprint("Customer - %s does not belong to project - %s. \n\nIf you want to use project for multiple customers then please make customer details blank in project - %s."%(self.doc.customer,self.doc.project_name,self.doc.project_name))
 				raise Exception
@@ -168,28 +167,28 @@
 		
 	def check_prev_docstatus(self):
 		for d in getlist(self.doclist, 'sales_order_details'):
-			cancel_quo = sql("select name from `tabQuotation` where docstatus = 2 and name = '%s'" % d.prevdoc_docname)
+			cancel_quo = webnotes.conn.sql("select name from `tabQuotation` where docstatus = 2 and name = '%s'" % d.prevdoc_docname)
 			if cancel_quo:
 				msgprint("Quotation :" + cstr(cancel_quo[0][0]) + " is already cancelled !")
 				raise Exception , "Validation Error. "
 	
 	def update_enquiry_status(self, prevdoc, flag):
-		enq = sql("select t2.prevdoc_docname from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.name=%s", prevdoc)
+		enq = webnotes.conn.sql("select t2.prevdoc_docname from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.name=%s", prevdoc)
 		if enq:
-			sql("update `tabOpportunity` set status = %s where name=%s",(flag,enq[0][0]))
+			webnotes.conn.sql("update `tabOpportunity` set status = %s where name=%s",(flag,enq[0][0]))
 
 	def update_prevdoc_status(self, flag):
 		for d in getlist(self.doclist, 'sales_order_details'):
 			if d.prevdoc_docname:
 				if flag=='submit':
-					sql("update `tabQuotation` set status = 'Order Confirmed' where name=%s",d.prevdoc_docname)
+					webnotes.conn.sql("update `tabQuotation` set status = 'Order Confirmed' where name=%s",d.prevdoc_docname)
 					
 					#update enquiry
 					self.update_enquiry_status(d.prevdoc_docname, 'Order Confirmed')
 				elif flag == 'cancel':
-					chk = sql("select t1.name from `tabSales Order` t1, `tabSales Order Item` t2 where t2.parent = t1.name and t2.prevdoc_docname=%s and t1.name!=%s and t1.docstatus=1", (d.prevdoc_docname,self.doc.name))
+					chk = webnotes.conn.sql("select t1.name from `tabSales Order` t1, `tabSales Order Item` t2 where t2.parent = t1.name and t2.prevdoc_docname=%s and t1.name!=%s and t1.docstatus=1", (d.prevdoc_docname,self.doc.name))
 					if not chk:
-						sql("update `tabQuotation` set status = 'Submitted' where name=%s",d.prevdoc_docname)
+						webnotes.conn.sql("update `tabQuotation` set status = 'Submitted' where name=%s",d.prevdoc_docname)
 						
 						#update enquiry
 						self.update_enquiry_status(d.prevdoc_docname, 'Quotation Sent')
@@ -219,35 +218,35 @@
 		
 	def check_nextdoc_docstatus(self):
 		# Checks Delivery Note
-		submit_dn = sql("select t1.name from `tabDelivery Note` t1,`tabDelivery Note Item` t2 where t1.name = t2.parent and t2.prevdoc_docname = '%s' and t1.docstatus = 1" % (self.doc.name))
+		submit_dn = webnotes.conn.sql("select t1.name from `tabDelivery Note` t1,`tabDelivery Note Item` t2 where t1.name = t2.parent and t2.prevdoc_docname = '%s' and t1.docstatus = 1" % (self.doc.name))
 		if submit_dn:
 			msgprint("Delivery Note : " + cstr(submit_dn[0][0]) + " has been submitted against " + cstr(self.doc.doctype) + ". Please cancel Delivery Note : " + cstr(submit_dn[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
 			
 		# Checks Sales Invoice
-		submit_rv = sql("select t1.name from `tabSales Invoice` t1,`tabSales Invoice Item` t2 where t1.name = t2.parent and t2.sales_order = '%s' and t1.docstatus = 1" % (self.doc.name))
+		submit_rv = webnotes.conn.sql("select t1.name from `tabSales Invoice` t1,`tabSales Invoice Item` t2 where t1.name = t2.parent and t2.sales_order = '%s' and t1.docstatus = 1" % (self.doc.name))
 		if submit_rv:
 			msgprint("Sales Invoice : " + cstr(submit_rv[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Sales Invoice : "+ cstr(submit_rv[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
 			
 		#check maintenance schedule
-		submit_ms = sql("select t1.name from `tabMaintenance Schedule` t1, `tabMaintenance Schedule Item` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
+		submit_ms = webnotes.conn.sql("select t1.name from `tabMaintenance Schedule` t1, `tabMaintenance Schedule Item` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
 		if submit_ms:
 			msgprint("Maintenance Schedule : " + cstr(submit_ms[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Maintenance Schedule : "+ cstr(submit_ms[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
 			
 		# check maintenance visit
-		submit_mv = sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
+		submit_mv = webnotes.conn.sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1",self.doc.name)
 		if submit_mv:
 			msgprint("Maintenance Visit : " + cstr(submit_mv[0][0]) + " has already been submitted against " +cstr(self.doc.doctype)+ ". Please cancel Maintenance Visit : " + cstr(submit_mv[0][0]) + " first and then cancel "+ cstr(self.doc.doctype), raise_exception = 1)
 		
 		# check production order
-		pro_order = sql("""select name from `tabProduction Order` where sales_order = %s and docstatus = 1""", self.doc.name)
+		pro_order = webnotes.conn.sql("""select name from `tabProduction Order` where sales_order = %s and docstatus = 1""", self.doc.name)
 		if pro_order:
 			msgprint("""Production Order: %s exists against this sales order. 
 				Please cancel production order first and then cancel this sales order""" % 
 				pro_order[0][0], raise_exception=1)
 
 	def check_modified_date(self):
-		mod_db = sql("select modified from `tabSales Order` where name = '%s'" % self.doc.name)
-		date_diff = sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
+		mod_db = webnotes.conn.sql("select modified from `tabSales Order` where name = '%s'" % self.doc.name)
+		date_diff = webnotes.conn.sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.doc.modified)))
 		if date_diff and date_diff[0][0]:
 			msgprint("%s: %s has been modified after you have opened. Please Refresh"
 				% (self.doc.doctype, self.doc.name), raise_exception=1)
diff --git a/selling/doctype/sms_center/sms_center.py b/selling/doctype/sms_center/sms_center.py
index 29e793c..eb331c20 100644
--- a/selling/doctype/sms_center/sms_center.py
+++ b/selling/doctype/sms_center/sms_center.py
@@ -10,7 +10,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
   
 # ----------
 
@@ -29,15 +28,15 @@
       where_clause = self.doc.sales_partner and " and ifnull(is_sales_partner, 0) = 1 and sales_partner = '%s'" % self.doc.sales_partner or " and ifnull(sales_partner, '') != ''"
 
     if self.doc.send_to in ['All Contact', 'All Customer Contact', 'All Supplier Contact', 'All Sales Partner Contact']:
-      rec = sql("select CONCAT(ifnull(first_name,''),'',ifnull(last_name,'')), mobile_no from `tabContact` where ifnull(mobile_no,'')!='' and docstatus != 2 %s" % where_clause)
+      rec = webnotes.conn.sql("select CONCAT(ifnull(first_name,''),'',ifnull(last_name,'')), mobile_no from `tabContact` where ifnull(mobile_no,'')!='' and docstatus != 2 %s" % where_clause)
     elif self.doc.send_to == 'All Lead (Open)':
-      rec = sql("select lead_name, mobile_no from tabLead where ifnull(mobile_no,'')!='' and docstatus != 2 and status = 'Open'")
+      rec = webnotes.conn.sql("select lead_name, mobile_no from tabLead where ifnull(mobile_no,'')!='' and docstatus != 2 and status = 'Open'")
     elif self.doc.send_to == 'All Employee (Active)':
       where_clause = self.doc.department and " and department = '%s'" % self.doc.department or ""
       where_clause += self.doc.branch and " and branch = '%s'" % self.doc.branch or ""
-      rec = sql("select employee_name, cell_number from `tabEmployee` where status = 'Active' and docstatus < 2 and ifnull(cell_number,'')!='' %s" % where_clause)
+      rec = webnotes.conn.sql("select employee_name, cell_number from `tabEmployee` where status = 'Active' and docstatus < 2 and ifnull(cell_number,'')!='' %s" % where_clause)
     elif self.doc.send_to == 'All Sales Person':
-      rec = sql("select sales_person_name, mobile_no from `tabSales Person` where docstatus != 2 and ifnull(mobile_no,'')!=''")
+      rec = webnotes.conn.sql("select sales_person_name, mobile_no from `tabSales Person` where docstatus != 2 and ifnull(mobile_no,'')!=''")
     rec_list = ''
     for d in rec:
       rec_list += d[0] + ' - ' + d[1] + '\n'
diff --git a/selling/utils/cart.py b/selling/utils/cart.py
index fc7d062..92d37ea 100644
--- a/selling/utils/cart.py
+++ b/selling/utils/cart.py
@@ -12,8 +12,8 @@
 def set_cart_count(quotation=None):
 	if not quotation:
 		quotation = _get_cart_quotation()
-	webnotes.add_cookies["cart_count"] = cstr(len(quotation.doclist.get(
-		{"parentfield": "quotation_details"})) or "")
+	cart_count = cstr(len(quotation.doclist.get({"parentfield": "quotation_details"})))
+	webnotes._response.set_cookie("cart_count", cart_count)
 
 @webnotes.whitelist()
 def get_cart_quotation(doclist=None):
@@ -47,7 +47,7 @@
 	sales_order.ignore_permissions = True
 	sales_order.insert()
 	sales_order.submit()
-	webnotes.add_cookies["cart_count"] = ""
+	webnotes._response.set_cookie("cart_count", "")
 	
 	return sales_order.doc.name
 
diff --git a/setup/doctype/authorization_control/authorization_control.py b/setup/doctype/authorization_control/authorization_control.py
index ddf0791..533f398 100644
--- a/setup/doctype/authorization_control/authorization_control.py
+++ b/setup/doctype/authorization_control/authorization_control.py
@@ -9,7 +9,6 @@
 from webnotes import session, msgprint
 from setup.utils import get_company_currency
 
-sql = webnotes.conn.sql
 	
 from utilities.transaction_base import TransactionBase
 
@@ -28,10 +27,10 @@
 				amt_list.append(flt(x[0]))
 			max_amount = max(amt_list)
 			
-			app_dtl = sql("select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and company = %s %s" % ('%s', '%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on, company))
+			app_dtl = webnotes.conn.sql("select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and company = %s %s" % ('%s', '%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on, company))
 			
 			if not app_dtl:
-				app_dtl = sql("select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and ifnull(company,'') = '' %s" % ('%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on)) 
+				app_dtl = webnotes.conn.sql("select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and ifnull(company,'') = '' %s" % ('%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on)) 
 			for d in app_dtl:
 				if(d[0]): appr_users.append(d[0])
 				if(d[1]): appr_roles.append(d[1])
@@ -58,18 +57,18 @@
 		add_cond1,add_cond2	= '',''
 		if based_on == 'Itemwise Discount':
 			add_cond1 += " and master_name = '"+cstr(item)+"'"
-			itemwise_exists = sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and company = %s and docstatus != 2 %s %s" % ('%s', '%s', '%s', '%s', cond, add_cond1), (doctype_name, total, based_on, company))
+			itemwise_exists = webnotes.conn.sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and company = %s and docstatus != 2 %s %s" % ('%s', '%s', '%s', '%s', cond, add_cond1), (doctype_name, total, based_on, company))
 			if not itemwise_exists:
-				itemwise_exists = sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and ifnull(company,'') = '' and docstatus != 2 %s %s" % ('%s', '%s', '%s', cond, add_cond1), (doctype_name, total, based_on))
+				itemwise_exists = webnotes.conn.sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and ifnull(company,'') = '' and docstatus != 2 %s %s" % ('%s', '%s', '%s', cond, add_cond1), (doctype_name, total, based_on))
 			if itemwise_exists:
 				self.get_appr_user_role(itemwise_exists, doctype_name, total, based_on, cond+add_cond1, item,company)
 				chk = 0
 		if chk == 1:
 			if based_on == 'Itemwise Discount': add_cond2 += " and ifnull(master_name,'') = ''"
-			appr = sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and company = %s and docstatus != 2 %s %s" % ('%s', '%s', '%s', '%s', cond, add_cond2), (doctype_name, total, based_on, company))
+			appr = webnotes.conn.sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and company = %s and docstatus != 2 %s %s" % ('%s', '%s', '%s', '%s', cond, add_cond2), (doctype_name, total, based_on, company))
 			
 			if not appr:
-				appr = sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and ifnull(company,'') = '' and docstatus != 2 %s %s"% ('%s', '%s', '%s', cond, add_cond2), (doctype_name, total, based_on))
+				appr = webnotes.conn.sql("select value from `tabAuthorization Rule` where transaction = %s and value <= %s and based_on = %s and ifnull(company,'') = '' and docstatus != 2 %s %s"% ('%s', '%s', '%s', cond, add_cond2), (doctype_name, total, based_on))
 			self.get_appr_user_role(appr, doctype_name, total, based_on, cond+add_cond2, item, company)
 			
 			
@@ -112,7 +111,7 @@
 		# ================
 		# Check for authorization set for individual user
 	 
-		based_on = [x[0] for x in sql("select distinct based_on from `tabAuthorization Rule` where transaction = %s and system_user = %s and (company = %s or ifnull(company,'')='') and docstatus != 2", (doctype_name, session['user'], company))]
+		based_on = [x[0] for x in webnotes.conn.sql("select distinct based_on from `tabAuthorization Rule` where transaction = %s and system_user = %s and (company = %s or ifnull(company,'')='') and docstatus != 2", (doctype_name, session['user'], company))]
 
 		for d in based_on:
 			self.bifurcate_based_on_type(doctype_name, total, av_dis, d, doc_obj, 1, company)
@@ -124,7 +123,7 @@
 		# Specific Role
 		# ===============
 		# Check for authorization set on particular roles
-		based_on = [x[0] for x in sql("""select based_on 
+		based_on = [x[0] for x in webnotes.conn.sql("""select based_on 
 			from `tabAuthorization Rule` 
 			where transaction = %s and system_role IN (%s) and based_on IN (%s) 
 			and (company = %s or ifnull(company,'')='') 
@@ -148,9 +147,9 @@
 	# payroll related check
 	def get_value_based_rule(self,doctype_name,employee,total_claimed_amount,company):
 		val_lst =[]
-		val = sql("select value from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)< %s and company = %s and docstatus!=2",(doctype_name,employee,employee,total_claimed_amount,company))
+		val = webnotes.conn.sql("select value from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)< %s and company = %s and docstatus!=2",(doctype_name,employee,employee,total_claimed_amount,company))
 		if not val:
-			val = sql("select value from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)< %s and ifnull(company,'') = '' and docstatus!=2",(doctype_name, employee, employee, total_claimed_amount))
+			val = webnotes.conn.sql("select value from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)< %s and ifnull(company,'') = '' and docstatus!=2",(doctype_name, employee, employee, total_claimed_amount))
 
 		if val:
 			val_lst = [y[0] for y in val]
@@ -158,9 +157,9 @@
 			val_lst.append(0)
 	
 		max_val = max(val_lst)
-		rule = sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and company = %s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)= %s and docstatus!=2",(doctype_name,company,employee,employee,flt(max_val)), as_dict=1)
+		rule = webnotes.conn.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and company = %s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)= %s and docstatus!=2",(doctype_name,company,employee,employee,flt(max_val)), as_dict=1)
 		if not rule:
-			rule = sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and ifnull(company,'') = '' and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)= %s and docstatus!=2",(doctype_name,employee,employee,flt(max_val)), as_dict=1)
+			rule = webnotes.conn.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and ifnull(company,'') = '' and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(value,0)= %s and docstatus!=2",(doctype_name,employee,employee,flt(max_val)), as_dict=1)
 
 		return rule
 	
@@ -175,9 +174,9 @@
 			if doctype_name == 'Expense Claim':
 				rule = self.get_value_based_rule(doctype_name,doc_obj.doc.employee,doc_obj.doc.total_claimed_amount, doc_obj.doc.company)
 			elif doctype_name == 'Appraisal':
-				rule = sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and company = %s and docstatus!=2",(doctype_name,doc_obj.doc.employee, doc_obj.doc.employee, doc_obj.doc.company),as_dict=1)				
+				rule = webnotes.conn.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and company = %s and docstatus!=2",(doctype_name,doc_obj.doc.employee, doc_obj.doc.employee, doc_obj.doc.company),as_dict=1)				
 				if not rule:
-					rule = sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(company,'') = '' and docstatus!=2",(doctype_name,doc_obj.doc.employee, doc_obj.doc.employee),as_dict=1)				
+					rule = webnotes.conn.sql("select name, to_emp, to_designation, approving_role, approving_user from `tabAuthorization Rule` where transaction=%s and (to_emp=%s or to_designation IN (select designation from `tabEmployee` where name=%s)) and ifnull(company,'') = '' and docstatus!=2",(doctype_name,doc_obj.doc.employee, doc_obj.doc.employee),as_dict=1)				
 			
 			if rule:
 				for m in rule:
@@ -185,7 +184,7 @@
 						if m['approving_user']:
 							app_specific_user.append(m['approving_user'])
 						elif m['approving_role']:
-							user_lst = [z[0] for z in sql("select distinct t1.name from `tabProfile` t1, `tabUserRole` t2 where t2.role=%s and t2.parent=t1.name and t1.name !='Administrator' and t1.name != 'Guest' and t1.docstatus !=2",m['approving_role'])]
+							user_lst = [z[0] for z in webnotes.conn.sql("select distinct t1.name from `tabProfile` t1, `tabUserRole` t2 where t2.role=%s and t2.parent=t1.name and t1.name !='Administrator' and t1.name != 'Guest' and t1.docstatus !=2",m['approving_role'])]
 							for x in user_lst:
 								if not x in app_user:
 									app_user.append(x)
diff --git a/setup/doctype/authorization_rule/authorization_rule.py b/setup/doctype/authorization_rule/authorization_rule.py
index 3d2de47..ea22b15 100644
--- a/setup/doctype/authorization_rule/authorization_rule.py
+++ b/setup/doctype/authorization_rule/authorization_rule.py
@@ -9,7 +9,6 @@
 from webnotes.model.bean import copy_doclist
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 
 
@@ -19,7 +18,7 @@
 
 
 	def check_duplicate_entry(self):
-		exists = sql("""select name, docstatus from `tabAuthorization Rule` 
+		exists = webnotes.conn.sql("""select name, docstatus from `tabAuthorization Rule` 
 			where transaction = %s and based_on = %s and system_user = %s 
 			and system_role = %s and approving_user = %s and approving_role = %s 
 			and to_emp =%s and to_designation=%s and name != %s""", 
@@ -39,12 +38,12 @@
 
 	def validate_master_name(self):
 		if self.doc.based_on == 'Customerwise Discount' and \
-				not sql("select name from tabCustomer where name = '%s' and docstatus != 2" % \
+				not webnotes.conn.sql("select name from tabCustomer where name = '%s' and docstatus != 2" % \
 				 	(self.doc.master_name)):
 			msgprint("Please select valid Customer Name for Customerwise Discount", 
 			 	raise_exception=1)
 		elif self.doc.based_on == 'Itemwise Discount' and \
-				not sql("select name from tabItem where name = '%s' and docstatus != 2" % \
+				not webnotes.conn.sql("select name from tabItem where name = '%s' and docstatus != 2" % \
 				 	(self.doc.master_name)):
 			msgprint("Please select valid Item Name for Itemwise Discount", raise_exception=1)
 		elif (self.doc.based_on == 'Grand Total' or \
@@ -65,7 +64,7 @@
 					Applicable To (Role).", raise_exception=1)
 			elif self.doc.system_user and self.doc.approving_role and \
 			 		has_common([self.doc.approving_role], [x[0] for x in \
-					sql("select role from `tabUserRole` where parent = '%s'" % \
+					webnotes.conn.sql("select role from `tabUserRole` where parent = '%s'" % \
 					 	(self.doc.system_user))]):
 				msgprint("System User : %s is assigned role : %s. So rule does not make sense" % 
 				 	(self.doc.system_user,self.doc.approving_role), raise_exception=1)
diff --git a/setup/doctype/backup_manager/backup_googledrive.py b/setup/doctype/backup_manager/backup_googledrive.py
index 5d7b6ad..daf852c 100644
--- a/setup/doctype/backup_manager/backup_googledrive.py
+++ b/setup/doctype/backup_manager/backup_googledrive.py
@@ -113,9 +113,9 @@
 
 def get_gdrive_flow():
 	from oauth2client.client import OAuth2WebServerFlow
-	import conf
+	from webnotes import conf
 	
-	if not hasattr(conf, "gdrive_client_id"):
+	if not "gdrive_client_id" in conf:
 		webnotes.msgprint(_("Please set Google Drive access keys in") + " conf.py", 
 		raise_exception=True)
 
@@ -169,4 +169,4 @@
 	return database['id']
 
 if __name__=="__main__":
-	backup_to_gdrive()
\ No newline at end of file
+	backup_to_gdrive()
diff --git a/setup/doctype/company/company.py b/setup/doctype/company/company.py
index 9746eb2..da220cc 100644
--- a/setup/doctype/company/company.py
+++ b/setup/doctype/company/company.py
@@ -10,7 +10,6 @@
 from webnotes.model.code import get_obj
 import webnotes.defaults
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self,d,dl):
diff --git a/setup/doctype/customer_group/customer_group.py b/setup/doctype/customer_group/customer_group.py
index 0940e1f..1264c1b 100644
--- a/setup/doctype/customer_group/customer_group.py
+++ b/setup/doctype/customer_group/customer_group.py
@@ -5,7 +5,6 @@
 import webnotes
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 from webnotes.utils.nestedset import DocTypeNestedSet
 class DocType(DocTypeNestedSet):
@@ -15,7 +14,7 @@
 		self.nsm_parent_field = 'parent_customer_group';
 
 	def validate(self): 
-		if sql("select name from `tabCustomer Group` where name = %s and docstatus = 2", 
+		if webnotes.conn.sql("select name from `tabCustomer Group` where name = %s and docstatus = 2", 
 		 		(self.doc.customer_group_name)):
 			msgprint("""Another %s record is trashed. 
 				To untrash please go to Setup -> Recycle Bin.""" % 
@@ -33,7 +32,7 @@
 				self.doc.name, raise_exception=1)
 
 	def on_trash(self):
-		cust = sql("select name from `tabCustomer` where ifnull(customer_group, '') = %s", 
+		cust = webnotes.conn.sql("select name from `tabCustomer` where ifnull(customer_group, '') = %s", 
 		 	self.doc.name)
 		cust = [d[0] for d in cust]
 		if cust:
@@ -42,7 +41,7 @@
 				To trash/delete this, remove/change customer group in customer master""" %
 				(self.doc.name, cust or ''), raise_exception=1)
 
-		if sql("select name from `tabCustomer Group` where parent_customer_group = %s \
+		if webnotes.conn.sql("select name from `tabCustomer Group` where parent_customer_group = %s \
 				and docstatus != 2", self.doc.name):
 			msgprint("Child customer group exists for this customer group. \
 				You can not trash/cancel/delete this customer group.", raise_exception=1)
diff --git a/setup/doctype/email_digest/email_digest.py b/setup/doctype/email_digest/email_digest.py
index 07efd16..9a00723 100644
--- a/setup/doctype/email_digest/email_digest.py
+++ b/setup/doctype/email_digest/email_digest.py
@@ -457,8 +457,8 @@
 	from webnotes.utils import getdate
 	now_date = now_datetime().date()
 	
-	import conf
-	if hasattr(conf, "expires_on") and now_date > getdate(conf.expires_on):
+	from webnotes import conf
+	if "expires_on" in conf and now_date > getdate(conf.expires_on):
 		# do not send email digests to expired accounts
 		return
 	
diff --git a/setup/doctype/email_settings/email_settings.py b/setup/doctype/email_settings/email_settings.py
index 219501e..aa511ee 100644
--- a/setup/doctype/email_settings/email_settings.py
+++ b/setup/doctype/email_settings/email_settings.py
@@ -3,7 +3,6 @@
 
 from __future__ import unicode_literals
 import webnotes
-sql = webnotes.conn.sql
 	
 from webnotes.utils import cint
 
diff --git a/setup/doctype/naming_series/naming_series.py b/setup/doctype/naming_series/naming_series.py
index 9cc4de2..4e85b15 100644
--- a/setup/doctype/naming_series/naming_series.py
+++ b/setup/doctype/naming_series/naming_series.py
@@ -8,7 +8,6 @@
 from webnotes import msgprint
 import webnotes.model.doctype
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self, d, dl):
@@ -23,7 +22,7 @@
 					where fieldname='naming_series'""")
 				)))),
 			"prefixes": "\n".join([''] + [i[0] for i in 
-				sql("""select name from tabSeries""")])
+				webnotes.conn.sql("""select name from tabSeries""")])
 		}
 	
 	def scrub_options_list(self, ol):
@@ -126,12 +125,12 @@
 	def insert_series(self, series):
 		"""insert series if missing"""
 		if not webnotes.conn.exists('Series', series):
-			sql("insert into tabSeries (name, current) values (%s,0)", (series))			
+			webnotes.conn.sql("insert into tabSeries (name, current) values (%s,0)", (series))			
 
 	def update_series_start(self):
 		if self.doc.prefix:
 			self.insert_series(self.doc.prefix)
-			sql("update `tabSeries` set current = '%s' where name = '%s'" % (self.doc.current_value,self.doc.prefix))
+			webnotes.conn.sql("update `tabSeries` set current = '%s' where name = '%s'" % (self.doc.current_value,self.doc.prefix))
 			msgprint("Series Updated Successfully")
 		else:
 			msgprint("Please select prefix first")
diff --git a/setup/doctype/notification_control/notification_control.py b/setup/doctype/notification_control/notification_control.py
index 6133d9b..0a15115 100644
--- a/setup/doctype/notification_control/notification_control.py
+++ b/setup/doctype/notification_control/notification_control.py
@@ -6,7 +6,6 @@
 
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self,d,dl):
@@ -14,7 +13,7 @@
 
 	def get_message(self, arg):
 		fn = arg.lower().replace(' ', '_') + '_message'
-		v = sql("select value from tabSingles where field=%s and doctype=%s", (fn, 'Notification Control'))
+		v = webnotes.conn.sql("select value from tabSingles where field=%s and doctype=%s", (fn, 'Notification Control'))
 		return v and v[0][0] or ''
 
 	def set_message(self, arg = ''):
diff --git a/setup/doctype/print_heading/print_heading.py b/setup/doctype/print_heading/print_heading.py
index ba7114a..134aaaf 100644
--- a/setup/doctype/print_heading/print_heading.py
+++ b/setup/doctype/print_heading/print_heading.py
@@ -7,7 +7,6 @@
 from webnotes.model import db_exists
 from webnotes.model.bean import copy_doclist
 
-sql = webnotes.conn.sql
 	
 
 
diff --git a/setup/doctype/sales_partner/sales_partner.py b/setup/doctype/sales_partner/sales_partner.py
index 0d7e12d..79a59db 100644
--- a/setup/doctype/sales_partner/sales_partner.py
+++ b/setup/doctype/sales_partner/sales_partner.py
@@ -5,7 +5,6 @@
 import webnotes
 from webnotes.utils import cint, cstr, filter_strip_join
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self, doc, doclist=None):
@@ -24,7 +23,7 @@
 		
 	def get_contacts(self,nm):
 		if nm:
-			contact_details =webnotes.conn.convert_to_lists(sql("select name, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')),contact_no,email_id from `tabContact` where sales_partner = '%s'"%nm))
+			contact_details =webnotes.conn.convert_to_lists(webnotes.conn.sql("select name, CONCAT(IFNULL(first_name,''),' ',IFNULL(last_name,'')),contact_no,email_id from `tabContact` where sales_partner = '%s'"%nm))
 			return contact_details
 		else:
 			return ''
diff --git a/startup/boot.py b/startup/boot.py
index 886b805..d27c0b7 100644
--- a/startup/boot.py
+++ b/startup/boot.py
@@ -32,9 +32,9 @@
 		
 		
 		# load subscription info
-		import conf
+		from webnotes import conf
 		for key in ['max_users', 'expires_on', 'max_space', 'status', 'commercial_support']:
-			if hasattr(conf, key): bootinfo[key] = getattr(conf, key)
+			if key in conf: bootinfo[key] = conf.get(key)
 
 		bootinfo['docs'] += webnotes.conn.sql("""select name, default_currency, cost_center
             from `tabCompany`""", as_dict=1, update={"doctype":":Company"})
@@ -53,4 +53,4 @@
 	ret = webnotes.conn.sql("""select name, content from `tabLetter Head` 
 		where ifnull(disabled,0)=0""")
 	return dict(ret)
-	
\ No newline at end of file
+	
diff --git a/startup/event_handlers.py b/startup/event_handlers.py
index 57345f3..fc95414 100644
--- a/startup/event_handlers.py
+++ b/startup/event_handlers.py
@@ -35,13 +35,13 @@
 		set_cart_count()
 		
 def on_logout(login_manager):
-	webnotes.add_cookies["cart_count"] = ""
+	webnotes._response.set_cookie("cart_count", "")
 		
 def check_if_expired():
 	"""check if account is expired. If expired, do not allow login"""
-	import conf
+	from webnotes import conf
 	# check if expires_on is specified
-	if not hasattr(conf, 'expires_on'): return
+	if not 'expires_on' in conf: return
 	
 	# check if expired
 	from datetime import datetime, date
@@ -75,4 +75,4 @@
 	"""add comment to feed"""
 	home.make_feed('Comment', doc.comment_doctype, doc.comment_docname, doc.comment_by,
 		'<i>"' + doc.comment + '"</i>', '#6B24B3')
-	
\ No newline at end of file
+	
diff --git a/stock/doctype/bin/bin.py b/stock/doctype/bin/bin.py
index 788642f..32407e2 100644
--- a/stock/doctype/bin/bin.py
+++ b/stock/doctype/bin/bin.py
@@ -5,7 +5,6 @@
 import webnotes
 from webnotes.utils import add_days, cint,flt, nowdate, get_url_to_form, formatdate
 from webnotes import msgprint, _
-sql = webnotes.conn.sql
 
 import webnotes.defaults
 
@@ -61,7 +60,7 @@
 		self.doc.save()
 		
 	def get_first_sle(self):
-		sle = sql("""
+		sle = webnotes.conn.sql("""
 			select * from `tabStock Ledger Entry`
 			where item_code = %s
 			and warehouse = %s
diff --git a/stock/doctype/landed_cost_wizard/landed_cost_wizard.py b/stock/doctype/landed_cost_wizard/landed_cost_wizard.py
index 0924957..f431537 100644
--- a/stock/doctype/landed_cost_wizard/landed_cost_wizard.py
+++ b/stock/doctype/landed_cost_wizard/landed_cost_wizard.py
@@ -98,4 +98,4 @@
 			pr_bean.run_method("update_ordered_qty")
 			pr_bean.run_method("update_stock")
 			pr_bean.run_method("update_serial_nos")
-			pr_bean.run_method("make_gl_entries")
\ No newline at end of file
+			pr_bean.run_method("make_gl_entries")
diff --git a/stock/doctype/stock_entry/stock_entry.py b/stock/doctype/stock_entry/stock_entry.py
index a54f9bf..de5636f 100644
--- a/stock/doctype/stock_entry/stock_entry.py
+++ b/stock/doctype/stock_entry/stock_entry.py
@@ -15,7 +15,6 @@
 from controllers.queries import get_match_cond
 import json
 
-sql = webnotes.conn.sql
 
 class NotUpdateStockError(webnotes.ValidationError): pass
 class StockOverReturnError(webnotes.ValidationError): pass
@@ -377,7 +376,7 @@
 	def get_item_details(self, arg):
 		arg = json.loads(arg)
 
-		item = sql("""select stock_uom, description, item_name from `tabItem` 
+		item = webnotes.conn.sql("""select stock_uom, description, item_name from `tabItem` 
 			where name = %s and (ifnull(end_of_life,'')='' or end_of_life ='0000-00-00' 
 			or end_of_life > now())""", (arg.get('item_code')), as_dict = 1)
 		if not item: 
@@ -401,7 +400,7 @@
 
 	def get_uom_details(self, arg = ''):
 		arg, ret = eval(arg), {}
-		uom = sql("""select conversion_factor from `tabUOM Conversion Detail` 
+		uom = webnotes.conn.sql("""select conversion_factor from `tabUOM Conversion Detail` 
 			where parent = %s and uom = %s""", (arg['item_code'], arg['uom']), as_dict = 1)
 		if not uom or not flt(uom[0].conversion_factor):
 			msgprint("There is no Conversion Factor for UOM '%s' in Item '%s'" % (arg['uom'],
@@ -512,7 +511,7 @@
 		
 		if self.doc.use_multi_level_bom:
 			# get all raw materials with sub assembly childs					
-			fl_bom_sa_child_item = sql("""select 
+			fl_bom_sa_child_item = webnotes.conn.sql("""select 
 					fb.item_code, 
 					ifnull(sum(fb.qty_consumed_per_unit),0)*%s as qty, 
 					fb.description, 
@@ -532,7 +531,7 @@
 				_make_items_dict(fl_bom_sa_child_item)
 		else:
 			# get only BOM items
-			fl_bom_sa_items = sql("""select 
+			fl_bom_sa_items = webnotes.conn.sql("""select 
 					`tabItem`.item_code,
 					ifnull(sum(`tabBOM Item`.qty_consumed_per_unit), 0) *%s as qty,
 					`tabItem`.description, 
@@ -590,7 +589,7 @@
 
 	def get_issued_qty(self):
 		issued_item_qty = {}
-		result = sql("""select t1.item_code, sum(t1.qty)
+		result = webnotes.conn.sql("""select t1.item_code, sum(t1.qty)
 			from `tabStock Entry Detail` t1, `tabStock Entry` t2
 			where t1.parent = t2.name and t2.production_order = %s and t2.docstatus = 1
 			and t2.purpose = 'Material Transfer'
@@ -636,7 +635,7 @@
 		
 	def get_cust_addr(self):
 		from utilities.transaction_base import get_default_address, get_address_display
-		res = sql("select customer_name from `tabCustomer` where name = '%s'"%self.doc.customer)
+		res = webnotes.conn.sql("select customer_name from `tabCustomer` where name = '%s'"%self.doc.customer)
 		address_display = None
 		customer_address = get_default_address("customer", self.doc.customer)
 		if customer_address:
@@ -657,7 +656,7 @@
 		
 	def get_supp_addr(self):
 		from utilities.transaction_base import get_default_address, get_address_display
-		res = sql("""select supplier_name from `tabSupplier`
+		res = webnotes.conn.sql("""select supplier_name from `tabSupplier`
 			where name=%s""", self.doc.supplier)
 		address_display = None
 		supplier_address = get_default_address("customer", self.doc.customer)
diff --git a/stock/doctype/stock_ledger/stock_ledger.py b/stock/doctype/stock_ledger/stock_ledger.py
new file mode 100644
index 0000000..1624b00
--- /dev/null
+++ b/stock/doctype/stock_ledger/stock_ledger.py
@@ -0,0 +1,57 @@
+# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import webnotes
+
+from webnotes.utils import add_days, cstr, flt, nowdate, cint, now
+from webnotes.model.doc import Document
+from webnotes.model.bean import getlist
+from webnotes.model.code import get_obj
+from webnotes import session, msgprint
+from stock.utils import get_valid_serial_nos
+
+
+class DocType:
+	def __init__(self, doc, doclist=[]):
+		self.doc = doc
+		self.doclist = doclist
+		
+	def update_stock(self, values, is_amended = 'No'):
+		for v in values:
+			sle_id = ''
+			
+			# reverse quantities for cancel
+			if v.get('is_cancelled') == 'Yes':
+				v['actual_qty'] = -flt(v['actual_qty'])
+				# cancel matching entry
+				webnotes.conn.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
+					modified=%s, modified_by=%s
+					where voucher_no=%s and voucher_type=%s""", 
+					(now(), webnotes.session.user, v['voucher_no'], v['voucher_type']))
+
+			if v.get("actual_qty"):
+				sle_id = self.make_entry(v)
+				
+			args = v.copy()
+			args.update({
+				"sle_id": sle_id,
+				"is_amended": is_amended
+			})
+			
+			get_obj('Warehouse', v["warehouse"]).update_bin(args)
+
+
+	def make_entry(self, args):
+		args.update({"doctype": "Stock Ledger Entry"})
+		sle = webnotes.bean([args])
+		sle.ignore_permissions = 1
+		sle.insert()
+		return sle.doc.name
+	
+	def repost(self):
+		"""
+		Repost everything!
+		"""
+		for wh in webnotes.conn.sql("select name from tabWarehouse"):
+			get_obj('Warehouse', wh[0]).repost_stock()
diff --git a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
index 321e3c9..1f1bafa 100644
--- a/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
+++ b/stock/doctype/stock_uom_replace_utility/stock_uom_replace_utility.py
@@ -10,7 +10,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self, d, dl=[]):
@@ -34,7 +33,7 @@
 			msgprint("Please Enter Conversion Factor.")
 			raise Exception
 		
-		stock_uom = sql("select stock_uom from `tabItem` where name = '%s'" % self.doc.item_code)
+		stock_uom = webnotes.conn.sql("select stock_uom from `tabItem` where name = '%s'" % self.doc.item_code)
 		stock_uom = stock_uom and stock_uom[0][0]
 		if cstr(self.doc.new_stock_uom) == cstr(stock_uom):
 			msgprint("Item Master is already updated with New Stock UOM " + cstr(self.doc.new_stock_uom))
@@ -50,9 +49,9 @@
 	def update_bin(self):
 		# update bin
 		if flt(self.doc.conversion_factor) != flt(1):
-			sql("update `tabBin` set stock_uom = '%s' , indented_qty = ifnull(indented_qty,0) * %s, ordered_qty = ifnull(ordered_qty,0) * %s, reserved_qty = ifnull(reserved_qty,0) * %s, planned_qty = ifnull(planned_qty,0) * %s, projected_qty = actual_qty + ordered_qty + indented_qty + planned_qty - reserved_qty	where item_code = '%s'" % (self.doc.new_stock_uom, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.item_code) )
+			webnotes.conn.sql("update `tabBin` set stock_uom = '%s' , indented_qty = ifnull(indented_qty,0) * %s, ordered_qty = ifnull(ordered_qty,0) * %s, reserved_qty = ifnull(reserved_qty,0) * %s, planned_qty = ifnull(planned_qty,0) * %s, projected_qty = actual_qty + ordered_qty + indented_qty + planned_qty - reserved_qty	where item_code = '%s'" % (self.doc.new_stock_uom, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.conversion_factor, self.doc.item_code) )
 		else:
-			sql("update `tabBin` set stock_uom = '%s' where item_code = '%s'" % (self.doc.new_stock_uom, self.doc.item_code) )
+			webnotes.conn.sql("update `tabBin` set stock_uom = '%s' where item_code = '%s'" % (self.doc.new_stock_uom, self.doc.item_code) )
 
 		# acknowledge user
 		msgprint(" All Bins Updated Successfully.")
@@ -62,16 +61,16 @@
 		from stock.stock_ledger import update_entries_after
 		
 		if flt(self.doc.conversion_factor) != flt(1):
-			sql("update `tabStock Ledger Entry` set stock_uom = '%s', actual_qty = ifnull(actual_qty,0) * '%s' where item_code = '%s' " % (self.doc.new_stock_uom, self.doc.conversion_factor, self.doc.item_code))
+			webnotes.conn.sql("update `tabStock Ledger Entry` set stock_uom = '%s', actual_qty = ifnull(actual_qty,0) * '%s' where item_code = '%s' " % (self.doc.new_stock_uom, self.doc.conversion_factor, self.doc.item_code))
 		else:
-			sql("update `tabStock Ledger Entry` set stock_uom = '%s' where item_code = '%s' " % (self.doc.new_stock_uom, self.doc.item_code))
+			webnotes.conn.sql("update `tabStock Ledger Entry` set stock_uom = '%s' where item_code = '%s' " % (self.doc.new_stock_uom, self.doc.item_code))
 		
 		# acknowledge user
 		msgprint("Stock Ledger Entries Updated Successfully.")
 		
 		# update item valuation
 		if flt(self.doc.conversion_factor) != flt(1):
-			wh = sql("select name from `tabWarehouse`")
+			wh = webnotes.conn.sql("select name from `tabWarehouse`")
 			for w in wh:
 				update_entries_after({"item_code": self.doc.item_code, "warehouse": w[0]})
 
diff --git a/stock/doctype/warehouse/warehouse.py b/stock/doctype/warehouse/warehouse.py
index c2b3284..1494428 100644
--- a/stock/doctype/warehouse/warehouse.py
+++ b/stock/doctype/warehouse/warehouse.py
@@ -8,7 +8,6 @@
 from webnotes.model.code import get_obj
 from webnotes import msgprint, _
 
-sql = webnotes.conn.sql
 
 class DocType:
 	def __init__(self, doc, doclist=[]):
@@ -60,9 +59,15 @@
 				webnotes.throw(_("Please enter account group under which account \
 					for warehouse ") + self.doc.name +_(" will be created"))
 			
-	def on_rename(self, new, old):
+	def on_rename(self, new, old, merge=False):
 		webnotes.conn.set_value("Account", {"account_type": "Warehouse", "master_name": old}, 
 			"master_name", new)
+			
+		if merge:
+			from stock.stock_ledger import update_entries_after
+			for item_code in webnotes.conn.sql("""select item_code from `tabBin` 
+				where warehouse=%s""", new):
+					update_entries_after({"item_code": item_code, "warehouse": new})
 
 	def merge_warehouses(self):
 		webnotes.conn.auto_commit_on_many_writes = 1
@@ -185,14 +190,14 @@
 
 	def on_trash(self):
 		# delete bin
-		bins = sql("select * from `tabBin` where warehouse = %s", self.doc.name, as_dict=1)
+		bins = webnotes.conn.sql("select * from `tabBin` where warehouse = %s", self.doc.name, as_dict=1)
 		for d in bins:
 			if d['actual_qty'] or d['reserved_qty'] or d['ordered_qty'] or \
 					d['indented_qty'] or d['projected_qty'] or d['planned_qty']:
 				msgprint("""Warehouse: %s can not be deleted as qty exists for item: %s""" 
 					% (self.doc.name, d['item_code']), raise_exception=1)
 			else:
-				sql("delete from `tabBin` where name = %s", d['name'])
+				webnotes.conn.sql("delete from `tabBin` where name = %s", d['name'])
 				
 		warehouse_account = webnotes.conn.get_value("Account", 
 			{"account_type": "Warehosue", "master_name": self.doc.name})
@@ -200,15 +205,9 @@
 			webnotes.delete_doc("Account", warehouse_account)
 				
 		# delete cancelled sle
-		if sql("""select name from `tabStock Ledger Entry` where warehouse = %s""", self.doc.name):
+		if webnotes.conn.sql("""select name from `tabStock Ledger Entry` where warehouse = %s""", self.doc.name):
 			msgprint("""Warehosue can not be deleted as stock ledger entry 
 				exists for this warehouse.""", raise_exception=1)
 		else:
-			sql("delete from `tabStock Ledger Entry` where warehouse = %s", self.doc.name)
+			webnotes.conn.sql("delete from `tabStock Ledger Entry` where warehouse = %s", self.doc.name)
 
-	def on_rename(self, newdn, olddn, merge=False):
-		if merge:
-			from stock.stock_ledger import update_entries_after
-			for item_code in webnotes.conn.sql("""select item_code from `tabBin` 
-				where warehouse=%s""", newdn):
-					update_entries_after({"item_code": item_code, "warehouse": newdn})
diff --git a/stock/stock_ledger.py b/stock/stock_ledger.py
index a3af5ad..fe5b685 100644
--- a/stock/stock_ledger.py
+++ b/stock/stock_ledger.py
@@ -10,6 +10,9 @@
 # future reposting
 class NegativeStockError(webnotes.ValidationError): pass
 
+_exceptions = webnotes.local('stockledger_exceptions')
+# _exceptions = []
+
 def make_sl_entries(sl_entries, is_amended=None):
 	from stock.utils import update_bin
 	
@@ -53,7 +56,6 @@
 	webnotes.conn.sql("""delete from `tabStock Ledger Entry` 
 		where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
 
-_exceptions = []
 def update_entries_after(args, verbose=1):
 	"""
 		update valution rate and qty after transaction 
@@ -66,8 +68,8 @@
 			"posting_time": "12:00"
 		}
 	"""
-	global _exceptions
-	_exceptions = []
+	if not _exceptions:
+		webnotes.local.stockledger_exceptions = []
 	
 	previous_sle = get_sle_before_datetime(args)
 	
@@ -188,10 +190,12 @@
 		will not consider cancelled entries
 	"""
 	diff = qty_after_transaction + flt(sle.actual_qty)
+
+	if not _exceptions:
+		webnotes.local.stockledger_exceptions = []
 	
 	if diff < 0 and abs(diff) > 0.0001:
 		# negative stock!
-		global _exceptions
 		exc = sle.copy().update({"diff": diff})
 		_exceptions.append(exc)
 		return False
@@ -325,4 +329,4 @@
 	sle = get_stock_ledger_entries(args, ["name != %(sle)s",
 		"timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
 		"desc", "limit 1", for_update=for_update)
-	return sle and sle[0] or {}
\ No newline at end of file
+	return sle and sle[0] or {}
diff --git a/support/doctype/customer_issue/customer_issue.py b/support/doctype/customer_issue/customer_issue.py
index 910e9b8..c099bf6 100644
--- a/support/doctype/customer_issue/customer_issue.py
+++ b/support/doctype/customer_issue/customer_issue.py
@@ -7,7 +7,6 @@
 from webnotes import session, msgprint
 from webnotes.utils import today
 
-sql = webnotes.conn.sql
 	
 
 from utilities.transaction_base import TransactionBase
@@ -28,7 +27,7 @@
 			self.doc.resolved_by = webnotes.session.user
 	
 	def on_cancel(self):
-		lst = sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent = t1.name and t2.prevdoc_docname = '%s' and	t1.docstatus!=2"%(self.doc.name))
+		lst = webnotes.conn.sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent = t1.name and t2.prevdoc_docname = '%s' and	t1.docstatus!=2"%(self.doc.name))
 		if lst:
 			lst1 = ','.join([x[0] for x in lst])
 			msgprint("Maintenance Visit No. "+lst1+" already created against this customer issue. So can not be Cancelled")
diff --git a/support/doctype/maintenance_schedule/maintenance_schedule.py b/support/doctype/maintenance_schedule/maintenance_schedule.py
index 59d3f8e..1682da5 100644
--- a/support/doctype/maintenance_schedule/maintenance_schedule.py
+++ b/support/doctype/maintenance_schedule/maintenance_schedule.py
@@ -9,7 +9,6 @@
 from webnotes.model.bean import getlist
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 
 from utilities.transaction_base import TransactionBase, delete_events
@@ -20,7 +19,7 @@
 		self.doclist = doclist
 	
 	def get_item_details(self, item_code):
-		item = sql("select item_name, description from `tabItem` where name = '%s'" %(item_code), as_dict=1)
+		item = webnotes.conn.sql("select item_name, description from `tabItem` where name = '%s'" %(item_code), as_dict=1)
 		ret = {
 			'item_name': item and item[0]['item_name'] or '',
 			'description' : item and item[0]['description'] or ''
@@ -30,7 +29,7 @@
 	def generate_schedule(self):
 		self.doclist = self.doc.clear_table(self.doclist, 'maintenance_schedule_detail')
 		count = 0
-		sql("delete from `tabMaintenance Schedule Detail` where parent='%s'" %(self.doc.name))
+		webnotes.conn.sql("delete from `tabMaintenance Schedule Detail` where parent='%s'" %(self.doc.name))
 		for d in getlist(self.doclist, 'item_maintenance_detail'):
 			self.validate_maintenance_detail()
 			s_list =[]	
@@ -67,7 +66,7 @@
 				email_map[d.incharge_name] = webnotes.bean("Sales Person", 
 					d.incharge_name).run_method("get_email_id")
 
-			scheduled_date =sql("select scheduled_date from `tabMaintenance Schedule Detail` \
+			scheduled_date =webnotes.conn.sql("select scheduled_date from `tabMaintenance Schedule Detail` \
 				where incharge_name='%s' and item_code='%s' and parent='%s' " %(d.incharge_name, \
 				d.item_code, self.doc.name), as_dict=1)
 
@@ -172,7 +171,7 @@
 	def validate_sales_order(self):
 		for d in getlist(self.doclist, 'item_maintenance_detail'):
 			if d.prevdoc_docname:
-				chk = sql("select t1.name from `tabMaintenance Schedule` t1, `tabMaintenance Schedule Item` t2 where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1", d.prevdoc_docname)
+				chk = webnotes.conn.sql("select t1.name from `tabMaintenance Schedule` t1, `tabMaintenance Schedule Item` t2 where t2.parent=t1.name and t2.prevdoc_docname=%s and t1.docstatus=1", d.prevdoc_docname)
 				if chk:
 					msgprint("Maintenance Schedule against "+d.prevdoc_docname+" already exist")
 					raise Exception
@@ -186,7 +185,7 @@
 				cur_s_no = cur_serial_no.split(',')
 				
 				for x in cur_s_no:
-					chk = sql("select name, status from `tabSerial No` where docstatus!=2 and name=%s", (x))
+					chk = webnotes.conn.sql("select name, status from `tabSerial No` where docstatus!=2 and name=%s", (x))
 					chk1 = chk and chk[0][0] or ''
 					status = chk and chk[0][1] or ''
 					
@@ -209,7 +208,7 @@
 				cur_s_no = cur_serial_no.split(',')
 				
 				for x in cur_s_no:
-					dt = sql("select delivery_date from `tabSerial No` where name = %s", x)
+					dt = webnotes.conn.sql("select delivery_date from `tabSerial No` where name = %s", x)
 					dt = dt and dt[0][0] or ''
 					
 					if dt:
@@ -225,7 +224,7 @@
 		cur_s_no = cur_serial_no.split(',')
 		
 		for x in cur_s_no:
-			sql("update `tabSerial No` set amc_expiry_date = '%s', maintenance_status = 'Under AMC' where name = '%s'"% (amc_end_date,x))
+			webnotes.conn.sql("update `tabSerial No` set amc_expiry_date = '%s', maintenance_status = 'Under AMC' where name = '%s'"% (amc_end_date,x))
 	
 	def on_update(self):
 		webnotes.conn.set(self.doc, 'status', 'Draft')
@@ -233,7 +232,7 @@
 	def validate_serial_no_warranty(self):
 		for d in getlist(self.doclist, 'item_maintenance_detail'):
 			if cstr(d.serial_no).strip():
-				dt = sql("""select warranty_expiry_date, amc_expiry_date 
+				dt = webnotes.conn.sql("""select warranty_expiry_date, amc_expiry_date 
 					from `tabSerial No` where name = %s""", d.serial_no, as_dict=1)
 				if dt[0]['warranty_expiry_date'] and dt[0]['warranty_expiry_date'] >= d.start_date:
 					webnotes.msgprint("""Serial No: %s is already under warranty upto %s. 
diff --git a/support/doctype/maintenance_visit/maintenance_visit.py b/support/doctype/maintenance_visit/maintenance_visit.py
index bf8767b..60cc371 100644
--- a/support/doctype/maintenance_visit/maintenance_visit.py
+++ b/support/doctype/maintenance_visit/maintenance_visit.py
@@ -8,7 +8,6 @@
 from webnotes.model.bean import getlist
 from webnotes import msgprint
 
-sql = webnotes.conn.sql
 	
 
 from utilities.transaction_base import TransactionBase
@@ -19,7 +18,7 @@
 		self.doclist = doclist
 	
 	def get_item_details(self, item_code):
-		item = sql("select item_name,description from `tabItem` where name = '%s'" %(item_code), as_dict=1)
+		item = webnotes.conn.sql("select item_name,description from `tabItem` where name = '%s'" %(item_code), as_dict=1)
 		ret = {
 			'item_name' : item and item[0]['item_name'] or '',
 			'description' : item and item[0]['description'] or ''
@@ -28,7 +27,7 @@
 			
 	def validate_serial_no(self):
 		for d in getlist(self.doclist, 'maintenance_visit_details'):
-			if d.serial_no and not sql("select name from `tabSerial No` where name = '%s' and docstatus != 2" % d.serial_no):
+			if d.serial_no and not webnotes.conn.sql("select name from `tabSerial No` where name = '%s' and docstatus != 2" % d.serial_no):
 				msgprint("Serial No: "+ d.serial_no + " not exists in the system")
 				raise Exception
 
@@ -52,7 +51,7 @@
 					elif self.doc.completion_status == 'Partially Completed':
 						status = 'Work In Progress'
 				else:
-					nm = sql("select t1.name, t1.mntc_date, t2.service_person, t2.work_done from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent = t1.name and t1.completion_status = 'Partially Completed' and t2.prevdoc_docname = %s and t1.name!=%s and t1.docstatus = 1 order by t1.name desc limit 1", (d.prevdoc_docname, self.doc.name))
+					nm = webnotes.conn.sql("select t1.name, t1.mntc_date, t2.service_person, t2.work_done from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent = t1.name and t1.completion_status = 'Partially Completed' and t2.prevdoc_docname = %s and t1.name!=%s and t1.docstatus = 1 order by t1.name desc limit 1", (d.prevdoc_docname, self.doc.name))
 					
 					if nm:
 						status = 'Work In Progress'
@@ -65,7 +64,7 @@
 						service_person = ''
 						work_done = ''
 				
-				sql("update `tabCustomer Issue` set resolution_date=%s, resolved_by=%s, resolution_details=%s, status=%s where name =%s",(mntc_date,service_person,work_done,status,d.prevdoc_docname))
+				webnotes.conn.sql("update `tabCustomer Issue` set resolution_date=%s, resolved_by=%s, resolution_details=%s, status=%s where name =%s",(mntc_date,service_person,work_done,status,d.prevdoc_docname))
 	
 
 	def check_if_last_visit(self):
@@ -77,7 +76,7 @@
 				check_for_doctype = d.prevdoc_doctype
 		
 		if check_for_docname:
-			check = sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent = t1.name and t1.name!=%s and t2.prevdoc_docname=%s and t1.docstatus = 1 and (t1.mntc_date > %s or (t1.mntc_date = %s and t1.mntc_time > %s))", (self.doc.name, check_for_docname, self.doc.mntc_date, self.doc.mntc_date, self.doc.mntc_time))
+			check = webnotes.conn.sql("select t1.name from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2 where t2.parent = t1.name and t1.name!=%s and t2.prevdoc_docname=%s and t1.docstatus = 1 and (t1.mntc_date > %s or (t1.mntc_date = %s and t1.mntc_time > %s))", (self.doc.name, check_for_docname, self.doc.mntc_date, self.doc.mntc_date, self.doc.mntc_time))
 			
 			if check:
 				check_lst = [x[0] for x in check]
diff --git a/support/doctype/newsletter/newsletter.py b/support/doctype/newsletter/newsletter.py
index b201cc5..a6b5aa2 100644
--- a/support/doctype/newsletter/newsletter.py
+++ b/support/doctype/newsletter/newsletter.py
@@ -90,8 +90,8 @@
 			webnotes.msgprint(_("""Please save the Newsletter before sending."""),
 				raise_exception=1)
 
-		import conf
-		if getattr(conf, "status", None) == "Trial":
+		from webnotes import conf
+		if (conf.get("status") or None) == "Trial":
 			webnotes.msgprint(_("""Sending newsletters is not allowed for Trial users, \
 				to prevent abuse of this feature."""), raise_exception=1)
 
@@ -105,7 +105,6 @@
 	}
 
 
-lead_naming_series = None
 def create_lead(email_id):
 	"""create a lead if it does not exist"""
 	from email.utils import parseaddr
@@ -119,7 +118,7 @@
 		"email_id": email_id,
 		"lead_name": real_name or email_id,
 		"status": "Contacted",
-		"naming_series": lead_naming_series or get_lead_naming_series(),
+		"naming_series": get_lead_naming_series(),
 		"company": webnotes.conn.get_default("company"),
 		"source": "Email"
 	})
@@ -127,7 +126,7 @@
 	
 def get_lead_naming_series():
 	"""gets lead's default naming series"""
-	global lead_naming_series
+	lead_naming_series = None
 	naming_series_field = webnotes.get_doctype("Lead").get_field("naming_series")
 	if naming_series_field.default:
 		lead_naming_series = naming_series_field.default
diff --git a/utilities/demo/demo_control_panel.py b/utilities/demo/demo_control_panel.py
index 1f381d5..3123f41 100644
--- a/utilities/demo/demo_control_panel.py
+++ b/utilities/demo/demo_control_panel.py
@@ -1,8 +1,8 @@
 
   def on_login(self):
     from webnotes.utils import validate_email_add
-    import conf
-    if hasattr(conf, "demo_notify_url"):
+    from webnotes import conf
+    if "demo_notify_url" in conf:
       if webnotes.form_dict.lead_email and validate_email_add(webnotes.form_dict.lead_email):
         import requests
         response = requests.post(conf.demo_notify_url, data={
@@ -10,4 +10,4 @@
           "subject":"Logged into Demo",
           "sender": webnotes.form_dict.lead_email,
           "message": "via demo.erpnext.com"
-        })
\ No newline at end of file
+        })
diff --git a/utilities/demo/demo_docs/Profile.csv b/utilities/demo/demo_docs/Profile.csv
index 2e7a2ce..eb456c1 100644
--- a/utilities/demo/demo_docs/Profile.csv
+++ b/utilities/demo/demo_docs/Profile.csv
@@ -1,40 +1,40 @@
-Data Import Template,,,,,,,,,,,,,,,,,,,,,

-Table:,Profile,,,,,,,,,,,,,,,,,,,,

-,,,,,,,,,,,,,,,,,,,,,

-,,,,,,,,,,,,,,,,,,,,,

-Notes:,,,,,,,,,,,,,,,,,,,,,

-Please do not change the template headings.,,,,,,,,,,,,,,,,,,,,,

-First data column must be blank.,,,,,,,,,,,,,,,,,,,,,

-"If you are uploading new records, leave the ""name"" (ID) column blank.",,,,,,,,,,,,,,,,,,,,,

-"If you are uploading new records, ""Naming Series"" becomes mandatory, if present.",,,,,,,,,,,,,,,,,,,,,

-Only mandatory fields are necessary for new records. You can delete non-mandatory columns if you wish.,,,,,,,,,,,,,,,,,,,,,

-"For updating, you can update only selective columns.",,,,,,,,,,,,,,,,,,,,,

-You can only upload upto 5000 records in one go. (may be less in some cases),,,,,,,,,,,,,,,,,,,,,

-,,,,,,,,,,,,,,,,,,,,,

-DocType:,Profile,,,,,,,,,,,,,,,,,,,,

-Column Labels:,ID,Email,First Name,User Type,Enabled,Middle Name (Optional),Last Name,Send Invite Email,Language,Birth Date,Gender,New Password,User Image,Background Image,Bio,Email Signature,Login After,Login Before,Restrict IP,Last Login,Last IP

-Column Name:,name,email,first_name,user_type,enabled,middle_name,last_name,send_invite_email,language,birth_date,gender,new_password,user_image,background_image,bio,email_signature,login_after,login_before,restrict_ip,last_login,last_ip

-Mandatory:,Yes,Yes,Yes,Yes,No,No,No,No,No,No,No,No,No,No,No,No,No,No,No,No,No

-Type:,Data (text),Data,Data,Select,Check,Data,Data,Check,Select,Date,Select,Password,Select,Select,Small Text,Small Text,Int,Int,Data,Read Only,Read Only

-Info:,,,,"One of: System User, Website User",0 or 1,,,0 or 1,"One of: العربية, Deutsch, english, español, français, हिंदी, Hrvatski, nederlands, português, português brasileiro, српски, தமிழ், ไทย",,"One of: Male, Female, Other",,One of: attach_files:,One of: attach_files:,,,Integer,Integer,,,

-Start entering data below this line,,,,,,,,,,,,,,,,,,,,,

-,,DikmanShervashidze@armyspy.com,Dikman,System User,1,V,Shervashidze,0,,,,testpass,,,,,,,,,

-,,Zukutakitoteka@teleworm.us,Zukutakitoteka,System User,1,,,0,,,,testpass,,,,,,,,,

-,,HatsueKashiwagi@cuvox.de,Hatsue,System User,1,H,Kashiwagi,0,,,,testpass,,,,,,,,,

-,,NuranVerkleij@einrot.com,Nuran,System User,1,T,Verkleij,0,,,,testpass,,,,,,,,,

-,,aromn@armyspy.com,Дмитрий,System User,1,З,Пирогов,0,,,,testpass,,,,,,,,,

-,,TildeLindqvist@cuvox.de,Tilde,System User,1,T,Lindqvist,0,,,,testpass,,,,,,,,,

-,,MichalSobczak@teleworm.us,Michał,System User,1,S,Sobczak,0,,,,testpass,,,,,,,,,

-,,GabrielleLoftus@superrito.com,Gabrielle,System User,1,J,Loftus,0,,,,testpass,,,,,,,,,

-,,VakhitaRyzaev@teleworm.us,Vakhita,System User,1,A,Ryzaev,0,,,,testpass,,,,,,,,,

-,,CharmaineGaudreau@cuvox.de,Charmaine,System User,1,D,Gaudreau,0,,,,testpass,,,,,,,,,

-,,RafaelaMaartens@cuvox.de,Rafaëla,System User,1,Z,Maartens,0,,,,testpass,,,,,,,,,

-,,NuguseYohannes@dayrep.com,Nuguse,System User,0,S,Yohannes,0,,,,testpass,,,,,,,,,

-,,panca@armyspy.com,Раиса,System User,0,В,Белякова,0,,,,testpass,,,,,,,,,

-,,CaYinLong@gustr.com,胤隆,System User,1,婷,蔡,0,,,,testpass,,,,,,,,,

-,,FreddieScott@armyspy.com,Freddie,System User,1,A,Scott,0,,,,testpass,,,,,,,,,

-,,BergoraVigfusdottir@superrito.com,Bergþóra,System User,1,Ö,Vigfúsdóttir,0,,,,testpass,,,,,,,,,

-,,WardNajmalDinKalb@cuvox.de,Ward,System User,1,N,Kalb,0,,,,testpass,,,,,,,,,

-,,WanMai@teleworm.us,Wan,System User,1,A,Mai,0,,,,testpass,,,,,,,,,

-,,LeonAbdulov@superrito.com,Leon,System User,1,A,Abdulov,0,,,,testpass,,,,,,,,,

-,,SabinaNovotna@superrito.com,Sabina,System User,1,J,Novotná,0,,,,testpass,,,,,,,,,
\ No newline at end of file
+Data Import Template,,,,,,,,,,,,,,,,,,,,
+Table:,Profile,,,,,,,,,,,,,,,,,,,
+,,,,,,,,,,,,,,,,,,,,
+,,,,,,,,,,,,,,,,,,,,
+Notes:,,,,,,,,,,,,,,,,,,,,
+Please do not change the template headings.,,,,,,,,,,,,,,,,,,,,
+First data column must be blank.,,,,,,,,,,,,,,,,,,,,
+"If you are uploading new records, leave the ""name"" (ID) column blank.",,,,,,,,,,,,,,,,,,,,
+"If you are uploading new records, ""Naming Series"" becomes mandatory, if present.",,,,,,,,,,,,,,,,,,,,
+Only mandatory fields are necessary for new records. You can delete non-mandatory columns if you wish.,,,,,,,,,,,,,,,,,,,,
+"For updating, you can update only selective columns.",,,,,,,,,,,,,,,,,,,,
+You can only upload upto 5000 records in one go. (may be less in some cases),,,,,,,,,,,,,,,,,,,,
+,,,,,,,,,,,,,,,,,,,,
+DocType:,Profile,,,,,,,,,,,,,,,,,,,
+Column Labels:,ID,Email,First Name,User Type,Enabled,Middle Name (Optional),Last Name,Language,Birth Date,Gender,New Password,User Image,Background Image,Bio,Email Signature,Login After,Login Before,Restrict IP,Last Login,Last IP
+Column Name:,name,email,first_name,user_type,enabled,middle_name,last_name,language,birth_date,gender,new_password,user_image,background_image,bio,email_signature,login_after,login_before,restrict_ip,last_login,last_ip
+Mandatory:,Yes,Yes,Yes,Yes,No,No,No,No,No,No,No,No,No,No,No,No,No,No,No,No
+Type:,Data (text),Data,Data,Select,Check,Data,Data,Select,Date,Select,Password,Select,Select,Small Text,Small Text,Int,Int,Data,Read Only,Read Only
+Info:,,,,"One of: System User, Website User",0 or 1,,,"One of: العربية, Deutsch, english, español, français, हिंदी, Hrvatski, nederlands, português, português brasileiro, српски, தமிழ், ไทย",,"One of: Male, Female, Other",,One of: attach_files:,One of: attach_files:,,,Integer,Integer,,,
+Start entering data below this line,,,,,,,,,,,,,,,,,,,,
+,,DikmanShervashidze@armyspy.com,Dikman,System User,1,V,Shervashidze,,,,testpass,,,,,,,,,
+,,Zukutakitoteka@teleworm.us,Zukutakitoteka,System User,1,,,,,,testpass,,,,,,,,,
+,,HatsueKashiwagi@cuvox.de,Hatsue,System User,1,H,Kashiwagi,,,,testpass,,,,,,,,,
+,,NuranVerkleij@einrot.com,Nuran,System User,1,T,Verkleij,,,,testpass,,,,,,,,,
+,,aromn@armyspy.com,Дмитрий,System User,1,З,Пирогов,,,,testpass,,,,,,,,,
+,,TildeLindqvist@cuvox.de,Tilde,System User,1,T,Lindqvist,,,,testpass,,,,,,,,,
+,,MichalSobczak@teleworm.us,Michał,System User,1,S,Sobczak,,,,testpass,,,,,,,,,
+,,GabrielleLoftus@superrito.com,Gabrielle,System User,1,J,Loftus,,,,testpass,,,,,,,,,
+,,VakhitaRyzaev@teleworm.us,Vakhita,System User,1,A,Ryzaev,,,,testpass,,,,,,,,,
+,,CharmaineGaudreau@cuvox.de,Charmaine,System User,1,D,Gaudreau,,,,testpass,,,,,,,,,
+,,RafaelaMaartens@cuvox.de,Rafaëla,System User,1,Z,Maartens,,,,testpass,,,,,,,,,
+,,NuguseYohannes@dayrep.com,Nuguse,System User,0,S,Yohannes,,,,testpass,,,,,,,,,
+,,panca@armyspy.com,Раиса,System User,0,В,Белякова,,,,testpass,,,,,,,,,
+,,CaYinLong@gustr.com,胤隆,System User,1,婷,蔡,,,,testpass,,,,,,,,,
+,,FreddieScott@armyspy.com,Freddie,System User,1,A,Scott,,,,testpass,,,,,,,,,
+,,BergoraVigfusdottir@superrito.com,Bergþóra,System User,1,Ö,Vigfúsdóttir,,,,testpass,,,,,,,,,
+,,WardNajmalDinKalb@cuvox.de,Ward,System User,1,N,Kalb,,,,testpass,,,,,,,,,
+,,WanMai@teleworm.us,Wan,System User,1,A,Mai,,,,testpass,,,,,,,,,
+,,LeonAbdulov@superrito.com,Leon,System User,1,A,Abdulov,,,,testpass,,,,,,,,,
+,,SabinaNovotna@superrito.com,Sabina,System User,1,J,Novotná,,,,testpass,,,,,,,,,
diff --git a/utilities/demo/make_demo.py b/utilities/demo/make_demo.py
index 046e81a..2d2d07e 100644
--- a/utilities/demo/make_demo.py
+++ b/utilities/demo/make_demo.py
@@ -36,11 +36,15 @@
 	
 	if reset:
 		setup()
+	else:
+		webnotes.connect()
+	
 	if simulate:
 		_simulate()
-	
+		
 def setup():
 	install()
+	webnotes.connect()
 	complete_setup()
 	make_customers_suppliers_contacts()
 	make_items()
@@ -357,7 +361,7 @@
 def install():
 	print "Creating Fresh Database..."
 	from webnotes.install_lib.install import Installer
-	import conf
+	from webnotes import conf
 	inst = Installer('root')
 	inst.import_from_db(conf.demo_db_name, verbose = 1)
 
diff --git a/utilities/demo/make_erpnext_demo.py b/utilities/demo/make_erpnext_demo.py
index 766da26..4a72e4b 100644
--- a/utilities/demo/make_erpnext_demo.py
+++ b/utilities/demo/make_erpnext_demo.py
@@ -5,9 +5,9 @@
 import webnotes, os
 import utilities.demo.make_demo
 
-def make_demo_app():
+def make_demo_app(site=None):
 	webnotes.mute_emails = 1
-	webnotes.connect()
+	webnotes.connect(site)
 	utilities.demo.make_demo.make(reset=True, simulate=False)
 	# setup demo user etc so that the site it up faster, while the data loads
 	make_demo_user()
@@ -42,7 +42,6 @@
 	p.doc.last_name = "User"
 	p.doc.enabled = 1
 	p.doc.user_type = "ERPNext Demo"
-	p.doc.send_invite_email = 0
 	p.doc.new_password = "demo"
 	p.insert()
 	add_roles(p)
@@ -58,7 +57,6 @@
 	p.doc.last_name = "User"
 	p.doc.enabled = 1
 	p.doc.user_type = "System User"
-	p.doc.send_invite_email = 0
 	p.doc.new_password = "admin010123"
 	p.insert()
 	roles.append("System Manager")
@@ -118,4 +116,4 @@
 	webnotes.conn.commit()
 
 if __name__=="__main__":
-	make_demo_app()
\ No newline at end of file
+	make_demo_app()
diff --git a/utilities/doctype/contact/contact.py b/utilities/doctype/contact/contact.py
index 84c8a59..58437f1 100644
--- a/utilities/doctype/contact/contact.py
+++ b/utilities/doctype/contact/contact.py
@@ -35,25 +35,24 @@
 		self.validate_primary_contact()
 
 	def validate_primary_contact(self):
-		sql = webnotes.conn.sql
 		if self.doc.is_primary_contact == 1:
 			if self.doc.customer:
-				sql("update tabContact set is_primary_contact=0 where customer = '%s'" % (self.doc.customer))
+				webnotes.conn.sql("update tabContact set is_primary_contact=0 where customer = '%s'" % (self.doc.customer))
 			elif self.doc.supplier:
-				sql("update tabContact set is_primary_contact=0 where supplier = '%s'" % (self.doc.supplier))	
+				webnotes.conn.sql("update tabContact set is_primary_contact=0 where supplier = '%s'" % (self.doc.supplier))	
 			elif self.doc.sales_partner:
-				sql("update tabContact set is_primary_contact=0 where sales_partner = '%s'" % (self.doc.sales_partner))
+				webnotes.conn.sql("update tabContact set is_primary_contact=0 where sales_partner = '%s'" % (self.doc.sales_partner))
 		else:
 			if self.doc.customer:
-				if not sql("select name from tabContact where is_primary_contact=1 and customer = '%s'" % (self.doc.customer)):
+				if not webnotes.conn.sql("select name from tabContact where is_primary_contact=1 and customer = '%s'" % (self.doc.customer)):
 					self.doc.is_primary_contact = 1
 			elif self.doc.supplier:
-				if not sql("select name from tabContact where is_primary_contact=1 and supplier = '%s'" % (self.doc.supplier)):
+				if not webnotes.conn.sql("select name from tabContact where is_primary_contact=1 and supplier = '%s'" % (self.doc.supplier)):
 					self.doc.is_primary_contact = 1
 			elif self.doc.sales_partner:
-				if not sql("select name from tabContact where is_primary_contact=1 and sales_partner = '%s'" % (self.doc.sales_partner)):
+				if not webnotes.conn.sql("select name from tabContact where is_primary_contact=1 and sales_partner = '%s'" % (self.doc.sales_partner)):
 					self.doc.is_primary_contact = 1
 
 	def on_trash(self):
 		webnotes.conn.sql("""update `tabSupport Ticket` set contact='' where contact=%s""",
-			self.doc.name)
\ No newline at end of file
+			self.doc.name)
diff --git a/utilities/doctype/sms_control/sms_control.py b/utilities/doctype/sms_control/sms_control.py
index 9c2319f..f183920 100644
--- a/utilities/doctype/sms_control/sms_control.py
+++ b/utilities/doctype/sms_control/sms_control.py
@@ -10,8 +10,6 @@
 from webnotes import msgprint
 from webnotes.model.bean import getlist, copy_doclist
 
-sql = webnotes.conn.sql
-	
 class DocType:
 	def __init__(self, doc, doclist=[]):
 		self.doc = doc
@@ -50,7 +48,7 @@
 	def get_contact_number(self, arg):
 		"returns mobile number of the contact"
 		args = load_json(arg)
-		number = sql("""select mobile_no, phone from tabContact where name=%s and %s=%s""" % 
+		number = webnotes.conn.sql("""select mobile_no, phone from tabContact where name=%s and %s=%s""" % 
 			('%s', args['key'], '%s'), (args['contact_name'], args['value']))
 		return number and (number[0][0] or number[0][1]) or ''
 	
@@ -119,4 +117,4 @@
 		sl.message = arg['message']
 		sl.no_of_requested_sms = len(arg['receiver_list'])
 		sl.no_of_sent_sms = sent_sms
-		sl.save(new=1)
\ No newline at end of file
+		sl.save(new=1)