Skip to content

Queries

Query

scylla_bridge.query.Query

Bases: ABC

Generic query expression.

build_query abstractmethod

build_query()

Builds the query into a string and its parameters as a list.

Returns:

Type Description
Tuple[str, List[Any]]

The query string and the corresponding parameters.

Source code in scylla_bridge/query.py
37
38
39
40
41
42
43
44
45
46
@abstractmethod
def build_query(self) -> Tuple[str, List[Any]]:
    """Builds the query into a string and its parameters as a list.

    Returns
    -------
    Tuple[str, List[Any]]
        The query string and the corresponding parameters.
    """
    raise NotImplementedError

execute async

execute(scylla_instance)

Executes the query using a Scylla instance.

Parameters:

Name Type Description Default
scylla_instance Scylla

The Scylla instance used to execute the query.

required

Returns:

Type Description
Any

The result of the executed query.

Source code in scylla_bridge/query.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
async def execute(self, scylla_instance: Scylla) -> Any:
    """Executes the query using a Scylla instance.

    Parameters
    ----------
    scylla_instance : Scylla
        The Scylla instance used to execute the query.

    Returns
    -------
    Any
        The result of the executed query.
    """
    query, parameters = self.build_query()
    result = await scylla_instance.execute(query, parameters)
    return result

Select

scylla_bridge.query.Select

Select(*columns)

Bases: Query

Select query from Scylla.

Initializes the Select query.

Parameters:

Name Type Description Default
*columns Column or AggregateExpr or Type[Table]

The columns to be selected in the query.

()
Source code in scylla_bridge/query.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def __init__(self, *columns: Column | AggregateExpr | Type[Table]) -> None:
    """Initializes the Select query.

    Parameters
    ----------
    *columns : Column or AggregateExpr or Type[Table]
        The columns to be selected in the query.
    """
    assert len(columns) > 0, "Select expression cannot be empty!"

    if inspect.isclass(columns[0]) and issubclass(columns[0], Table):
        self._table = columns[0].__tablename__
        self._keyspace = columns[0].__keyspace__
        self._select = "*"
        self._columns: List[Column | AggregateExpr] = []
    else:
        self._table: str = columns[0]._table  # type:ignore
        self._keyspace: str = columns[0]._keyspace  # type:ignore
        assert all(
            [
                isinstance(col, (Column, AggregateExpr))
                and (col._table == self._table)
                and (col._keyspace == self._keyspace)
                for col in columns
            ]
        ), "Columns do not originate from the same table or is invalid"
        self._select = ", ".join(
            [
                (
                    f"{col._name}{f' AS {col.rename}' if col.rename is not None else ''}"
                    if isinstance(col, Column)
                    else f"{col.operator}({col._name}){f' AS {col.rename}' if col.rename is not None else ''}"  # type:ignore
                )
                for col in columns
            ]
        )
        self._columns = columns  # type:ignore

    self._where: List[ColumnExpr] = []
    self._allow_filtering: bool = False
    self._limit: int = 0
    self._distinct: bool = False
    self._group_by: Optional[str] = None

allow_filtering

allow_filtering()

Enables the 'ALLOW FILTERING' option in the query.

Returns:

Type Description
Select

The updated Select query with 'ALLOW FILTERING' enabled.

Source code in scylla_bridge/query.py
107
108
109
110
111
112
113
114
115
116
117
118
119
def allow_filtering(self) -> Select:
    """Enables the 'ALLOW FILTERING' option in the query.

    Returns
    -------
    Select
        The updated Select query with 'ALLOW FILTERING' enabled.
    """
    logger.warning(
        "Allow filtering usually leads to degraded performance. Consider reviewing your query."
    )
    self._allow_filtering = True
    return self

build_query

build_query()

Builds the SELECT query into a string and its parameters.

Returns:

Type Description
Tuple[str, List[Any]]

The query string and the corresponding parameters.

Source code in scylla_bridge/query.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def build_query(self) -> Tuple[str, List[Any]]:
    """Builds the SELECT query into a string and its parameters.

    Returns
    -------
    Tuple[str, List[Any]]
        The query string and the corresponding parameters.
    """
    query = f"SELECT {'DISTINCT' if self._distinct else ''} {self._select} FROM {self._keyspace}.{self._table}"
    parameters = []
    if self._where:
        predicates = []
        for predicate in self._where:
            predicates.append(f"{predicate._name} {predicate.operator} ?")
            parameters.append(predicate.value)
        query = f"{query} WHERE {' AND '.join(predicates)}"
    if self._group_by:
        query = f"{query} GROUP BY {self._group_by}"
    if self._limit:
        query = f"{query} LIMIT {self._limit}"
    if self._allow_filtering:
        query = f"{query} ALLOW FILTERING"
    return query, parameters

