# Buggy code
def _format_conditions(self, filters, id_field, modified_field, prefix="filters"):
    """Format the filters list in SQL, with placeholders for safe escaping.

    .. note::
        All conditions are combined using AND.

    .. note::

        Field name and value are escaped as they come from HTTP API.

    :returns: A SQL string with placeholders, and a dict mapping
        placeholders to actual values.
    :rtype: tuple
    """
    operators = {
        COMPARISON.EQ: "=",
        COMPARISON.NOT: "<>",
        COMPARISON.IN: "IN",
        COMPARISON.EXCLUDE: "NOT IN",
    }

    conditions = []
    holders = {}
    for i, filtr in enumerate(filters):
        value = filtr.value

        if filtr.field == id_field:
            sql_field = "id"
        elif filtr.field == modified_field:
            sql_field = "as_epoch(last_modified)"
        else:
            # Safely escape field name
            field_holder = "%s_field_%s" % (prefix, i)
            holders[field_holder] = filtr.field

            # JSON operator ->> retrieves values as text.
            # If field is missing, we default to ''.
            sql_field = "coalesce(data->>:%s, '')" % field_holder
            if isinstance(value, (int, float)) and value not in (True, False):
                sql_field = "(data->>:%s)::numeric" % field_holder

        if filtr.operator not in (COMPARISON.IN, COMPARISON.EXCLUDE):
            # For the IN operator, let psycopg escape the values list.
            # Otherwise JSON-ify the native value (e.g. True -> 'true')
            if not isinstance(filtr.value, six.string_types):
                value = json.dumps(filtr.value).strip('"')
        else:
            value = tuple(value)

        # Safely escape value
        value_holder = "%s_value_%s" % (prefix, i)
        holders[value_holder] = value

        sql_operator = operators.setdefault(filtr.operator, filtr.operator.value)
        cond = "%s %s :%s" % (sql_field, sql_operator, value_holder)
        conditions.append(cond)

    safe_sql = " AND ".join(conditions)
    return safe_sql, holders


