Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow copying databases from custom assets path #94

Merged
merged 4 commits into from
May 12, 2024
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ jobs:
yarn turbo run build:android --cache-dir="${{ env.TURBO_CACHE_DIR }}"
build-ios:
runs-on: self-hosted
runs-on: macos-latest
env:
TURBO_CACHE_DIR: .turbo/ios
steps:
Expand Down Expand Up @@ -126,7 +126,7 @@ jobs:
yarn turbo run build:ios --cache-dir="${{ env.TURBO_CACHE_DIR }}"
build-ios-sqlcipher:
runs-on: self-hosted
runs-on: macos-latest
env:
TURBO_CACHE_DIR: .turbo/ios
steps:
Expand Down
26 changes: 19 additions & 7 deletions android/src/main/java/com/op/sqlite/OPSQLiteModule.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package com.op.sqlite

import android.util.Log
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReadableMap
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import com.facebook.react.util.RNLog;

//@ReactModule(name = OPSQLiteModule.NAME)
internal class OPSQLiteModule(context: ReactApplicationContext?) : ReactContextBaseJavaModule(context) {
Expand Down Expand Up @@ -47,25 +50,33 @@ internal class OPSQLiteModule(context: ReactApplicationContext?) : ReactContextB
}
}

@ReactMethod(isBlockingSynchronousMethod = true)
fun moveAssetsDatabase(name: String, extension: String): Boolean {
@ReactMethod
fun moveAssetsDatabase(args: ReadableMap, promise: Promise) {
val filename = args.getString("filename")!!
val path = args.getString("path") ?: "custom"
val overwrite = if(args.hasKey("overwrite")) { args.getBoolean("overwrite") } else false
val context = reactApplicationContext
val assetsManager = context.assets

try {
// Open the input stream for the asset file
val inputStream: InputStream = assetsManager.open("custom/$name.$extension")
val inputStream: InputStream = assetsManager.open("$path/$filename")

// Create the output file in the documents directory
val databasesFolder =
context.getDatabasePath("defaultDatabase")
.absolutePath
.replace("defaultDatabase", "")

val outputFile = File(databasesFolder, "$name.$extension")
val outputFile = File(databasesFolder, filename)

if (outputFile.exists()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it not be more efficient to check if the output file exists before even opening the input stream, so that it is only opened if we will actually use it? This doesn't matter if we are overwriting the file, but in the case where we're not and the file already exists, it would make a difference.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't think opening a stream makes such a difference, but I will move it.

return true
if(overwrite) {
outputFile.delete()
} else {
promise.resolve(true)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the input stream be closed here before resolving the promise and returning?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solved by moving the instantiation down

return
}
}

// Open the output stream for the output file
Expand All @@ -82,9 +93,10 @@ internal class OPSQLiteModule(context: ReactApplicationContext?) : ReactContextB
inputStream.close()
outputStream.close()

return true
promise.resolve(true)
} catch (exception: Exception) {
return false
RNLog.e(this.reactApplicationContext, "Exception: $exception")
promise.resolve(false)
}
}

Expand Down
Binary file not shown.
4 changes: 4 additions & 0 deletions example/android/link-assets-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
{
"path": "assets/sample.sqlite",
"sha1": "0f1675ac593b261b41a5144bc14f41163bd2a0c2"
},
{
"path": "assets/sqlite/sample2.sqlite",
"sha1": "0f1675ac593b261b41a5144bc14f41163bd2a0c2"
}
]
}
Binary file added example/assets/sqlite/sample2.sqlite
Binary file not shown.
4 changes: 4 additions & 0 deletions example/ios/OPSQLiteExample.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
3B5A9E3FD2C56B364AF5A4F3 /* libPods-OPSQLiteExample.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 6EE3066EB7AAB7E17B1CAB50 /* libPods-OPSQLiteExample.a */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
AC1DF06E9759460CAA51B7B1 /* sample2.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 9218E48CFB1F478CAC374D68 /* sample2.sqlite */; };
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
Expand All @@ -31,6 +32,7 @@
89C6BE57DB24E9ADA2F236DE /* Pods-OPSQLiteExample-OPSQLiteExampleTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OPSQLiteExample-OPSQLiteExampleTests.release.xcconfig"; path = "Target Support Files/Pods-OPSQLiteExample-OPSQLiteExampleTests/Pods-OPSQLiteExample-OPSQLiteExampleTests.release.xcconfig"; sourceTree = "<group>"; };
96FD9FD0FC4F4540AC7A9CE6 /* sample.sqlite */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = sample.sqlite; path = ../assets/sample.sqlite; sourceTree = "<group>"; };
ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
9218E48CFB1F478CAC374D68 /* sample2.sqlite */ = {isa = PBXFileReference; name = "sample2.sqlite"; path = "../assets/sqlite/sample2.sqlite"; sourceTree = "<group>"; fileEncoding = undefined; lastKnownFileType = unknown; explicitFileType = undefined; includeInIndex = 0; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -102,6 +104,7 @@
isa = PBXGroup;
children = (
96FD9FD0FC4F4540AC7A9CE6 /* sample.sqlite */,
9218E48CFB1F478CAC374D68 /* sample2.sqlite */,
);
name = Resources;
sourceTree = "<group>";
Expand Down Expand Up @@ -181,6 +184,7 @@
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
022AA638EE144393ADDCAEC0 /* sample.sqlite in Resources */,
AC1DF06E9759460CAA51B7B1 /* sample2.sqlite in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
2 changes: 1 addition & 1 deletion example/ios/OPSQLiteExample/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
<true/>
</dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<string/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
Expand Down
4 changes: 4 additions & 0 deletions example/ios/link-assets-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
{
"path": "assets/sample.sqlite",
"sha1": "0f1675ac593b261b41a5144bc14f41163bd2a0c2"
},
{
"path": "assets/sqlite/sample2.sqlite",
"sha1": "0f1675ac593b261b41a5144bc14f41163bd2a0c2"
}
]
}
2 changes: 1 addition & 1 deletion example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export default function App() {
};

const openAssetsDb = async () => {
const moved = moveAssetsDatabase('sample', 'sqlite');
const moved = await moveAssetsDatabase({filename: 'sample.sqlite'});
console.log('moved', moved);
const db = open({name: 'sample.sqlite'});
const users = db.execute('SELECT * FROM User');
Expand Down
24 changes: 24 additions & 0 deletions example/src/tests/dbsetup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ANDROID_EXTERNAL_FILES_PATH,
IOS_LIBRARY_PATH,
isSQLCipher,
moveAssetsDatabase,
open,
} from '@op-engineering/op-sqlite';
import chai from 'chai';
Expand Down Expand Up @@ -91,6 +92,29 @@ export function dbSetupTests() {
db.delete();
});

it('Moves assets database simple', async () => {
const copied = await moveAssetsDatabase({filename: 'sample.sqlite'});

expect(copied).to.equal(true);
});
it('Moves assets database with path', async () => {
const copied = await moveAssetsDatabase({
filename: 'sample2.sqlite',
path: 'sqlite',
});

expect(copied).to.equal(true);
});
it('Moves assets database with path and overwrite', async () => {
const copied = await moveAssetsDatabase({
filename: 'sample2.sqlite',
path: 'sqlite',
overwrite: true,
});

expect(copied).to.equal(true);
});

// it('Should fail creating in-memory with non-bool arg', async () => {
// try {
// open({
Expand Down
41 changes: 29 additions & 12 deletions ios/OPSQLite.mm
Original file line number Diff line number Diff line change
Expand Up @@ -87,29 +87,46 @@ - (NSDictionary *)getConstants {
return @true;
}

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(moveAssetsDatabase
: (NSString *)name extension
: (NSString *)extension) {
RCT_EXPORT_METHOD(moveAssetsDatabase
: (NSDictionary *)args resolve
: (RCTPromiseResolveBlock)resolve reject
: (RCTPromiseRejectBlock)reject) {
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(
NSLibraryDirectory, NSUserDomainMask, true) objectAtIndex:0];
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:name
ofType:extension];

NSString *destinationPath = [documentPath
stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", name,
extension]];
NSString *filename = args[@"filename"];
BOOL overwrite = args[@"overwrite"];

NSString *sourcePath = [[NSBundle mainBundle] pathForResource:filename
ofType:nil];

NSString *destinationPath =
[documentPath stringByAppendingPathComponent:filename];

NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:destinationPath]) {
return @true;
if (overwrite) {
[fileManager removeItemAtPath:destinationPath error:&error];
if (error) {
NSLog(@"Error: %@", error);
resolve(@false);
return;
}
} else {
resolve(@true);
return;
}
}

NSError *error;
[fileManager copyItemAtPath:sourcePath toPath:destinationPath error:&error];
if (error) {
return @false;
NSLog(@"Error: %@", error);
resolve(@false);
return;
}
return @true;
resolve(@true);
return;
}

// #if RCT_NEW_ARCH_ENABLED
Expand Down
11 changes: 6 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,11 +489,12 @@ export const open = (options: {
};
};

export const moveAssetsDatabase = (
dbName: string,
extension: string
): boolean => {
return NativeModules.OPSQLite.moveAssetsDatabase(dbName, extension);
export const moveAssetsDatabase = (args: {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method's native implementation is now async so the definition here needs to be updated to reflect that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah yeah, missed that. Thanks!

filename: string;
path?: string;
overwrite?: boolean;
}): boolean => {
return NativeModules.OPSQLite.moveAssetsDatabase(args);
};

export const isSQLCipher = (): boolean => {
Expand Down
Loading