Giter VIP home page Giter VIP logo

cordova-sqlite-porter's Introduction

SQLite Porter Cordova/Phonegap Plugin Latest Stable Version Total Downloads

Table of Contents

Overview

This Cordova/Phonegap plugin can be used to import/export to/from a SQLite database using either SQL or JSON.

  • Works on all Cordova platforms that support HTML5 WebSQL DB in the WebView:
    • Android
    • iOS
    • Tizen
    • Blackberry 10
  • Works for native SQLite DB via a plugin. This can be used for platforms that don't have WebSQL in WebView (e.g. Windows) or for unlimited storage on platforms that do:
    • Android
    • iOS
    • Amazon Fire-OS
    • Windows Universal (8.1)
    • Windows Phone 7
    • Windows Phone 8
  • Import/export either just the table data or the entire table structure as well.

The plugin is registered on npm as uk.co.workingedge.cordova.plugin.sqliteporter

donate

I dedicate a considerable amount of my free time to developing and maintaining this Cordova plugin, along with my other Open Source software. To help ensure this plugin is kept updated, new features are added and bugfixes are implemented quickly, please donate a couple of dollars (or a little more if you can stretch) as this will help me to afford to dedicate time to its maintenance. Please consider donating if you're using this plugin in an app that makes you money, if you're being paid to make the app, if you're asking for new features or priority bug fixes.

Usage scenarios

  • Create and populate a database from a database dump.
  • Update an existing database by importing inserts/updates/deletes.
  • Export and send data from a database.

Installation

Using the Cordova/Phonegap CLI

$ cordova plugin add uk.co.workingedge.cordova.plugin.sqliteporter
$ phonegap plugin add uk.co.workingedge.cordova.plugin.sqliteporter

NOTE: Make sure your Cordova CLI version is 5.0.0+ (check with cordova -v). Cordova 4.x and below uses the now deprecated Cordova Plugin Registry as its plugin repository, so using a version of Cordova 4.x or below will result in installing an old version of this plugin.

$ plugman install --plugin=uk.co.workingedge.cordova.plugin.sqliteporter --platform=<platform> --project=<project_path> --plugins_dir=plugins

For example, to install for the Android platform

$ plugman install --plugin=uk.co.workingedge.cordova.plugin.sqliteporter --platform=android --project=platforms/android --plugins_dir=plugins

PhoneGap Build

Add the following xml to your config.xml to use the latest version of this plugin from npm:

<gap:plugin name="uk.co.workingedge.cordova.plugin.sqliteporter" source="npm" />

Usage

The plugin is exposed via the cordova.plugins.sqlitePorter object and provides the following functions:

importSqlToDb()

Executes a set of SQL statements against the defined database. Can be used to import data defined in the SQL statements into the database, and may additionally include commands to create the table structure.

cordova.plugins.sqlitePorter.importSqlToDb(db, sql, opts);

Parameters

  • {Database} db - open SQLite database to import into
  • {string} sql - SQL statements to execute against database.
  • {object} opts - optional parameters:
    • {function} successFn - callback function to execute once import is complete, called with arguments:
      • {integer} count - total number of statements executed in the given SQL string.
    • {function} errorFn - callback function to execute on error during import, called with arguments:
      • {object} error - object representing the error.
    • {function} progressFn - callback function to execute after each successful execution of SQL statement, called with arguments:
      • {integer} count - number of statements executed so far.
      • {integer} totalCount - total number of statements in the given SQL string.

Example usage

Create a database from a SQL dump

var db = window.openDatabase("Test", "1.0", "TestDB", 1 * 1024);
var sql = "CREATE TABLE Artist ([Id] PRIMARY KEY, [Title]);"+
    "INSERT INTO Artist(Id,Title) VALUES ('1','Fred');";
var successFn = function(count){
    alert("Successfully imported "+count+" SQL statements to DB");
};
var errorFn = function(error){
    alert("The following error occurred: "+error.message);
};
var progressFn = function(current, total){
    console.log("Imported "+current+"/"+total+" statements");
};
cordova.plugins.sqlitePorter.importSqlToDb(db, sql, {
    successFn: successFn,
    errorFn: errorFn,
    progressFn: progressFn
});

Update an existing database

var db = window.openDatabase("Test", "1.0", "TestDB", 1 * 1024);
var sql = "INSERT INTO Artist(Id,Title) VALUES ('6','Jane');"+
    "UPDATE Artist SET Title='Susan' WHERE Id='2';"+
    "DELETE FROM Artist WHERE Id='5';";
