Merge pull request #56546 from mihir-kandoi/pg-rawsql-to-orm

refactor: convert convertible raw frappe.db.sql to ORM
This commit is contained in:
Mihir Kandoi
2026-06-26 12:21:25 +05:30
committed by GitHub
18 changed files with 165 additions and 215 deletions

View File

@@ -2,6 +2,7 @@
# See license.txt # See license.txt
import frappe import frappe
from frappe.query_builder.functions import Sum
from frappe.utils import today from frappe.utils import today
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
@@ -63,13 +64,9 @@ class TestLoyaltyPointEntry(ERPNextTestSuite):
self.assertEqual(doc.loyalty_points, -7) self.assertEqual(doc.loyalty_points, -7)
# Check balance # Check balance
balance = frappe.db.sql( lpe = frappe.qb.DocType("Loyalty Point Entry")
""" balance = (
SELECT SUM(loyalty_points) frappe.qb.from_(lpe).select(Sum(lpe.loyalty_points)).where(lpe.customer == self.customer_name)
FROM `tabLoyalty Point Entry` ).run()[0][0]
WHERE customer = %s
""",
(self.customer_name,),
)[0][0]
self.assertEqual(balance, 3) # 10 added, 7 redeemed self.assertEqual(balance, 3) # 10 added, 7 redeemed

View File

