editfmah / sharkorm

Shark ORM for iOS/macOS/tvOS/watchOS
http://sharkorm.com
Other
247 stars 39 forks source link

Import external DB #100

Open stefanosisto opened 6 years ago

stefanosisto commented 6 years ago

Hello! I'm asking if with SharkORM I can import an external DB. What I want to do is:

I hope you understand! Thanks, Stefano

editfmah commented 6 years ago

Hi,

Yes you could SharkORM.rawQuery("ATTACH DATABASE 'assetDatabase.db' as Assets"), then do a SELECT INTO ............

Here is an example we did for a data fix.

[SharkORM executeSQL:[NSString stringWithFormat:@"ATTACH DATABASE '%@' as DataFix", [[NSBundle mainBundle] pathForResource:@"DataFix" ofType:@".db"]] inDatabase:nil];
SRKRawResults* spoiledResources = [SharkORM rawQuery:@"SELECT * FROM DataFix.ResourceGuidDataFix WHERE ResourceGuidDataFix.resourceId IN (SELECT Resource.resourceId FROM Resource)"];

if (spoiledResources.rowCount) {
    for (int i=0; i<spoiledResources.rowCount; i++) {

        NSNumber* resourceId = [spoiledResources valueForColumn:@"resourceId" atRow:i];
        NSString* guid = [spoiledResources valueForColumn:@"guid" atRow:i];

        Resource* r = [Resource objectWithId:resourceId.intValue];

        for (Favourite* f in [[[Favourite query] whereWithFormat:@"resourceGuid = %@", r.guid] fetch]) {
            f.resourceGuid = guid;
            [f commit];
        }

        r.guid = guid;
        [r commit];

    }
}
[Settings setJun18DataFixRun];
[SharkORM executeSQL:@"DETACH DATABASE DataFix" inDatabase:nil];
stefanosisto commented 6 years ago

Thanks!!!

stefanosisto commented 6 years ago

Just another question. Can I also insert a .db as asset and use it in the app without creating a new one?

editfmah commented 6 years ago

That can be troublesome, because the bundle is signed and is therefore readonly. So things can get pretty weird and unreliable. You normally have to copy it out to something like the documents folder and the use that name in the open method.

stefanosisto commented 6 years ago

Another question! Can i check if exist a DB in the app and if not exist, attacch 'assetDb' ?

editfmah commented 6 years ago

So you could do that with standard SQLite. execute a raw query with something like, "PRAGMA table_info(myTableName)".