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
This commit is contained in:
Suraj Shetty 2018-09-21 10:20:52 +05:30 committed by Rushabh Mehta
parent f9b3511880
commit bfc195dd8b
53 changed files with 189 additions and 182 deletions

View File

@ -106,7 +106,7 @@ 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':

View File

@ -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 = ""

View File

@ -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

View File

@ -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

View File

@ -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")

View File

@ -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))

View File

@ -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

View File

@ -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

View File

@ -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,

View File

@ -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 ""

View File

@ -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 ""

View File

@ -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,

View File

@ -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():

View File

@ -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),

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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):

View File

@ -117,9 +117,9 @@ 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

View File

@ -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)

View File

@ -295,9 +295,9 @@ 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

View File

@ -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`

View File

@ -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

View File

@ -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 += ""

View File

@ -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 += ""

View File

@ -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))

View File

@ -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:

View File

@ -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))

View File

@ -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
`tabSerial No`
SET
sales_invoice='{sales_invoice}'
sales_invoice={sales_invoice}
WHERE
name in ({serial_nos})
""".format(

View File

@ -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)

View File

@ -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})

View File

@ -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")
})

View File

@ -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))

View File

@ -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 """

View File

@ -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"

View File

@ -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""" %

View File

@ -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)

View File

@ -93,7 +93,7 @@ def delete_lead_addresses(company_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

View File

@ -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,

View File

@ -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
})

View File

@ -28,8 +28,9 @@ 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():

View File

@ -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`""",

View File

@ -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:

View File

@ -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 + '%')
})

View File

@ -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

View File

@ -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"])

View File

@ -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)

View File

@ -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)
@ -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)

View File

@ -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

View File

@ -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):

View File

@ -30,7 +30,7 @@ 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"

View File

@ -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"]
}

View File

@ -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)
)