@@ -3,6 +3,7 @@
import unittest import unittest
import frappe import frappe
from frappe.query_builder.functions import Sum
from frappe.utils import cint, flt, getdate, today from frappe.utils import cint, flt, getdate, today
from erpnext.accounts.doctype.loyalty_program.loyalty_program import ( from erpnext.accounts.doctype.loyalty_program.loyalty_program import (
@@ -262,14 +263,12 @@ class TestLoyaltyProgram(ERPNextTestSuite):
def get_points_earned(self): def get_points_earned(self):
def get_returned_amount(): def get_returned_amount():
returned_amount = frappe.db.sql( si = frappe.qb.DocType("Sales Invoice")
""" returned_amount = (
select sum(grand_total) frappe.qb.from_(si)
from `tabSales Invoice` .select(Sum(si.grand_total))
where docstatus=1 and is_return=1 and ifnull(return_against, '')=%s .where((si.docstatus == 1) & (si.is_return == 1) & (si.return_against == self.name))
""", ).run()
self.name,
)
return abs(flt(returned_amount[0][0])) if returned_amount else 0 return abs(flt(returned_amount[0][0])) if returned_amount else 0
lp_details = get_loyalty_program_details_with_points( lp_details = get_loyalty_program_details_with_points(

View File

@@ -10,9 +10,9 @@ from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_pu
class TestPOSInvoiceMerging(POSInvoiceTestMixin): class TestPOSInvoiceMerging(POSInvoiceTestMixin):
def clear_pos_data(self): def clear_pos_data(self):
frappe.db.sql("delete from `tabPOS Opening Entry`;") frappe.db.delete("POS Opening Entry")
frappe.db.sql("delete from `tabPOS Closing Entry`;") frappe.db.delete("POS Closing Entry")
frappe.db.sql("delete from `tabPOS Invoice`;") frappe.db.delete("POS Invoice")
def setUp(self): def setUp(self):
self.clear_pos_data() self.clear_pos_data()

View File

@@ -25,15 +25,11 @@ class TestPOSProfile(ERPNextTestSuite):
items = get_items_list(doc, doc.company) items = get_items_list(doc, doc.company)
customers = get_customers_list(doc) customers = get_customers_list(doc)
products_count = frappe.db.sql( products_count = frappe.db.count("Item", {"item_group": "_Test Item Group"})
""" select count(name) from tabItem where item_group = '_Test Item Group'""", as_list=1 customers_count = frappe.db.count("Customer", {"customer_group": "_Test Customer Group"})
)
customers_count = frappe.db.sql(
""" select count(name) from tabCustomer where customer_group = '_Test Customer Group'"""
)
self.assertEqual(len(items), products_count[0][0]) self.assertEqual(len(items), products_count)
self.assertEqual(len(customers), customers_count[0][0]) self.assertEqual(len(customers), customers_count)
def test_disabled_pos_profile_creation(self): def test_disabled_pos_profile_creation(self):
make_pos_profile(name="_Test POS Profile 001", disabled=1) make_pos_profile(name="_Test POS Profile 001", disabled=1)
@@ -83,7 +79,6 @@ class TestPOSProfile(ERPNextTestSuite):
def get_customers_list(pos_profile=None): def get_customers_list(pos_profile=None):
if pos_profile is None: if pos_profile is None:
pos_profile = {} pos_profile = {}
cond = "1=1"
customer_groups = [] customer_groups = []
if pos_profile.get("customer_groups"): if pos_profile.get("customer_groups"):
# Get customers based on the customer groups defined in the POS profile # Get customers based on the customer groups defined in the POS profile
@@ -91,14 +86,16 @@ def get_customers_list(pos_profile=None):
customer_groups.extend( customer_groups.extend(
[d.get("name") for d in get_child_nodes("Customer Group", d.get("customer_group"))] [d.get("name") for d in get_child_nodes("Customer Group", d.get("customer_group"))]
) )
cond = "customer_group in ({})".format(", ".join(["%s"] * len(customer_groups)))
filters = {"disabled": 0}
if customer_groups:
filters["customer_group"] = ["in", customer_groups]
return ( return (
frappe.db.sql( frappe.get_all(
f""" select name, customer_name, customer_group, territory from tabCustomer where disabled = 0 "Customer",
and {cond}""", filters=filters,
tuple(customer_groups), fields=["name", "customer_name", "customer_group", "territory"],
as_dict=1,
) )
or {} or {}
) )
@@ -135,8 +132,8 @@ def get_items_list(pos_profile, company):
def make_pos_profile(**args): def make_pos_profile(**args):
frappe.db.sql("delete from `tabPOS Payment Method`") frappe.db.delete("POS Payment Method")
frappe.db.sql("delete from `tabPOS Profile`") frappe.db.delete("POS Profile")
args = frappe._dict(args) args = frappe._dict(args)

View File

@@ -91,7 +91,9 @@ class TestPricingRule(ERPNextTestSuite):
details = get_item_details(args) details = get_item_details(args)
self.assertEqual(details.get("discount_percentage"), 5) self.assertEqual(details.get("discount_percentage"), 5)
frappe.db.sql("update `tabPricing Rule` set priority=NULL where campaign='_Test Campaign'") frappe.db.set_value(
"Pricing Rule", {"campaign": "_Test Campaign"}, "priority", None, update_modified=False
)
from erpnext.accounts.doctype.pricing_rule.utils import MultiplePricingRuleConflict from erpnext.accounts.doctype.pricing_rule.utils import MultiplePricingRuleConflict
self.assertRaises(MultiplePricingRuleConflict, get_item_details, args) self.assertRaises(MultiplePricingRuleConflict, get_item_details, args)

View File

@@ -597,11 +597,21 @@ def execute_synced_report(filters):
def get_data_duckdb(filters, conn): def get_data_duckdb(filters, conn):
# accounts and all metadata via frappe.db — only GL Entry comes from DuckDB # accounts and all metadata via frappe.db — only GL Entry comes from DuckDB
accounts = frappe.db.sql( accounts = frappe.get_all(
"""select name, account_number, parent_account, account_name, root_type, report_type, is_group, lft, rgt "Account",
from `tabAccount` where company=%s order by lft""", filters={"company": filters.company},
filters.company, fields=[
as_dict=True, "name",
"account_number",
"parent_account",
"account_name",
"root_type",
"report_type",
"is_group",
"lft",
"rgt",
],
order_by="lft",
) )
if not accounts: if not accounts:
return None return None

View File

@@ -238,22 +238,13 @@ class TestAssetRepair(ERPNextTestSuite):
submit=1, submit=1,
) )
gl_entries = frappe.db.sql( gle = frappe.qb.DocType("GL Entry")
""" gl_entries = (
select frappe.qb.from_(gle)
account, .select(gle.account, Sum(gle.debit).as_("debit"), Sum(gle.credit).as_("credit"))
sum(debit) as debit, .where((gle.voucher_type == "Asset Repair") & (gle.voucher_no == asset_repair.name))
sum(credit) as credit .groupby(gle.account)
from `tabGL Entry` ).run(as_dict=True)
where
voucher_type='Asset Repair'
and voucher_no=%s
group by
account
""",
asset_repair.name,
as_dict=1,
)
self.assertTrue(gl_entries) self.assertTrue(gl_entries)
@@ -287,22 +278,13 @@ class TestAssetRepair(ERPNextTestSuite):
submit=1, submit=1,
) )
gl_entries = frappe.db.sql( gle = frappe.qb.DocType("GL Entry")
""" gl_entries = (
select frappe.qb.from_(gle)
account, .select(gle.account, Sum(gle.debit).as_("debit"), Sum(gle.credit).as_("credit"))
sum(debit) as debit, .where((gle.voucher_type == "Asset Repair") & (gle.voucher_no == asset_repair.name))
sum(credit) as credit .groupby(gle.account)
from `tabGL Entry` ).run(as_dict=True)
where
voucher_type='Asset Repair'
and voucher_no=%s
group by
account
""",
asset_repair.name,
as_dict=1,
)
self.assertTrue(gl_entries) self.assertTrue(gl_entries)