distinct

distinct()

Enables the DISTINCT option in the query.

Returns:

Type Description
Select

The updated Select query with DISTINCT enabled.

Source code in scylla_bridge/query.py
188
189
190
191
192
193
194
195
196
197
def distinct(self) -> Select:
    """Enables the DISTINCT option in the query.

    Returns
    -------
    Select
        The updated Select query with DISTINCT enabled.
    """
    self._distinct = True
    return self

execute async

execute(scylla_instance)

Executes the query using a Scylla instance.

Parameters:

Name Type Description Default
scylla_instance Scylla

The Scylla instance used to execute the query.

required

Returns:

Type Description
Any

The result of the executed query.

Source code in scylla_bridge/query.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
async def execute(self, scylla_instance: Scylla) -> Any:
    """Executes the query using a Scylla instance.

    Parameters
    ----------
    scylla_instance : Scylla
        The Scylla instance used to execute the query.

    Returns
    -------
    Any
        The result of the executed query.
    """
    query, parameters = self.build_query()
    result = await scylla_instance.execute(query, parameters)
    return result

group_by

group_by(*columns)

Adds GROUP BY conditions to the query.

Parameters:

Name Type Description Default
*columns Column

The columns to group by in the query.

()

Returns:

Type Description
Select

The updated Select query with GROUP BY conditions.

Source code in scylla_bridge/query.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@validate_call
def group_by(self, *columns: Column) -> Select:
    """Adds GROUP BY conditions to the query.

    Parameters
    ----------
    *columns : Column
        The columns to group by in the query.

    Returns
    -------
    Select
        The updated Select query with GROUP BY conditions.
    """
    assert len(columns) > 0, "group_by condition cannot be empty!"
    assert all(
        [
            (col._table == self._table) and (col._keyspace == self._keyspace)
            for col in columns
        ]
    ), "Columns do not originate from the same table"
    self._group_by = ", ".join([str(column._name) for column in columns])
    return self

limit

limit(_limit)

Sets a limit on the number of rows returned by the query.

Parameters:

Name Type Description Default
_limit int

The maximum number of rows to return.

required

Returns:

Type Description
Select

The updated Select query with a limit.

Source code in scylla_bridge/query.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@validate_call
def limit(self, _limit: int) -> Select:
    """Sets a limit on the number of rows returned by the query.

    Parameters
    ----------
    _limit : int
        The maximum number of rows to return.

    Returns
    -------
    Select
        The updated Select query with a limit.
    """
    assert _limit > 0, "Limit cannot be null nor negative"
    self._limit = _limit
    return self

where

where(*predicates)

Adds WHERE conditions to the query.

Parameters:

Name Type Description Default
*predicates ColumnExpr

The column expressions to be used in the WHERE clause.

()

Returns:

Type Description
Select

The updated Select query with WHERE conditions.

Source code in scylla_bridge/query.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
@validate_call
def where(self, *predicates: ColumnExpr) -> Select:
    """Adds WHERE conditions to the query.

    Parameters
    ----------
    *predicates : ColumnExpr
        The column expressions to be used in the WHERE clause.

    Returns
    -------
    Select
        The updated Select query with WHERE conditions.
    """
    assert len(predicates) > 0, "where condition cannot be empty!"
    assert all(
        [
            (predicate._table == self._table)
            and (predicate._keyspace == self._keyspace)
            for predicate in predicates
        ]
    ), "Columns do not originate from the same table"
    self._where.extend(predicates)
    return self

Update

scylla_bridge.query.Update

Update(table)

Bases: Query

Update query.

Initializes the Update query.

Parameters:

Name Type Description Default
table Type[Table]

The table to be updated.

required
Source code in scylla_bridge/query.py
227
228
229
230
231
232
233
234
235
236
237
238
239
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def __init__(self, table: Type[Table]):
    """Initializes the Update query.

    Parameters
    ----------
    table : Type[Table]
        The table to be updated.
    """
    self._table = table
    self._keyspace = table.__keyspace__
    self._where: List[ColumnExpr] = []
    self._set_values: Dict[str, Any] = {}

build_query

build_query()

Builds the UPDATE query into a string and its parameters.

Returns:

Type Description
Tuple[str, List[Any]]

The query string and the corresponding parameters.

