# Buggy code
def rebuild_for_doctype(doctype):
    """
    Rebuild entries of doctype's documents in __global_search on change of
    searchable fields
    :param doctype: Doctype
    """
    if frappe.local.conf.get("disable_global_search"):
        return

    if frappe.local.conf.get("disable_global_search"):
        return

    def _get_filters():
        filters = frappe._dict({"docstatus": ["!=", 2]})
        if meta.has_field("enabled"):
            filters.enabled = 1
        if meta.has_field("disabled"):
            filters.disabled = 0

        return filters

    meta = frappe.get_meta(doctype)
    if cint(meta.istable) == 1:
        parent_doctypes = frappe.get_all(
            "DocField",
            fields="parent",
            filters={
                "fieldtype": ["in", frappe.model.table_fields],
                "options": doctype,
            },
        )
        for p in parent_doctypes:
            rebuild_for_doctype(p.parent)

        return

    # Delete records
    delete_global_search_records_for_doctype(doctype)

    parent_search_fields = meta.get_global_search_fields()
    fieldnames = get_selected_fields(meta, parent_search_fields)

    # Get all records from parent doctype table
    all_records = frappe.get_all(doctype, fields=fieldnames, filters=_get_filters())

    # Children data
    all_children, child_search_fields = get_children_data(doctype, meta)
    all_contents = []

    for doc in all_records:
        content = []
        for field in parent_search_fields:
            value = doc.get(field.fieldname)
            if value:
                content.append(get_formatted_value(value, field))

        # get children data
        for child_doctype, records in all_children.get(doc.name, {}).items():
            for field in child_search_fields.get(child_doctype):
                for r in records:
                    if r.get(field.fieldname):
                        content.append(
                            get_formatted_value(r.get(field.fieldname), field)
                        )

        if content:
            # if doctype published in website, push title, route etc.
            published = 0
            title, route = "", ""
            try:
                if (
                    hasattr(get_controller(doctype), "is_website_published")
                    and meta.allow_guest_to_view
                ):
                    d = frappe.get_doc(doctype, doc.name)
                    published = 1 if d.is_website_published() else 0
                    title = d.get_title()
                    route = d.get("route")
            except ImportError:
                # some doctypes has been deleted via future patch, hence controller does not exists
                pass

            all_contents.append(
                {
                    "doctype": frappe.db.escape(doctype),
                    "name": frappe.db.escape(doc.name),
                    "content": frappe.db.escape(" ||| ".join(content or "")),
                    "published": published,
                    "title": frappe.db.escape(title or "")[
                        : int(frappe.db.VARCHAR_LEN)
                    ],
                    "route": frappe.db.escape(route or "")[
                        : int(frappe.db.VARCHAR_LEN)
                    ],
                }
            )
    if all_contents:
        insert_values_for_multiple_docs(all_contents)


# Traceback (pymysql.err.ProgrammingError)
Traceback (most recent call last):
File "/usr/lib/python3.5/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/bob/frappe-bench/apps/frappe/frappe/utils/bench_helper.py", line 97, in <module>
main()
File "/home/bob/frappe-bench/apps/frappe/frappe/utils/bench_helper.py", line 18, in main
click.Group(commands=commands)(prog_name='bench')
File "/home/bob/frappe-bench/env/lib/python3.5/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/home/bob/frappe-bench/env/lib/python3.5/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/home/bob/frappe-bench/env/lib/python3.5/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/bob/frappe-bench/env/lib/python3.5/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/bob/frappe-bench/env/lib/python3.5/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/bob/frappe-bench/env/lib/python3.5/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/home/bob/frappe-bench/env/lib/python3.5/site-packages/click/decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "/home/bob/frappe-bench/apps/frappe/frappe/commands/__init__.py", line 25, in _func
ret = f(frappe._dict(ctx.obj), *args, **kwargs)
File "/home/bob/frappe-bench/apps/frappe/frappe/commands/utils.py", line 677, in rebuild_global_search
rebuild_for_doctype(doctype)
File "/home/bob/frappe-bench/apps/frappe/frappe/utils/global_search.py", line 101, in rebuild_for_doctype
all_records = frappe.get_all(doctype, fields=fieldnames, filters=_get_filters())
File "/home/bob/frappe-bench/apps/frappe/frappe/__init__.py", line 1302, in get_all
return get_list(doctype, *args, **kwargs)
File "/home/bob/frappe-bench/apps/frappe/frappe/__init__.py", line 1275, in get_list
return frappe.model.db_query.DatabaseQuery(doctype).execute(None, *args, **kwargs)
File "/home/bob/frappe-bench/apps/frappe/frappe/model/db_query.py", line 96, in execute
result = self.build_and_run()
File "/home/bob/frappe-bench/apps/frappe/frappe/model/db_query.py", line 110, in build_and_run
args = self.prepare_args()
File "/home/bob/frappe-bench/apps/frappe/frappe/model/db_query.py", line 136, in prepare_args
self.set_optional_columns()
File "/home/bob/frappe-bench/apps/frappe/frappe/model/db_query.py", line 294, in set_optional_columns
columns = get_table_columns(self.doctype)
File "/home/bob/frappe-bench/apps/frappe/frappe/model/meta.py", line 49, in get_table_columns
return frappe.db.get_table_columns(doctype)
File "/home/bob/frappe-bench/apps/frappe/frappe/database/database.py", line 864, in get_table_columns
raise self.TableMissingError('DocType', doctype)
pymysql.err.ProgrammingError: ('DocType', 'Quick Stock Balance')