View File

@@ -94,11 +94,12 @@ class TestAssetValueAdjustment(ERPNextTestSuite):
("_Test Fixed Asset - _TC", 0.0, 4625.29), ("_Test Fixed Asset - _TC", 0.0, 4625.29),
) )
gle = frappe.db.sql( gle = frappe.get_all(
"""select account, debit, credit from `tabGL Entry` "GL Entry",
where voucher_type='Journal Entry' and voucher_no = %s filters={"voucher_type": "Journal Entry", "voucher_no": adj_doc.journal_entry},
order by account""", fields=["account", "debit", "credit"],
adj_doc.journal_entry, order_by="account",
as_list=True,
) )
self.assertSequenceEqual(gle, expected_gle) self.assertSequenceEqual(gle, expected_gle)
@@ -184,11 +185,12 @@ class TestAssetValueAdjustment(ERPNextTestSuite):
("_Test Fixed Asset - _TC", 0.0, 5175.29), ("_Test Fixed Asset - _TC", 0.0, 5175.29),
) )
gle = frappe.db.sql( gle = frappe.get_all(
"""select account, debit, credit from `tabGL Entry` "GL Entry",
where voucher_type='Journal Entry' and voucher_no = %s filters={"voucher_type": "Journal Entry", "voucher_no": adj_doc.journal_entry},
order by account""", fields=["account", "debit", "credit"],
adj_doc.journal_entry, order_by="account",
as_list=True,
) )
self.assertSequenceEqual(gle, expected_gle) self.assertSequenceEqual(gle, expected_gle)

View File