Source code in scylla_bridge/query.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def build_query(self) -> Tuple[str, List[Any]]:
    """Builds the UPDATE query into a string and its parameters.

    Returns
    -------
    Tuple[str, List[Any]]
        The query string and the corresponding parameters.
    """
    if not self._set_values:
        raise ValueError("No SET in update query!")

    set_keys, parameters = [], []

    for key, value in self._set_values.items():

        set_keys.append(f"{key} = ?")
        parameters.append(value)

    set_values = ", ".join(set_keys)
    query = f"UPDATE {self._keyspace}.{self._table.__tablename__} SET {set_values}"

    if self._where:
        predicates = []
        for predicate in self._where:
            predicates.append(f"{predicate._name} {predicate.operator} ?")
            parameters.append(predicate.value)
        query = f"{query} WHERE {' AND '.join(predicates)}"
    return query, parameters

execute async

execute(scylla_instance)

Executes the query using a Scylla instance.

Parameters:

Name Type Description Default
scylla_instance Scylla

The Scylla instance used to execute the query.

required

Returns:

Type Description
Any

The result of the executed query.

Source code in scylla_bridge/query.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
async def execute(self, scylla_instance: Scylla) -> Any:
    """Executes the query using a Scylla instance.

    Parameters
    ----------
    scylla_instance : Scylla
        The Scylla instance used to execute the query.

    Returns
    -------
    Any
        The result of the executed query.
    """
    query, parameters = self.build_query()
    result = await scylla_instance.execute(query, parameters)
    return result

set

set(column, value)

Sets the values to be updated in the query.

Parameters:

Name Type Description Default
column Column

The column to update.

required
value Any

The new value for the column.

required

Returns:

Type Description
Update

The updated Update query with the new SET values.

Source code in scylla_bridge/query.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
@validate_call
def set(self, column: Column, value: Any) -> Update:
    """Sets the values to be updated in the query.

    Parameters
    ----------
    column : Column
        The column to update.
    value : Any
        The new value for the column.

    Returns
    -------
    Update
        The updated Update query with the new SET values.
    """
    assert column._name != None, "Column is not associated with a table!"
    self._set_values[column._name] = value
    return self

where

where(*predicates)

Adds WHERE conditions to the update query.

Parameters:

Name Type Description Default
*predicates ColumnExpr

The column expressions to be used in the WHERE clause.

()

Returns:

Type Description
Update

The updated Update query with WHERE conditions.

Source code in scylla_bridge/query.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
@validate_call
def where(self, *predicates: ColumnExpr) -> Update:
    """Adds WHERE conditions to the update query.

    Parameters
    ----------
    *predicates : ColumnExpr
        The column expressions to be used in the WHERE clause.

    Returns
    -------
    Update
        The updated Update query with WHERE conditions.
    """
    assert len(predicates) > 0, "where condition cannot be empty!"
    assert all(
        [
            (predicate._table == self._table.__tablename__)
            and (predicate._keyspace == self._keyspace)
            for predicate in predicates
        ]
    ), "Columns do not originate from the same table"
    self._where.extend(predicates)
    return self

Delete

scylla_bridge.query.Delete

Delete(table)

Bases: Query

Delete query.

Initializes the Delete query.

Parameters:

Name Type Description Default
table Type[Table]

The table from which records are to be deleted.

required
Source code in scylla_bridge/query.py
319
320
321
322
323
324
325
326
327
328
329
330
331
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def __init__(self, table: Type[Table]):
    """Initializes the Delete query.

    Parameters
    ----------
    table : Type[Table]
        The table from which records are to be deleted.
    """
    self._table = table
    self._keyspace = table.__keyspace__
    self._where: List[ColumnExpr] = []
    self._if_exists: bool = False

build_query

build_query()

Builds the DELETE query into a string and its parameters.

Returns:

Type Description
Tuple[str, List[Any]]

The query string and the corresponding parameters.

Source code in scylla_bridge/query.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def build_query(self) -> Tuple[str, List[Any]]:
    """Builds the DELETE query into a string and its parameters.

    Returns
    -------
    Tuple[str, List[Any]]
        The query string and the corresponding parameters.
    """
    query = f"DELETE FROM {self._keyspace}.{self._table.__tablename__}"
    parameters = []
    if self._where:
        predicates = []
        for predicate in self._where:
            predicates.append(f"{predicate._name} {predicate.operator} ?")
            parameters.append(predicate.value)
        query = f"{query} WHERE {' AND '.join(predicates)}"
    if self._if_exists:
        query = f"{query} IF EXISTS"
    return query, parameters

execute async

execute(scylla_instance)

Executes the query using a Scylla instance.

Parameters:

Name Type Description Default
scylla_instance Scylla

The Scylla instance used to execute the query.

required

Returns:

Type Description
Any

The result of the executed query.

Source code in scylla_bridge/query.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
async def execute(self, scylla_instance: Scylla) -> Any:
    """Executes the query using a Scylla instance.

    Parameters
    ----------
    scylla_instance : Scylla
        The Scylla instance used to execute the query.

    Returns
    -------
    Any
        The result of the executed query.
    """
    query, parameters = self.build_query()
    result = await scylla_instance.execute(query, parameters)
    return result

if_exists

if_exists()

Adds the IF EXISTS clause to the query.

Returns:

Type Description
Delete

The updated Delete query with IF EXISTS enabled.

Source code in scylla_bridge/query.py
333
334
335
336
337
338
339
340
341
342
def if_exists(self) -> Delete:
    """Adds the IF EXISTS clause to the query.

    Returns
    -------
    Delete
        The updated Delete query with IF EXISTS enabled.
    """
    self._if_exists = True
    return self

where

where(*predicates)

Adds WHERE conditions to the delete query.

Parameters:

Name Type Description Default
*predicates ColumnExpr

The column expressions to be used in the WHERE clause.

()

Returns:

Type Description
Delete

The updated Delete query with WHERE conditions.

Source code in scylla_bridge/query.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
@validate_call
def where(self, *predicates: ColumnExpr) -> Delete:
    """Adds WHERE conditions to the delete query.

    Parameters
    ----------
    *predicates : ColumnExpr
        The column expressions to be used in the WHERE clause.

    Returns
    -------
    Delete
        The updated Delete query with WHERE conditions.
    """
    assert len(predicates) > 0, "where condition cannot be empty!"
    assert all(
        [
            (predicate._table == self._table.__tablename__)
            and (predicate._keyspace == self._keyspace)
            for predicate in predicates
        ]
    ), "Columns do not originate from the same table"
    self._where.extend(predicates)
    return self

Insert

scylla_bridge.query.Insert

Insert(table)

Bases: Query

Insert query.

Suboptimal way to insert, as the "best way" is to batch insert using directly scyllaft.

Initializes the Insert query.

Parameters:

Name Type Description Default
table Type[Table]

The table into which records are to be inserted.

required
Source code in scylla_bridge/query.py
396
397
398
399
400
401
402
403
404
405
406
407
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def __init__(self, table: Type[Table]):
    """Initializes the Insert query.

    Parameters
    ----------
    table : Type[Table]
        The table into which records are to be inserted.
    """
    self._table = table
    self._keyspace = table.__keyspace__
    self._values: List[dict] = []

build_query

build_query()

Builds the DELETE query into a string and its parameters.

Returns:

Type Description
Tuple[str, List[Any]]

The query string and the corresponding parameters.

Source code in scylla_bridge/query.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def build_query(self) -> List[Tuple[str, List[Any]]]:  # type:ignore
    """Builds the DELETE query into a string and its parameters.

    Returns
    -------
    Tuple[str, List[Any]]
        The query string and the corresponding parameters.
    """
    query = f"INSERT INTO {self._keyspace}.{self._table.__tablename__}"
    queries = []
    for stmt in self._values:
        c, v = zip(*stmt.items())
        queries.append(
            (
                f"{query} ({', '.join(c)}) VALUES ({', '.join(['?' for i in c])})",
                list(v),
            )
        )
    if not queries:
        raise ValueError("No data to insert!")
    return queries

execute async

execute(scylla_instance)

Executes the query using a Scylla instance.

Parameters:

Name Type Description Default
scylla_instance Scylla

The Scylla instance used to execute the query.

required

Returns:

Type Description
Any

The result of the executed query.

Source code in scylla_bridge/query.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
async def execute(self, scylla_instance: Scylla) -> Any:
    """Executes the query using a Scylla instance.

    Parameters
    ----------
    scylla_instance : Scylla
        The Scylla instance used to execute the query.

    Returns
    -------
    Any
        The result of the executed query.
    """
    queries = self.build_query()
    result = []
    for query, parameters in list(queries):
        result.append(await scylla_instance.execute(query, parameters))
    return result

values

values(*values)

Specifies the values to be inserted.

Parameters:

Name Type Description Default
*values Table

The values to be inserted into the table.

()

Returns:

Type Description
Insert

The updated Insert query with values.

Source code in scylla_bridge/query.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
@validate_call()
def values(self, *values: dict) -> Insert:
    """Specifies the values to be inserted.

    Parameters
    ----------
    *values : Table
        The values to be inserted into the table.

    Returns
    -------
    Insert
        The updated Insert query with values.
    """
    self._values.extend(values)
    return self