# Fixed code
def rebuild_for_doctype(doctype):
    """
    Rebuild entries of doctype's documents in __global_search on change of
    searchable fields
    :param doctype: Doctype
    """
    if frappe.local.conf.get("disable_global_search"):
        return

    if frappe.local.conf.get("disable_global_search"):
        return

    def _get_filters():
        filters = frappe._dict({"docstatus": ["!=", 2]})
        if meta.has_field("enabled"):
            filters.enabled = 1
        if meta.has_field("disabled"):
            filters.disabled = 0

        return filters

    meta = frappe.get_meta(doctype)

    if cint(meta.issingle) == 1:
        return

    if cint(meta.istable) == 1:
        parent_doctypes = frappe.get_all(
            "DocField",
            fields="parent",
            filters={
                "fieldtype": ["in", frappe.model.table_fields],
                "options": doctype,
            },
        )
        for p in parent_doctypes:
            rebuild_for_doctype(p.parent)

        return

    # Delete records
    delete_global_search_records_for_doctype(doctype)

    parent_search_fields = meta.get_global_search_fields()
    fieldnames = get_selected_fields(meta, parent_search_fields)

    # Get all records from parent doctype table
    all_records = frappe.get_all(doctype, fields=fieldnames, filters=_get_filters())

    # Children data
    all_children, child_search_fields = get_children_data(doctype, meta)
    all_contents = []

    for doc in all_records:
        content = []
        for field in parent_search_fields:
            value = doc.get(field.fieldname)
            if value:
                content.append(get_formatted_value(value, field))

        # get children data
        for child_doctype, records in all_children.get(doc.name, {}).items():
            for field in child_search_fields.get(child_doctype):
                for r in records:
                    if r.get(field.fieldname):
                        content.append(
                            get_formatted_value(r.get(field.fieldname), field)
                        )

        if content:
            # if doctype published in website, push title, route etc.
            published = 0
            title, route = "", ""
            try:
                if (
                    hasattr(get_controller(doctype), "is_website_published")
                    and meta.allow_guest_to_view
                ):
                    d = frappe.get_doc(doctype, doc.name)
                    published = 1 if d.is_website_published() else 0
                    title = d.get_title()
                    route = d.get("route")
            except ImportError:
                # some doctypes has been deleted via future patch, hence controller does not exists
                pass

            all_contents.append(
                {
                    "doctype": frappe.db.escape(doctype),
                    "name": frappe.db.escape(doc.name),
                    "content": frappe.db.escape(" ||| ".join(content or "")),
                    "published": published,
                    "title": frappe.db.escape(title or "")[
                        : int(frappe.db.VARCHAR_LEN)
                    ],
                    "route": frappe.db.escape(route or "")[
                        : int(frappe.db.VARCHAR_LEN)
                    ],
                }
            )
    if all_contents:
        insert_values_for_multiple_docs(all_contents)