@@ -97,10 +97,10 @@ class TestBOM(ERPNextTestSuite):
update_cost_in_all_boms_in_test() update_cost_in_all_boms_in_test()
# check if new valuation rate updated in all BOMs # check if new valuation rate updated in all BOMs
for d in frappe.db.sql( for d in frappe.get_all(
"""select base_rate from `tabBOM Item` "BOM Item",
where item_code='_Test Item 2' and docstatus=1 and parenttype='BOM'""", filters={"item_code": "_Test Item 2", "docstatus": 1, "parenttype": "BOM"},
as_dict=1, fields=["base_rate"],
): ):
self.assertEqual(d.base_rate, rm_base_rate + 10) self.assertEqual(d.base_rate, rm_base_rate + 10)
@@ -881,12 +881,8 @@ def reset_item_valuation_rate(item_code, warehouse_list=None, qty=None, rate=Non
warehouse_list = [warehouse_list] warehouse_list = [warehouse_list]
if not warehouse_list: if not warehouse_list:
warehouse_list = frappe.db.sql_list( warehouse_list = frappe.get_all(
""" "Bin", filters={"item_code": item_code, "actual_qty": [">", 0]}, pluck="warehouse"
select warehouse from `tabBin`
where item_code=%s and actual_qty > 0
""",
item_code,
) )
if not warehouse_list: if not warehouse_list:

View File

@@ -5249,11 +5249,8 @@ def update_job_card(job_card, jc_qty=None, days=None):
def get_secondary_item_details(bom_no): def get_secondary_item_details(bom_no):
secondary_items = {} secondary_items = {}
for item in frappe.db.sql( for item in frappe.get_all(
"""select item_code, stock_qty from `tabBOM Secondary Item` "BOM Secondary Item", filters={"parent": bom_no}, fields=["item_code", "stock_qty"]
where parent = %s""",
bom_no,
as_dict=1,
): ):
secondary_items[item.item_code] = item.stock_qty secondary_items[item.item_code] = item.stock_qty

View File

@@ -49,7 +49,7 @@ class TestProject(ERPNextTestSuite):
def test_project_with_template_having_no_parent_and_depend_tasks(self): def test_project_with_template_having_no_parent_and_depend_tasks(self):
project_name = "Test Project with Template - No Parent and Dependend Tasks" project_name = "Test Project with Template - No Parent and Dependend Tasks"
frappe.db.sql(""" delete from tabTask where project = %s """, project_name) frappe.db.delete("Task", {"project": project_name})
frappe.delete_doc("Project", project_name) frappe.delete_doc("Project", project_name)
task1 = task_exists("Test Template Task with No Parent and Dependency") task1 = task_exists("Test Template Task with No Parent and Dependency")
@@ -82,7 +82,7 @@ class TestProject(ERPNextTestSuite):
if frappe.db.get_value("Project", {"project_name": project_name}, "name"): if frappe.db.get_value("Project", {"project_name": project_name}, "name"):
project_name = frappe.db.get_value("Project", {"project_name": project_name}, "name") project_name = frappe.db.get_value("Project", {"project_name": project_name}, "name")
frappe.db.sql(""" delete from tabTask where project = %s """, project_name) frappe.db.delete("Task", {"project": project_name})
frappe.delete_doc("Project", project_name) frappe.delete_doc("Project", project_name)
task1 = task_exists("Test Template Task Parent") task1 = task_exists("Test Template Task Parent")
@@ -137,7 +137,7 @@ class TestProject(ERPNextTestSuite):
def test_project_template_having_dependent_tasks(self): def test_project_template_having_dependent_tasks(self):
project_name = "Test Project with Template - Dependent Tasks" project_name = "Test Project with Template - Dependent Tasks"
frappe.db.sql(""" delete from tabTask where project = %s """, project_name) frappe.db.delete("Task", {"project": project_name})
frappe.delete_doc("Project", project_name) frappe.delete_doc("Project", project_name)
task1 = task_exists("Test Template Task for Dependency") task1 = task_exists("Test Template Task for Dependency")
@@ -252,7 +252,7 @@ class TestProject(ERPNextTestSuite):
def test_project_having_no_tasks_complete(self): def test_project_having_no_tasks_complete(self):
project_name = "Test Project - No Tasks Completion" project_name = "Test Project - No Tasks Completion"
frappe.db.sql(""" delete from tabTask where project = %s """, project_name) frappe.db.delete("Task", {"project": project_name})
frappe.delete_doc("Project", project_name) frappe.delete_doc("Project", project_name)
project = frappe.get_doc( project = frappe.get_doc(

View File

@@ -7,6 +7,7 @@ from unittest.mock import patch
import frappe import frappe
import frappe.permissions import frappe.permissions
from frappe.core.doctype.user_permission.test_user_permission import create_user from frappe.core.doctype.user_permission.test_user_permission import create_user
from frappe.query_builder.functions import Sum
from frappe.tests import change_settings from frappe.tests import change_settings
from frappe.utils import add_days, flt, getdate, nowdate, today from frappe.utils import add_days, flt, getdate, nowdate, today
@@ -907,10 +908,12 @@ class TestSalesOrder(ERPNextTestSuite):
item_doc.save() item_doc.save()
else: else:
# update valid from # update valid from
frappe.db.sql( frappe.db.set_value(
"""UPDATE `tabItem Tax` set valid_from = CURRENT_DATE "Item Tax",
where parent = %(item)s and item_tax_template = %(tax)s""", {"parent": item, "item_tax_template": tax_template},
{"item": item, "tax": tax_template}, "valid_from",
today(),
update_modified=False,
) )
so = make_sales_order(item_code=item, qty=1, do_not_save=1) so = make_sales_order(item_code=item, qty=1, do_not_save=1)
@@ -960,10 +963,12 @@ class TestSalesOrder(ERPNextTestSuite):
self.assertEqual(so.taxes[1].total, 480) self.assertEqual(so.taxes[1].total, 480)
# teardown # teardown
frappe.db.sql( frappe.db.set_value(
"""UPDATE `tabItem Tax` set valid_from = NULL "Item Tax",
where parent = %(item)s and item_tax_template = %(tax)s""", {"parent": item, "item_tax_template": tax_template},
{"item": item, "tax": tax_template}, "valid_from",
None,
update_modified=False,
) )
so.cancel() so.cancel()
so.delete() so.delete()
@@ -1559,10 +1564,12 @@ class TestSalesOrder(ERPNextTestSuite):
# Check if Work Orders were raised # Check if Work Orders were raised
for item in so_item_name: for item in so_item_name:
wo_qty = frappe.db.sql( wo = frappe.qb.DocType("Work Order")
"select sum(qty) from `tabWork Order` where sales_order=%s and sales_order_item=%s", wo_qty = (
(so.name, item), frappe.qb.from_(wo)
) .select(Sum(wo.qty))
.where((wo.sales_order == so.name) & (wo.sales_order_item == item))
).run()
self.assertEqual(wo_qty[0][0], so_item_name.get(item)) self.assertEqual(wo_qty[0][0], so_item_name.get(item))
def test_advance_payment_entry_unlink_against_sales_order(self): def test_advance_payment_entry_unlink_against_sales_order(self):
@@ -1742,9 +1749,7 @@ class TestSalesOrder(ERPNextTestSuite):
mr_dict["include_exploded_items"] = 0 mr_dict["include_exploded_items"] = 0
mr_dict["ignore_existing_ordered_qty"] = 1 mr_dict["ignore_existing_ordered_qty"] = 1
make_raw_material_request(mr_dict, so.company, so.name) make_raw_material_request(mr_dict, so.company, so.name)
mr = frappe.db.sql( mr = frappe.get_all("Material Request", fields=["name"], order_by="creation desc", limit=1)[0]
"""select name from `tabMaterial Request` ORDER BY creation DESC LIMIT 1""", as_dict=1
)[0]
mr_doc = frappe.get_doc("Material Request", mr.get("name")) mr_doc = frappe.get_doc("Material Request", mr.get("name"))
self.assertEqual(mr_doc.items[0].sales_order, so.name) self.assertEqual(mr_doc.items[0].sales_order, so.name)

View File

@@ -2,6 +2,7 @@
# License: GNU General Public License v3. See license.txt # License: GNU General Public License v3. See license.txt
import frappe import frappe
from frappe.query_builder.functions import Max
from frappe.utils.nestedset import ( from frappe.utils.nestedset import (
NestedSetChildExistsError, NestedSetChildExistsError,
NestedSetInvalidMergeError, NestedSetInvalidMergeError,
@@ -20,7 +21,8 @@ class TestItemGroup(ERPNextTestSuite):
def test_basic_tree(self, records=None): def test_basic_tree(self, records=None):
min_lft = 1 min_lft = 1
max_rgt = frappe.db.sql("select max(rgt) from `tabItem Group`")[0][0] ig = frappe.qb.DocType("Item Group")
max_rgt = frappe.qb.from_(ig).select(Max(ig.rgt)).run()[0][0]
if not records: if not records:
records = self.globalTestRecords["Item Group"][2:] records = self.globalTestRecords["Item Group"][2:]
@@ -131,12 +133,7 @@ class TestItemGroup(ERPNextTestSuite):
frappe.db.get_value("Item Group", parent_item_group, "rgt") frappe.db.get_value("Item Group", parent_item_group, "rgt")
ancestors = get_ancestors_of("Item Group", "_Test Item Group B - 3") ancestors = get_ancestors_of("Item Group", "_Test Item Group B - 3")
ancestors = frappe.db.sql( ancestors = frappe.get_all("Item Group", filters={"name": ["in", ancestors]}, fields=["name", "rgt"])
"""select name, rgt from `tabItem Group`
where name in ({})""".format(", ".join(["%s"] * len(ancestors))),
tuple(ancestors),
as_dict=True,
)
frappe.delete_doc("Item Group", "_Test Item Group B - 3") frappe.delete_doc("Item Group", "_Test Item Group B - 3")
records_to_test = self.globalTestRecords["Item Group"][2:] records_to_test = self.globalTestRecords["Item Group"][2:]
@@ -168,9 +165,8 @@ class TestItemGroup(ERPNextTestSuite):
self.test_basic_tree() self.test_basic_tree()
# move its children back # move its children back
for name in frappe.db.sql_list( for name in frappe.get_all(
"""select name from `tabItem Group` "Item Group", filters={"parent_item_group": "_Test Item Group C"}, pluck="name"
where parent_item_group='_Test Item Group C'"""
): ):
doc = frappe.get_doc("Item Group", name) doc = frappe.get_doc("Item Group", name)
doc.parent_item_group = "_Test Item Group B" doc.parent_item_group = "_Test Item Group B"
@@ -218,11 +214,7 @@ class TestItemGroup(ERPNextTestSuite):
def get_no_of_children(item_groups, no_of_children): def get_no_of_children(item_groups, no_of_children):
children = [] children = []
for ig in item_groups: for ig in item_groups:
children += frappe.db.sql_list( children += frappe.get_all("Item Group", filters={"parent_item_group": ig}, pluck="name")
"""select name from `tabItem Group`
where ifnull(parent_item_group, '')=%s""",
ig or "",
)
if len(children): if len(children):
return get_no_of_children(children, no_of_children + len(children)) return get_no_of_children(children, no_of_children + len(children))

View File

@@ -746,11 +746,11 @@ class TestMaterialRequest(ERPNextTestSuite):
mr = frappe.get_doc("Material Request", mr.name) mr = frappe.get_doc("Material Request", mr.name)
mr.submit() mr.submit()
completed_qty = mr.items[0].ordered_qty completed_qty = mr.items[0].ordered_qty
requested_qty = frappe.db.sql( requested_qty = frappe.db.get_value(
"""select indented_qty from `tabBin` where \ "Bin",
item_code= %s and warehouse= %s """, {"item_code": mr.items[0].item_code, "warehouse": mr.items[0].warehouse},
(mr.items[0].item_code, mr.items[0].warehouse), "indented_qty",
)[0][0] )
prod_order = raise_work_orders(mr.name, mr.company) prod_order = raise_work_orders(mr.name, mr.company)
po = frappe.get_doc("Work Order", prod_order[0]) po = frappe.get_doc("Work Order", prod_order[0])
@@ -760,11 +760,11 @@ class TestMaterialRequest(ERPNextTestSuite):
mr = frappe.get_doc("Material Request", mr.name) mr = frappe.get_doc("Material Request", mr.name)
self.assertEqual(completed_qty + po.qty, mr.items[0].ordered_qty) self.assertEqual(completed_qty + po.qty, mr.items[0].ordered_qty)
new_requested_qty = frappe.db.sql( new_requested_qty = frappe.db.get_value(
"""select indented_qty from `tabBin` where \ "Bin",
item_code= %s and warehouse= %s """, {"item_code": mr.items[0].item_code, "warehouse": mr.items[0].warehouse},
(mr.items[0].item_code, mr.items[0].warehouse), "indented_qty",
)[0][0] )
self.assertEqual(requested_qty - po.qty, new_requested_qty) self.assertEqual(requested_qty - po.qty, new_requested_qty)
@@ -773,11 +773,11 @@ class TestMaterialRequest(ERPNextTestSuite):
mr = frappe.get_doc("Material Request", mr.name) mr = frappe.get_doc("Material Request", mr.name)
self.assertEqual(completed_qty, mr.items[0].ordered_qty) self.assertEqual(completed_qty, mr.items[0].ordered_qty)
new_requested_qty = frappe.db.sql( new_requested_qty = frappe.db.get_value(
"""select indented_qty from `tabBin` where \ "Bin",
item_code= %s and warehouse= %s """, {"item_code": mr.items[0].item_code, "warehouse": mr.items[0].warehouse},
(mr.items[0].item_code, mr.items[0].warehouse), "indented_qty",
)[0][0] )
self.assertEqual(requested_qty, new_requested_qty) self.assertEqual(requested_qty, new_requested_qty)
def test_requested_qty_multi_uom(self): def test_requested_qty_multi_uom(self):

View File

@@ -40,19 +40,12 @@ from erpnext.tests.utils import ERPNextTestSuite
def get_sle(**args): def get_sle(**args):
condition, values = "", [] return frappe.get_all(
for key, value in args.items(): "Stock Ledger Entry",
condition += " and " if condition else " where " filters=args,
condition += f"`{key}`=%s" fields=["*"],
values.append(value) order_by="posting_datetime desc, creation desc",
limit=1,
return frappe.db.sql(
# posting_datetime is the precomputed date+time column; MySQL-only timestamp(date,time) errors on Postgres
"""select * from `tabStock Ledger Entry` %s
order by posting_datetime desc, creation desc limit 1"""
% condition,
values,
as_dict=1,
) )
@@ -269,20 +262,10 @@ class TestStockEntry(ERPNextTestSuite):
mr.cancel() mr.cancel()
self.assertTrue( self.assertTrue(
frappe.db.sql( frappe.db.exists("Stock Ledger Entry", {"voucher_type": "Stock Entry", "voucher_no": mr.name})
"""select * from `tabStock Ledger Entry`
where voucher_type='Stock Entry' and voucher_no=%s""",
mr.name,
)
) )
self.assertTrue( self.assertTrue(frappe.db.exists("GL Entry", {"voucher_type": "Stock Entry", "voucher_no": mr.name}))
frappe.db.sql(
"""select * from `tabGL Entry`
where voucher_type='Stock Entry' and voucher_no=%s""",
mr.name,
)
)
def test_material_issue_gl_entry(self): def test_material_issue_gl_entry(self):
company = frappe.db.get_value("Warehouse", "Stores - TCP1", "company") company = frappe.db.get_value("Warehouse", "Stores - TCP1", "company")
@@ -361,12 +344,7 @@ class TestStockEntry(ERPNextTestSuite):
if source_warehouse_account == target_warehouse_account: if source_warehouse_account == target_warehouse_account:
# no gl entry as both source and target warehouse has linked to same account. # no gl entry as both source and target warehouse has linked to same account.
self.assertFalse( self.assertFalse(
frappe.db.sql( frappe.db.exists("GL Entry", {"voucher_type": "Stock Entry", "voucher_no": mtn.name})
"""select * from `tabGL Entry`
where voucher_type='Stock Entry' and voucher_no=%s""",
mtn.name,
as_dict=1,
)
) )
else: else:
@@ -460,14 +438,9 @@ class TestStockEntry(ERPNextTestSuite):
], ],
) )
gl_entries = frappe.db.sql( self.assertFalse(
"""select account, debit, credit frappe.db.exists("GL Entry", {"voucher_type": "Stock Entry", "voucher_no": repack.name})
from `tabGL Entry` where voucher_type='Stock Entry' and voucher_no=%s
order by account desc""",
repack.name,
as_dict=1,
) )
self.assertFalse(gl_entries)
def test_repack_with_additional_costs(self): def test_repack_with_additional_costs(self):
company = frappe.db.get_value("Warehouse", "Stores - TCP1", "company") company = frappe.db.get_value("Warehouse", "Stores - TCP1", "company")
@@ -601,15 +574,15 @@ class TestStockEntry(ERPNextTestSuite):
expected_sle.sort(key=lambda x: x[1]) expected_sle.sort(key=lambda x: x[1])
# check stock ledger entries # check stock ledger entries
sle = frappe.db.sql( sle = frappe.get_all(
"""select item_code, warehouse, actual_qty "Stock Ledger Entry",
from `tabStock Ledger Entry` where voucher_type = %s filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
and voucher_no = %s order by item_code, warehouse, actual_qty""", fields=["item_code", "warehouse", "actual_qty"],
(voucher_type, voucher_no), order_by="item_code, warehouse, actual_qty",
as_list=1, as_list=True,
) )
self.assertTrue(sle) self.assertTrue(sle)
sle.sort(key=lambda x: x[1]) sle = sorted(sle, key=lambda x: x[1])
for i, sle_value in enumerate(sle): for i, sle_value in enumerate(sle):
self.assertEqual(expected_sle[i][0], sle_value[0]) self.assertEqual(expected_sle[i][0], sle_value[0])
@@ -619,16 +592,16 @@ class TestStockEntry(ERPNextTestSuite):
def check_gl_entries(self, voucher_type, voucher_no, expected_gl_entries): def check_gl_entries(self, voucher_type, voucher_no, expected_gl_entries):
expected_gl_entries.sort(key=lambda x: x[0]) expected_gl_entries.sort(key=lambda x: x[0])
gl_entries = frappe.db.sql( gl_entries = frappe.get_all(
"""select account, debit, credit "GL Entry",
from `tabGL Entry` where voucher_type=%s and voucher_no=%s filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
order by account asc, debit asc""", fields=["account", "debit", "credit"],
(voucher_type, voucher_no), order_by="account asc, debit asc",
as_list=1, as_list=True,
) )
self.assertTrue(gl_entries) self.assertTrue(gl_entries)
gl_entries.sort(key=lambda x: x[0]) gl_entries = sorted(gl_entries, key=lambda x: x[0])
for i, gle in enumerate(gl_entries): for i, gle in enumerate(gl_entries):
self.assertEqual(expected_gl_entries[i][0], gle[0]) self.assertEqual(expected_gl_entries[i][0], gle[0])
self.assertEqual(expected_gl_entries[i][1], gle[1]) self.assertEqual(expected_gl_entries[i][1], gle[1])

View File

@@ -85,11 +85,10 @@ class TestStockReconciliation(ERPNextTestSuite, StockTestMixin):
) )
# check stock value # check stock value
sle = frappe.db.sql( sle = frappe.get_all(
"""select * from `tabStock Ledger Entry` "Stock Ledger Entry",
where voucher_type='Stock Reconciliation' and voucher_no=%s""", filters={"voucher_type": "Stock Reconciliation", "voucher_no": stock_reco.name},
stock_reco.name, fields=["qty_after_transaction", "stock_value"],
as_dict=1,
) )
qty_after_transaction = flt(d[0]) if d[0] != "" else flt(last_sle.get("qty_after_transaction")) qty_after_transaction = flt(d[0]) if d[0] != "" else flt(last_sle.get("qty_after_transaction"))

