signal-desktop/ts/sql/util.ts

426 lines
10 KiB
TypeScript
Raw Normal View History

2021-10-26 22:59:08 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
2024-11-06 19:27:54 +00:00
/* eslint-disable max-classes-per-file */
2021-10-26 22:59:08 +00:00
import { isNumber, last } from 'lodash';
2024-07-22 18:16:33 +00:00
import type { ReadableDB, WritableDB } from './Interface';
2021-10-26 22:59:08 +00:00
export type EmptyQuery = [];
export type ArrayQuery = Array<ReadonlyArray<null | number | bigint | string>>;
2022-08-03 17:10:49 +00:00
export type Query = {
[key: string]: null | number | bigint | string | Uint8Array;
};
2021-10-26 22:59:08 +00:00
export type JSONRows = Array<{ readonly json: string }>;
export type TableType =
| 'attachment_downloads'
| 'conversations'
| 'identityKeys'
| 'items'
| 'kyberPreKeys'
2021-10-26 22:59:08 +00:00
| 'messages'
| 'preKeys'
| 'senderKeys'
| 'sessions'
| 'signedPreKeys'
| 'stickers'
| 'unprocessed';
// This value needs to be below SQLITE_MAX_VARIABLE_NUMBER.
const MAX_VARIABLE_COUNT = 100;
export function objectToJSON<T>(data: T): string {
return JSON.stringify(data);
}
export function jsonToObject<T>(json: string): T {
return JSON.parse(json);
}
2024-05-20 18:15:39 +00:00
export type QueryTemplateParam =
| Uint8Array
| string
| number
| null
| undefined;
2023-03-20 22:23:53 +00:00
export type QueryFragmentValue = QueryFragment | QueryTemplateParam;
2024-11-06 19:27:54 +00:00
export class QueryFragment {
constructor(
public readonly fragment: string,
public readonly fragmentParams: ReadonlyArray<QueryTemplateParam>
) {}
}
2023-03-20 22:23:53 +00:00
/**
* You can use tagged template literals to build "fragments" of SQL queries
*
* ```ts
* const [query, params] = sql`
* SELECT * FROM examples
* WHERE groupId = ${groupId}
* ORDER BY timestamp ${asc ? sqlFragment`ASC` : sqlFragment`DESC`}
* `;
* ```
*
* SQL Fragments can contain other SQL fragments, but must be finalized with
* `sql` before being passed to `Database#prepare`.
*
* The name `sqlFragment` comes from several editors that support SQL syntax
* highlighting inside JavaScript template literals.
*/
export function sqlFragment(
strings: TemplateStringsArray,
...values: ReadonlyArray<QueryFragmentValue>
): QueryFragment {
let query = '';
2023-08-09 00:53:06 +00:00
const params: Array<QueryTemplateParam> = [];
2023-03-20 22:23:53 +00:00
strings.forEach((string, index) => {
const value = values[index];
query += string;
if (index < values.length) {
2024-11-06 19:27:54 +00:00
if (value instanceof QueryFragment) {
const { fragment, fragmentParams } = value;
2023-03-20 22:23:53 +00:00
query += fragment;
params.push(...fragmentParams);
} else {
query += '?';
params.push(value);
}
}
});
2024-11-06 19:27:54 +00:00
return new QueryFragment(query, params);
2023-03-20 22:23:53 +00:00
}
2023-08-09 00:53:06 +00:00
export function sqlConstant(value: QueryTemplateParam): QueryFragment {
let fragment;
if (value == null) {
fragment = 'NULL';
} else if (typeof value === 'number') {
fragment = `${value}`;
} else if (typeof value === 'boolean') {
fragment = `${value}`;
} else {
fragment = `'${value}'`;
}
2024-11-06 19:27:54 +00:00
return new QueryFragment(fragment, []);
2023-08-09 00:53:06 +00:00
}
2023-03-20 22:23:53 +00:00
/**
* Like `Array.prototype.join`, but for SQL fragments.
*/
2023-11-22 22:48:53 +00:00
const SQL_JOIN_SEPARATOR = ',';
2023-03-20 22:23:53 +00:00
export function sqlJoin(
2023-11-22 22:48:53 +00:00
items: ReadonlyArray<QueryFragmentValue>
2023-03-20 22:23:53 +00:00
): QueryFragment {
let query = '';
2023-08-09 00:53:06 +00:00
const params: Array<QueryTemplateParam> = [];
2023-03-20 22:23:53 +00:00
items.forEach((item, index) => {
2024-11-06 19:27:54 +00:00
const { fragment, fragmentParams } = sqlFragment`${item}`;
2023-03-20 22:23:53 +00:00
query += fragment;
params.push(...fragmentParams);
if (index < items.length - 1) {
2023-11-22 22:48:53 +00:00
query += SQL_JOIN_SEPARATOR;
2023-03-20 22:23:53 +00:00
}
});
2024-11-06 19:27:54 +00:00
return new QueryFragment(query, params);
2023-03-20 22:23:53 +00:00
}
2023-08-09 00:53:06 +00:00
export type QueryTemplate = [string, ReadonlyArray<QueryTemplateParam>];
2023-03-20 22:23:53 +00:00
/**
* You can use tagged template literals to build SQL queries
* that can be passed to `Database#prepare`.
*
* ```ts
* const [query, params] = sql`
* SELECT * FROM examples
* WHERE groupId = ${groupId}
* ORDER BY timestamp ASC
* `;
* db.prepare(query).all(params);
* ```
*
* SQL queries can contain other SQL fragments, but cannot contain other SQL
* queries.
*
* The name `sql` comes from several editors that support SQL syntax
* highlighting inside JavaScript template literals.
*/
export function sql(
strings: TemplateStringsArray,
2024-05-20 18:15:39 +00:00
...values: Array<QueryFragment | QueryTemplateParam>
2023-03-20 22:23:53 +00:00
): QueryTemplate {
2024-11-06 19:27:54 +00:00
const { fragment, fragmentParams } = sqlFragment(strings, ...values);
return [fragment, fragmentParams];
2023-03-20 22:23:53 +00:00
}
type QueryPlanRow = Readonly<{
id: number;
parent: number;
details: string;
}>;
type QueryPlan = Readonly<{
query: string;
plan: ReadonlyArray<QueryPlanRow>;
}>;
/**
* Returns typed objects of the query plan for the given query.
*
*
* ```ts
* const [query, params] = sql`
* SELECT * FROM examples
* WHERE groupId = ${groupId}
* ORDER BY timestamp ASC
* `;
* log.info('Query plan', explainQueryPlan(db, [query, params]));
* db.prepare(query).all(params);
* ```
*/
export function explainQueryPlan(
2024-07-22 18:16:33 +00:00
db: ReadableDB,
2023-03-20 22:23:53 +00:00
template: QueryTemplate
): QueryPlan {
const [query, params] = template;
const plan = db.prepare(`EXPLAIN QUERY PLAN ${query}`).all(params);
return { query, plan };
}
2021-10-26 22:59:08 +00:00
//
// Database helpers
//
2024-07-22 18:16:33 +00:00
export function getSQLiteVersion(db: ReadableDB): string {
2021-10-26 22:59:08 +00:00
const { sqlite_version: version } = db
.prepare<EmptyQuery>('select sqlite_version() AS sqlite_version')
.get();
return version;
}
2024-07-22 18:16:33 +00:00
export function getSchemaVersion(db: ReadableDB): number {
2021-10-26 22:59:08 +00:00
return db.pragma('schema_version', { simple: true });
}
2024-07-22 18:16:33 +00:00
export function setUserVersion(db: WritableDB, version: number): void {
2021-10-26 22:59:08 +00:00
if (!isNumber(version)) {
throw new Error(`setUserVersion: version ${version} is not a number`);
}
db.pragma(`user_version = ${version}`);
}
2024-07-22 18:16:33 +00:00
export function getUserVersion(db: ReadableDB): number {
2021-10-26 22:59:08 +00:00
return db.pragma('user_version', { simple: true });
}
2024-07-22 18:16:33 +00:00
export function getSQLCipherVersion(db: ReadableDB): string | undefined {
2021-10-26 22:59:08 +00:00
return db.pragma('cipher_version', { simple: true });
}
//
// Various table helpers
//
export function batchMultiVarQuery<ValueT>(
2024-07-22 18:16:33 +00:00
db: ReadableDB,
values: ReadonlyArray<ValueT>,
query: (batch: ReadonlyArray<ValueT>) => void
2021-10-26 22:59:08 +00:00
): [];
export function batchMultiVarQuery<ValueT, ResultT>(
2024-07-22 18:16:33 +00:00
db: ReadableDB,
values: ReadonlyArray<ValueT>,
query: (batch: ReadonlyArray<ValueT>) => Array<ResultT>
2021-10-26 22:59:08 +00:00
): Array<ResultT>;
export function batchMultiVarQuery<ValueT, ResultT>(
2024-07-22 18:16:33 +00:00
db: ReadableDB,
values: ReadonlyArray<ValueT>,
2021-10-26 22:59:08 +00:00
query:
| ((batch: ReadonlyArray<ValueT>) => void)
| ((batch: ReadonlyArray<ValueT>) => Array<ResultT>)
2021-10-26 22:59:08 +00:00
): Array<ResultT> {
if (values.length > MAX_VARIABLE_COUNT) {
const result: Array<ResultT> = [];
db.transaction(() => {
for (let i = 0; i < values.length; i += MAX_VARIABLE_COUNT) {
const batch = values.slice(i, i + MAX_VARIABLE_COUNT);
const batchResult = query(batch);
if (Array.isArray(batchResult)) {
result.push(...batchResult);
}
}
})();
return result;
}
const result = query(values);
return Array.isArray(result) ? result : [];
}
export function createOrUpdate<Key extends string | number>(
2024-07-22 18:16:33 +00:00
db: WritableDB,
2021-10-26 22:59:08 +00:00
table: TableType,
data: Record<string, unknown> & { id: Key }
): void {
const { id } = data;
if (!id) {
throw new Error('createOrUpdate: Provided data did not have a truthy id');
}
db.prepare<Query>(
`
INSERT OR REPLACE INTO ${table} (
id,
json
) values (
$id,
$json
)
`
).run({
id,
json: objectToJSON(data),
});
}
export function bulkAdd(
2024-07-22 18:16:33 +00:00
db: WritableDB,
2021-10-26 22:59:08 +00:00
table: TableType,
array: Array<Record<string, unknown> & { id: string | number }>
): void {
db.transaction(() => {
for (const data of array) {
createOrUpdate(db, table, data);
}
})();
}
export function getById<Key extends string | number, Result = unknown>(
2024-07-22 18:16:33 +00:00
db: ReadableDB,
2021-10-26 22:59:08 +00:00
table: TableType,
id: Key
): Result | undefined {
const row = db
.prepare<Query>(
`
SELECT *
FROM ${table}
WHERE id = $id;
`
)
.get({
id,
});
if (!row) {
return undefined;
}
return jsonToObject(row.json);
}
export function removeById<Key extends string | number>(
2024-07-22 18:16:33 +00:00
db: WritableDB,
tableName: TableType,
2021-10-26 22:59:08 +00:00
id: Key | Array<Key>
): number {
const table = sqlConstant(tableName);
2021-10-26 22:59:08 +00:00
if (!Array.isArray(id)) {
const [query, params] = sql`
2021-10-26 22:59:08 +00:00
DELETE FROM ${table}
WHERE id = ${id};
`;
return db.prepare(query).run(params).changes;
2021-10-26 22:59:08 +00:00
}
if (!id.length) {
throw new Error('removeById: No ids to delete!');
}
let totalChanges = 0;
const removeByIdsSync = (ids: ReadonlyArray<string | number>): void => {
const [query, params] = sql`
2021-10-26 22:59:08 +00:00
DELETE FROM ${table}
2023-11-22 22:48:53 +00:00
WHERE id IN (${sqlJoin(ids)});
`;
totalChanges += db.prepare(query).run(params).changes;
2021-10-26 22:59:08 +00:00
};
batchMultiVarQuery(db, id, removeByIdsSync);
return totalChanges;
2021-10-26 22:59:08 +00:00
}
2024-07-22 18:16:33 +00:00
export function removeAllFromTable(db: WritableDB, table: TableType): number {
return db.prepare<EmptyQuery>(`DELETE FROM ${table};`).run().changes;
2021-10-26 22:59:08 +00:00
}
2024-07-22 18:16:33 +00:00
export function getAllFromTable<T>(db: ReadableDB, table: TableType): Array<T> {
2021-10-26 22:59:08 +00:00
const rows: JSONRows = db
.prepare<EmptyQuery>(`SELECT json FROM ${table};`)
.all();
return rows.map(row => jsonToObject(row.json));
}
2024-07-22 18:16:33 +00:00
export function getCountFromTable(db: ReadableDB, table: TableType): number {
2021-10-26 22:59:08 +00:00
const result: null | number = db
.prepare<EmptyQuery>(`SELECT count(*) from ${table};`)
.pluck(true)
.get();
if (isNumber(result)) {
return result;
}
throw new Error(`getCountFromTable: Unable to get count from table ${table}`);
}
export class TableIterator<ObjectType extends { id: string }> {
constructor(
2024-07-22 18:16:33 +00:00
private readonly db: ReadableDB,
2021-10-26 22:59:08 +00:00
private readonly table: TableType,
private readonly pageSize = 500
) {}
*[Symbol.iterator](): Iterator<ObjectType> {
const fetchObject = this.db.prepare<Query>(
`
SELECT json FROM ${this.table}
WHERE id > $id
ORDER BY id ASC
LIMIT $pageSize;
`
);
let complete = false;
let id = '';
while (!complete) {
const rows: JSONRows = fetchObject.all({
id,
pageSize: this.pageSize,
});
const messages: Array<ObjectType> = rows.map(row =>
jsonToObject(row.json)
);
yield* messages;
const lastMessage: ObjectType | undefined = last(messages);
if (lastMessage) {
({ id } = lastMessage);
}
complete = messages.length < this.pageSize;
}
}
}