# Buggy code
def set_gl_entries_by_account(
    company,
    from_date,
    to_date,
    root_lft,
    root_rgt,
    filters,
    gl_entries_by_account,
    ignore_closing_entries=False,
):
    """Returns a dict like { "account": [gl entries], ... }"""

    additional_conditions = get_additional_conditions(
        from_date, ignore_closing_entries, filters
    )

    accounts = frappe.db.sql_list(
        """select name from `tabAccount`
		where lft >= %s and rgt <= %s and company = %s""",
        (root_lft, root_rgt, company),
    )

    if accounts:
        additional_conditions += " and account in ({})".format(
            ", ".join([frappe.db.escape(d) for d in accounts])
        )

        gl_filters = {
            "company": company,
            "from_date": from_date,
            "to_date": to_date,
            "finance_book": cstr(filters.get("finance_book")),
        }

        if filters.get("include_default_book_entries"):
            gl_filters["company_fb"] = frappe.db.get_value(
                "Company", company, "default_finance_book"
            )

        for key, value in filters.items():
            if value:
                gl_filters.update({key: value})

        distributed_cost_center_query = ""
        if filters and filters.get("cost_center"):
            distributed_cost_center_query = """
			UNION ALL
			SELECT posting_date,
				account,
				debit*(DCC_allocation.percentage_allocation/100) as debit,
				credit*(DCC_allocation.percentage_allocation/100) as credit,
				is_opening,
				fiscal_year,
				debit_in_account_currency*(DCC_allocation.percentage_allocation/100) as debit_in_account_currency,
				credit_in_account_currency*(DCC_allocation.percentage_allocation/100) as credit_in_account_currency,
				account_currency
			FROM `tabGL Entry`,
			(
				SELECT parent, sum(percentage_allocation) as percentage_allocation
				FROM `tabDistributed Cost Center`
				WHERE cost_center IN %(cost_center)s
				AND parent NOT IN %(cost_center)s
				GROUP BY parent
			) as DCC_allocation
			WHERE company=%(company)s
			{additional_conditions}
			AND posting_date <= %(to_date)s
			AND is_cancelled = 0
			AND cost_center = DCC_allocation.parent
			""".format(
                additional_conditions=additional_conditions.replace(
                    "and cost_center in %(cost_center)s ", ""
                )
            )

        gl_entries = frappe.db.sql(
            """select posting_date, account, debit, credit, is_opening, fiscal_year, debit_in_account_currency, credit_in_account_currency, account_currency from `tabGL Entry`
			where company=%(company)s
			{additional_conditions}
			and posting_date <= %(to_date)s
			and is_cancelled = 0
			{distributed_cost_center_query}
			order by account, posting_date""".format(
                additional_conditions=additional_conditions,
                distributed_cost_center_query=distributed_cost_center_query,
            ),
            gl_filters,
            as_dict=True,
        )  # nosec

        if filters and filters.get("presentation_currency"):
            convert_to_presentation_currency(gl_entries, get_currency(filters))

        for entry in gl_entries:
            gl_entries_by_account.setdefault(entry.account, []).append(entry)

        return gl_entries_by_account


# Traceback (pymysql.err.ProgrammingError)
$ bench --site test.site install-app erpnext