var successFn = function(count){
    alert("Successfully imported "+count+" SQL statements to DB");
};
var errorFn = function(error){
    alert("The following error occurred: "+error.message);
};
var progressFn = function(current, total){
    console.log("Imported "+current+"/"+total+" statements";
};
cordova.plugins.sqlitePorter.importSqlToDb(db, sql, {
    successFn: successFn,
    errorFn: errorFn,
    progressFn: progressFn
});

exportDbToSql()

Exports a SQLite DB as a set of SQL statements.

cordova.plugins.sqlitePorter.exportDbToSql(db, opts);

Parameters

  • {Database} db - open SQLite database to export
  • {object} opts - optional parameters:
    • {function} successFn - callback function to execute after export is complete, with arguments:
      • {string} sql - exported SQL statements combined into a single string.
      • {integer} count - number of SQL statements in exported string.
    • {boolean} dataOnly - if true, only row data will be exported. Otherwise, table structure will also be exported. Defaults to false.
    • {boolean} structureOnly - if true, only table structure will be exported. Otherwise, row will also be exported. Defaults to false.
    • {array} tables - list of table names to export. If not specified, all tables will be exported.

Example usage

var db = window.openDatabase("Test", "1.0", "TestDB", 1 * 1024);
var successFn = function(sql, count){
    console.log("Exported SQL: "+sql);
    alert("Exported SQL contains "+count+" statements");
};
cordova.plugins.sqlitePorter.exportDbToSql(db, {
    successFn: successFn
});

importJsonToDb()

Converts table structure and/or row data contained within a JSON structure into SQL statements that can be executed against a SQLite database. Can be used to import data into the database and/or create the table structure.

cordova.plugins.sqlitePorter.importJsonToDb(db, json, opts);

Parameters

  • {Database} db - open SQLite database to import into
  • {string/object} json - JSON structure containing row data and/or table structure as either a JSON object or string
  • {object} opts - optional parameters:
    • {function} successFn - callback function to execute once import is complete, called with arguments:
      • {integer} count - total number of statements executed in the given SQL string.
    • {function} errorFn - callback function to execute on error during import, called with arguments:
      • {object} error - object representing the error.
    • {function} progressFn - callback function to execute after each successful execution of SQL statement, called with arguments:
      • {integer} count - number of statements executed so far.
      • {integer} totalCount - total number of statements in the given SQL string.
    • {integer} batchInsertSize - maximum number of inserts to batch into a SQL statement using UNION SELECT method. Defaults to 250 if not specified. Set to 1 to disable batching and perform 1 insert per SQL statement. You can tweak this to optimize performance but numbers higher than 500 may cause the app to run out of memory and crash.

The structure

Example usage

Create a database from a SQL dump

var db = window.openDatabase("Test", "1.0", "TestDB", 1 * 1024);
var json = {
    "structure":{
        "tables":{
            "Artist":"([Id] PRIMARY KEY, [Title])"
        },
       "otherSQL": [
            "CREATE UNIQUE INDEX Artist_ID ON Artist(Id)"
       ]
    },
    "data":{
        "inserts":{
            "Artist":[
                {"Id":"1","Title":"Fred"},
                {"Id":"2","Title":"Bob"},
                {"Id":"3","Title":"Jack"},
                {"Id":"4","Title":"John"}
            ]
        }
    }
};
var successFn = function(count){
    alert("Successfully imported JSON to DB; equivalent to "+count+" SQL statements");
};
var errorFn = function(error){
    alert("The following error occurred: "+error.message);
};
var progressFn = function(current, total){
    console.log("Imported "+current+"/"+total+" statements";
};
cordova.plugins.sqlitePorter.importJsonToDb(db, json, {
    successFn: successFn,
    errorFn: errorFn,
    progressFn: progressFn,
    batchInsertSize: 500
});

Update an existing database

var db = window.openDatabase("Test", "1.0", "TestDB", 1 * 1024);
var json = {
    "data":{
        "inserts":{
            "Artist":[
                {"Id":"1","Title":"Fred"},
                {"Id":"2","Title":"Bob"}
            ]
        },
        "updates":{
            "Artist":
                [
                    {
                        "set": {"Title":"Jill"},
                        "where": {"Id":"3"}
                    },
                    {
                        "set": {"Title":"Susan"},
                        "where": {"Id":"4"}
                    }
                ]
            },
        },
        "deletes":{
            "Artist":[
                {"Id":"5"},
                {"Id":"6"}
            ]
        }
    }
};
var successFn = function(count){
    alert("Successfully imported JSON to DB; equivalent to "+count+" SQL statements");
};
var errorFn = function(error){
    alert("The following error occurred: "+error.message);
};
var progressFn = function(current, total){
    console.log("Imported "+current+"/"+total+" statements";
};
cordova.plugins.sqlitePorter.importJsonToDb(db, json, {
    successFn: successFn,
    errorFn: errorFn,
    progressFn: progressFn
});

exportDbToJson()

Exports a SQLite DB as a JSON structure

cordova.plugins.sqlitePorter.exportDbToJson(db, opts);

Parameters

  • {Database} db - open SQLite database to export
  • {object} opts - optional parameters:
    • {function} successFn - callback function to execute after export is complete, with arguments:
      • {object} json - exported JSON structure.
      • {integer} count - number of SQL statements that exported JSON structure corresponds to.
    • {boolean} dataOnly - if true, only row data will be exported. Otherwise, table structure will also be exported. Defaults to false.
    • {boolean} structureOnly - if true, only table structure will be exported. Otherwise, row will also be exported. Defaults to false.
    • {array} tables - list of table names to export. If not specified, all tables will be exported.

Example usage

var db = window.openDatabase("Test", "1.0", "TestDB", 1 * 1024);
var successFn = function(json, count){
        console.log("Exported JSON: "+json);
        alert("Exported JSON contains equivalent of "+count+" SQL statements");
    };
cordova.plugins.sqlitePorter.exportDbToJson(db, {
    successFn: successFn
});

wipeDb()

Wipes all data from a database by dropping all existing tables.

cordova.plugins.sqlitePorter.wipeDb(db, opts);

Parameters

  • {Database} db - open SQLite database to wipe
  • {object} opts - optional parameters:
    • {function} successFn - callback function to execute once wipe is complete, called with arguments:
      • {integer} count - number of tables dropped.
    • {function} errorFn - callback function to execute on error during wipe, called with arguments:
      • {object} error - object representing the error.
    • {function} progressFn - callback function to execute after each successful table drop, called with arguments:
      • {integer} count - number of tables dropped so far.
      • {integer} totalCount - total number of tables to drop.

Example usage

var db = window.openDatabase("Test", "1.0", "TestDB", 1 * 1024);
var successFn = function(count){
    alert("Successfully wiped "+count+" tables");
};
var errorFn = function(error){
    alert("The following error occurred: "+error.message);
};
var progressFn = function(current, total){
    console.log("Wiped "+current+"/"+total+" tables";
};
cordova.plugins.sqlitePorter.wipeDb(db, {
    successFn: successFn,
    errorFn: errorFn,
    progressFn: progressFn
});

JSON structure

This json parameter uses a custom data structure defined by this plugin for the import/export of SQLite table structure and data.

There are two top-level keys, both of which are optional:

{
    "structure": ...,
    "data": ...
}

structure

Defines the table structure of the SQLite DB and other non-data-related SQL statements (e.g. index definitions). There are two possible keys:

{
    "structure":{
        "tables": ...,
        "otherSQL": ...
    }
}

tables

A key/value map which defines table structure, where the key is the table name and the value is the SQL table definition.

Note: on importing a tables structure, if a table with same name as a key exists in the target database, it will be dropped and recreated using the specified table structure.

For example, the SQL statement CREATE TABLE Artist ([Id] PRIMARY KEY, [Title]); would have the corresponding tables entry:

{
    "structure":{
        "tables": {
            "Artist":"([Id] PRIMARY KEY, [Title])"
        }
    }
}

otherSQL

A list of SQL statements which are not related to table structure or data insertion, for example the creation of indices, for example:

{
   "otherSQL": [
        "CREATE UNIQUE INDEX Artist_ID ON Artist(Id)"
   ]
}

data

Defines data to insert into database tables. There are 3 optional keys:

{
    "structure":{
        "data": {
            "inserts": ...,
            "updates": ...,
            "deletes": ...
        }
    }
}

inserts

A key/value map of row data to insert, where the key is the table name and the value is a list of row data objects in which the key is the field name and the value is the field value.

For example, the SQL statement:

INSERT INTO Artist(Id,Title) VALUES ('6','Jane');

Would be represented as:

{
    "structure":{
        "data": {
            "inserts": {
                "Artist":[
                    {
                        "Id":"6",
                        "Title":"Jane"
                    }
                ]
            }
        }
    }
}

updates

A key/value map of row data to update, where the key is the table name and the value is a list of row update objects. A row update update consists of a where key which identifies the row to update via the primary key and a set object which defines the row data to insert.

For example, the SQL statement:

UPDATE Artist SET Title='Susan' WHERE Id='2';

Would be represented as:

{
    "structure":{
        "data": {
            "updates": {
                "Artist":[
                    {
                        "set": {
                            "Title":"Susan"
                        },
                        "where": {
                            "Id":"2"
                        }
                    }
                ]
            }
        }
    }
}

deletes

A key/value map of rows to delete, where the key is the table name and the value is an object define the primary key of the row to delete.

For example, the SQL statement:

DELETE FROM Artist WHERE Id='5';

Would be represented as:

{
    "structure":{
        "data": {
            "deletes": {
                "Artist":[
                    {
                        "Id":"5"
                    }
                ]
            }
        }
    }
}

JSON structure examples

Table creation

A JSON structure to create a table structure, but not insert any row data, might look like this:

{
    "structure":{
        "tables":{
          "Album":"([AlbumId] PRIMARY KEY, [Title])",
          "TrackDetails":"([TrackId] PRIMARY KEY, [Name])"
        },
        "otherSQL": [
          "CREATE UNIQUE INDEX Album_ID ON Album(AlbumId)"
        ]
    }
}

Table creation and data insertion

A JSON structure to create a table structure and insert row data might look like this:

{
  "structure":{
    "tables":{
      "Album":"([AlbumId] PRIMARY KEY, [Title])",
      "TrackDetails":"([TrackId] PRIMARY KEY, [Name])"
    },
    "otherSQL": [
      "CREATE UNIQUE INDEX Album_ID ON Album(AlbumId)"
    ]
  },
  "data":{
    "inserts":{
      "Album":[
        {
          "AlbumId":"1",
          "Title":"Fred"
        },
        {
          "AlbumId":"2",
          "Title":"Bob"
        },
        {
          "AlbumId":"3",
          "Title":"Tom"
        },
        {
          "AlbumId":"4",
          "Title":"Dick"
        },
        {
          "AlbumId":"5",
          "Title":"Harry"
        }
      ],
      "TrackDetails":[
        {
          "TrackId":"1",
          "Name":"This track is cool"
        },
        {
            "TrackId":"1",
            "Name":"This track sucks"
        }
      ]
    }
  }
}

Data updates

A JSON structure which updates row data but doesn't change the table structure might look like this:

{
    "data":{
        "inserts":{
            "Artist":[
                {
                    "Id":"1",
                    "Title":"Fred"
                },
                {
                    "Id":"2",
                    "Title":"Bob"
                }
            ]
        },
        "updates":{
            "Artist":
                [
                    {
                        "set": {
                            "Title":"Jill"
                        },
                        "where": {
                            "Id":"3"
                        }
                    },
                    {
                        "set": {
                            "Title":"Susan"
                        },
                        "where": {
                            "Id":"4"
                        }
                    }
                ]
            },
        },
        "deletes":{
            "Artist":[
                {
                    "Id":"5"
                },
                {
                    "Id":"6"
                }
            ]
        }
    }
}

JSON import optimisations

The JSON structure passed to the importJsonToDb() function is parsed in order to generate corresponding SQL commands. In doing so, the following optimisations have been made to minimize time taken to import large amounts of data:

Batched inserts

When importing large amounts of data to the database, INSERT statements can be time consuming. Therefore, the plugin uses the UNION SELECT method (see this stackoverflow post for details), if the JSON structure contains "inserts", to batch multiple inserts in a single SQL statement, which leads to significant performance gains when bulk importing data as to populate a database.

The default batch size is a maximum of 250 inserts per INSERT statement; this can be overridden using the batchInsertSize option. Setting this to 1 disables batching and performs 1 insert per SQL statement. You can tweak this to optimize performance but numbers higher than 500 may cause the app to run out of memory and crash.

In the example project illustrating use of this plugin, the complex database example is actually the Chinook database - a sample database which contains over 15,000 INSERTS in the SQL file. Running the example project on my Samsung Galaxy S4 with no batching, importing the SQL file takes around 300 seconds (5 mins). Whereas the JSON equivalent, using UNION SELECTs with a batch size of 500, has only 17 INSERT statements and importing this takes around 3 seconds - 100 times faster!

Note: when using the importSqlToDb(), you must make any optimisations in your SQL.

Delayed index creation

If the JSON structure "otherSql" key contains CREATE INDEX statements, these are executed after all other SQL commands, and in a separate transaction in order to optimise performance when inserting large amounts of data.

Example projects

HTML5 WebSQL

https://github.com/dpa99c/cordova-sqlite-porter-example

This example project illustrates how the plugin can be used to import/export data from a WebSQL database in the WebView.

Native SQLite

https://github.com/dpa99c/cordova-sqlite-porter-example-native-plugin

This example project illustrates how the plugin can be used to import/export data from a native SQLite database using a native SQLite plugin

License

================

The MIT License

Copyright (c) 2015 Working Edge Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

cordova-sqlite-porter's People

Contributors

alexhisen avatar devnix avatar dpa99c avatar eyalin avatar grayver avatar hectorcolasvaltuena avatar joaovrgumiero avatar leoruhland avatar marqusg avatar mikelhamer avatar torvaldz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-sqlite-porter's Issues

Plugin doesn't work on iOS using Ionic DevApp

I'm submitting a ... (check one with "x"):

  • bug report
  • feature request
  • documentation issue

Bug report

Current behavior:

Started a Ionic3 blank project and installed plugins and npm packages for sqlite and sqlite-porter. Database was created successfully using sqlite, but when trying to fill the database using sqlite-porter to import a sql file, it throws the error "plugin_not_installed".

Expected behavior:

Data should be imported to the database after the sql statements being executed with importSqlToDb.

Steps to reproduce:

  1. Installed Ionic 3.20
  2. Started blank project
  3. Installed sqlite and sqlite-porter plugins using:
$ ionic cordova plugin add cordova-sqlite-storage
$ npm install --save @ionic-native/sqlite
$ ionic cordova plugin add uk.co.workingedge.cordova.plugin.sqliteporter
$ npm install --save @ionic-native/sqlite-porter
  1. Implemented the code as seen in https://github.com/rodrake1/sqlite-app
  2. Ran it on iPhone 7 using Ionic DevApp latest version
  3. Created database using first button
  4. Tried to fill database using second button

Environment information

  • Cordova CLI version : 7.0.1

  • Cordova platform version:
    android ~6.2.2
    blackberry10 ~3.8.0 (deprecated)
    browser ~4.1.0
    webos ~3.7.0
    windows ~5.0.0

  • Plugins & versions installed in project (including this plugin)
    cordova-sqlite-storage 2.5.2 "Cordova sqlite storage plugin"
    uk.co.workingedge.cordova.plugin.sqliteporter 1.1.0 "sqlite porter"

  • Dev machine OS and version, e.g.

    • Windows 7

Runtime issue

  • Device details

    • iPhone 7
  • OS details

    • iOS 12.1
  • Node JS version: 8.12.0

Related code:

insert any relevant code here such as plugin API calls / input parameters

Console output

plugin_not_installed

// Paste any relevant JS/native console output here



Other information:

Feature request

Documentation issue

Could this be a pure JavaScript package instead?

@dpa99c I just discovered this plugin from Ionic-native. I would like to start with a note of appreciation for your hard work to help people deal with some of the issues they encounter with sqlite and Cordova in general. I made a small donation and would like to give you a word of encouragement to keep up the good work. I am sure your work will be recognized more and more over time.

Looking at this project I see that it could be just as useful for either Cordova or Web SQL in the browser. While the Web SQL spec is unfortunately deprecated and not supported by some newer browsers such as Edge I can imagine some possible uses including:

Ideally it should be possible to consume as a CommonJS (ES5) module or ES6 module by systems such as Browserify, Webpack, Rollup, or prepack.io. You may want to look at what I did in https://github.com/brodybits/sql-promise-helper in the past.

I would love to make this contribution but am pretty swamped with backlog right now.

importJsontoDb - is building invalid sql statement

"INSERT OR REPLACE INTO TableName(column1, column2, column3, function(){for(var e={},n=[],t=0,o=this.length;t<o;t++)e[this[t]]||(e[this[t]]=1,n.push(this[t]));return n}, function(e){for(var n=new Array,t={},o=0;o<e.length;o++)t[e[o]]=1;for(var r=0;r<this.length;r++)t[this[r]]||(t[this[r]]=1,n.push(this[r]));return n})...

table name escaping

While exporting a database, the "SELECT * FROM " + tableName query fails to execute for table names with a hyphen (e.g., table-name).

I tried adding quotes around the table name in the query, but the JSON result included them like so:
{"structure": {"tables": {"'table-name'": ...} } }
and the importJSON function didn't work.

sqlite_sequence error

By documentation you can't drop this table (sqlite_sequence) on import:
message:"Failed to import SQL; message=sqlite3_prepare_v2 failure: table sqlite_sequence may not be dropped"

So... need to remove from exported sql:

DROP TABLE IF EXISTS `sqlite_sequence`;
CREATE TABLE sqlite_sequence(name,seq);

window.openDatabase is showing error in Ionic framework.

I tried to create database using Sqlite-porter alone without using standard sqlite plugin. but window.openDatabase(); is showing this error all the time. "Property 'openDatabase' does not exist on type 'Window & typeof globalThis'." Is there any way to resolve this. or this plugin cannot be used to "create" database in Ionic ??

Passing the json with columns without null values?

I am receiving a JSON which only has valid values (not null) but I am getting an error saying 15 columns are there and only 12 values are applied.If I pass the null values for all the columns then the query executes successfully. Is there any chance the plugin can support the JSON which only has valid values?

BUG WITH THIS NEW VERSION PLUGIN

I'm submitting a ... (check one with "x"):

  • bug report

  • documentation issue

  • feature request

Bug report

Current behavior:

Ionic3
On iOS don't show erros, but importJsonToDb and importSqlToDb don't work.
On Android show a error:
:8100/plugins/uk.co.workingedge.cordova.plugin.sqliteporter/www/sqlitePorter.js:649 Uncaught SyntaxError: missing ) after argument list
polyfills.js:3 Uncaught Error: Module uk.co.workingedge.cordova.plugin.sqliteporter.sqlitePorter does not exist.

Expected behavior:
Import .sql or .json to .db

Steps to reproduce:
Create a new empty project ionic3, install plugin and try to import .sql or .json

Environment information
MacBook Pro HIGH-SIERRA 10.13.5 - (Retina, 13-inch, Early 2015) 2,7 GHz Intel Core i5, 8 GB 1867 MHz DDR3

  • Cordova CLI version
    • 8.0.0
  • Cordova platform version
    • Installed platforms:
      android 7.0.0
      ios 4.5.4
      Available platforms:
      browser ~5.0.1
      osx ~4.0.1
      windows ~5.0.0
      www ^3.12.0
  • Plugins & versions installed in project (including this plugin)
    cordova-plugin-device 2.0.2 "Device"
    cordova-plugin-file 6.0.1 "File"
    cordova-plugin-inappbrowser 3.0.0 "InAppBrowser"
    cordova-plugin-inapppurchase 1.1.0 "In App Purchase"
    cordova-plugin-ionic-keyboard 2.0.5 "cordova-plugin-ionic-keyboard"
    cordova-plugin-ionic-webview 1.1.19 "cordova-plugin-ionic-webview"
    cordova-plugin-splashscreen 5.0.2 "Splashscreen"
    cordova-plugin-statusbar 2.4.2 "StatusBar"
    cordova-plugin-whitelist 1.3.3 "Whitelist"
    cordova-sqlite-storage 2.3.2 "Cordova sqlite storage plugin"
    onesignal-cordova-plugin 2.4.0 "OneSignal Push Notifications"
    uk.co.workingedge.cordova.plugin.sqliteporter 1.0.3 "sqlite porter"
  • Dev machine OS and version, e.g.
    • OSX
      ProductName: Mac OS X
      ProductVersion: 10.13.5
      BuildVersion: 17F77

Runtime issue

  • Device details
    • iPhone X Simulator
  • OS details
    • Android 7.0.1_

Android build issue:

  • Node JS version
    • v10.1.0
  • Gradle version
    • 4.1 4.6 buildOutputCleanup
  • Target Android SDK version
    • 16
  • Android SDK details
    • sdkmanager --list | sed -e '/Available Packages/q'

iOS build issue:

  • Node JS version
    • v10.1.0
  • XCode version Version 9.4.1 (9F2000)

If using an Ionic Native Typescript wrapper for this plugin:

  • Ionic environment info
    cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils : 1.19.2
    ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : 8.0.0

local packages:

@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0 ios 4.5.4
Ionic Framework    : ionic-angular 3.9.2

System:

Android SDK Tools : 26.1.1
ios-deploy        : 1.9.2
Node              : v10.1.0
npm               : 5.6.0
OS                : macOS High Sierra
Xcode             : Xcode 9.4.1 Build version 9F2000

Environment Variables:

ANDROID_HOME : /Users/user/Library/Android/sdk

Misc:

backend : pro

Related code:
this.sqlitePorter.importSqlToDb()

Console output
none

Other information:
I see the file sqlitePorter.js and they have a new function to remove comments maybe this new version came out with bug.

Feature request

Documentation issue

define composite key

wanted to create composite key where i want to define 3 columns as a primary key , can anyone tell me how do i achieve using this plugin

Some bugs

console.log("Imported "+current+"/"+total+" statements"; missing closing ')'

cordova.plugins.sqlitePorter.wipeData(db, opts); should be

cordova.plugins.sqlitePorter.wipeDb(db, opts);

Unable to import all items

I am using the plugin to import hundreds to thousands of items. Depending on the size of the json array I am importing using different batch sizes will yield a different number items imported. Sometimes they all import and sometimes only some items will import. Only using the 0.1.2 version of the plugin will consistently yield all items imported.

importJsonToDb is not working

hi @dpa99c ,

i am new come from ionic,
i would like to import some data from server side, following the structure you define like

{
    "structure":{
        "tables":{
            "Album":"([AlbumId] PRIMARY KEY, [Title])",
            "TrackDetails":"([TrackId] PRIMARY KEY, [Name])"
        },
        "otherSQL": [
            "CREATE UNIQUE INDEX Album_ID ON Album(AlbumId)"
        ]
    },
    "data":{
        "inserts":{
            "Album":[
                {
                    "AlbumId":"1",
                    "Title":"Fred"
                },
                {
                    "AlbumId":"2",
                    "Title":"Bob"
                },
                {
                    "AlbumId":"3",
                    "Title":"Tom"
                },
                {
                    "AlbumId":"4",
                    "Title":"Dick"
                },
                {
                    "AlbumId":"5",
                    "Title":"Harry"
                }
            ],
            "TrackDetails":[
                {
                    "TrackId":"1",
                    "Name":"This track is cool"
                },
                {
                    "TrackId":"1",
                    "Name":"This track sucks"
                }
            ]
        }
    }
}

however, after import i try to query from sqlite by following statement
SELECT * FROM Album, it's return error message
sqlite3_prepare_v2 failure: no such table: Album

this is some code from my project, it show you how i import

    let newdata = {
        "structure":{
            "tables":{
                "Album":"([AlbumId] PRIMARY KEY, [Title])",
                "TrackDetails":"([TrackId] PRIMARY KEY, [Name])"
            },
            "otherSQL": [
                "CREATE UNIQUE INDEX Album_ID ON Album(AlbumId)"
            ]
        },
        "data":{
            "inserts":{
                "Album":[
                    {
                        "AlbumId":"1",
                        "Title":"Fred"
                    },
                    {
                        "AlbumId":"2",
                        "Title":"Bob"
                    },
                    {
                        "AlbumId":"3",
                        "Title":"Tom"
                    },
                    {
                        "AlbumId":"4",
                        "Title":"Dick"
                    },
                    {
                        "AlbumId":"5",
                        "Title":"Harry"
                    }
                ],
                "TrackDetails":[
                    {
                        "TrackId":"1",
                        "Name":"This track is cool"
                    },
                    {
                        "TrackId":"1",
                        "Name":"This track sucks"
                    }
                ]
            }
        }
    }

    this.sqlite.create(this._dbConfig)
        .then((db: SQLiteObject) => {
            this.porter.importJsonToDb(db, newdata)
                .then(() => {
                    console.log("done");//show done here, without error but no record
                })
                .catch(err => {
                    console.log(err);
                })
        })

and this is my query statement:

    this.sqlite.create(this._dbConfig)
        .then((db: SQLiteObject) => {
            db.executeSql("SELECT * FROM Album")
                .then(data => {
                    foreach(let i = 0; i < data.rows.length, i++) {
                        console.log(data.rows.item(i));
                    }
                })
                .catch(err => {
                    console.log(err);
                    //prompt error here: sqlite3_prepare_v2 failure: no such table: Album
                })
        })

this is my environment:

cli packages: (x:\nvm\v8.9.4\node_modules)

    @ionic/cli-utils  : 1.19.2
    ionic (Ionic CLI) : 3.20.0

global packages:

    cordova (Cordova CLI) : 8.0.0

local packages:

    @ionic/app-scripts : 3.1.10
    Cordova Platforms  : android 7.0.0
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    Node              : v8.9.4
    npm               : 5.6.0
    OS                : Windows 10

thank you for help...

IOS importJsonToDb doesn't import all the data

Hello,

I use this plugin to import json data in database. It works fine on Android but on IOS if i have a large json, not all the data is inserted (and i have no erros log). Is there any max size for the json on IOS ? Thanks.

importJsonToDb is failing suddenly

Sqlite Porter plugin function importJsonToDb is failing suddenly

ERROR Error: Uncaught (in promise): TypeError: handleError is not a function
TypeError: handleError is not a function
at SQLitePluginTransaction.fn (sqlitePorter.js:121)
at SQLitePluginTransaction.start (SQLitePlugin.js:331)
at SQLitePlugin.js:145
at ZoneDelegate.invokeTask (polyfills.js:3505)
at Object.onInvokeTask (vendor.js:89204)
at ZoneDelegate.invokeTask (polyfills.js:3504)
at Zone.runTask (polyfills.js:3273)
at invokeTask (polyfills.js:3586)
at ZoneTask.invoke (polyfills.js:3575)
at timer (polyfills.js:5658)
at resolvePromise (polyfills.js:3904)
at SQLitePluginTransaction.error (polyfills.js:3811)
at SQLitePluginTransaction.start (SQLitePlugin.js:338)
at SQLitePlugin.js:145
at ZoneDelegate.invokeTask (polyfills.js:3505)
at Object.onInvokeTask (vendor.js:89204)
at ZoneDelegate.invokeTask (polyfills.js:3504)
at Zone.runTask (polyfills.js:3273)
at invokeTask (polyfills.js:3586)
at ZoneTask.invoke (polyfills.js:3575)

statement count missing 1 quantity

[{"catalog":"6191-1-001","lotcode":"RJM326","expiration":"06/01/200707/31/2008"},
{"catalog":"5532-G-616","lotcode":"MRPMJD","expiration":"06/01/200705/29/2012"},
{"catalog":"5532-G-409","lotcode":"M0VMJD","expiration":"06/01/200705/29/2012"},
{"catalog":"5530-G-416","lotcode":"MR8MJD","expiration":"06/01/200705/29/2012"},
{"catalog":"5551-G-320","lotcode":"Z541","expiration":"06/01/200705/29/2012"}]

console-via-logger.js:174 Imported 1/4 statements
console-via-logger.js:174 Imported 2/4 statements
console-via-logger.js:174 Imported 3/4 statements
console-via-logger.js:174 Imported 4/4 statements

I got it counted 4 but the output should be 5.

window.openDatabase is undefied

I'm submitting a ... (check one with "x"):

  • bug report
  • feature request
  • documentation issue

Bug report

Current behavior:

Expected behavior:

Steps to reproduce:

Environment information

  • Cordova CLI version
    • cordova -v
  • Cordova platform version
    • cordova platform ls
  • Plugins & versions installed in project (including this plugin)
    • cordova plugin ls
  • Dev machine OS and version, e.g.
    • OSX
      • sw_vers
    • Windows 10
      • winver

Runtime issue

  • Device details
    • e.g. iPhone 7, Samsung Galaxy S8, iPhone X Simulator, Pixel XL Emulator
  • OS details
    • e.g. iOS 11.2, Android 8.1

Android build issue:

  • Node JS version
    • node -v
  • Gradle version
    • ls platforms/android/.gradle
  • Target Android SDK version
    • android:targetSdkVersion in AndroidManifest.xml
  • Android SDK details
    • sdkmanager --list | sed -e '/Available Packages/q'

iOS build issue:

  • Node JS version
    • node -v
  • XCode version

If using an Ionic Native Typescript wrapper for this plugin:

  • Ionic environment info
    • ionic info
  • Installed Ionic Native modules and versions
    • npm list | grep "@ionic-native"

Related code:

insert any relevant code here such as plugin API calls / input parameters

Console output

console output

// Paste any relevant JS/native console output here



Other information:

Feature request

Documentation issue

ionic3 window.openDatabase in undefied

I'm submitting a ... (check one with "x"):

  • bug report
  • feature request
  • documentation issue

Bug report

Current behavior:

Expected behavior:

Steps to reproduce:

Environment information

  • Cordova CLI version
    • cordova -v
  • Cordova platform version
    • cordova platform ls
  • Plugins & versions installed in project (including this plugin)
    • cordova plugin ls
  • Dev machine OS and version, e.g.
    • OSX
      • sw_vers
    • Windows 10
      • winver

Runtime issue

  • Device details
    • e.g. iPhone 7, Samsung Galaxy S8, iPhone X Simulator, Pixel XL Emulator
  • OS details
    • e.g. iOS 11.2, Android 8.1

Android build issue:

  • Node JS version
    • node -v
  • Gradle version
    • ls platforms/android/.gradle
  • Target Android SDK version
    • android:targetSdkVersion in AndroidManifest.xml
  • Android SDK details
    • sdkmanager --list | sed -e '/Available Packages/q'

iOS build issue:

  • Node JS version
    • node -v
  • XCode version

If using an Ionic Native Typescript wrapper for this plugin:

  • Ionic environment info
    • ionic info
  • Installed Ionic Native modules and versions
    • npm list | grep "@ionic-native"

Related code:

insert any relevant code here such as plugin API calls / input parameters

Console output

console output

// Paste any relevant JS/native console output here



Other information:

Feature request

Documentation issue

Importing from SQL dump fails because of bugged removeComments(sql)

I have encountered some issues when importing data from SQL dumps through the sqlitePorter.importSqlToDb function

Reproduction steps:

version: 1.1.1

Try to ingest

CREATE TRIGGER IF NOT EXISTS update_person_updated_at AFTER UPDATE ON person
BEGIN
    UPDATE person SET updated_at = (strftime('%Y-%m-%d %H:%M:%f', 'now', 'utc')) WHERE id = OLD.id;
END;

Error

"Failed to import SQL; message=sqlite3_prepare_v2 failure: incomplete input","code":5,"statement":"CREATE TRIGGER update_person_updated_at UPDATE ON person\nBEGIN\n    UPDATE person SET updated_at = (strftime('%Y-%m-%d %H:%M:%f', 'now', 'utc')) WHERE id = OLD.id"}

I believe that the bug is caused by the removeComments(sql) function, which I have inspected and shows that the SQL command is interpreted as two different statements:

  1. First statement: BEGIN UPDATE person SET updated_at = (strftime('%Y-%m-%d %H:%M:%f', 'now', 'utc')) WHERE id = OLD.id
  2. Second statement: END

This of course is not right since it must be interpreted as a single SQL statement.

I have made a temporary fix with:

sqlitePorter.importSqlToDb = function (db, sql, opts){
    opts = opts || {};
    if(!isValidDB(db, opts)) return;
    db.transaction(function(tx) {
        try {
            //Clean SQL + split into statements
            var totalCount, currentCount;

            var tempStatements = removeComments(sql).match(statementRegEx);;
            var statements = [];
            for (let i = 0; i < tempStatements.length; i++) {
                if (tempStatements[i].toUpperCase() === 'END') {
                    statements[statements.length - 1] += ';\nEND';
                } else {
                    statements.push(tempStatements[i]);
                }
            }
# ...

Which works, but it the best approach is solving it directly inside the removeComments function.

It would be nice to have an official fix. Let me know if more details are needed.

hard coded worked but import directly from cvs to JSON failed

I got CVS2JSON(cvs) out put as below to console:

[{"catalog":"6191-1-001","lotcode":"RJM326","expiration":"06/01/200707/31/2008"},
{"catalog":"5532-G-616","lotcode":"MRPMJD","expiration":"06/01/200705/29/2012"},
{"catalog":"5532-G-409","lotcode":"M0VMJD","expiration":"06/01/200705/29/2012"},
{"catalog":"5530-G-416","lotcode":"MR8MJD","expiration":"06/01/200705/29/2012"},
{"catalog":"5551-G-320","lotcode":"Z541","expiration":"06/01/200705/29/2012"}]

if I hard copy this to the importJSONtoDB() it works just fine. But if I do

var dataJSONRead = CVS2JSON(cvs);
function importJSONtoDB(dataJSONRead){
....

 "itemPartData": dataJSONRead
....
}

it will throw the error:

"could not prepare statement (1 unrecognized token: ":") 

the log console also looks wrong since I only have 5 records as shown above:

Imported 1/7529 statements
Imported 2/7529 statements
Imported 3/7529 statements

and it stops at 3/7529 statements and no data was inserted to the db.

README.md error

Nice lib!

In example of exportDbToJson()
cordova.plugins.sqlitePorter.exportDbToSql -----> cordova.plugins.sqlitePorter. exportDbToJson

The importJsonToDb() function does not use the column names when importing a json

  • bug report
  • feature request
  • documentation issue

Feature request

Problem:

When importing, the plugin does not use the json column keys to enter the values, it imports considering the order that is in json. Below I give an example:

My table:

CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY, name VARCHAR(40), age INTEGER)

My json:

{  
   "data":{  
      "inserts":{  
         "person":[  
            {  
               "id":"1",
               "age":18,
               "name":"João Gumiero"
            },
            {  
               "id":"2",
               "age":17,
               "name":"Renan Nakamura"
            }
         ]
      }
   }
}

Result of import:

SELECT * FROM person;
[  
   {  
      "id":1,
      "name":"18",
      "age":"João Gumiero"
   },
   {  
      "id":2,
      "name":"17",
      "age":"Renan Nakamura"
   }
]

Why is this a problem?

Why json is "An object is an unordered set of name/value pairs". So to accomplish the import it must consider the json keys.

Solution:

I changed the importJsonToDb() method so when creating the query to add the table field names according to the provided json keys

Code snippet (current code)

if(_count === 0){
    mainSql += "INSERT OR REPLACE INTO " + sqlEscape(tableName) + " SELECT";
    for(var j = 0; j < _fields.length; j++){
        if(typeof _values[j] === "undefined" || _values[j] === null || _values[j].toLowerCase() == 'null'){
            mainSql += " NULL AS '" + _fields[j] + "'";
        }else{
            mainSql += " '" + _values[j] + "' AS '" + _fields[j] + "'";
        }
        if(j < _fields.length-1){
            mainSql += ",";
        }
    }
}

Code snippet (my change)

if(_count === 0){
    mainSql += "INSERT OR REPLACE INTO " + sqlEscape(tableName) + "(";
    for(var field in _fields) {
      if(field == 0) {
        mainSql += _fields[field];
      } else {
        mainSql += ", " + _fields[field];
      }
    }
    mainSql += ") SELECT";
    for(var j = 0; j < _fields.length; j++){
        if(typeof _values[j] === "undefined" || _values[j] === null || _values[j].toLowerCase() == 'null'){
            mainSql += " NULL AS '" + _fields[j] + "'";
        }else{
            mainSql += " '" + _values[j] + "' AS '" + _fields[j] + "'";
        }
        if(j < _fields.length-1){
            mainSql += ",";
        }
    }
}

Result of import (after my change):

SELECT * FROM person;
[  
   {  
      "id":1,
      "name":"João Gumiero",
      "age":18
   },
   {  
      "id":2,
      "name":"Renan Nakamura",
      "age":17
   }
]

Waiting for pull request acceptance (06/04/18)

Several bugs in export of DDL statements

I'm submitting a ... (check one with "x"):

  • bug report
  • feature request
  • documentation issue

Bug report

Current behavior:

Bug 1:
If table name contains an underscore in it, i.e. android_metadata, the exported sql for it does not remove the 'CREATE TABLE android_metadata' part. This is caused by an unnecessary sqlEscape of the tableName when removing it.

Bug2:
Given DDL like this:

CREATE TABLE myTable (
-- a comment
myColumn1 TEXT,
myColumn2 TEXT,
);

The exported sql will remove the newline after the comment and therefore, in a subsequent import, the statement will get all jumbled up and error.
This is caused by a .replace(/\s+/g, " ") call in several places in the code. It should be instead done as .replace(/[^\S\r\n]/g, " ") (i.e. all whitespace except newlines (using a not-not-whitespace regexp)

Info needed on the Json format and methods for dump'ing an existing database

First of all thank you for this plugin, it is a lifesaver..

I'm submitting a ... (check one with "x"):

  • bug report
  • feature request
  • documentation issue

Current behavior:
We have a web application using MySql. I want to use a simplified copy of this database in an Ionic 3 based Android App. So I wrote some batch scripts to download, convert, cleanup etc. The ".sql" version worked fine, but I wanted to switch to JSON import to minimize the startup time.

Environment information
ionic info cli packages: (C:\Users\xxx\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.19.1 ionic (Ionic CLI) : 3.19.1 global packages: cordova (Cordova CLI) : 7.1.0 local packages: @ionic/app-scripts : 3.1.8 Cordova Platforms : android 6.3.0 Ionic Framework : ionic-angular 3.9.2 System: Android SDK Tools : 26.1.1 Node : v8.9.4 npm : 5.6.0 OS : Windows 10 Environment Variables: ANDROID_HOME : C:\DEV\Android\sdk Misc: backend : pro

Documentation issue

I used SQLiteStudio to export in JSON format but that gave a line of errors (Google didn't help) when I used the Json import method. When I checked the examples given here I saw the format is completely different.

Document including the following will be very helpful:

  • A description of the required JSON format, at least a link if specified elsewhere.
  • List of tools/methods to create the required JSON format

Thank you in advance...

Getting datatype mismatch error while importing from json.

I have a table created with the following statement

CREATE TABLE IF NOT EXISTS exam_table (id integer primary key AUTOINCREMENT, moodleexamid integer unique, examname text, examdesc text, examinstructions text, noofstations integer, examvenue text, examstartdate numeric, examstarttime numeric, examenddate numeric, examendtime numeric, examstaffid text, isDownloaded integer, isuploaded integer, timecreated DATETIME, timemodified datetime DEFAULT CURRENT_TIMESTAMP)"

I am able to export data from the db but when I am trying to import the data I a getting the following error.(Note - The data contains string with html tags)

`The following error occurred: {"code":0,"message":"Failed to import SQL; message=datatype mismatch","statement":"INSERT OR REPLACE INTO exam_table SELECT 'Test Examination2' AS 'examname', '1' AS 'id', '22:40:00' AS 'examstarttime', '0' AS 'isDownloaded', '22:40:00' AS 'examendtime', '

Test Examination2

' AS 'examinstructions', '8-06-2016' AS 'examenddate', '8-06-2016' AS 'timecreated', 'sydney' AS 'examvenue', '2' AS 'noofstations', '0' AS 'isuploaded', '2017-01-05 11:10:49' AS 'timemodified', 'teststaff1' AS 'examstaffid', '14' AS 'moodleexamid', '

Test Examination2

' AS 'examdesc', '8-06-2016' AS 'examstartdate' UNION SELECT 'Test Exam - 8/6/2016', '2', '02:25:00', '0', '02:25:00', '

Test Exam - 8/6/2016

', '9-06-2016', '9-06-2016', 'sydney', '2', '0', '2017-01-05 11:10:49', 'teststaff1', '15', '

Test Exam - 8/6/2016

', '9-06-2016' UNION SELECT 'Test Exam - CE243010', '3', '19:55:00', '1', '19:55:00', '

Test Exam - CE243010

', '9-06-2016', '9-06-2016', 'sydney', '2', '0', '2017-01-05 11:10:49', 'teststaff1', '19', '

Test Exam - CE243010

', '9-06-2016' UNION SELECT 'Testing Issue 158', '4', '15:50:00', '0', '23:50:00', '

This exam is created to test the OSCE issue #158

sdgsdfg

sdfhdfghdfh

df dfhjgh fdghgfjh ghjghj,kfghjk dhgdkfgh dskjghkdfgh fghdfkh kdfg dfkghkdfhk fdhdfhkdfjhkj fghdfkghdkfhdkfghgfhkdfk


', '24-11-2016', '22-11-2016', 'sydney', '2', '0', '2017-01-05 11:10:49', 'teststaff1', '22', '

This exam is created to test the OSCE issue #158

sdgsdfg

sdfhdfghdfh

df dfhjgh fdghgfjh ghjghj,kfghjk dhgdkfgh dskjghkdfgh fghdfkh kdfg dfkghkdfhk fdhdfhkdfjhkj fghdfkghdkfhdkfghgfhkdfk


', '22-11-2016'"}

`

wipeDb should also delete Views

Hi,

I was just wondering if we can add a feature to delete Views as well as a part of the wipeDb function.

If that is acceptable, I will update and do a pull request.

Export in JSON but using the sql query

I want to export my data as JSON format. But I want also add a (select) query with some (where) condition to select some specific data. So, Is it possible to export data which are matched with the where conditions only??

TypeError: undefined is not an object (evaluating 'cordova.plugins.sqliteporter')

After successfully building a project for iOS and running on a target device, I see the following error in the XCode Console:
Error in Success callbackId: SQLitePlugin1372263263 : TypeError: undefined is not an object (evaluating 'cordova.plugins.sqliteporter')
The plugin is installed and shows up if I use plugin ls at the command line.
The plugin is being called after deviceready.

commit a3d3016 breaks null values

This commit introduces .toLowerString() call against values that are null, in fact this could never have worked correctly as values can be null. The line number is 394. My call stack for my error:

"Failed to parse JSON structure to SQL: Cannot call method 'toLowerCase' of null"
stack: "TypeError: Cannot call method 'toLowerCase' of null↵ at Object.sqlitePorter.importJsonToDb (file:///android_asset/www/plugins/uk.co.workingedge.cordova.plugin.sqliteporter/www/sqlitePorter.js:394:47)↵ at file:///android_asset/www/js/libraries/webservice.js:2573:39↵From previous event:↵ at Array. (file:///android_asset/www/js/libraries/webservice.js:2578:12)↵ at Function.r.extend.each (file:///android_asset/www/js/extensions/jquery-3.1.0.min.js:2:2865)↵ at check_connectivity.then.$DB.exec.then.addListRecords (file:///android_asset/www/js/libraries/webservice.js:2461:9)↵ at file:///android_asset/www/js/libraries/webservice.js:2614:16"

Exported SQL CREATE before DELETE

I am testing exportDBToSql function and it seems in the exported SQL, the create statement is written first before DROP table. For example:

CREATE TABLE kv (key text primary key, value text);
DROP TABLE IF EXISTS kv;

Is this a bug?

Stripping out comments in importSqlToDb results in invalid statements

var statements = sql
   .replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm,"") // strip out comments
   .match(statementRegEx);

The data that I tried to import included a value that contained two forward slashes ("foo//bar"). Applying the regular expression resulted in a statement that has been cut off within the columns value, making it fail. In my case (since I'm in full control of the SQL that my app receives and know that it will never include any comments), I'm able to remove the line for stripping out comments, but this might not apply to other users of this plugin.

importing JSON to SQLite with child JSON data

Is it possible to ignore JSON strings and insert them into a CELL as TEXT and not as an OBJECT.

Some of my table data is JSON string.. i could stringify it - but wanted to know if there was alceaner solution

Thanks

RETURN FALSE ON IMPORTJSONTODB OR IMPORTSQLTODB WITH NO ERRORS

I'm submitting a ... (check one with "x"):

  • bug report
  • feature request
  • documentation issue

Bug report

Current behavior:
functions importSqlToDb & importJsonToDb both return false with no errors on .then and .catch don't show errors..
e.g.:
let sql = 'CREATE TABLE Artist ([Id] PRIMARY KEY, [Title]);' + 'INSERT INTO Artist(Id,Title) VALUES ("1","Fred");'; // SAME AS DOCUMENTATION
this.sqlitePorter.importSqlToDb(db, sql).then((done) => {
console.log('IMPORT', JSON.stringify(done)); // "done" is 0 => "false" and after all that they don't import Tables and Rows to .db

Expected behavior:
Import .sql to .db

Steps to reproduce:
Create a new blank project ionic3 and install plugin sqlite and sqlite porter for documentation of ionic3 website e try to import .sql to .db

Environment information

  • Cordova CLI version
    • 8.0.0
  • Cordova platform version
    • Installed platforms:
      android 7.0.0
      ios 4.5.4
      Available platforms:
      browser ~5.0.1
      osx ~4.0.1
      windows ~5.0.0
      www ^3.12.0
  • Plugins & versions installed in project (including this plugin)
    • cordova-plugin-device 2.0.2 "Device"
      cordova-plugin-file 6.0.1 "File"
      cordova-plugin-inappbrowser 3.0.0 "InAppBrowser"
      cordova-plugin-inapppurchase 1.1.0 "In App Purchase"
      cordova-plugin-ionic-keyboard 2.0.5 "cordova-plugin-ionic-keyboard"
      cordova-plugin-ionic-webview 1.1.19 "cordova-plugin-ionic-webview"
      cordova-plugin-splashscreen 5.0.2 "Splashscreen"
      cordova-plugin-statusbar 2.4.2 "StatusBar"
      cordova-plugin-whitelist 1.3.3 "Whitelist"
      cordova-sqlite-storage 2.3.3 "Cordova sqlite storage plugin"
      onesignal-cordova-plugin 2.4.0 "OneSignal Push Notifications"
      uk.co.workingedge.cordova.plugin.sqliteporter 1.0.4 "sqlite porter"
  • Dev machine OS and version, e.g.
    • OSX
      • ProductName: Mac OS X
        ProductVersion: 10.13.5
        BuildVersion: 17F77

Runtime issue

  • Device details
    • _e.g. iPhone X Simulator
  • OS details
    • _e.g.Android 7.0.1

Android build issue:

  • Node JS version

    • v10.1.0
  • Gradle version

    • 4.1 4.6 buildOutputCleanup
  • Target Android SDK version

    • 26
  • XCode version
    9.4.1

If using an Ionic Native Typescript wrapper for this plugin:

  • Ionic environment info
    cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils : 1.19.2
    ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : 8.0.0

local packages:

@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0 ios 4.5.4
Ionic Framework    : ionic-angular 3.9.2

System:

Android SDK Tools : 26.1.1
ios-deploy        : 1.9.2
Node              : v10.1.0
npm               : 5.6.0
OS                : macOS High Sierra
Xcode             : Xcode 9.4.1 Build version 9F2000

Environment Variables:

ANDROID_HOME : /Users/user/Library/Android/sdk

Misc:

backend : pro

Related code:

this.sqlite.create({
  name: 'mydb.db',
  location: 'default'
}).then((db: SQLiteObject) => {
  console.log('CHECK DB', JSON.stringify(db));
  let sql = 'CREATE TABLE Artist ([Id] PRIMARY KEY, [Title]);' + 'INSERT INTO Artist(Id,Title) VALUES ("1","Fred");';
  this.sqlitePorter.importSqlToDb(db, sql).then((done) => {
    console.log('IMPORT', JSON.stringify(done));
    db.executeSql("SELECT * FROM Artist;", {}).then((data) => {
      console.log(JSON.stringify(data.rows));
      let grupos = [];
      for (var i = 0; i < data.rows.length; i++) {
        grupos.push(data.rows.item(i));
      }
      console.log('grupos', JSON.stringify(grupos));
      this.sqlitePorter.exportDbToJson(db).then((data) => {
        console.log('EXPORT', JSON.stringify(data));
      });
    }).catch((e) => {console.error('SELECT ERROR', JSON.stringify(e));});
  });
}).catch((e) => {console.error('CHECK DB ERROR', JSON.stringify(e));});

Console output
IMPORT 0

Other information:

Feature request

Documentation issue

Expected 2 arguments but got 3

this.sqlitePorter.importJsonToDb(this.database, json,successfn)

Hi i am stucked in this and i want to know how to pass the 3rd parameter to importjsonTodb function.
Whenever i include the 3rd opts param it says expected 2 but u given 3 in cordova ionic.
Anyone can help please ??

Importing 16mb sql file error: "Maximum call stack size exceeded"

Hi,
I'm trying to import a 16 mb sql file and I'm getting this error. Is it related to your plugin or to SQLitePlugin?

RangeError: Maximum call stack size exceeded
    at String.match (native)
    at null.fn (file:///android_asset/www/plugins/uk.co.workingedge.cordova.plugin.sqliteporter/www/sqlitePorter.js:75:22)
    at SQLitePluginTransaction.start (file:///android_asset/www/plugins/io.litehelpers.cordova.sqlite/www/SQLitePlugin.js:283:12)
    at file:///android_asset/www/plugins/io.litehelpers.cordova.sqlite/www/SQLitePlugin.js:144:32

Debugging Help

When inspecting our android app I can see the following error:

polyfills.js:3 Unhandled Promise rejection: Cannot read property 'replace' of undefined ; Zone: ; Task: null ; Value: TypeError: Cannot read property 'replace' of undefined(…) TypeError: Cannot read property 'replace' of undefined
at trimWhitespace (file:///android_asset/www/plugins/uk.co.workingedge.cordova.plugin.sqliteporter/www/sqlitePorter.js:538:19)
at applyStatements (file:///android_asset/www/plugins/uk.co.workingedge.cordova.plugin.sqliteporter/www/sqlitePorter.js:88:41)
at tx.executeSql.error.message (file:///android_asset/www/plugins/uk.co.workingedge.cordova.plugin.sqliteporter/www/sqlitePorter.js:94:29)
at SQLitePluginTransaction.handleStatementSuccess (file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js:386:5)
at Object.success (file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js:412:18)
at mycb (file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js:457:20)
at Object.callbackFromNative (file:///android_asset/www/cordova.js:293:58)
at :1:9o @ polyfills.js:3r @ polyfills.js:3i @ polyfills.js:3
polyfills.js:3 Error: Uncaught (in promise): TypeError: Cannot read property 'replace' of undefined(…)

When drilling in to the executeSql.error.message get the following:
function applyStatements() {
if (statements.length > 0) {
var statement = trimWhitespace(statements.shift());
tx.executeSql(statement, [], function(){
currentCount++;
if(opts.progressFn){
opts.progressFn(currentCount, totalCount);
}
applyStatements();
}, function (tx, error) {
error.message = "Failed to import SQL; message="+ error.message;
error.statement = statement;
handleError(error);
});
} else if(opts.successFn){
opts.successFn(totalCount);
}

I'm pretty confident there is a data quality issue with the data we are trying to import. We've found and eliminated special characters such as double single quotes and semi-colons. Can you provide any other insight into special characters or other potential data things we should look specifically for?

Thanks! Much appreciated for any help you can provide!

Incorrect string escaping of character sequence ''&\"

Hi it looks like the character sequence ''&" is not escaped properly (test code below).
I'm not a sqlite specialist neither a regex one so i'm unable to suggest a solution.

Thanks.

var json = {
   "structure":{
      "tables":{
         "test":"([Id] PRIMARY KEY, [Title])"
      },
      "otherSQL":[]
   },
   "data":{
      "inserts":{
         "test":[{
           "Id":"1",
           "Title":"''&\""
          }]
      }
   }
};

cordova.plugins.sqlitePorter.importJsonToDb(db, json);
{
  "message":"Failed to import SQL; message=sqlite3_prepare_v2 failure: near \"&\": syntax error",
  "code":5,
  "statement":"INSERT OR REPLACE INTO test SELECT '1' AS 'Id', ''''&"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.