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
5 changes: 5 additions & 0 deletions examples/TypeScriptMessaging/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
MessageInput,
MessageList,
OverlayProvider,
QuickSqliteClient,
Streami18n,
Thread,
ThreadContextValue,
Expand Down Expand Up @@ -53,6 +54,10 @@ const options = {

I18nManager.forceRTL(false);

QuickSqliteClient.logger = (level, message, extraData) => {
console.log(level, `QuickSqliteClient: ${message}`, extraData);
};

const chatClient = StreamChat.getInstance<StreamChatGenerics>('q95x9hkbyd6p');
const userToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoicm9uIn0.eRVjxLvd4aqCEHY_JRa97g6k7WpHEhxL7Z4K4yTot1c';
Expand Down
43 changes: 40 additions & 3 deletions package/src/store/QuickSqliteClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ try {
// 2. Offline support is disabled, in which case this library is not installed.
}

import { Logger } from 'stream-chat';

import { DB_LOCATION, DB_NAME } from './constants';
import { tables } from './schema';
import { createCreateTableQuery } from './sqlite-utils/createCreateTableQuery';
Expand All @@ -32,6 +34,7 @@ export class QuickSqliteClient {

static dbName = DB_NAME;
static dbLocation = DB_LOCATION;
static logger: Logger | undefined;

static getDbVersion = () => QuickSqliteClient.dbVersion;
// Force a specific db version. This is mainly useful for testsuit.
Expand All @@ -42,6 +45,9 @@ export class QuickSqliteClient {
sqlite.open(QuickSqliteClient.dbName, QuickSqliteClient.dbLocation);
sqlite.execute(QuickSqliteClient.dbName, `PRAGMA foreign_keys = ON`, []);
} catch (e) {
this.logger?.('error', `Error opening database ${QuickSqliteClient.dbName}`, {
error: e,
});
console.error(`Error opening database ${QuickSqliteClient.dbName}: ${e}`);
}
};
Expand All @@ -50,6 +56,9 @@ export class QuickSqliteClient {
try {
sqlite.close(QuickSqliteClient.dbName);
} catch (e) {
this.logger?.('error', `Error closing database ${QuickSqliteClient.dbName}`, {
error: e,
});
console.error(`Error closing database ${QuickSqliteClient.dbName}: ${e}`);
}
};
Expand All @@ -64,7 +73,11 @@ export class QuickSqliteClient {
QuickSqliteClient.closeDB();
} catch (e) {
QuickSqliteClient.closeDB();
throw new Error(`Query/queries failed: ${e}`);
this.logger?.('error', `SqlBatch queries failed`, {
error: e,
queries,
});
throw new Error(`Queries failed: ${e}`);
}
};

Expand All @@ -77,7 +90,11 @@ export class QuickSqliteClient {
return rows ? rows._array : [];
} catch (e) {
QuickSqliteClient.closeDB();
throw new Error(`Query/queries failed: ${e}: `);
this.logger?.('error', `Sql single query failed`, {
error: e,
query,
});
throw new Error(`Query failed: ${e}: `);
}
};

Expand All @@ -86,14 +103,25 @@ export class QuickSqliteClient {
`DROP TABLE IF EXISTS ${table}`,
[],
]);

this.logger?.('info', `Dropping tables`, {
tables: Object.keys(tables),
});
QuickSqliteClient.executeSqlBatch(queries);
};

