Browse Source

Changes to support refactor in frappe pg-poc branch (#15287)

* Remove quotes from sql to make it compatible with postgres as well

* Fix queries
- Replace mysql specifc queries with standard ones

* Make repo URL chages to test pg-poc

* Add root passowrd to test site config

* Fix quotes issue

* Remove debug flag from a pricing rule query

* Remove python 3.6 version from travis.yml

* Fix improper query issue

* Fix incorrect query

* Fix a query

- This fix need to be changed when we will  start supporting postgres
since date_format is not supported by postgres

* Get price list map as dict

* Convert price_list_currency_map to dict
develop
Suraj Shetty 6 years ago
committed by Rushabh Mehta
parent
commit
bfc195dd8b
  1. 30
      erpnext/accounts/doctype/budget/budget.py
  2. 2
      erpnext/accounts/doctype/gl_entry/gl_entry.py
  3. 2
      erpnext/accounts/doctype/loyalty_program/loyalty_program.py
  4. 6
      erpnext/accounts/doctype/payment_entry/payment_entry.py
  5. 30
      erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py
  6. 2
      erpnext/accounts/doctype/pos_profile/pos_profile.py
  7. 8
      erpnext/accounts/doctype/pricing_rule/pricing_rule.py
  8. 6
      erpnext/accounts/doctype/tax_rule/tax_rule.py
  9. 2
      erpnext/accounts/party.py
  10. 14
      erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py
  11. 4
      erpnext/accounts/report/financial_statements.py
  12. 12
      erpnext/accounts/utils.py
  13. 9
      erpnext/assets/doctype/location/location.py
  14. 2
      erpnext/buying/doctype/purchase_order/purchase_order.py
  15. 2
      erpnext/controllers/buying_controller.py
  16. 2
      erpnext/controllers/item_variant.py
  17. 16
      erpnext/controllers/queries.py
  18. 2
      erpnext/controllers/status_updater.py
  19. 6
      erpnext/education/doctype/fee_schedule/fee_schedule.py
  20. 12
      erpnext/hotels/doctype/hotel_room_reservation/hotel_room_reservation.py
  21. 16
      erpnext/hr/doctype/expense_claim/expense_claim.py
  22. 8
      erpnext/manufacturing/doctype/production_plan/production_plan.py
  23. 8
      erpnext/manufacturing/doctype/production_planning_tool/production_planning_tool.py
  24. 2
      erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
  25. 2
      erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py
  26. 4
      erpnext/patches/v10_0/update_territory_and_customer_group.py
  27. 4
      erpnext/patches/v11_0/update_total_qty_field.py
  28. 2
      erpnext/patches/v8_0/create_domain_docs.py
  29. 12
      erpnext/patches/v8_0/set_sales_invoice_serial_number_from_delivery_note.py
  30. 2
      erpnext/patches/v8_10/change_default_customer_credit_days.py
  31. 3
      erpnext/projects/doctype/task/task.py
  32. 2
      erpnext/projects/doctype/timesheet/timesheet.py
  33. 4
      erpnext/projects/utils.py
  34. 10
      erpnext/regional/report/gstr_1/gstr_1.py
  35. 2
      erpnext/selling/page/point_of_sale/point_of_sale.py
  36. 2
      erpnext/setup/doctype/authorization_control/authorization_control.py
  37. 26
      erpnext/setup/doctype/company/company.py
  38. 12
      erpnext/setup/doctype/company/delete_company_transactions.py
  39. 2
      erpnext/setup/doctype/item_group/item_group.py
  40. 2
      erpnext/setup/doctype/party_type/party_type.py
  41. 9
      erpnext/shopping_cart/doctype/shopping_cart_settings/shopping_cart_settings.py
  42. 7
      erpnext/startup/boot.py
  43. 2
      erpnext/stock/doctype/item/item.py
  44. 2
      erpnext/stock/doctype/item_alternative/item_alternative.py
  45. 2
      erpnext/stock/doctype/serial_no/serial_no.py
  46. 8
      erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
  47. 2
      erpnext/stock/report/item_variant_details/item_variant_details.py
  48. 22
      erpnext/stock/report/stock_balance/stock_balance.py
  49. 4
      erpnext/stock/report/stock_ledger/stock_ledger.py
  50. 8
      erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
  51. 4
      erpnext/stock/report/total_stock_summary/total_stock_summary.py
  52. 1
      test_sites/test_site/site_config.json
  53. 6
      travis/bench_init.sh

30
erpnext/accounts/doctype/budget/budget.py

@ -15,7 +15,7 @@ class DuplicateBudgetError(frappe.ValidationError): pass
class Budget(Document):
def autoname(self):
self.name = make_autoname(self.get(frappe.scrub(self.budget_against))
self.name = make_autoname(self.get(frappe.scrub(self.budget_against))
+ "/" + self.fiscal_year + "/.###")
def validate(self):
@ -89,7 +89,7 @@ def validate_expense_against_budget(args):
if args.get('company') and not args.fiscal_year:
args.fiscal_year = get_fiscal_year(args.get('posting_date'), company=args.get('company'))[0]
frappe.flags.exception_approver_role = frappe.get_cached_value('Company',
frappe.flags.exception_approver_role = frappe.get_cached_value('Company',
args.get('company'), 'exception_budget_approver_role')
if not args.account:
@ -106,12 +106,12 @@ def validate_expense_against_budget(args):
and frappe.db.get_value("Account", {"name": args.account, "root_type": "Expense"})):
if args.project and budget_against == 'project':
condition = "and b.project='%s'" % frappe.db.escape(args.project)
condition = "and b.project=%s" % frappe.db.escape(args.project)
args.budget_against_field = "Project"
elif args.cost_center and budget_against == 'cost_center':
cc_lft, cc_rgt = frappe.db.get_value("Cost Center", args.cost_center, ["lft", "rgt"])
condition = """and exists(select name from `tabCost Center`
condition = """and exists(select name from `tabCost Center`
where lft<=%s and rgt>=%s and name=b.cost_center)""" % (cc_lft, cc_rgt)
args.budget_against_field = "Cost Center"
@ -126,13 +126,13 @@ def validate_expense_against_budget(args):
b.action_if_annual_budget_exceeded, b.action_if_accumulated_monthly_budget_exceeded,
b.action_if_annual_budget_exceeded_on_mr, b.action_if_accumulated_monthly_budget_exceeded_on_mr,
b.action_if_annual_budget_exceeded_on_po, b.action_if_accumulated_monthly_budget_exceeded_on_po
from
from
`tabBudget` b, `tabBudget Account` ba
where
b.name=ba.parent and b.fiscal_year=%s
b.name=ba.parent and b.fiscal_year=%s
and ba.account=%s and b.docstatus=1
{condition}
""".format(condition=condition,
""".format(condition=condition,
budget_against_field=frappe.scrub(args.get("budget_against_field"))),
(args.fiscal_year, args.account), as_dict=True)
@ -151,12 +151,12 @@ def validate_budget_records(args, budget_records):
args["month_end_date"] = get_last_day(args.posting_date)
compare_expense_with_budget(args, budget_amount,
compare_expense_with_budget(args, budget_amount,
_("Accumulated Monthly"), monthly_action, budget.budget_against, amount)
if yearly_action in ("Stop", "Warn") and monthly_action != "Stop" \
and yearly_action != monthly_action:
compare_expense_with_budget(args, flt(budget.budget_amount),
compare_expense_with_budget(args, flt(budget.budget_amount),
_("Annual"), yearly_action, budget.budget_against, amount)
def compare_expense_with_budget(args, budget_amount, action_for, action, budget_against, amount=0):
@ -166,9 +166,9 @@ def compare_expense_with_budget(args, budget_amount, action_for, action, budget_
currency = frappe.get_cached_value('Company', args.company, 'default_currency')
msg = _("{0} Budget for Account {1} against {2} {3} is {4}. It will exceed by {5}").format(
_(action_for), frappe.bold(args.account), args.budget_against_field,
_(action_for), frappe.bold(args.account), args.budget_against_field,
frappe.bold(budget_against),
frappe.bold(fmt_money(budget_amount, currency=currency)),
frappe.bold(fmt_money(budget_amount, currency=currency)),
frappe.bold(fmt_money(diff, currency=currency)))
if (frappe.flags.exception_approver_role
@ -250,12 +250,12 @@ def get_actual_expense(args):
condition1 = " and gle.posting_date <= %(month_end_date)s" \
if args.get("month_end_date") else ""
if args.budget_against_field == "Cost Center":
lft_rgt = frappe.db.get_value(args.budget_against_field,
lft_rgt = frappe.db.get_value(args.budget_against_field,
args.budget_against, ["lft", "rgt"], as_dict=1)
args.update(lft_rgt)
condition2 = """and exists(select name from `tabCost Center`
condition2 = """and exists(select name from `tabCost Center`
where lft>=%(lft)s and rgt<=%(rgt)s and name=gle.cost_center)"""
elif args.budget_against_field == "Project":
condition2 = "and exists(select name from `tabProject` where name=gle.project and gle.project = %(budget_against)s)"

2
erpnext/accounts/doctype/gl_entry/gl_entry.py

@ -162,7 +162,7 @@ def check_freezing_date(posting_date, adv_adj=False):
def update_outstanding_amt(account, party_type, party, against_voucher_type, against_voucher, on_cancel=False):
if party_type and party:
party_condition = " and party_type='{0}' and party='{1}'"\
party_condition = " and party_type={0} and party={1}"\
.format(frappe.db.escape(party_type), frappe.db.escape(party))
else:
party_condition = ""

2
erpnext/accounts/doctype/loyalty_program/loyalty_program.py

@ -19,7 +19,7 @@ def get_loyalty_details(customer, loyalty_program, expiry_date=None, company=Non
condition = ''
if company:
condition = " and company='%s' " % frappe.db.escape(company)
condition = " and company=%s " % frappe.db.escape(company)
if not include_expired_entry:
condition += " and expiry_date>='%s' " % expiry_date

6
erpnext/accounts/doctype/payment_entry/payment_entry.py

@ -299,12 +299,12 @@ class PaymentEntry(AccountsController):
if self.payment_type == "Receive" \
and self.base_total_allocated_amount < self.base_received_amount + total_deductions \
and self.total_allocated_amount < self.paid_amount + (total_deductions / self.source_exchange_rate):
self.unallocated_amount = (self.base_received_amount + total_deductions -
self.unallocated_amount = (self.base_received_amount + total_deductions -
self.base_total_allocated_amount) / self.source_exchange_rate
elif self.payment_type == "Pay" \
and self.base_total_allocated_amount < (self.base_paid_amount - total_deductions) \
and self.total_allocated_amount < self.received_amount + (total_deductions / self.target_exchange_rate):
self.unallocated_amount = (self.base_paid_amount - (total_deductions +
self.unallocated_amount = (self.base_paid_amount - (total_deductions +
self.base_total_allocated_amount)) / self.target_exchange_rate
def set_difference_amount(self):
@ -549,7 +549,7 @@ def get_outstanding_reference_documents(args):
# Get positive outstanding sales /purchase invoices/ Fees
condition = ""
if args.get("voucher_type") and args.get("voucher_no"):
condition = " and voucher_type='{0}' and voucher_no='{1}'"\
condition = " and voucher_type={0} and voucher_no={1}"\
.format(frappe.db.escape(args["voucher_type"]), frappe.db.escape(args["voucher_no"]))
# Add cost center condition

30
erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py

@ -13,20 +13,20 @@ class PaymentReconciliation(Document):
def get_unreconciled_entries(self):
self.get_nonreconciled_payment_entries()
self.get_invoice_entries()
def get_nonreconciled_payment_entries(self):
self.check_mandatory_to_fetch()
payment_entries = self.get_payment_entries()
journal_entries = self.get_jv_entries()
self.add_payment_entries(payment_entries + journal_entries)
def get_payment_entries(self):
order_doctype = "Sales Order" if self.party_type=="Customer" else "Purchase Order"
payment_entries = get_advance_payment_entries(self.party_type, self.party,
payment_entries = get_advance_payment_entries(self.party_type, self.party,
self.receivable_payable_account, order_doctype, against_all_orders=True)
return payment_entries
def get_jv_entries(self):
@ -38,8 +38,8 @@ class PaymentReconciliation(Document):
journal_entries = frappe.db.sql("""
select
"Journal Entry" as reference_type, t1.name as reference_name,
t1.posting_date, t1.remark as remarks, t2.name as reference_row,
"Journal Entry" as reference_type, t1.name as reference_name,
t1.posting_date, t1.remark as remarks, t2.name as reference_row,
{dr_or_cr} as amount, t2.is_advance
from
`tabJournal Entry` t1, `tabJournal Entry Account` t2
@ -47,8 +47,8 @@ class PaymentReconciliation(Document):
t1.name = t2.parent and t1.docstatus = 1 and t2.docstatus = 1
and t2.party_type = %(party_type)s and t2.party = %(party)s
and t2.account = %(account)s and {dr_or_cr} > 0
and (t2.reference_type is null or t2.reference_type = '' or
(t2.reference_type in ('Sales Order', 'Purchase Order')
and (t2.reference_type is null or t2.reference_type = '' or
(t2.reference_type in ('Sales Order', 'Purchase Order')
and t2.reference_name is not null and t2.reference_name != ''))
and (CASE
WHEN t1.voucher_type in ('Debit Note', 'Credit Note')
@ -106,7 +106,7 @@ class PaymentReconciliation(Document):
self.validate_invoice()
dr_or_cr = ("credit_in_account_currency"
if erpnext.get_party_account_type(self.party_type) == 'Receivable' else "debit_in_account_currency")
lst = []
for e in self.get('payments'):
if e.invoice_number and e.allocated_amount:
@ -124,11 +124,11 @@ class PaymentReconciliation(Document):
'unadjusted_amount' : flt(e.amount),
'allocated_amount' : flt(e.allocated_amount)
}))
if lst:
from erpnext.accounts.utils import reconcile_against_document
reconcile_against_document(lst)
msgprint(_("Successfully Reconciled"))
self.get_unreconciled_entries()
@ -171,8 +171,8 @@ class PaymentReconciliation(Document):
frappe.throw(_("Please select Allocated Amount, Invoice Type and Invoice Number in atleast one row"))
def check_condition(self):
cond = " and posting_date >= '{0}'".format(frappe.db.escape(self.from_date)) if self.from_date else ""
cond += " and posting_date <= '{0}'".format(frappe.db.escape(self.to_date)) if self.to_date else ""
cond = " and posting_date >= {0}".format(frappe.db.escape(self.from_date)) if self.from_date else ""
cond += " and posting_date <= {0}".format(frappe.db.escape(self.to_date)) if self.to_date else ""
dr_or_cr = ("debit_in_account_currency" if erpnext.get_party_account_type(self.party_type) == 'Receivable'
else "credit_in_account_currency")

2
erpnext/accounts/doctype/pos_profile/pos_profile.py

@ -107,7 +107,7 @@ def get_item_groups(pos_profile):
if pos_profile.get('item_groups'):
# Get items based on the item groups defined in the POS profile
for data in pos_profile.get('item_groups'):
item_groups.extend(["'%s'" % frappe.db.escape(d.name) for d in get_child_nodes('Item Group', data.item_group)])
item_groups.extend(["%s" % frappe.db.escape(d.name) for d in get_child_nodes('Item Group', data.item_group)])
return list(set(item_groups))

8
erpnext/accounts/doctype/pricing_rule/pricing_rule.py

@ -255,10 +255,12 @@ def get_pricing_rules(args):
if parent_groups:
if allow_blank: parent_groups.append('')
condition = " ifnull("+field+", '') in ('" + \
"', '".join([frappe.db.escape(d) for d in parent_groups])+"')"
frappe.flags.tree_conditions[key] = condition
condition = "ifnull({field}, '') in ({parent_groups})".format(
field=field,
parent_groups=", ".join([frappe.db.escape(d) for d in parent_groups])
)
frappe.flags.tree_conditions[key] = condition
return condition

6
erpnext/accounts/doctype/tax_rule/tax_rule.py

@ -75,7 +75,7 @@ class TaxRule(Document):
for d in filters:
if conds:
conds += " and "
conds += """ifnull({0}, '') = '{1}'""".format(d, frappe.db.escape(cstr(filters[d])))
conds += """ifnull({0}, '') = {1}""".format(d, frappe.db.escape(cstr(filters[d])))
if self.from_date and self.to_date:
conds += """ and ((from_date > '{from_date}' and from_date < '{to_date}') or
@ -152,7 +152,7 @@ def get_tax_template(posting_date, args):
customer_group_condition = get_customer_group_condition(value)
conditions.append("ifnull({0}, '') in ('', {1})".format(key, customer_group_condition))
else:
conditions.append("ifnull({0}, '') in ('', '{1}')".format(key, frappe.db.escape(cstr(value))))
conditions.append("ifnull({0}, '') in ('', {1})".format(key, frappe.db.escape(cstr(value))))
tax_rule = frappe.db.sql("""select * from `tabTax Rule`
where {0}""".format(" and ".join(conditions)), as_dict = True)
@ -180,7 +180,7 @@ def get_tax_template(posting_date, args):
def get_customer_group_condition(customer_group):
condition = ""
customer_groups = ["'%s'"%(frappe.db.escape(d.name)) for d in get_parent_customer_groups(customer_group)]
customer_groups = ["%s"%(frappe.db.escape(d.name)) for d in get_parent_customer_groups(customer_group)]
if customer_groups:
condition = ",".join(['%s'] * len(customer_groups))%(tuple(customer_groups))
return condition

2
erpnext/accounts/party.py

@ -443,7 +443,7 @@ def get_timeline_data(doctype, name):
# fetch and append data from Activity Log
data += frappe.db.sql("""select {fields}
from `tabActivity Log`
where reference_doctype="{doctype}" and reference_name="{name}"
where reference_doctype={doctype} and reference_name={name}
and status!='Success' and creation > {after}
{group_by} order by creation desc
""".format(doctype=frappe.db.escape(doctype), name=frappe.db.escape(name), fields=fields,

14
erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py

@ -100,7 +100,7 @@ def get_income_expense_data(companies, fiscal_year, filters):
net_profit_loss = get_net_profit_loss(income, expense, companies, filters.company, company_currency, True)
return income, expense, net_profit_loss
def get_cash_flow_data(fiscal_year, companies, filters):
cash_flow_accounts = get_cash_flow_accounts()
@ -122,7 +122,7 @@ def get_cash_flow_data(fiscal_year, companies, filters):
# add first net income in operations section
if net_profit_loss:
net_profit_loss.update({
"indent": 1,
"indent": 1,
"parent_account": cash_flow_accounts[0]['section_header']
})
data.append(net_profit_loss)
@ -268,7 +268,7 @@ def get_companies(filters):
return all_companies, companies
def get_subsidiary_companies(company):
lft, rgt = frappe.get_cached_value('Company',
lft, rgt = frappe.get_cached_value('Company',
company, ["lft", "rgt"])
return frappe.db.sql_list("""select name from `tabCompany`
@ -322,7 +322,7 @@ def set_gl_entries_by_account(from_date, to_date, root_lft, root_rgt, filters, g
accounts_by_name, ignore_closing_entries=False):
"""Returns a dict like { "account": [gl entries], ... }"""
company_lft, company_rgt = frappe.get_cached_value('Company',
company_lft, company_rgt = frappe.get_cached_value('Company',
filters.get('company'), ["lft", "rgt"])
additional_conditions = get_additional_conditions(from_date, ignore_closing_entries, filters)
@ -330,7 +330,7 @@ def set_gl_entries_by_account(from_date, to_date, root_lft, root_rgt, filters, g
gl_entries = frappe.db.sql("""select gl.posting_date, gl.account, gl.debit, gl.credit, gl.is_opening, gl.company,
gl.fiscal_year, gl.debit_in_account_currency, gl.credit_in_account_currency, gl.account_currency,
acc.account_name, acc.account_number
from `tabGL Entry` gl, `tabAccount` acc where acc.name = gl.account and gl.company in
from `tabGL Entry` gl, `tabAccount` acc where acc.name = gl.account and gl.company in
(select name from `tabCompany` where lft >= %(company_lft)s and rgt <= %(company_rgt)s)
{additional_conditions} and gl.posting_date <= %(to_date)s and acc.lft >= %(lft)s and acc.rgt <= %(rgt)s
order by gl.account, gl.posting_date""".format(additional_conditions=additional_conditions),
@ -368,10 +368,10 @@ def get_additional_conditions(from_date, ignore_closing_entries, filters):
company_finance_book = erpnext.get_default_finance_book(filters.get("company"))
if not filters.get('finance_book') or (filters.get('finance_book') == company_finance_book):
additional_conditions.append("ifnull(finance_book, '') in ('%s', '')" %
additional_conditions.append("ifnull(finance_book, '') in (%s, '')" %
frappe.db.escape(company_finance_book))
elif filters.get("finance_book"):
additional_conditions.append("ifnull(finance_book, '') = '%s' " %
additional_conditions.append("ifnull(finance_book, '') = %s " %
frappe.db.escape(filters.get("finance_book")))
return " and {}".format(" and ".join(additional_conditions)) if additional_conditions else ""

4
erpnext/accounts/report/financial_statements.py

@ -389,10 +389,10 @@ def get_additional_conditions(from_date, ignore_closing_entries, filters):
company_finance_book = erpnext.get_default_finance_book(filters.get("company"))
if not filters.get('finance_book') or (filters.get('finance_book') == company_finance_book):
additional_conditions.append("ifnull(finance_book, '') in ('%s', '')" %
additional_conditions.append("ifnull(finance_book, '') in (%s, '')" %
frappe.db.escape(company_finance_book))
elif filters.get("finance_book"):
additional_conditions.append("ifnull(finance_book, '') = '%s' " %
additional_conditions.append("ifnull(finance_book, '') = %s " %
frappe.db.escape(filters.get("finance_book")))
return " and {}".format(" and ".join(additional_conditions)) if additional_conditions else ""

12
erpnext/accounts/utils.py

@ -99,7 +99,7 @@ def get_balance_on(account=None, date=None, party_type=None, party=None, company
cond = []
if date:
cond.append("posting_date <= '%s'" % frappe.db.escape(cstr(date)))
cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
else:
# get balance of all entries that exist
date = nowdate()
@ -158,14 +158,14 @@ def get_balance_on(account=None, date=None, party_type=None, party=None, company
if acc.account_currency == frappe.get_cached_value('Company', acc.company, "default_currency"):
in_account_currency = False
else:
cond.append("""gle.account = "%s" """ % (frappe.db.escape(account, percent=False), ))
cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False), ))
if party_type and party:
cond.append("""gle.party_type = "%s" and gle.party = "%s" """ %
cond.append("""gle.party_type = %s and gle.party = %s """ %
(frappe.db.escape(party_type), frappe.db.escape(party, percent=False)))
if company:
cond.append("""gle.company = "%s" """ % (frappe.db.escape(company, percent=False)))
cond.append("""gle.company = %s """ % (frappe.db.escape(company, percent=False)))
if account or (party_type and party):
if in_account_currency:
@ -183,7 +183,7 @@ def get_balance_on(account=None, date=None, party_type=None, party=None, company
def get_count_on(account, fieldname, date):
cond = []
if date:
cond.append("posting_date <= '%s'" % frappe.db.escape(cstr(date)))
cond.append("posting_date <= %s" % frappe.db.escape(cstr(date)))
else:
# get balance of all entries that exist
date = nowdate()
@ -218,7 +218,7 @@ def get_count_on(account, fieldname, date):
and ac.lft >= %s and ac.rgt <= %s
)""" % (acc.lft, acc.rgt))
else:
cond.append("""gle.account = "%s" """ % (frappe.db.escape(account, percent=False), ))
cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False), ))
entries = frappe.db.sql("""
SELECT name, posting_date, account, party_type, party,debit,credit,

9
erpnext/assets/doctype/location/location.py

@ -203,12 +203,11 @@ def get_children(doctype, parent=None, location=None, is_root=False):
from
`tab{doctype}` comp
where
ifnull(parent_location, "")="{parent}"
ifnull(parent_location, "")={parent}
""".format(
doctype=frappe.db.escape(doctype),
parent=frappe.db.escape(parent)
), as_dict=1)
doctype=doctype,
parent=frappe.db.escape(parent)
), as_dict=1)
@frappe.whitelist()
def add_node():

2
erpnext/buying/doctype/purchase_order/purchase_order.py

@ -182,7 +182,7 @@ class PurchaseOrder(BuyingController):
def check_modified_date(self):
mod_db = frappe.db.sql("select modified from `tabPurchase Order` where name = %s",
self.name)
date_diff = frappe.db.sql("select TIMEDIFF('%s', '%s')" % ( mod_db[0][0],cstr(self.modified)))
date_diff = frappe.db.sql("select '%s' - '%s' " % (mod_db[0][0], cstr(self.modified)))
if date_diff and date_diff[0][0]:
msgprint(_("{0} {1} has been modified. Please refresh.").format(self.doctype, self.name),

2
erpnext/controllers/buying_controller.py

@ -746,7 +746,7 @@ def validate_item_type(doc, fieldname, message):
if not items:
return
item_list = ", ".join(["'%s'" % frappe.db.escape(d) for d in items])
item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
invalid_items = [d[0] for d in frappe.db.sql("""
select item_code from tabItem where name in ({0}) and {1}=0

2
erpnext/controllers/item_variant.py

@ -119,7 +119,7 @@ def get_attribute_values(item):
return frappe.flags.attribute_values, frappe.flags.numeric_values
def find_variant(template, args, variant_item_code=None):
conditions = ["""(iv_attribute.attribute="{0}" and iv_attribute.attribute_value="{1}")"""\
conditions = ["""(iv_attribute.attribute={0} and iv_attribute.attribute_value={1})"""\
.format(frappe.db.escape(key), frappe.db.escape(cstr(value))) for key, value in args.items()]
conditions = " or ".join(conditions)

16
erpnext/controllers/queries.py

@ -208,9 +208,9 @@ def bom(doctype, txt, searchfield, start, page_len, filters):
limit %(start)s, %(page_len)s """.format(
fcond=get_filters_cond(doctype, filters, conditions),
mcond=get_match_cond(doctype),
key=frappe.db.escape(searchfield)),
key=searchfield),
{
'txt': "%%%s%%" % frappe.db.escape(txt),
'txt': frappe.db.escape('%' + txt + '%'),
'_txt': txt.replace("%", ""),
'start': start or 0,
'page_len': page_len or 20
@ -353,7 +353,7 @@ def get_income_account(doctype, txt, searchfield, start, page_len, filters):
{condition} {match_condition}
order by idx desc, name"""
.format(condition=condition, match_condition=get_match_cond(doctype), key=searchfield), {
'txt': "%%%s%%" % frappe.db.escape(txt),
'txt': frappe.db.escape('%' + txt + '%'),
'company': filters.get("company", "")
})
@ -375,10 +375,10 @@ def get_expense_account(doctype, txt, searchfield, start, page_len, filters):
and tabAccount.docstatus!=2
and tabAccount.{key} LIKE %(txt)s
{condition} {match_condition}"""
.format(condition=condition, key=frappe.db.escape(searchfield),
.format(condition=condition, key=searchfield,
match_condition=get_match_cond(doctype)), {
'company': filters.get("company", ""),
'txt': "%%%s%%" % frappe.db.escape(txt)
'txt': frappe.db.escape('%' + txt + '%')
})
@ -406,7 +406,7 @@ def warehouse_query(doctype, txt, searchfield, start, page_len, filters):
{start}, {page_len}
""".format(
sub_query=sub_query,
key=frappe.db.escape(searchfield),
key=searchfield,
fcond=get_filters_cond(doctype, filter_dict.get("Warehouse"), conditions),
mcond=get_match_cond(doctype),
start=start,
@ -430,9 +430,9 @@ def get_batch_numbers(doctype, txt, searchfield, start, page_len, filters):
query = """select batch_id from `tabBatch`
where disabled = 0
and (expiry_date >= CURDATE() or expiry_date IS NULL)
and name like '{txt}'""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
and name like {txt}""".format(txt = frappe.db.escape('%{0}%'.format(txt)))
if filters and filters.get('item'):
query += " and item = '{item}'".format(item = frappe.db.escape(filters.get('item')))
query += " and item = {item}".format(item = frappe.db.escape(filters.get('item')))
return frappe.db.sql(query, filters)

2
erpnext/controllers/status_updater.py

@ -308,7 +308,7 @@ class StatusUpdater(Document):
def _update_modified(self, args, update_modified):
args['update_modified'] = ''
if update_modified:
args['update_modified'] = ', modified = now(), modified_by = "{0}"'\
args['update_modified'] = ', modified = now(), modified_by = {0}'\
.format(frappe.db.escape(frappe.session.user))
def update_billing_status_for_zero_amount_refdoc(self, ref_dt):

6
erpnext/education/doctype/fee_schedule/fee_schedule.py

@ -117,14 +117,14 @@ def generate_fee(fee_schedule):
def get_students(student_group, academic_year, academic_term=None, student_category=None):
conditions = ""
if student_category:
conditions = " and pe.student_category='{}'".format(frappe.db.escape(student_category))
conditions = " and pe.student_category={}".format(frappe.db.escape(student_category))
if academic_term:
conditions = " and pe.academic_term='{}'".format(frappe.db.escape(academic_term))
conditions = " and pe.academic_term={}".format(frappe.db.escape(academic_term))
students = frappe.db.sql("""
select pe.student, pe.student_name, pe.program, pe.student_batch_name
from `tabStudent Group Student` sgs, `tabProgram Enrollment` pe
where
where
pe.student = sgs.student and pe.academic_year = %s
and sgs.parent = %s and sgs.active = 1
{conditions}

12
erpnext/hotels/doctype/hotel_room_reservation/hotel_room_reservation.py

@ -59,15 +59,15 @@ class HotelRoomReservation(Document):
if not d.item:
continue
day_rate = frappe.db.sql("""
select
item.rate
from
select
item.rate
from
`tabHotel Room Pricing Item` item,
`tabHotel Room Pricing` pricing
where
item.parent = pricing.name
and item.item = %s
and %s between pricing.from_date
and %s between pricing.from_date
and pricing.to_date""", (d.item, day))
if day_rate:
@ -90,7 +90,7 @@ def get_room_rate(hotel_room_reservation):
def get_rooms_booked(room_type, day, exclude_reservation=None):
exclude_condition = ''
if exclude_reservation:
exclude_condition = 'and reservation.name != "{0}"'.format(frappe.db.escape(exclude_reservation))
exclude_condition = 'and reservation.name != {0}'.format(frappe.db.escape(exclude_reservation))
return frappe.db.sql("""
select sum(item.qty)
@ -105,5 +105,5 @@ def get_rooms_booked(room_type, day, exclude_reservation=None):
and reservation.docstatus = 1
{exclude_condition}
and %s between reservation.from_date
and reservation.to_date""".format(exclude_condition=exclude_condition),
and reservation.to_date""".format(exclude_condition=exclude_condition),
(room_type, day))[0][0] or 0

16
erpnext/hr/doctype/expense_claim/expense_claim.py

@ -18,7 +18,7 @@ class ExpenseApproverIdentityError(frappe.ValidationError): pass
class ExpenseClaim(AccountsController):
def onload(self):
self.get("__onload").make_payment_via_journal_entry = frappe.db.get_single_value('Accounts Settings',
self.get("__onload").make_payment_via_journal_entry = frappe.db.get_single_value('Accounts Settings',
'make_payment_via_journal_entry')
def validate(self):
@ -103,7 +103,7 @@ class ExpenseClaim(AccountsController):
self.validate_account_details()
payable_amount = flt(self.total_sanctioned_amount) - flt(self.total_advance_amount)
# payable entry
if payable_amount:
gl_entry.append(
@ -232,7 +232,7 @@ class ExpenseClaim(AccountsController):
expense.default_account = get_expense_claim_account(expense.expense_type, self.company)["account"]
def update_reimbursed_amount(doc):
amt = frappe.db.sql("""select ifnull(sum(debit_in_account_currency), 0) as amt
amt = frappe.db.sql("""select ifnull(sum(debit_in_account_currency), 0) as amt
from `tabGL Entry` where against_voucher_type = 'Expense Claim' and against_voucher = %s
and party = %s """, (doc.name, doc.employee) ,as_dict=1)[0].amt
@ -287,7 +287,7 @@ def get_expense_claim_account(expense_claim_type, company):
if not account:
frappe.throw(_("Please set default account in Expense Claim Type {0}")
.format(expense_claim_type))
return {
"account": account
}
@ -295,14 +295,14 @@ def get_expense_claim_account(expense_claim_type, company):
@frappe.whitelist()
def get_advances(employee, advance_id=None):
if not advance_id:
condition = 'docstatus=1 and employee="{0}" and paid_amount > 0 and paid_amount > claimed_amount'.format(frappe.db.escape(employee))
condition = 'docstatus=1 and employee={0} and paid_amount > 0 and paid_amount > claimed_amount'.format(frappe.db.escape(employee))
else:
condition = 'name="{0}"'.format(frappe.db.escape(advance_id))
condition = 'name={0}'.format(frappe.db.escape(advance_id))
return frappe.db.sql("""
select
select
name, posting_date, paid_amount, claimed_amount, advance_account
from
from
`tabEmployee Advance`
where {0}
""".format(condition), as_dict=1)

8
erpnext/manufacturing/doctype/production_plan/production_plan.py

@ -103,7 +103,7 @@ class ProductionPlan(Document):
item_condition = ""
if self.item_code:
item_condition = ' and so_item.item_code = "{0}"'.format(frappe.db.escape(self.item_code))
item_condition = ' and so_item.item_code = {0}'.format(frappe.db.escape(self.item_code))
items = frappe.db.sql("""select distinct parent, item_code, warehouse,
(qty - work_order_qty) * conversion_factor as pending_qty, name
@ -114,7 +114,7 @@ class ProductionPlan(Document):
(", ".join(["%s"] * len(so_list)), item_condition), tuple(so_list), as_dict=1)
if self.item_code:
item_condition = ' and so_item.item_code = "{0}"'.format(frappe.db.escape(self.item_code))
item_condition = ' and so_item.item_code = {0}'.format(frappe.db.escape(self.item_code))
packed_items = frappe.db.sql("""select distinct pi.parent, pi.item_code, pi.warehouse as warehouse,
(((so_item.qty - so_item.work_order_qty) * pi.qty) / so_item.qty)
@ -138,7 +138,7 @@ class ProductionPlan(Document):
item_condition = ""
if self.item_code:
item_condition = " and mr_item.item_code ='{0}'".format(frappe.db.escape(self.item_code))
item_condition = " and mr_item.item_code ={0}".format(frappe.db.escape(self.item_code))
items = frappe.db.sql("""select distinct parent, name, item_code, warehouse,
(qty - ordered_qty) as pending_qty
@ -512,7 +512,7 @@ def get_bin_details(row):
conditions = ""
warehouse = row.source_warehouse or row.default_warehouse or row.warehouse
if warehouse:
conditions = " and warehouse='{0}'".format(frappe.db.escape(warehouse))
conditions = " and warehouse={0}".format(frappe.db.escape(warehouse))
item_projected_qty = frappe.db.sql(""" select ifnull(sum(projected_qty),0) as projected_qty,
ifnull(sum(actual_qty),0) as actual_qty from `tabBin`

8
erpnext/manufacturing/doctype/production_planning_tool/production_planning_tool.py

@ -127,7 +127,7 @@ class ProductionPlanningTool(Document):
item_condition = ""
if self.fg_item:
item_condition = ' and so_item.item_code = "{0}"'.format(frappe.db.escape(self.fg_item))
item_condition = ' and so_item.item_code = {0}'.format(frappe.db.escape(self.fg_item))
items = frappe.db.sql("""select distinct parent, item_code, warehouse,
(qty - delivered_qty)*conversion_factor as pending_qty
@ -138,7 +138,7 @@ class ProductionPlanningTool(Document):
(", ".join(["%s"] * len(so_list)), item_condition), tuple(so_list), as_dict=1)
if self.fg_item:
item_condition = ' and pi.item_code = "{0}"'.format(frappe.db.escape(self.fg_item))
item_condition = ' and pi.item_code = {0}'.format(frappe.db.escape(self.fg_item))
packed_items = frappe.db.sql("""select distinct pi.parent, pi.item_code, pi.warehouse as warehouse,
(((so_item.qty - so_item.delivered_qty) * pi.qty) / so_item.qty)
@ -161,7 +161,7 @@ class ProductionPlanningTool(Document):
item_condition = ""
if self.fg_item:
item_condition = ' and mr_item.item_code = "' + frappe.db.escape(self.fg_item, percent=False) + '"'
item_condition = ' and mr_item.item_code =' + frappe.db.escape(self.fg_item, percent=False)
items = frappe.db.sql("""select distinct parent, name, item_code, warehouse,
(qty - ordered_qty) as pending_qty
@ -487,7 +487,7 @@ class ProductionPlanningTool(Document):
def get_item_projected_qty(self,item):
conditions = ""
if self.purchase_request_for_warehouse:
conditions = " and warehouse='{0}'".format(frappe.db.escape(self.purchase_request_for_warehouse))
conditions = " and warehouse={0}".format(frappe.db.escape(self.purchase_request_for_warehouse))
item_projected_qty = frappe.db.sql("""
select ifnull(sum(projected_qty),0) as qty

2
erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py

@ -62,7 +62,7 @@ def get_bom_stock(filters):
where wh.lft >= %s and wh.rgt <= %s and ledger.warehouse = wh.name)" % (warehouse_details.lft,
warehouse_details.rgt)
else:
conditions += " and ledger.warehouse = '%s'" % frappe.db.escape(filters.get("warehouse"))
conditions += " and ledger.warehouse = %s" % frappe.db.escape(filters.get("warehouse"))
else:
conditions += ""

2
erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py

@ -43,7 +43,7 @@ def get_bom_stock(filters):
where wh.lft >= %s and wh.rgt <= %s and ledger.warehouse = wh.name)" % (warehouse_details.lft,
warehouse_details.rgt)
else:
conditions += " and ledger.warehouse = '%s'" % frappe.db.escape(filters.get("warehouse"))
conditions += " and ledger.warehouse = %s" % frappe.db.escape(filters.get("warehouse"))
else:
conditions += ""

4
erpnext/patches/v10_0/update_territory_and_customer_group.py

@ -15,8 +15,8 @@ def execute():
value = frappe.db.escape(frappe.as_unicode(customer.get("customer_group")))
when_then.append('''
WHEN `%s` = "%s" and %s != "%s"
THEN "%s"
WHEN `%s` = %s and %s != %s
THEN %s
'''%(d["master_fieldname"], frappe.db.escape(frappe.as_unicode(customer.name)),
d["linked_to_fieldname"], value, value))

4
erpnext/patches/v11_0/update_total_qty_field.py

@ -9,7 +9,7 @@ def execute():
frappe.reload_doc('stock', 'doctype', 'purchase_receipt')
frappe.reload_doc('accounts', 'doctype', 'sales_invoice')
frappe.reload_doc('accounts', 'doctype', 'purchase_invoice')
doctypes = ["Sales Order", "Sales Invoice", "Delivery Note",\
"Purchase Order", "Purchase Invoice", "Purchase Receipt", "Quotation", "Supplier Quotation"]
@ -25,7 +25,7 @@ def execute():
when_then = []
for d in total_qty:
when_then.append("""
when dt.name = '{0}' then {1}
when dt.name = {0} then {1}
""".format(frappe.db.escape(d.get("parent")), d.get("qty")))
if when_then:

2
erpnext/patches/v8_0/create_domain_docs.py

@ -22,7 +22,7 @@ def execute():
condition = ""
company = erpnext.get_default_company()
if company:
condition = " and name='{0}'".format(frappe.db.escape(company))
condition = " and name={0}".format(frappe.db.escape(company))
domains = frappe.db.sql_list("select distinct domain from `tabCompany` where domain != 'Other' {0}".format(condition))

12
erpnext/patches/v8_0/set_sales_invoice_serial_number_from_delivery_note.py

@ -10,9 +10,9 @@ def execute():
frappe.reload_doc("stock", "doctype", "serial_no")
frappe.db.sql(""" update `tabSales Invoice Item` sii inner join
frappe.db.sql(""" update `tabSales Invoice Item` sii inner join
`tabDelivery Note Item` dni on sii.dn_detail=dni.name and sii.qty=dni.qty
set sii.serial_no=dni.serial_no where sii.parent IN (select si.name
set sii.serial_no=dni.serial_no where sii.parent IN (select si.name
from `tabSales Invoice` si where si.update_stock=0 and si.docstatus=1)""")
items = frappe.db.sql(""" select sii.parent, sii.serial_no from `tabSales Invoice Item` sii
@ -26,13 +26,13 @@ def execute():
if not sales_invoice or not serial_nos:
continue
serial_nos = ["'%s'"%frappe.db.escape(no) for no in serial_nos.split("\n")]
serial_nos = ["{}".format(frappe.db.escape(no)) for no in serial_nos.split("\n")]
frappe.db.sql("""
UPDATE
UPDATE
`tabSerial No`
SET
sales_invoice='{sales_invoice}'
SET
sales_invoice={sales_invoice}
WHERE
name in ({serial_nos})
""".format(

2
erpnext/patches/v8_10/change_default_customer_credit_days.py

@ -35,7 +35,7 @@ def execute():
else:
template = frappe.get_doc("Payment Terms Template", pyt_template_name)
payment_terms.append('WHEN `name`="%s" THEN "%s"' % (frappe.db.escape(party_name), template.template_name))
payment_terms.append('WHEN `name`={0} THEN {1}'.format(frappe.db.escape(party_name), template.template_name))
records.append(frappe.db.escape(party_name))
begin_query_str = "UPDATE `tab{0}` SET `payment_terms` = CASE ".format(doctype)

3
erpnext/projects/doctype/task/task.py

@ -167,7 +167,8 @@ def get_project(doctype, txt, searchfield, start, page_len, filters):
%(mcond)s
order by name
limit %(start)s, %(page_len)s """ % {'key': searchfield,
'txt': "%%%s%%" % frappe.db.escape(txt), 'mcond':get_match_cond(doctype),
'txt': frappe.db.escape('%' + txt + '%'),
'mcond':get_match_cond(doctype),
'start': start, 'page_len': page_len})

2
erpnext/projects/doctype/timesheet/timesheet.py

@ -223,7 +223,7 @@ def get_timesheet(doctype, txt, searchfield, start, page_len, filters):
and tsd.parent LIKE %(txt)s {condition}
order by tsd.parent limit %(start)s, %(page_len)s"""
.format(condition=condition), {
"txt": "%%%s%%" % frappe.db.escape(txt),
'txt': frappe.db.escape('%' + txt + '%'),
"start": start, "page_len": page_len, 'project': filters.get("project")
})

4
erpnext/projects/utils.py

@ -23,6 +23,6 @@ def query_task(doctype, txt, searchfield, start, page_len, filters):
`%s`,
subject
limit %s, %s""" %
(frappe.db.escape(searchfield), "%s", "%s", match_conditions, "%s",
frappe.db.escape(searchfield), "%s", frappe.db.escape(searchfield), "%s", "%s"),
(searchfield, "%s", "%s", match_conditions, "%s",
searchfield, "%s", searchfield, "%s", "%s"),
(search_string, search_string, order_by_string, order_by_string, start, page_len))

10
erpnext/regional/report/gstr_1/gstr_1.py

@ -117,7 +117,7 @@ class Gstr1Report(object):
if self.filters.get("type_of_business") == "B2B":
conditions += """ and ifnull(invoice_type, '') != 'Export' and is_return != 1
and customer in ('{0}')""".format("', '".join([frappe.db.escape(c.name) for c in customers]))
and customer in ({0})""".format(", ".join([frappe.db.escape(c.name) for c in customers]))
if self.filters.get("type_of_business") in ("B2C Large", "B2C Small"):
b2c_limit = frappe.db.get_single_value('GSt Settings', 'b2c_limit')
@ -126,13 +126,13 @@ class Gstr1Report(object):
if self.filters.get("type_of_business") == "B2C Large":
conditions += """ and SUBSTR(place_of_supply, 1, 2) != SUBSTR(company_gstin, 1, 2)
and grand_total > {0} and is_return != 1 and customer in ('{1}')""".\
format(flt(b2c_limit), "', '".join([frappe.db.escape(c.name) for c in customers]))
and grand_total > {0} and is_return != 1 and customer in ({1})""".\
format(flt(b2c_limit), ", ".join([frappe.db.escape(c.name) for c in customers]))
elif self.filters.get("type_of_business") == "B2C Small":
conditions += """ and (
SUBSTR(place_of_supply, 1, 2) = SUBSTR(company_gstin, 1, 2)
or grand_total <= {0}) and is_return != 1 and customer in ('{1}')""".\
format(flt(b2c_limit), "', '".join([frappe.db.escape(c.name) for c in customers]))
or grand_total <= {0}) and is_return != 1 and customer in ({1})""".\
format(flt(b2c_limit), ", ".join([frappe.db.escape(c.name) for c in customers]))
elif self.filters.get("type_of_business") == "CDNR":
conditions += """ and is_return = 1 """

2
erpnext/selling/page/point_of_sale/point_of_sale.py

@ -126,7 +126,7 @@ def get_conditions(item_code, serial_no, batch_no, barcode):
condition = """(i.name like %(item_code)s
or i.item_name like %(item_code)s)"""
return '%%%s%%'%(frappe.db.escape(item_code)), condition
return frappe.db.escape('%' + item_code + '%'), condition
def get_item_group_condition(pos_profile):
cond = "and 1=1"

2
erpnext/setup/doctype/authorization_control/authorization_control.py

@ -40,7 +40,7 @@ class AuthorizationControl(TransactionBase):
chk = 1
add_cond1,add_cond2 = '',''
if based_on == 'Itemwise Discount':
add_cond1 += " and master_name = '"+frappe.db.escape(cstr(item))+"'"
add_cond1 += " and master_name = " + frappe.db.escape(cstr(item))
itemwise_exists = frappe.db.sql("""select value from `tabAuthorization Rule`
where transaction = %s and value <= %s
and based_on = %s and company = %s and docstatus != 2 %s %s""" %

26
erpnext/setup/doctype/company/company.py

@ -388,17 +388,19 @@ def update_company_current_month_sales(company):
current_month_year = formatdate(today(), "MM-yyyy")
results = frappe.db.sql('''
select
sum(base_grand_total) as total, date_format(posting_date, '%m-%Y') as month_year
from
SELECT
SUM(base_grand_total) AS total,
DATE_FORMAT(`posting_date`, '%m-%Y') AS month_year
FROM
`tabSales Invoice`
where
date_format(posting_date, '%m-%Y')="{0}"
and docstatus = 1
and company = "{1}"
group by
WHERE
DATE_FORMAT(`posting_date`, '%m-%Y') = '{current_month_year}'
AND docstatus = 1
AND company = {company}
GROUP BY
month_year
'''.format(current_month_year, frappe.db.escape(company)), as_dict = True)
'''.format(current_month_year=current_month_year, company=frappe.db.escape(company)),
as_dict = True)
monthly_total = results[0]['total'] if len(results) > 0 else 0
@ -408,7 +410,7 @@ def update_company_monthly_sales(company):
'''Cache past year monthly sales of every company based on sales invoices'''
from frappe.utils.goal import get_monthly_results
import json
filter_str = "company = '{0}' and status != 'Draft' and docstatus=1".format(frappe.db.escape(company))
filter_str = "company = {0} and status != 'Draft' and docstatus=1".format(frappe.db.escape(company))
month_to_value_dict = get_monthly_results("Sales Invoice", "base_grand_total",
"posting_date", filter_str, "sum")
@ -440,9 +442,9 @@ def get_children(doctype, parent=None, company=None, is_root=False):
from
`tab{doctype}` comp
where
ifnull(parent_company, "")="{parent}"
ifnull(parent_company, "")={parent}
""".format(
doctype = frappe.db.escape(doctype),
doctype = doctype,
parent=frappe.db.escape(parent)
), as_dict=1)

12
erpnext/setup/doctype/company/delete_company_transactions.py

@ -89,18 +89,18 @@ def delete_lead_addresses(company_name):
leads = [ "'%s'"%row.get("name") for row in leads ]
addresses = []
if leads:
addresses = frappe.db.sql_list("""select parent from `tabDynamic Link` where link_name
addresses = frappe.db.sql_list("""select parent from `tabDynamic Link` where link_name
in ({leads})""".format(leads=",".join(leads)))
if addresses:
addresses = ["'%s'"%frappe.db.escape(addr) for addr in addresses]
addresses = ["%s" % frappe.db.escape(addr) for addr in addresses]
frappe.db.sql("""delete from tabAddress where name in ({addresses}) and
name not in (select distinct dl1.parent from `tabDynamic Link` dl1
inner join `tabDynamic Link` dl2 on dl1.parent=dl2.parent
frappe.db.sql("""delete from tabAddress where name in ({addresses}) and
name not in (select distinct dl1.parent from `tabDynamic Link` dl1
inner join `tabDynamic Link` dl2 on dl1.parent=dl2.parent
and dl1.link_doctype<>dl2.link_doctype)""".format(addresses=",".join(addresses)))
frappe.db.sql("""delete from `tabDynamic Link` where link_doctype='Lead'
frappe.db.sql("""delete from `tabDynamic Link` where link_doctype='Lead'
and parenttype='Address' and link_name in ({leads})""".format(leads=",".join(leads)))
frappe.db.sql("""update tabCustomer set lead_name=NULL where lead_name in ({leads})""".format(leads=",".join(leads)))

2
erpnext/setup/doctype/item_group/item_group.py

@ -88,7 +88,7 @@ def get_product_list_for_group(product_group=None, start=0, limit=10, search=Non
# return child item groups if the type is of "Is Group"
return get_child_groups_for_list_in_html(item_group, start, limit, search)
child_groups = ", ".join(['"' + frappe.db.escape(i[0]) + '"' for i in get_child_groups(product_group)])
child_groups = ", ".join([frappe.db.escape(i[0]) for i in get_child_groups(product_group)])
# base query
query = """select I.name, I.item_name, I.item_code, I.route, I.image, I.website_image, I.thumbnail, I.item_group,

2
erpnext/setup/doctype/party_type/party_type.py

@ -20,6 +20,6 @@ def get_party_type(doctype, txt, searchfield, start, page_len, filters):
where `{key}` LIKE %(txt)s {cond}
order by name limit %(start)s, %(page_len)s"""
.format(key=searchfield, cond=cond), {
'txt': "%%%s%%" % frappe.db.escape(txt),
'txt': frappe.db.escape('%' + txt + '%'),
'start': start, 'page_len': page_len
})

9
erpnext/shopping_cart/doctype/shopping_cart_settings/shopping_cart_settings.py

@ -28,9 +28,10 @@ class ShoppingCartSettings(Document):
raise_exception=ShoppingCartSetupError)
price_list_currency_map = frappe.db.get_values("Price List",
[self.price_list],
"currency")
[self.price_list], "currency")
price_list_currency_map = dict(price_list_currency_map)
# check if all price lists have a currency
for price_list, currency in price_list_currency_map.items():
if not currency:
@ -39,8 +40,8 @@ class ShoppingCartSettings(Document):
expected_to_exist = [currency + "-" + company_currency
for currency in price_list_currency_map.values()
if currency != company_currency]
# manqala 20/09/2016: set up selection parameters for query from tabCurrency Exchange
# manqala 20/09/2016: set up selection parameters for query from tabCurrency Exchange
from_currency = [currency for currency in price_list_currency_map.values() if currency != company_currency]
to_currency = company_currency
# manqala end

7
erpnext/startup/boot.py

@ -26,11 +26,12 @@ def boot_session(bootinfo):
'default_valid_till'))
# if no company, show a dialog box to create a new company
bootinfo.customer_count = frappe.db.sql("""select count(*) from tabCustomer""")[0][0]
bootinfo.customer_count = frappe.db.sql("""SELECT count(*) FROM `tabCustomer`""")[0][0]
if not bootinfo.customer_count:
bootinfo.setup_complete = frappe.db.sql("""select name from
tabCompany limit 1""") and 'Yes' or 'No'
bootinfo.setup_complete = frappe.db.sql("""SELECT `name`
FROM `tabCompany`
LIMIT 1""") and 'Yes' or 'No'
bootinfo.docs += frappe.db.sql("""select name, default_currency, cost_center, default_terms,
default_letter_head, default_bank_account, enable_perpetual_inventory from `tabCompany`""",

2
erpnext/stock/doctype/item/item.py

@ -961,7 +961,7 @@ def get_uom_conv_factor(uom, stock_uom):
value = ""
uom_details = frappe.db.sql("""select to_uom, from_uom, value from `tabUOM Conversion Factor`\
where to_uom in ({0})
""".format(', '.join(['"' + frappe.db.escape(i, percent=False) + '"' for i in uoms])), as_dict=True)
""".format(', '.join([frappe.db.escape(i, percent=False) for i in uoms])), as_dict=True)
for d in uom_details:
if d.from_uom == stock_uom and d.to_uom == uom:

2
erpnext/stock/doctype/item_alternative/item_alternative.py

@ -36,5 +36,5 @@ def get_alternative_items(doctype, txt, searchfield, start, page_len, filters):
and two_way = 1) limit {0}, {1}
""".format(start, page_len), {
"item_code": frappe.db.escape(filters.get('item_code')),
"txt": "%%%s%%" % frappe.db.escape(txt)
"txt": frappe.db.escape('%' + txt + '%')
})

2
erpnext/stock/doctype/serial_no/serial_no.py

@ -171,7 +171,7 @@ class SerialNo(StockController):
where fieldname='serial_no' and fieldtype in ('Text', 'Small Text')"""):
for item in frappe.db.sql("""select name, serial_no from `tab%s`
where serial_no like '%%%s%%'""" % (dt[0], frappe.db.escape(old))):
where serial_no like %s""" % (dt[0], frappe.db.escape('%' + old + '%'))):
serial_nos = map(lambda i: new if i.upper()==old.upper() else i, item[1].split('\n'))
frappe.db.sql("""update `tab%s` set serial_no = %s

8
erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py

@ -124,11 +124,11 @@ class StockLedgerEntry(Document):
is_group_warehouse(self.warehouse)
def on_doctype_update():
if not frappe.db.sql("""show index from `tabStock Ledger Entry`
where Key_name="posting_sort_index" """):
if not frappe.db.has_index('tabStock Ledger Entry', 'posting_sort_index'):
frappe.db.commit()
frappe.db.sql("""alter table `tabStock Ledger Entry`
add index posting_sort_index(posting_date, posting_time, name)""")
frappe.db.add_index("Stock Ledger Entry",
fields=["posting_date", "posting_time", "name"],
index_name="posting_sort_index")
frappe.db.add_index("Stock Ledger Entry", ["voucher_no", "voucher_type"])
frappe.db.add_index("Stock Ledger Entry", ["batch_no", "item_code", "warehouse"])

2
erpnext/stock/report/item_variant_details/item_variant_details.py

@ -22,7 +22,7 @@ def get_data(item):
frappe.msgprint(_("There isn't any item variant for the selected item"))
return []
else:
variants = ",".join(['"' + frappe.db.escape(variant['name']) + '"' for variant in variant_results])
variants = ", ".join([frappe.db.escape(variant['name']) for variant in variant_results])
order_count_map = get_open_sales_orders_map(variants)
stock_details_map = get_stock_details_map(variants)

22
erpnext/stock/report/stock_balance/stock_balance.py

@ -94,7 +94,7 @@ def get_conditions(filters):
frappe.throw(_("'From Date' is required"))
if filters.get("to_date"):
conditions += " and sle.posting_date <= '%s'" % frappe.db.escape(filters.get("to_date"))
conditions += " and sle.posting_date <= %s" % frappe.db.escape(filters.get("to_date"))
else:
frappe.throw(_("'To Date' is required"))
@ -112,7 +112,7 @@ def get_stock_ledger_entries(filters, items):
item_conditions_sql = ''
if items:
item_conditions_sql = ' and sle.item_code in ({})'\
.format(', '.join(['"' + frappe.db.escape(i, percent=False) + '"' for i in items]))
.format(', '.join([frappe.db.escape(i, percent=False) for i in items]))
conditions = get_conditions(filters)
@ -166,15 +166,15 @@ def get_item_warehouse_map(filters, sle):
qty_dict.val_rate = d.valuation_rate
qty_dict.bal_qty += qty_diff
qty_dict.bal_val += value_diff
iwb_map = filter_items_with_no_transactions(iwb_map)
return iwb_map
def filter_items_with_no_transactions(iwb_map):
for (company, item, warehouse) in sorted(iwb_map):
qty_dict = iwb_map[(company, item, warehouse)]
no_transactions = True
float_precision = cint(frappe.db.get_default("float_precision")) or 3
for key, val in iteritems(qty_dict):
@ -182,7 +182,7 @@ def filter_items_with_no_transactions(iwb_map):
qty_dict[key] = val
if key != "val_rate" and val:
no_transactions = False
if no_transactions:
iwb_map.pop((company, item, warehouse))
@ -211,10 +211,10 @@ def get_item_details(items, sle, filters):
if items:
for item in frappe.db.sql("""
select name, item_name, description, item_group, brand, stock_uom
from `tabItem`
where name in ({0}) and ifnull(disabled, 0) = 0
""".format(', '.join(['"' + frappe.db.escape(i, percent=False) + '"' for i in items])), as_dict=1):
SELECT `name`, `item_name`, `description`, `item_group`, `brand`, `stock_uom`
FROM `tabItem`
WHERE `name` IN ({0}) AND ifnull(`disabled`, 0) = 0
""".format(', '.join([frappe.db.escape(i, percent=False) for i in items])), as_dict=1):
item_details.setdefault(item.name, item)
if filters.get('show_variant_attributes', 0) == 1:
@ -231,7 +231,7 @@ def get_item_reorder_details(items):
select parent, warehouse, warehouse_reorder_qty, warehouse_reorder_level
from `tabItem Reorder`
where parent in ({0})
""".format(', '.join(['"' + frappe.db.escape(i, percent=False) + '"' for i in items])), as_dict=1)
""".format(', '.join([frappe.db.escape(i, percent=False) for i in items])), as_dict=1)
return dict((d.parent + d.warehouse, d) for d in item_reorder_details)

4
erpnext/stock/report/stock_ledger/stock_ledger.py

@ -56,7 +56,7 @@ def get_stock_ledger_entries(filters, items):
item_conditions_sql = ''
if items:
item_conditions_sql = 'and sle.item_code in ({})'\
.format(', '.join(['"' + frappe.db.escape(i) + '"' for i in items]))
.format(', '.join([frappe.db.escape(i) for i in items]))
return frappe.db.sql("""select concat_ws(" ", posting_date, posting_time) as date,
item_code, warehouse, actual_qty, qty_after_transaction, incoming_rate, valuation_rate,
@ -100,7 +100,7 @@ def get_item_details(items, sl_entries):
select name, item_name, description, item_group, brand, stock_uom
from `tabItem`
where name in ({0})
""".format(', '.join(['"' + frappe.db.escape(i,percent=False) + '"' for i in items])), as_dict=1):
""".format(', '.join([frappe.db.escape(i,percent=False) for i in items])), as_dict=1):
item_details.setdefault(item.name, item)
return item_details

8
erpnext/stock/report/stock_projected_qty/stock_projected_qty.py

@ -64,10 +64,10 @@ def get_data(filters):
def get_bin_list(filters):
conditions = []
if filters.item_code:
conditions.append("item_code = '%s' "%filters.item_code)
if filters.warehouse:
warehouse_details = frappe.db.get_value("Warehouse", filters.warehouse, ["lft", "rgt"], as_dict=1)
@ -88,7 +88,7 @@ def get_item_map(item_code):
condition = ""
if item_code:
condition = 'and item_code = "{0}"'.format(frappe.db.escape(item_code, percent=False))
condition = 'and item_code = {0}'.format(frappe.db.escape(item_code, percent=False))
items = frappe.db.sql("""select * from `tabItem` item
where is_stock_item = 1
@ -100,7 +100,7 @@ def get_item_map(item_code):
condition = ""
if item_code:
condition = 'where parent="{0}"'.format(frappe.db.escape(item_code, percent=False))
condition = 'where parent={0}'.format(frappe.db.escape(item_code, percent=False))
reorder_levels = frappe._dict()
for ir in frappe.db.sql("""select * from `tabItem Reorder` {condition}""".format(condition=condition), as_dict=1):

4
erpnext/stock/report/total_stock_summary/total_stock_summary.py

@ -30,8 +30,8 @@ def get_total_stock(filters):
if filters.get("group_by") == "Warehouse":
if filters.get("company"):
conditions += " AND warehouse.company = '%s'" % frappe.db.escape(filters.get("company"), percent=False)
conditions += " AND warehouse.company = %s" % frappe.db.escape(filters.get("company"), percent=False)
conditions += " GROUP BY ledger.warehouse, item.item_code"
columns += "'' as company, ledger.warehouse"
else:

1
test_sites/test_site/site_config.json

@ -7,6 +7,7 @@
"mail_password": "test",
"admin_password": "admin",
"run_selenium_tests": 1,
"root_password": "travis",
"host_name": "http://localhost:8000",
"install_apps": ["erpnext"]
}

6
travis/bench_init.sh

@ -1,8 +1,8 @@
#!/bin/bash
cd ~/
curl -I https://github.com/frappe/frappe/tree/$TRAVIS_BRANCH | head -n 1 | cut -d $' ' -f2 | (
curl -I https://github.com/surajshetty3416/frappe/tree/pg-poc | head -n 1 | cut -d $' ' -f2 | (
read response;
[ $response == '200' ] && branch=$TRAVIS_BRANCH || branch='develop';
bench init frappe-bench --frappe-path https://github.com/frappe/frappe.git --frappe-branch $branch --python $(which python)
[ $response == '200' ] && branch='pg-poc' || branch='develop';
bench init frappe-bench --frappe-path https://github.com/surajshetty3416/frappe.git --frappe-branch $branch --python $(which python)
)

Loading…
Cancel
Save