# Buggy code
def delete_lead_addresses(company_name):
    """Delete addresses to which leads are linked"""
    leads = frappe.get_all("Lead", filters={"company": 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 
			in ({leads})""".format(leads=",".join(leads))
        )

        if addresses:
            addresses = ["'%s'" % 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 
				and dl1.link_doctype<>dl2.link_doctype)""".format(
                    addresses=",".join(addresses)
                )
            )

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


# Traceback (ProgrammingError)
Traceback (most recent call last):
File "/home/frappe/frappe-bench/apps/frappe/frappe/app.py", line 62, in application
response = frappe.handler.handle()
File "/home/frappe/frappe-bench/apps/frappe/frappe/handler.py", line 22, in handle
data = execute_cmd(cmd)
File "/home/frappe/frappe-bench/apps/frappe/frappe/handler.py", line 53, in execute_cmd
return frappe.call(method, **frappe.form_dict)
File "/home/frappe/frappe-bench/apps/frappe/frappe/__init__.py", line 939, in call
return fn(*args, **newargs)
File "/home/frappe/frappe-bench/apps/erpnext/erpnext/setup/doctype/company/delete_company_transactions.py", line 21, in delete_company_transactions
delete_lead_addresses(company_name)
File "/home/frappe/frappe-bench/apps/erpnext/erpnext/setup/doctype/company/delete_company_transactions.py", line 93, in delete_lead_addresses
and dl1.link_doctype<>dl2.link_doctype)""".format(addresses=",".join(addresses)))
File "/home/frappe/frappe-bench/apps/frappe/frappe/database.py", line 176, in sql
self._cursor.execute(query)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/cursors.py", line 165, in execute
result = self._query(query)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/cursors.py", line 321, in _query
conn.query(q)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/connections.py", line 860, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/connections.py", line 1061, in _read_query_result
result.read()
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/connections.py", line 1349, in read
first_packet = self.connection._read_packet()
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/connections.py", line 1018, in _read_packet
packet.check_error()
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/connections.py", line 384, in check_error
err.raise_mysql_exception(self._data)
File "/home/frappe/frappe-bench/env/local/lib/python2.7/site-packages/pymysql/err.py", line 107, in raise_mysql_exception
raise errorclass(errno, errval)
ProgrammingError: (1064, u"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's Seafood-Billing','New Wave Seafood-Billing','Sea Well Seafood, Inc.-Billing','' at line 1")

# Fixed code
def delete_lead_addresses(company_name):
    """Delete addresses to which leads are linked"""
    leads = frappe.get_all("Lead", filters={"company": 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 
			in ({leads})""".format(leads=",".join(leads))
        )

        if 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 
				and dl1.link_doctype<>dl2.link_doctype)""".format(
                    addresses=",".join(addresses)
                )
            )

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