Skip to content

Commit

Permalink
Merge pull request #71 from OP-Engineering/export
Browse files Browse the repository at this point in the history
Add get db path function
  • Loading branch information
ospfranco authored Mar 13, 2024
2 parents d2cd29d + 4e2ec31 commit 9e044f8
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 65 deletions.
25 changes: 25 additions & 0 deletions cpp/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,30 @@ void install(jsi::Runtime &rt,
return {};
});

auto get_db_path = HOSTFN("getDbPath", 2) {
std::string db_name = args[0].asString(rt).utf8(rt);
std::string path = std::string(basePath);
if (count > 1 && !args[1].isUndefined() && !args[1].isNull()) {
if (!args[1].isString()) {
throw std::runtime_error(
"[op-sqlite][open] database location must be a string");
}

std::string lastPath = args[1].asString(rt).utf8(rt);

if (lastPath == ":memory:") {
path = ":memory:";
} else if (lastPath.rfind("/", 0) == 0) {
path = lastPath;
} else {
path = path + "/" + lastPath;
}
}

auto result = opsqlite_get_db_path(db_name, path);
return jsi::String::createFromUtf8(rt, result);
});

jsi::Object module = jsi::Object(rt);

module.setProperty(rt, "open", std::move(open));
Expand All @@ -653,6 +677,7 @@ void install(jsi::Runtime &rt,
module.setProperty(rt, "prepareStatement", std::move(prepare_statement));
module.setProperty(rt, "loadExtension", std::move(load_extension));
module.setProperty(rt, "executeRawAsync", std::move(execute_raw_async));
module.setProperty(rt, "getDbPath", std::move(get_db_path));

rt.global().setProperty(rt, "__OPSQLiteProxy", std::move(module));
}
Expand Down
18 changes: 9 additions & 9 deletions cpp/bridge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ inline void check_db_open(std::string const &db_name) {

/// Returns the completely formed db path, but it also creates any sub-folders
/// along the way
std::string get_db_path(std::string const &db_name,
std::string const &location) {
std::string opsqlite_get_db_path(std::string const &db_name,
std::string const &location) {

if (location == ":memory:") {
return location;
Expand All @@ -49,7 +49,7 @@ BridgeResult opsqlite_open(std::string const &dbName,
BridgeResult opsqlite_open(std::string const &dbName,
std::string const &last_path) {
#endif
std::string dbPath = get_db_path(dbName, last_path);
std::string dbPath = opsqlite_get_db_path(dbName, last_path);

int sqlOpenFlags =
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
Expand All @@ -63,12 +63,12 @@ BridgeResult opsqlite_open(std::string const &dbName,
}

dbMap[dbName] = db;

#ifdef OP_SQLITE_USE_SQLCIPHER
auto encryptionResult =
opsqlite_execute(dbName, "PRAGMA key = '" + encryptionKey + "'", nullptr,
nullptr, nullptr);
LOGD("Encrypting database");
opsqlite_execute(dbName, "PRAGMA key = '" + encryptionKey + "'", nullptr,
nullptr, nullptr);
#endif

return BridgeResult{.type = SQLiteOk, .affectedRows = 0};
}

Expand All @@ -91,7 +91,7 @@ BridgeResult opsqlite_attach(std::string const &mainDBName,
std::string const &docPath,
std::string const &databaseToAttach,
std::string const &alias) {
std::string dbPath = get_db_path(databaseToAttach, docPath);
std::string dbPath = opsqlite_get_db_path(databaseToAttach, docPath);
std::string statement = "ATTACH DATABASE '" + dbPath + "' AS " + alias;

BridgeResult result =
Expand Down Expand Up @@ -135,7 +135,7 @@ BridgeResult opsqlite_remove(std::string const &dbName,
}
}

std::string dbPath = get_db_path(dbName, docPath);
std::string dbPath = opsqlite_get_db_path(dbName, docPath);

if (!file_exists(dbPath)) {
return {.type = SQLiteError,
Expand Down
3 changes: 3 additions & 0 deletions cpp/bridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ typedef std::function<void(std::string dbName, std::string tableName,
typedef std::function<void(std::string dbName)> CommitCallback;
typedef std::function<void(std::string dbName)> RollbackCallback;

std::string opsqlite_get_db_path(std::string const &db_name,
std::string const &location);

#ifdef OP_SQLITE_USE_SQLCIPHER
BridgeResult opsqlite_open(std::string const &dbName, std::string const &dbPath,
std::string const &encryptionKey);
Expand Down
6 changes: 3 additions & 3 deletions example/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ PODS:
- hermes-engine/Pre-built (= 0.73.1)
- hermes-engine/Pre-built (0.73.1)
- libevent (2.1.12)
- op-sqlite (2.0.22):
- op-sqlite (3.0.1):
- React
- React-callinvoker
- React-Core
Expand Down Expand Up @@ -1240,7 +1240,7 @@ SPEC CHECKSUMS:
glog: c5d68082e772fa1c511173d6b30a9de2c05a69a2
hermes-engine: 34df9d5034e90bd9bf1505e1ca198760373935af
libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913
op-sqlite: 6e2f955abb2f307107edfb2f128c99089b03ef8d
op-sqlite: 24443c22e059972abf4109b4e781d3f03336a761
RCT-Folly: 7169b2b1c44399c76a47b5deaaba715eeeb476c0
RCTRequired: 6dda55e483f75d2b43781d8ad5bd7df276a50981
RCTTypeSafety: df0f2632f4e89938b9b9f6152b5e6c66fc6e969e
Expand Down Expand Up @@ -1289,4 +1289,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: 0ab74fecad6ac2e35f8eab32fe5772c19d2015b2

COCOAPODS: 1.14.0
COCOAPODS: 1.14.3
64 changes: 12 additions & 52 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, {useEffect, useState} from 'react';
import {
ActivityIndicator,
Button,
Clipboard,
SafeAreaView,
ScrollView,
Text,
Expand Down Expand Up @@ -39,8 +40,6 @@ export default function App() {
[],
);
const [singleRecordTime, setSingleRecordTime] = useState<number>(0);
const [sqliteMMSetTime, setSqliteMMSetTime] = useState(0);
const [sqliteGetTime, setSqliteMMGetTime] = useState(0);
const [rawExecutionTimes, setRawExecutionTimes] = useState<number[]>([]);
useEffect(() => {
setResults([]);
Expand Down Expand Up @@ -84,70 +83,31 @@ export default function App() {
}
};

const queryAndReload = async () => {
queryLargeDB();
setTimeout(() => {
RNRestart.restart();
}, 200);
const copyDbPathToClipboad = async () => {
const db = await open({name: 'dbPath.sqlite'});
db.execute('CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT)');
const path = db.getDbPath();
await db.close();
console.warn(path);
Clipboard.setString(path);
};

const allTestsPassed = results.reduce((acc: boolean, r: any) => {
return acc && r.type !== 'incorrect';
}, true);

const testAgainstMMKV = () => {
const db = open({
name: 'mmkvTestDb',
});

db.execute('PRAGMA mmap_size=268435456');
// db.execute('PRAGMA journal_mode = OFF;');
db.execute('DROP TABLE IF EXISTS mmkvTest;');
db.execute('CREATE TABLE mmkvTest (text TEXT);');

let insertStatment = db.prepareStatement(
'INSERT INTO "mmkvTest" (text) VALUES (?)',
);
insertStatment.bind(['quack']);

let start = performance.now();
insertStatment.execute();
let end = performance.now();
setSqliteMMSetTime(end - start);

let readStatement = db.prepareStatement('SELECT text from mmkvTest;');
start = performance.now();
readStatement.execute();
end = performance.now();
setSqliteMMGetTime(end - start);

db.close();
};

return (
<SafeAreaView className="flex-1 bg-neutral-900">
<StyledScrollView>
<View className="flex-row p-2 bg-neutral-800 items-center">
<Text className={'font-bold flex-1 text-white'}>Tools</Text>
</View>
<Button title="Reload app middle of query" onPress={queryAndReload} />
<Button
title="Copy DB Path to clipboard"
onPress={copyDbPathToClipboad}
/>
<Button title="Create 300k Record DB" onPress={createLargeDb} />
<Button title="Query 300k Records" onPress={queryLargeDb} />
{/* <Button title="Query single record" onPress={querySingleRecord} />
<Button title="Against MMKV" onPress={testAgainstMMKV} /> */}
<View className="gap-2 items-center mt-4">
{!!sqliteMMSetTime && (
<Text className="text-white">
MM SQLite Write: {sqliteMMSetTime.toFixed(3)} ms
</Text>
)}

{!!sqliteGetTime && (
<Text className="text-white">
MM SQLite Get: {sqliteGetTime.toFixed(3)} ms
</Text>
)}
</View>
{isLoading && <ActivityIndicator color={'white'} size="large" />}

{!!singleRecordTime && (
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@op-engineering/op-sqlite",
"version": "3.0.0",
"version": "3.0.1",
"description": "Next generation SQLite for React Native",
"main": "lib/commonjs/index",
"module": "lib/module/index",
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ interface ISQLite {
query: string,
params?: any[]
) => Promise<any[]>;
getDbPath: (dbName: string, location?: string) => string;
}

const locks: Record<
Expand Down Expand Up @@ -428,6 +429,7 @@ export type OPSQLiteConnection = {
prepareStatement: (query: string) => PreparedStatementObj;
loadExtension: (path: string, entryPoint?: string) => void;
executeRawAsync: (query: string, params?: any[]) => Promise<any[]>;
getDbPath: () => string;
};

export const open = (options: {
Expand Down Expand Up @@ -465,5 +467,6 @@ export const open = (options: {
OPSQLite.loadExtension(options.name, path, entryPoint),
executeRawAsync: (query, params) =>
OPSQLite.executeRawAsync(options.name, query, params),
getDbPath: () => OPSQLite.getDbPath(options.name, options.location),
};
};

0 comments on commit 9e044f8

Please sign in to comment.