Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions cqlsl/statements/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ def __init__(self, *args, **kwargs):
BaseStatement.__init__(self, *args, **kwargs)
WhereClauseMixin.__init__(self)
self._fields_to_select = []
self._fields_to_order_by = []
self._limit = None
self._allow_filtering = False

def fields(self, *fields_to_select):
self._fields_to_select = fields_to_select
Expand All @@ -19,6 +21,14 @@ def limit(self, limit_to):
self._limit = limit_to
return self

def order_by(self, *fields_to_order_by):
self._fields_to_order_by = fields_to_order_by
return self

def allow_filtering(self):
self._allow_filtering = True
return self

@property
def query(self):
query_ = 'SELECT {fields_clause} FROM {table}'.format(
Expand All @@ -29,9 +39,15 @@ def query(self):
if self._where_conditions:
query_ += ' WHERE {}'.format(self._get_where_clause())

if self._fields_to_order_by:
query_ += ' ORDER BY {}'.format(self._get_ordering_clause())

if self._limit:
query_ += ' LIMIT %s'

if self._allow_filtering:
query_ += ' ALLOW FILTERING'

return query_

@property
Expand All @@ -46,5 +62,17 @@ def context(self):
def _get_fields_clause(self):
return ', '.join(self._fields_to_select) or '*'

def _get_ordering_clause(self):
ordering = []
for field in self._fields_to_order_by:
if field.startswith('-'):
ordering.append('{} DESC'.format(field[1:]))
elif field.startswith('+'):
ordering.append('{} ASC'.format(field[1:]))
else:
ordering.append('{} ASC'.format(field))

return ', '.join(ordering)


select = SelectStatement
12 changes: 12 additions & 0 deletions tests/units/test_statements.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ def test_select_with_limit(self):
self.assertEqual('SELECT * FROM test_table LIMIT %s', stmt.query)
self.assertEqual((10,), stmt.context)

def test_select_with_ordering(self):
stmt = select('test_table').where(id=1).order_by('date', '-order').limit(10)

self.assertEqual('SELECT * FROM test_table WHERE id = %s ORDER BY date ASC, order DESC LIMIT %s', stmt.query)
self.assertEqual((1, 10), stmt.context)

def test_select_with_allow_filtering(self):
stmt = select('test_table').where(id__gt=1).allow_filtering()

self.assertEqual('SELECT * FROM test_table WHERE id > %s ALLOW FILTERING', stmt.query)
self.assertEqual((1,), stmt.context)

def test_delete(self):
stmt = delete('test_table').where(some_id=1)

Expand Down