# Traceback (BackendError)
{"Pid":4280,"EnvVersion":"2.0","Hostname":"ip-172-31-4-126","Timestamp":1462794460764000000,"Fields":{"lang":null,"exception":"Traceback (most recent call last):
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/tweens.py\", line 20, in excview_tween
response = handler(request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid_tm\/__init__.py\", line 101, in tm_tween
reraise(*exc_info)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid_tm\/__init__.py\", line 83, in tm_tween
response = handler(request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/router.py\", line 145, in handle_request
view_name
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/view.py\", line 541, in _call_view
response = view_callable(context, request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/config\/views.py\", line 602, in __call__
return view(context, request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/config\/views.py\", line 328, in attr_view
return view(context, request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/config\/views.py\", line 304, in predicate_wrapper
return view(context, request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/config\/views.py\", line 244, in _secured_view
return view(context, request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/config\/views.py\", line 353, in rendered_view
result = view(context, request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/pyramid\/config\/views.py\", line 507, in _requestonly_view
response = view(request)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/cornice\/service.py\", line 571, in wrapper
response = view_()
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/kinto\/views\/records.py\", line 76, in collection_get
result = super(Record, self).collection_get()
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/cliquet\/resource\/__init__.py\", line 240, in collection_get
include_deleted=include_deleted)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/cliquet\/resource\/model.py\", line 104, in get_records
auth=self.auth)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/cliquet\/storage\/postgresql\/__init__.py\", line 538, in get_all
retrieved = result.fetchmany(self._max_fetch_size)
File \"\/usr\/lib64\/python2.7\/contextlib.py\", line 35, in __exit__
self.gen.throw(type, value, traceback)
File \"\/data\/kinto-dist\/lib\/python2.7\/site-packages\/cliquet\/storage\/postgresql\/client.py\", line 53, in connect
raise exceptions.BackendError(original=e)
BackendError: ProgrammingError: (psycopg2.ProgrammingError) operator does not exist: text <> integer
LINE 7:                AND id NOT IN (1)
^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
[SQL: '\
WITH total_filtered AS (\
SELECT COUNT(id) AS count\
FROM records\
WHERE parent_id = %(parent_id)s\
AND collection_id = %(collection_id)s\
AND id NOT IN %(filters_value_0)s\
),\
collection_filtered AS (\
SELECT id, last_modified, data\
FROM records\
WHERE parent_id = %(parent_id)s\
AND collection_id = %(collection_id)s\
AND id NOT IN %(filters_value_0)s\
LIMIT 10000\
),\
fake_deleted AS (\
SELECT (%(deleted_field)s)::JSONB AS data\
),\
filtered_deleted AS (\
SELECT id, last_modified, fake_deleted.data AS data\
FROM deleted, fake_deleted\
WHERE parent_id = %(parent_id)s\
AND collection_id = %(collection_id)s\
AND id NOT IN %(filters_value_0)s\
LIMIT 0\
),\
all_records AS (\
SELECT * FROM filtered_deleted\
UNION ALL\
SELECT * FROM collection_filtered\
),\
paginated_records AS (\
SELECT DISTINCT id\
FROM all_records\
\
)\
SELECT total_filtered.count AS count_total,\
a.id, as_epoch(a.last_modified) AS last_modified, a.data\
FROM paginated_records AS p JOIN all_records AS a ON (a.id = p.id),\
total_filtered\
ORDER BY last_modified DESC\
;\
'] [parameters: {'collection_id': 'record', 'deleted_field': '{\"deleted\":true}', 'parent_id': u'\/buckets\/blocklists\/collections\/certificates', 'filters_value_0': (1,)}]","uid":null,"errno":null,"querystring":"{\"exclude_id\":\"1\"}","agent":"Amazon CloudFront","method":"GET","collection_id":"record","path":"\/v1\/buckets\/blocklists\/collections\/certificates\/records","authn_type":null,"collection_timestamp":1461920076590},"Logger":"kinto","Type":["(psycopg2.ProgrammingError) operator does not exist: text <> integer
LINE 7:                AND id NOT IN (1)
^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
"],"Severity":0}

# Fixed code
def _format_conditions(self, filters, id_field, modified_field, prefix="filters"):
    """Format the filters list in SQL, with placeholders for safe escaping.

    .. note::
        All conditions are combined using AND.

    .. note::

        Field name and value are escaped as they come from HTTP API.

    :returns: A SQL string with placeholders, and a dict mapping
        placeholders to actual values.
    :rtype: tuple
    """
    operators = {
        COMPARISON.EQ: "=",
        COMPARISON.NOT: "<>",
        COMPARISON.IN: "IN",
        COMPARISON.EXCLUDE: "NOT IN",
    }

    conditions = []
    holders = {}
    for i, filtr in enumerate(filters):
        value = filtr.value

        if filtr.field == id_field:
            sql_field = "id"
        elif filtr.field == modified_field:
            sql_field = "as_epoch(last_modified)"
        else:
            # Safely escape field name
            field_holder = "%s_field_%s" % (prefix, i)
            holders[field_holder] = filtr.field

            # JSON operator ->> retrieves values as text.
            # If field is missing, we default to ''.
            sql_field = "coalesce(data->>:%s, '')" % field_holder
            if isinstance(value, (int, float)) and value not in (True, False):
                sql_field = "(data->>:%s)::numeric" % field_holder

        if filtr.operator not in (COMPARISON.IN, COMPARISON.EXCLUDE):
            # For the IN operator, let psycopg escape the values list.
            # Otherwise JSON-ify the native value (e.g. True -> 'true')
            if not isinstance(filtr.value, six.string_types):
                value = json.dumps(filtr.value).strip('"')
        else:
            value = tuple(value)
            if filtr.field == id_field:
                value = tuple(
                    [v if isinstance(v, six.string_types) else None for v in value]
                )
            if filtr.field == modified_field:
                value = tuple(
                    [v if isinstance(v, six.integer_types) else None for v in value]
                )

        # Safely escape value
        value_holder = "%s_value_%s" % (prefix, i)
        holders[value_holder] = value

        sql_operator = operators.setdefault(filtr.operator, filtr.operator.value)
        cond = "%s %s :%s" % (sql_field, sql_operator, value_holder)
        conditions.append(cond)

    safe_sql = " AND ".join(conditions)
    return safe_sql, holders