Skip to content

Commit

Permalink
updated from main
Browse files Browse the repository at this point in the history
  • Loading branch information
stevensJourney committed May 9, 2024
2 parents 450a0b2 + a637d32 commit 6e28327
Show file tree
Hide file tree
Showing 19 changed files with 112 additions and 175 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ jobs:
run: |
cd tests
yarn install --frozen-lockfile
- name: Install Cocoapods
- name: Install Cocoapods
run: |
cd tests/ios && pod install
Expand Down
2 changes: 1 addition & 1 deletion .mtslconfig.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"ignore_dirs":[".git","node_modules","tests"]}
{ "ignore_dirs": [".git", "node_modules", "tests"] }
14 changes: 14 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Ignore all node_modules
**/node_modules/**

# Autogenerated files
**/.expo/**
**/.next/**
**/.idea/**
**/.fleet/**

# Other
**/android/**
**/assets/**
**/bin/**
**/ios/**
9 changes: 9 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"jsxBracketSameLine": true,
"useTabs": false,
"printWidth": 120,
"trailingComma": "none"
}
4 changes: 2 additions & 2 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ module.exports = {
plugins: [
'babel-plugin-transform-typescript-metadata',
['@babel/plugin-proposal-decorators', { legacy: true }],
['@babel/plugin-proposal-class-properties', { loose: true }],
],
['@babel/plugin-proposal-class-properties', { loose: true }]
]
};
9 changes: 2 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"scripts": {
"build": "bob build",
"clean": "rm -rf lib tsconfig.tsbuildinfo",
"format": "prettier --write .",
"typescript": "tsc --noEmit",
"prepare": "bob build",
"example": "yarn --cwd example",
Expand All @@ -48,6 +49,7 @@
"homepage": "https://github.com/margelo/react-native-quick-sqlite#readme",
"devDependencies": {
"@changesets/cli": "^2.26.2",
"prettier": "^3.2.4",
"react": "18.2.0",
"react-native": "0.71.0",
"react-native-builder-bob": "^0.18.2",
Expand All @@ -57,13 +59,6 @@
"react": "*",
"react-native": "*"
},
"prettier": {
"quoteProps": "consistent",
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"useTabs": false
},
"react-native-builder-bob": {
"source": "src",
"output": "lib",
Expand Down
2 changes: 1 addition & 1 deletion scripts/bootstrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const options = {
cwd: process.cwd(),
env: process.env,
stdio: 'inherit',
encoding: 'utf-8',
encoding: 'utf-8'
};

let result;
Expand Down
25 changes: 10 additions & 15 deletions src/DBListenerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
BatchedUpdateNotification,
TransactionEvent,
UpdateCallback,
UpdateNotification,
UpdateNotification
} from './types';
import { BaseListener, BaseObserver } from './utils/BaseObserver';

Expand Down Expand Up @@ -49,9 +49,7 @@ export class DBListenerManagerInternal extends DBListenerManager {
constructor(protected options: DBListenerManagerOptions) {
super();
this.updateBuffer = [];
registerUpdateHook(this.options.dbName, (update) =>
this.handleTableUpdates(update)
);
registerUpdateHook(this.options.dbName, (update) => this.handleTableUpdates(update));
registerTransactionHook(this.options.dbName, (eventType) => {
switch (eventType) {
/**
Expand All @@ -65,7 +63,7 @@ export class DBListenerManagerInternal extends DBListenerManager {

this.iterateListeners((l) =>
l.writeTransaction?.({
type: eventType,
type: eventType
})
);
});
Expand All @@ -76,20 +74,17 @@ export class DBListenerManagerInternal extends DBListenerManager {
return;
}

const groupedUpdates = this.updateBuffer.reduce(
(grouping: Record<string, UpdateNotification[]>, update) => {
const { table } = update;
const updateGroup = grouping[table] || (grouping[table] = []);
updateGroup.push(update);
return grouping;
},
{}
);
const groupedUpdates = this.updateBuffer.reduce((grouping: Record<string, UpdateNotification[]>, update) => {
const { table } = update;
const updateGroup = grouping[table] || (grouping[table] = []);
updateGroup.push(update);
return grouping;
}, {});

const batchedUpdate: BatchedUpdateNotification = {
groupedUpdates,
rawUpdates: this.updateBuffer,
tables: Object.keys(groupedUpdates),
tables: Object.keys(groupedUpdates)
};
this.updateBuffer = [];
this.iterateListeners((l) => l.tablesUpdated?.(batchedUpdate));
Expand Down
92 changes: 25 additions & 67 deletions src/setup-open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
UpdateCallback,
SQLBatchTuple,
OpenOptions,
QueryResult,
QueryResult
} from './types';

import { enhanceQueryResult } from './utils';
Expand All @@ -23,7 +23,7 @@ type LockCallbackRecord = {

enum TransactionFinalizer {
COMMIT = 'commit',
ROLLBACK = 'rollback',
ROLLBACK = 'rollback'
}

const DEFAULT_READ_CONNECTIONS = 4;
Expand All @@ -47,10 +47,7 @@ function closeContextLock(dbName: string, id: ContextLockID) {
* @param lockId
* @returns
*/
global.onLockContextIsAvailable = async (
dbName: string,
lockId: ContextLockID
) => {
global.onLockContextIsAvailable = async (dbName: string, lockId: ContextLockID) => {
// Don't hold C++ bridge side up waiting to complete
setImmediate(async () => {
try {
Expand All @@ -62,15 +59,10 @@ global.onLockContextIsAvailable = async (
// @ts-expect-error This is not part of the public interface, but is used internally
_contextId: lockId,
execute: async (sql: string, args?: any[]) => {
const result = await proxy.executeInContext(
dbName,
lockId,
sql,
args
);
const result = await proxy.executeInContext(dbName, lockId, sql, args);
enhanceQueryResult(result);
return result;
},
}
});
} catch (ex) {
console.error(ex);
Expand All @@ -93,15 +85,11 @@ export function setupOpen(QuickSQLite: ISQLite) {
* By default opens DB in WAL mode with 4 Read connections and a single
* write connection
*/
open: (
dbName: string,
options: OpenOptions = {}
): QuickSQLiteConnection => {
open: (dbName: string, options: OpenOptions = {}): QuickSQLiteConnection => {
// Opens the connection
QuickSQLite.open(dbName, {
...options,
numReadConnections:
options?.numReadConnections ?? DEFAULT_READ_CONNECTIONS,
numReadConnections: options?.numReadConnections ?? DEFAULT_READ_CONNECTIONS
});

const listenerManager = new DBListenerManagerInternal({ dbName });
Expand Down Expand Up @@ -143,7 +131,7 @@ export function setupOpen(QuickSQLite: ISQLite) {
} finally {
hooks?.lockReleased?.();
}
},
}
} as LockCallbackRecord);

try {
Expand All @@ -164,20 +152,15 @@ export function setupOpen(QuickSQLite: ISQLite) {
});
};

const readLock = <T>(
callback: (context: LockContext) => Promise<T>,
options?: LockOptions
): Promise<T> => requestLock(ConcurrentLockType.READ, callback, options);
const readLock = <T>(callback: (context: LockContext) => Promise<T>, options?: LockOptions): Promise<T> =>
requestLock(ConcurrentLockType.READ, callback, options);

const writeLock = <T>(
callback: (context: LockContext) => Promise<T>,
options?: LockOptions
): Promise<T> =>
const writeLock = <T>(callback: (context: LockContext) => Promise<T>, options?: LockOptions): Promise<T> =>
requestLock(ConcurrentLockType.WRITE, callback, options, {
lockReleased: async () => {
// flush updates once a write lock has been released
listenerManager.flushUpdates();
},
}
});