View File

@@ -19,11 +19,10 @@ class TestWarehouse(ERPNextTestSuite):
def test_warehouse_hierarchy(self): def test_warehouse_hierarchy(self):
p_warehouse = frappe.get_doc("Warehouse", "_Test Warehouse Group - _TC") p_warehouse = frappe.get_doc("Warehouse", "_Test Warehouse Group - _TC")
child_warehouses = frappe.db.sql( child_warehouses = frappe.get_all(
"""select name, is_group, parent_warehouse from `tabWarehouse` wh "Warehouse",
where wh.lft > %s and wh.rgt < %s""", filters={"lft": [">", p_warehouse.lft], "rgt": ["<", p_warehouse.rgt]},
(p_warehouse.lft, p_warehouse.rgt), fields=["name", "is_group", "parent_warehouse"],
as_dict=1,
) )
for child_warehouse in child_warehouses: for child_warehouse in child_warehouses:

View File

@@ -14,11 +14,11 @@ from erpnext.tests.utils import ERPNextTestSuite
class TestSetUp(ERPNextTestSuite): class TestSetUp(ERPNextTestSuite):
def setUp(self): def setUp(self):
frappe.db.sql("delete from `tabService Level Agreement`") frappe.db.delete("Service Level Agreement")
frappe.db.sql("delete from `tabService Level Priority`") frappe.db.delete("Service Level Priority")
frappe.db.sql("delete from `tabSLA Fulfilled On Status`") frappe.db.delete("SLA Fulfilled On Status")
frappe.db.sql("delete from `tabPause SLA On Status`") frappe.db.delete("Pause SLA On Status")
frappe.db.sql("delete from `tabService Day`") frappe.db.delete("Service Day")
frappe.db.set_single_value("Support Settings", "track_service_level_agreement", 1) frappe.db.set_single_value("Support Settings", "track_service_level_agreement", 1)
create_service_level_agreements_for_issues() create_service_level_agreements_for_issues()