+import ldap
+
+from django.db.models.sql import aggregates, compiler
+from django.db.models.sql.where import AND, OR
+
+def get_lookup_operator(lookup_type):
+ if lookup_type == 'gte':
+ return '>='
+ elif lookup_type == 'lte':
+ return '<='
+ else:
+ return '='
+
+def query_as_ldap(query):
+ filterstr = ''.join(['(objectClass=%s)' % cls for cls in query.model.object_classes])
+ sql, params = where_as_ldap(query.where)
+ filterstr += sql
+ return '(&%s)' % filterstr
+
+def where_as_ldap(self):
+ bits = []
+ for item in self.children:
+ if hasattr(item, 'as_sql'):
+ sql, params = where_as_ldap(item)
+ bits.append(sql)
+ continue
+
+ constraint, lookup_type, y, values = item
+ comp = get_lookup_operator(lookup_type)
+ if lookup_type == 'in':
+ equal_bits = [ "(%s%s%s)" % (constraint.col, comp, value) for value in values ]
+ clause = '(|%s)' % ''.join(equal_bits)
+ else:
+ clause = "(%s%s%s)" % (constraint.col, comp, values)
+
+ bits.append(clause)
+
+ if not len(bits):
+ return '', []
+
+ if len(bits) == 1:
+ sql_string = bits[0]
+ elif self.connector == AND:
+ sql_string = '(&%s)' % ''.join(bits)
+ elif self.connector == OR:
+ sql_string = '(|%s)' % ''.join(bits)
+ else:
+ raise Exception("Unhandled WHERE connector: %s" % self.connector)
+
+ if self.negated:
+ sql_string = ('(!%s)' % sql_string)
+
+ return sql_string, []
+