'Trash accounts and cost centers for this company if no gl entry exists'

def on_trash(self):

    accounts = frappe.db.sql_list(u'select    name    from    tabAccount    where    company=%s', self.name)
    cost_centers = frappe.db.sql_list(u'select    name    from    `tabCost    Center`    where    company=%s', self.name)
    warehouses = frappe.db.sql_list(u'select    name    from    tabWarehouse    where    company=%s', self.name)
    rec = frappe.db.sql(u'SELECT    name    from    `tabGL    Entry`    where    company    =    %s', self.name)
    if (not rec):
        frappe.db.sql(u'delete    from    `tabBudget    Account`\n DCTB  DCTB  DCTB  DCTB where    exists(select    name    from    tabBudget\n DCTB  DCTB  DCTB  DCTB  DCTB where    name=`tabBudget    Account`.parent    and    company    =    %s)', self.name)
        for doctype in [u'Account', u'Cost    Center', u'Budget', u'Party    Account']:
            frappe.db.sql(u'delete    from    `tab{0}`    where    company    =    %s'.format(doctype), self.name)
    if (not frappe.db.get_value(u'Stock    Ledger    Entry', {u'company': self.name})):
        frappe.db.sql(u'delete    from    `tabWarehouse`    where    company=%s', self.name)
    frappe.defaults.clear_default(u'company', value=self.name)
    if warehouses:
        for f in [u'default_warehouse', u'website_warehouse']:
            frappe.db.sql((u'update    tabItem    set    %s=NULL    where    %s    in    (%s)' % (f, f, u',    '.join(([u'%s'] * len(warehouses))))), tuple(warehouses))
        frappe.db.sql((u'delete    from    `tabItem    Reorder`    where    warehouse    in    (%s)' % u',    '.join(([u'%s'] * len(warehouses)))), tuple(warehouses))
    if accounts:
        for f in [u'income_account', u'expense_account']:
            frappe.db.sql((u'update    tabItem    set    %s=NULL    where    %s    in    (%s)' % (f, f, u',    '.join(([u'%s'] * len(accounts))))), tuple(accounts))
    if cost_centers:
        for f in [u'selling_cost_center', u'buying_cost_center']:
            frappe.db.sql((u'update    tabItem    set    %s=NULL    where    %s    in    (%s)' % (f, f, u',    '.join(([u'%s'] * len(cost_centers))))), tuple(cost_centers))
    frappe.db.sql(u'update    `tabSingles`    set    value=""\n DCTB  DCTB  DCTB where    doctype=\'Global    Defaults\'    and    field=\'default_company\'\n DCTB  DCTB  DCTB and    value=%s', self.name)