const wrapTransaction = async <T>(
Expand All @@ -198,23 +181,17 @@ export function setupOpen(QuickSQLite: ISQLite) {
return action();
};

const commit = finalizedStatement(async () =>
context.execute('COMMIT')
);
const commit = finalizedStatement(async () => context.execute('COMMIT'));

const rollback = finalizedStatement(async () =>
context.execute('ROLLBACK')
);
const rollback = finalizedStatement(async () => context.execute('ROLLBACK'));

const wrapExecute =
<T>(
method: (sql: string, params?: any[]) => Promise<QueryResult>
): ((sql: string, params?: any[]) => Promise<QueryResult>) =>
async (sql: string, params?: any[]) => {
if (finalized) {
throw new Error(
`Cannot execute in transaction after it has been finalized with commit/rollback.`
);
throw new Error(`Cannot execute in transaction after it has been finalized with commit/rollback.`);
}
return method(sql, params);
};
Expand All @@ -224,7 +201,7 @@ export function setupOpen(QuickSQLite: ISQLite) {
...context,
commit,
rollback,
execute: wrapExecute(context.execute),
execute: wrapExecute(context.execute)
});
switch (defaultFinalizer) {
case TransactionFinalizer.COMMIT:
Expand All @@ -244,45 +221,26 @@ export function setupOpen(QuickSQLite: ISQLite) {
// Return the concurrent connection object
return {
close: () => QuickSQLite.close(dbName),
execute: (sql: string, args?: any[]) =>
writeLock((context) => context.execute(sql, args)),
execute: (sql: string, args?: any[]) => writeLock((context) => context.execute(sql, args)),
readLock,
readTransaction: async <T>(
callback: (context: TransactionContext) => Promise<T>,
options?: LockOptions
) => readLock((context) => wrapTransaction(context, callback)),
readTransaction: async <T>(callback: (context: TransactionContext) => Promise<T>, options?: LockOptions) =>
readLock((context) => wrapTransaction(context, callback)),
writeLock,
writeTransaction: async <T>(
callback: (context: TransactionContext) => Promise<T>,
options?: LockOptions
) =>
writeLock(
(context) =>
wrapTransaction(context, callback, TransactionFinalizer.COMMIT),
options
),
writeTransaction: async <T>(callback: (context: TransactionContext) => Promise<T>, options?: LockOptions) =>
writeLock((context) => wrapTransaction(context, callback, TransactionFinalizer.COMMIT), options),
delete: () => QuickSQLite.delete(dbName, options?.location),
executeBatch: (commands: SQLBatchTuple[]) =>
writeLock((context) =>
QuickSQLite.executeBatch(
dbName,
commands,
(context as any)._contextId
)
),
writeLock((context) => QuickSQLite.executeBatch(dbName, commands, (context as any)._contextId)),
attach: (dbNameToAttach: string, alias: string, location?: string) =>
QuickSQLite.attach(dbName, dbNameToAttach, alias, location),
detach: (alias: string) => QuickSQLite.detach(dbName, alias),
loadFile: (location: string) =>
writeLock((context) =>
QuickSQLite.loadFile(dbName, location, (context as any)._contextId)
),
writeLock((context) => QuickSQLite.loadFile(dbName, location, (context as any)._contextId)),
listenerManager,
registerUpdateHook: (callback: UpdateCallback) =>
listenerManager.registerListener({ rawTableChange: callback }),
registerTablesChangedHook: (callback) =>
listenerManager.registerListener({ tablesUpdated: callback }),
registerTablesChangedHook: (callback) => listenerManager.registerListener({ tablesUpdated: callback })
};
},
}
};
}
22 changes: 4 additions & 18 deletions src/type-orm.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
// _________ _______ ______ ____ _____ __ __ _____ _____
// |__ __\ \ / / __ \| ____/ __ \| __ \| \/ | /\ | __ \_ _|
// | | \ \_/ /| |__) | |__ | | | | |__) | \ / | / \ | |__) || |
// | | \ / | ___/| __|| | | | _ /| |\/| | / /\ \ | ___/ | |
// | | | | | | | |___| |__| | | \ \| | | | / ____ \| | _| |_
// |_| |_| |_| |______\____/|_| \_\_| |_| /_/ \_\_| |_____|