static deleteDatabase = () => {
this.logger?.('info', `deleteDatabase`, {
dbLocation: QuickSqliteClient.dbLocation,
dbname: QuickSqliteClient.dbName,
});
try {
sqlite.delete(QuickSqliteClient.dbName, QuickSqliteClient.dbLocation);
} catch (e) {
this.logger?.('error', `Error deleting DB`, {
dbLocation: QuickSqliteClient.dbLocation,
dbname: QuickSqliteClient.dbName,
error: e,
});
throw new Error(`Error deleting DB: ${e}`);
}

Expand All @@ -110,9 +138,13 @@ export class QuickSqliteClient {
const version = QuickSqliteClient.getUserPragmaVersion();

if (version !== QuickSqliteClient.dbVersion) {
QuickSqliteClient.logger?.('info', `DB version mismatch`);
QuickSqliteClient.dropTables();
QuickSqliteClient.updateUserPragmaVersion(QuickSqliteClient.dbVersion);
}
QuickSqliteClient.logger?.('info', `create tables if not exists`, {
tables: Object.keys(tables),
});
const q = (Object.keys(tables) as Table[]).reduce<PreparedQueries[]>(
(queriesSoFar, tableName) => {
queriesSoFar.push(...createCreateTableQuery(tableName));
Expand All @@ -125,6 +157,7 @@ export class QuickSqliteClient {
};

static updateUserPragmaVersion = (version: number) => {
QuickSqliteClient.logger?.('info', `updateUserPragmaVersion to ${version}`);
QuickSqliteClient.openDB();
sqlite.execute(DB_NAME, `PRAGMA user_version = ${version}`, []);
QuickSqliteClient.closeDB();
Expand All @@ -135,6 +168,9 @@ export class QuickSqliteClient {
try {
const { rows } = sqlite.execute(DB_NAME, `PRAGMA user_version`, []);
const result = rows ? rows._array : [];
this.logger?.('info', `getUserPragmaVersion`, {
result,
});
QuickSqliteClient.closeDB();
return result[0].user_version as number;
} catch (e) {
Expand All @@ -144,6 +180,7 @@ export class QuickSqliteClient {
};

static resetDB = () => {
this.logger?.('info', `resetDB`);
QuickSqliteClient.dropTables();
QuickSqliteClient.initializeDatabase();
};
Expand Down
21 changes: 20 additions & 1 deletion package/src/store/apis/addPendingTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,33 @@ import { createDeleteQuery } from '../sqlite-utils/createDeleteQuery';
import { createUpsertQuery } from '../sqlite-utils/createUpsertQuery';
import type { PendingTask } from '../types';

/*
* addPendingTask - Adds a pending task to the database
*
* @param {PendingTask} task - The task to add
*
* @return {() => void} - A function that can be called to remove the task from the database
*/
export const addPendingTask = (task: PendingTask) => {
const storable = mapTaskToStorable(task);
const { channelId, channelType, payload, type } = storable;
const query = createUpsertQuery('pendingTasks', storable);
QuickSqliteClient.logger?.('info', 'addPendingTask', {
channelId,
channelType,
id: task.id,
type,
});

QuickSqliteClient.executeSql.apply(null, query);

return () => {
const { channelId, channelType, payload, type } = storable;
QuickSqliteClient.logger?.('info', 'deletePendingTaskAfterAddition', {
channelId,
channelType,
id: task.id,
type,
});
const query = createDeleteQuery('pendingTasks', {
channelId,
channelType,
Expand Down
5 changes: 5 additions & 0 deletions package/src/store/apis/deleteChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ export const deleteChannel = ({ cid, flush = true }: { cid: string; flush?: bool
cid,
});

QuickSqliteClient.logger?.('info', 'deleteChannel', {
cid,
flush,
});

if (flush) {
QuickSqliteClient.executeSql.apply(null, query);
}
Expand Down
6 changes: 6 additions & 0 deletions package/src/store/apis/deleteMember.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export const deleteMember = ({
userId: member.user_id,
});

QuickSqliteClient.logger?.('info', 'deleteMember', {
cid,
flush,
userId: member.user_id,
});

if (flush) {
QuickSqliteClient.executeSql.apply(null, query);
}
Expand Down
6 changes: 6 additions & 0 deletions package/src/store/apis/deleteMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ export const deleteMessage = ({ flush = true, id }: { id: string; flush?: boolea
const query = createDeleteQuery('messages', {
id,
});

QuickSqliteClient.logger?.('info', 'deleteMessage', {
flush,
id,
});

if (flush) {
QuickSqliteClient.executeSql.apply(null, query);
}
Expand Down
6 changes: 6 additions & 0 deletions package/src/store/apis/deleteMessagesForChannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ export const deleteMessagesForChannel = ({
const query = createDeleteQuery('messages', {
cid,
});

QuickSqliteClient.logger?.('info', 'deleteMessagesForChannel', {
cid,
flush,
});

if (flush) {
QuickSqliteClient.executeSql.apply(null, query);
}
Expand Down
4 changes: 4 additions & 0 deletions package/src/store/apis/deletePendingTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ export const deletePendingTask = ({ id }: { id: number }) => {
id,
});

QuickSqliteClient.logger?.('info', 'deletePendingTask', {
id,
});

QuickSqliteClient.executeSql.apply(null, query);

return [query];
Expand Down
6 changes: 6 additions & 0 deletions package/src/store/apis/deleteReaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ export const deleteReaction = ({
userId,
});

QuickSqliteClient.logger?.('info', 'deleteReaction', {
messageId,
type: reactionType,
userId,
});

if (flush) {
QuickSqliteClient.executeSql.apply(null, query);
}
Expand Down
11 changes: 5 additions & 6 deletions package/src/store/apis/deleteReactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,12 @@ export const deleteReactionsForMessage = ({
const query = createDeleteQuery('reactions', {
messageId,
});
console.log('deleteReactionsForMessage', {
flush,
messageId,
});
if (flush) {
QuickSqliteClient.executeSql.apply(
null,
createDeleteQuery('reactions', {
messageId,
}),
);
QuickSqliteClient.executeSql.apply(null, query);
}

return [query];
Expand Down
3 changes: 3 additions & 0 deletions package/src/store/apis/getAllChannelIds.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { selectChannels } from './queries/selectChannels';

import { QuickSqliteClient } from '../QuickSqliteClient';

export const getAllChannelIds = () => {
const channels = selectChannels();

QuickSqliteClient.logger?.('info', 'getAllChannelIds');
return channels.map((c) => c.cid);
};
3 changes: 3 additions & 0 deletions package/src/store/apis/getAppSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ export const getAppSettings = ({
}: {
currentUserId: string;
}): AppSettingsAPIResponse => {
QuickSqliteClient.logger?.('info', 'getAppSettings', {
currentUserId,
});
const result = QuickSqliteClient.executeSql.apply(
null,
createSelectQuery('userSyncStatus', ['*'], {
Expand Down
5 changes: 5 additions & 0 deletions package/src/store/apis/getChannelMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { selectReactionsForMessages } from './queries/selectReactionsForMessages
import type { DefaultStreamChatGenerics } from '../../types/types';
import { isBlockedMessage } from '../../utils/utils';
import { mapStorableToMessage } from '../mappers/mapStorableToMessage';
import { QuickSqliteClient } from '../QuickSqliteClient';
import type { TableRowJoinedUser } from '../types';

export const getChannelMessages = <
Expand All @@ -18,6 +19,10 @@ export const getChannelMessages = <
channelIds: string[];
currentUserId: string;
}) => {
QuickSqliteClient.logger?.('info', 'getChannelMessages', {
channelIds,
currentUserId,
});
const messageRows = selectMessagesForChannels(channelIds);
const messageIds = messageRows.map(({ id }) => id);

Expand Down
2 changes: 2 additions & 0 deletions package/src/store/apis/getChannels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { selectChannels } from './queries/selectChannels';

import type { DefaultStreamChatGenerics } from '../../types/types';
import { mapStorableToChannel } from '../mappers/mapStorableToChannel';
import { QuickSqliteClient } from '../QuickSqliteClient';

/**
* Returns the list of channels with state enriched for given channel ids.
Expand All @@ -26,6 +27,7 @@ export const getChannels = <
channelIds: string[];
currentUserId: string;
}): Omit<ChannelAPIResponse<StreamChatGenerics>, 'duration'>[] => {
QuickSqliteClient.logger?.('info', 'getChannels', { channelIds, currentUserId });
const channels = selectChannels({ channelIds });

const cidVsMembers = getMembers<StreamChatGenerics>({ channelIds });
Expand Down
4 changes: 4 additions & 0 deletions package/src/store/apis/getChannelsForFilterSort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { ChannelAPIResponse, ChannelFilters, ChannelSort } from 'stream-cha
import { getChannels } from './getChannels';
import { selectChannelIdsForFilterSort } from './queries/selectChannelIdsForFilterSort';

import { QuickSqliteClient } from '../QuickSqliteClient';

/**
* Gets the channels from database for given filter and sort query.
*
Expand All @@ -30,6 +32,8 @@ export const getChannelsForFilterSort = <
return null;
}

QuickSqliteClient.logger?.('info', 'getChannelsForFilterSort', { filters, sort });

const channelIds = selectChannelIdsForFilterSort({ filters, sort });

if (!channelIds) return null;
Expand Down
1 change: 1 addition & 0 deletions package/src/store/apis/getLastSyncedAt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const getLastSyncedAt = ({
}: {
currentUserId: string;
}): number | undefined => {
QuickSqliteClient.logger?.('info', 'getLastSyncedAt', { currentUserId });
const result = QuickSqliteClient.executeSql.apply(
null,
createSelectQuery('userSyncStatus', ['*'], {
Expand Down
2 changes: 2 additions & 0 deletions package/src/store/apis/getMembers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { selectMembersForChannels } from './queries/selectMembersForChannels';

import type { DefaultStreamChatGenerics } from '../../types/types';
import { mapStorableToMember } from '../mappers/mapStorableToMember';
import { QuickSqliteClient } from '../QuickSqliteClient';

export const getMembers = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
Expand All @@ -12,6 +13,7 @@ export const getMembers = <
}: {
channelIds: string[];
}) => {
QuickSqliteClient.logger?.('info', 'getMembers', { channelIds });
const memberRows = selectMembersForChannels(channelIds);
const cidVsMembers: Record<string, ChannelMemberResponse<StreamChatGenerics>[]> = {};
memberRows.forEach((member) => {
Expand Down
1 change: 1 addition & 0 deletions package/src/store/apis/getPendingTasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const getPendingTasks = (conditions: { messageId?: string } = {}) => {
createdAt: 1,
});

QuickSqliteClient.logger?.('info', 'getPendingTasks', { conditions });
const result = QuickSqliteClient.executeSql.apply(null, query);

return result.map((r: TableRowJoinedUser<'pendingTasks'>) => mapStorableToTask(r));
Expand Down
2 changes: 2 additions & 0 deletions package/src/store/apis/getReads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { selectReadsForChannels } from './queries/selectReadsForChannels';

import type { DefaultStreamChatGenerics } from '../../types/types';
import { mapStorableToRead } from '../mappers/mapStorableToRead';
import { QuickSqliteClient } from '../QuickSqliteClient';

export const getReads = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
Expand All @@ -12,6 +13,7 @@ export const getReads = <
}: {
channelIds: string[];
}) => {
QuickSqliteClient.logger?.('info', 'getReads', { channelIds });
const reads = selectReadsForChannels(channelIds);
const cidVsReads: Record<string, ReadResponse<StreamChatGenerics>[]> = {};

Expand Down
Loading