Installing erpnext...
Updating DocTypes for erpnext       : [===                                     ] 9%An error occurred while installing erpnext:
Traceback (most recent call last):
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/commands/site.py", line 215, in install_app
_install_app(app, verbose=context.verbose)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/installer.py", line 84, in install_app
sync_for(name, force=True, sync_everything=True, verbose=verbose, reset_permissions=True)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/sync.py", line 69, in sync_for
import_file_by_path(doc_path, force=force, ignore_version=True,
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/modules/import_file.py", line 69, in import_file_by_path
import_doc(doc, force=force, data_import=data_import, pre_process=pre_process,
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/modules/import_file.py", line 143, in import_doc
doc.insert()
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/document.py", line 268, in insert
self.run_post_save_methods()
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/document.py", line 964, in run_post_save_methods
self.run_method("on_update")
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/document.py", line 831, in run_method
out = Document.hook(fn)(self, *args, **kwargs)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/document.py", line 1116, in composer
return composed(self, method, *args, **kwargs)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/document.py", line 1099, in runner
add_to_return_value(self, fn(self, *args, **kwargs))
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/document.py", line 825, in <lambda>
fn = lambda self, *args, **kwargs: getattr(self, method)(*args, **kwargs)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/core/doctype/doctype/doctype.py", line 291, in on_update
self.run_module_method("on_doctype_update")
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/core/doctype/doctype/doctype.py", line 357, in run_module_method
module = load_doctype_module(self.name, self.module)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/modules/utils.py", line 204, in load_doctype_module
doctype_python_modules[key] = frappe.get_module(module_name)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/__init__.py", line 858, in get_module
return importlib.import_module(modulename)
File "/home/haris/myproject/frappe-bench/env/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/haris/myproject/frappe-bench/apps/erpnext/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py", line 8, in <module>
from erpnext.accounts.report.general_ledger.general_ledger import execute as get_soa
File "/home/haris/myproject/frappe-bench/apps/erpnext/erpnext/accounts/report/general_ledger/general_ledger.py", line 7, in <module>
from erpnext.accounts.report.utils import get_currency, convert_to_presentation_currency
File "/home/haris/myproject/frappe-bench/apps/erpnext/erpnext/accounts/report/utils.py", line 10, in <module>
sum(frappe.get_list('Account', fields=['name'], or_filters=[{'root_type': 'Income'}, {'root_type': 'Expense'}], as_list=True), ())
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/__init__.py", line 1329, in get_list
return frappe.model.db_query.DatabaseQuery(doctype).execute(None, *args, **kwargs)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/db_query.py", line 96, in execute
result = self.build_and_run()
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/db_query.py", line 110, in build_and_run
args = self.prepare_args()
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/db_query.py", line 136, in prepare_args
self.set_optional_columns()
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/db_query.py", line 302, in set_optional_columns
columns = get_table_columns(self.doctype)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/model/meta.py", line 49, in get_table_columns
return frappe.db.get_table_columns(doctype)
File "/home/haris/myproject/frappe-bench/apps/frappe/frappe/database/database.py", line 893, in get_table_columns
raise self.TableMissingError('DocType', doctype)
pymysql.err.ProgrammingError: ('DocType', 'Account')

# Fixed code
def set_gl_entries_by_account(
    company,
    from_date,
    to_date,
    root_lft,
    root_rgt,
    filters,
    gl_entries_by_account,
    ignore_closing_entries=False,
):
    """Returns a dict like { "account": [gl entries], ... }"""

    additional_conditions = get_additional_conditions(
        from_date, ignore_closing_entries, filters
    )

    accounts = frappe.db.sql_list(
        """select name from `tabAccount`
		where lft >= %s and rgt <= %s and company = %s""",
        (root_lft, root_rgt, company),
    )

    if accounts:
        additional_conditions += " and account in ({})".format(
            ", ".join([frappe.db.escape(d) for d in accounts])
        )

        gl_filters = {
            "company": company,
            "from_date": from_date,
            "to_date": to_date,
            "finance_book": cstr(filters.get("finance_book")),
        }

        if filters.get("include_default_book_entries"):
            gl_filters["company_fb"] = frappe.db.get_value(
                "Company", company, "default_finance_book"
            )

        for key, value in filters.items():
            if value:
                gl_filters.update({key: value})

        distributed_cost_center_query = ""
        if filters and filters.get("cost_center"):
            distributed_cost_center_query = """
			UNION ALL
			SELECT posting_date,
				account,
				debit*(DCC_allocation.percentage_allocation/100) as debit,
				credit*(DCC_allocation.percentage_allocation/100) as credit,
				is_opening,
				fiscal_year,
				debit_in_account_currency*(DCC_allocation.percentage_allocation/100) as debit_in_account_currency,
				credit_in_account_currency*(DCC_allocation.percentage_allocation/100) as credit_in_account_currency,
				account_currency
			FROM `tabGL Entry`,
			(
				SELECT parent, sum(percentage_allocation) as percentage_allocation
				FROM `tabDistributed Cost Center`
				WHERE cost_center IN %(cost_center)s
				AND parent NOT IN %(cost_center)s
				GROUP BY parent
			) as DCC_allocation
			WHERE company=%(company)s
			{additional_conditions}
			AND posting_date <= %(to_date)s
			AND is_cancelled = 0
			AND cost_center = DCC_allocation.parent
			""".format(
                additional_conditions=additional_conditions.replace(
                    "and cost_center in %(cost_center)s ", ""
                )
            )

        gl_entries = frappe.db.sql(
            """select posting_date, account, debit, credit, is_opening, fiscal_year, debit_in_account_currency, credit_in_account_currency, account_currency from `tabGL Entry`
			where company=%(company)s
			{additional_conditions}
			and posting_date <= %(to_date)s
			and is_cancelled = 0
			{distributed_cost_center_query}
			order by account, posting_date""".format(
                additional_conditions=additional_conditions,
                distributed_cost_center_query=distributed_cost_center_query,
            ),
            gl_filters,
            as_dict=True,
        )  # nosec

        if filters and filters.get("presentation_currency"):
            convert_to_presentation_currency(
                gl_entries, get_currency(filters), filters.get("company")
            )

        for entry in gl_entries:
            gl_entries_by_account.setdefault(entry.account, []).append(entry)

        return gl_entries_by_account