import { QueryResult, TransactionContext, Open } from './types';

/**
Expand Down Expand Up @@ -37,9 +30,7 @@ export const setupTypeORMDriver = (open: Open) => ({
fail(e);
}
},
transaction: (
fn: (tx: TransactionContext) => Promise<void>
): Promise<void> => {
transaction: (fn: (tx: TransactionContext) => Promise<void>): Promise<void> => {
return _con.writeTransaction(fn);
},
close: (ok: any, fail: any) => {
Expand All @@ -50,19 +41,14 @@ export const setupTypeORMDriver = (open: Open) => ({
fail(e);
}
},
attach: (
dbNameToAttach: string,
alias: string,
location: string | undefined,
callback: () => void
) => {
attach: (dbNameToAttach: string, alias: string, location: string | undefined, callback: () => void) => {
_con.attach(dbNameToAttach, alias, location);
callback();
},
detach: (alias, callback: () => void) => {
_con.detach(alias);
callback();
},
}
};

ok(connection);
Expand All @@ -71,5 +57,5 @@ export const setupTypeORMDriver = (open: Open) => ({
} catch (e) {
fail(e);
}
},
}
});
4 changes: 1 addition & 3 deletions src/utils/BaseObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ export type BaseListener = {
[key: string]: (...event: any) => any;
};

export class BaseObserver<T extends BaseListener = BaseListener>
implements BaseObserverInterface<T>
{
export class BaseObserver<T extends BaseListener = BaseListener> implements BaseObserverInterface<T> {
protected listeners: Set<Partial<T>>;

constructor() {
Expand Down

0 comments on commit 6e28327

Please sign in to comment.