Skip to content

Commit

Permalink
Introduce count method (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
Antony1060 authored Jun 19, 2023
1 parent 2e2d212 commit ebbbf24
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const selectFromRaw = <
extra?: string
): QueryBuild => ({
query: `SELECT ${
select == '*' ? select : select.join(',')
Array.isArray(select) ? select.join(',') : select
} FROM ${keyspace}.${table} ${
criteria && Object.keys(criteria).length > 0
? 'WHERE ' + renderCriteria(criteria)
Expand All @@ -68,12 +68,12 @@ export const selectOneFromRaw = <
>(
keyspace: string,
table: F,
select: '*' | (keyof TableMap[F])[],
select: '*' | (keyof TableMap[F])[] | (string & {}),
criteria?: Criteria<TableMap[F]>,
extra?: string
): QueryBuild => ({
query: `SELECT ${
select == '*' ? select : select.join(',')
Array.isArray(select) ? select.join(',') : select
} FROM ${keyspace}.${table} ${
criteria && Object.keys(criteria).length > 0
? 'WHERE ' + renderCriteria(criteria)
Expand Down
33 changes: 32 additions & 1 deletion src/ScylloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const fromObjectScyllo = (
) =>
Object.assign(
{},
...row.keys().map((item: any) => ({
...row.keys().map((item) => ({
[item]: ensureExistingCollections(
fromScyllo(row.get(item)),
encodingOptions,
Expand Down Expand Up @@ -223,6 +223,37 @@ export class ScylloClient<Tables extends TableScheme> {
fromObjectScyllo(row, this.encodingOptions, result.columns)
) as Pick<Tables[TableName], ColumnName>[];
}

/**
* count rows
* in a table and return based on criteria.
*/
async count<TableName extends keyof Tables>(
table: TableName,
criteria?: Criteria<Tables[TableName]>,
extra?: string
): Promise<bigint> {
const query = selectOneFromRaw<Tables, TableName>(
this.keyspace,
table,
'COUNT(*)',
criteria,
extra
);
const result = await this.query(query);

const rows: Record<string, unknown>[] = result.rows.map((row) =>
fromObjectScyllo(row, this.encodingOptions, result.columns)
);

const entry = rows.at(0);

if (!entry || !('count' in entry) || typeof entry.count !== 'bigint')
throw new Error('invalid cassandra response');

return entry.count;
}

/**
* Select one from
* a table and return based on criteria.
Expand Down

0 comments on commit ebbbf24

Please sign in to comment.