Ionic Sqlite not running on chrome - sqlite

import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
username='name';
items = [];
constructor(public navCtrl: NavController, private sqlite: SQLite) {
}
save()
{
alert();
this.sqlite.create({
name: 'data.db',
location: 'default'
})
.then((db: SQLiteObject) => {
//data insert section
db.executeSql('CREATE TABLE IF NOT EXISTS usernameList(id INTEGER PRIMARY KEY AUTOINCREMENT,name)', {})
.then(() => alert('Executed SQL'))
.catch(e => console.log(e));
//data insert section
db.executeSql('INSERT INTO usernameList(name) VALUES(?)', [this.username])
.then(() => alert('Executed SQL'))
.catch(e => console.log(e));
//data retrieve section
db.executeSql('select * from usernameList', {}).then((data) => {
alert(JSON.stringify(data));
//alert(data.rows.length);
//alert(data.rows.item(5).name);
this.items = [];
if(data.rows.length > 0) {
for(var i = 0; i < data.rows.length; i++) {
//alert(data.rows.item(i).name);�
this.items.push({name: data.rows.item(i).name});
}
}
}, (err) => {
alert('Unable to execute sql: '+JSON.stringify(err));
});
})
.catch(e => alert(JSON.stringify(e)));
}
}
Why I am not able to test my code on broswe
I even try using ionic cordova run browser
This is my console error
OPEN database:
data.db cordova.js:1003 Error: exec proxy not found for
:: SQLitePlugin :: close cordova.js:1003 Error: exec proxy not found
for :: SQLitePlugin :: open
plugins/cordova-sqlite-storage/www/SQLitePlugin.js:196 OPEN database:
data.db FAILED, aborting any pending transactions
plugins/cordova-sqlite-storage/www/SQLitePlugin.js:174 OPEN database:
data.db cordova.js:1003 Error: exec proxy not found for ::
SQLitePlugin :: close cordova.js:1003 Error: exec proxy not found for
:: SQLitePlugin :: open
plugins/cordova-sqlite-storage/www/SQLitePlugin.js:196 OPEN database:
data.db FAILED, aborting any pending transactions

Mysql doesnot support on ionic for testing on browser. Cordova doesnot support it. You need to test in native app

SQLite is not meant to be used on non-"native" builds of your Ionic app:
https://ionicframework.com/docs/native/sqlite/ - see the platforms listed there and there is no "browser" as supported platform.
To test it you should run your app on a device via something like:
ionic cordova run android
Depending on your use case & your requirements for local persistence sometimes it make sense to use Ionic Storage: https://ionicframework.com/docs/storage/ which can use sqlite and can "fallback" / use another type of persistence that is supported by a browser (websql, indexeddb). In this case you can develop and test your app in browser using "ionic serve" and then later on validate that it also works fine on a real device.

Related

pdf.getDocument does not throw a PasswordException

Using react web app
package.json
"react": "^16.10.2",
"react-pdf": "^5.7.2",
imports:
import {pdfjs} from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist#${pdfjs.version}/build/pdf.worker.min.js`;
When loading encrypted (protected) pdf file, promise does not throw a PasswordException as it should
code
const data = convertDataURIToBinary(base64PdfData); //implementation not important
pdfjs.getDocument({data, password: ''}).promise.then(doc => {
console.warn('ends up here even with wrong password!')
}).catch(e => {
console.error('never executed, why?')
})
imported pdfjs dependency is version 2.12.313 so API should match

Firebase Functions ENOENT: no such file or directory, open 'HttpsErrorImpl'

I'm fighting with this issue for over 3 days. I have no idea what is happening.
Firebase Functions throws error only when I try to use Emulator. I try to execute this function in useEffect hook. Again, when I call deployed Cloud Functions everything seems fine, unfortunately in case of using Emulator things don't want to go so well.
const resolvePromise = async () => {
functions.useEmulator("https://0.0.0.0:5001");
const query = functions.httpsCallable("helloWorld");
query()
.then((result) => console.log(result))
.catch((err) => console.log(err));
};
I receive this useless (for me) error.
Error: ENOENT: no such file or directory, open 'HttpsErrorImpl#http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at getCodeFrame (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:1296:18)
at Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:1367:24
at Generator.next (<anonymous>)
at asyncGeneratorStep (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:146:24)
at _next (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:168:9)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
internal
at HttpsErrorImpl#http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197178:29 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197273:29 in _errorForResponse
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197751:39 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170357:26 in step
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170287:21 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170241:31 in fulfilled
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31526:15 in tryCallOne
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31627:26 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31955:16 in _callTimer
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31994:16 in _callImmediatesPass
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:32211:32 in callImmediates
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3457:34 in __callImmediates
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3236:33 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3440:14 in __guard
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3235:20 in flushedQueue
This is all the text which I can see after visiting
http://192.168.0.104:19000/index.bundle -- https://pastebin.com/ggsCMN0W
http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false -- https://pastebin.com/LSeufs8H
It don't make any sense for me. At second address it seems like it's correlated to metro dependency so I updated it, it didn't work.
Any ideas? Thanks in advance :D
Edit 1: All errors are logged at client site, it seems like client can't even call emulator.
Edit 2:
I tried to update entire firebase to v.9 aswell as Expo to 44 SKD with react-native to 0.64.3
This is how my Request function looks now:
const requestApi = () => {
const functions = getFunctions(app);
connectFunctionsEmulator(functions, "127.0.0.1", 5001);
const helloWorld = httpsCallable(functions, "helloWorld");
helloWorld()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message, error.code, error.details);
});
};
I receive only this from catch block :(
internal functions/internal undefined
I also receive warning about Timer after executing that function
Setting a timer for a long period of time, i.e. multiple minutes, is a
performance and correctness issue on Android as it keeps the timer
module awake, and timers can only be called when the app is in the
foreground. See https://github.com/facebook/react-native/issues/12981
for more info. (Saw setTimeout with duration 70000ms)
It don't work only when I try to use Emulator
Couple of potential issues here:
Assuming you're using the latest version of Firebase, functions is actually a method: firebase.functions().useEmulator("localhost", 5001); - Note the () after functions. See docs for more info.
Maybe you've already done this, but have you made sure that the functions emulator is actually running and connectable on port 5001)? Could be useful to test it via Postman or similar.
Make sure you're using the correct IP address for the functions emulator given your setup. 0.0.0.0 probably doesn't map where you want it to... assuming the app is running locally and the functions emulator is too, try 127.0.0.1 or "localhost" ... this answer has more options to troubleshoot.
I am not sure if it is your case, but I had a function:
exports.findUserInAuth = functions.https.onCall((data, context) => {
let field = data.field;
let value = data.value;
if (!field || !value) {
return false;
}
if (field === "email") {
return admin.auth().getUserByEmail(value);
}
});
This one returns a promise, I had to change it to wait for the result before doing a return and problem solved...
exports.findUserInAuth = functions.https.onCall((data, context) => {
let field = data.field;
let value = data.value;
if (!field || !value) {
return false;
}
if (field === "email") {
admin.auth().getUserByEmail(value).then((result) => {
return result;
})
.catch((error) => {
if (error.code === "auth/user-not-found") {
return "Email or Password is incorrect";
}
return `${error.code} ${error.message}`;
});
}
return false;
});
Ok, so after almost a week of fighting with this sh!t.
When you use Expo Go like me. You should copy the host address on which you are emulating your app, and use the same address you emulate your functions (or other tools).
app.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"emulators": {
"functions": {
"host": "192.168.0.104",
"port": 5001
}
}
}
and final code of requestApi function
const requestApi = async () => {
const functions = firebase.functions()
functions.useEmulator("192.168.0.104", 5001); <--- ADDRESS!!!
const helloWorld = functions.httpsCallable("helloWorld");
helloWorld()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message, error.code, error.details);
});
};

Migrate Appcelerator App to React Native maintain SQLite database

Not really "migrating" our app per se, but actually we are building a new version from scratch using React Native.
We will be using the same BundleID etc etc so that this update just installs over the top of the last app.
What we would like to do though, is have access to the SQLite database that existed in the Appcelerator project.
From reading a few articles it seems like it should be possible, however everytime I connect my new app to the simulator or use and Ad Hoc build to update from the previous version, it seems that the database is empty.
database.js
import SQLite from 'react-native-sqlite-storage';
SQLite.DEBUG(true);
SQLite.enablePromise(true);
export default class DbTest {
static listTables(callback) {
const errorCB = err => {
console.log('SQL Error: ' + err);
};
return SQLite.openDatabase({name: '_alloy_'}, callback, errorCB);
}
}
App.js
saveToState(db) {
db.transaction(tx => {
tx.executeSql('select * from sqlite_master', [], (_, results) => {
console.log('Query completed', results);
this.setState(previousState => ({results}));
// Get rows with Web SQL Database spec compliance.
});
});
}
componentDidMount() {
DbTest.listTables(this.saveToState);
}
If I log out what results has in it I get
LOG Query completed {"insertId": undefined, "rows": {"item": [Function item], "length": 0, "raw": [Function raw]}, "rowsAffected": 0}
LOG SQLite.backgroundExecuteSqlBatch({"dbargs":{"dbname":"_alloy_"},"executes":[{"qid":1111,"sql":"COMMIT","params":[]}]})
LOG SQLite.backgroundExecuteSqlBatch({"dbargs":{"dbname":"_alloy_"},"executes":[{"qid":1111,"sql":"BEGIN","params":[]},{"qid":1111,"sql":"select * from sqlite_master","params":[]}]})
If anyone has any experience or can point me to an article I would be very grateful.
Thanks.
Run your Appcelerator app in the simulator or on a device. Then go grab the "alloy" database using Finder and put it into your React project. I open and query the database created when I install my apps on a simulator all the time using DB Browser for SQLite.

Jest Test - The current environment does not support the specified persistence type

I use jest to run some test on my Create React App with Firebase Web SDK coupled with FirebaseUI
Whenever I try to run some tests with --env=jsdom - I run into :
The current environment does not support the specified persistence type. seems related to Auth
Are there any known related issue/workaround ? the code seems to work/compile properly aside from the tests.
Google didn't help much
Here is the test, pretty basic.
HAd to add import "firebase/storage"; because of this : firebase.storage() is not a function in jest test cases
Thanks in advance
import React from "react";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import "firebase/storage";
import {filterIngredientsToRemove} from "./shoppingList-reducer";
Enzyme.configure({adapter: new Adapter()});
describe("", () => {
let shoppingList;
let recipeId;
beforeEach(() => {
shoppingList = {
shoppingListItems: {
"1234": {ingredientId: 987, name: "patate", recipeId: 1234},
"2345": {ingredientId: 987, name: "patate", recipeId: 5432}
},
shoppingListRecipes: {
"1234": {portion: 3}
}
};
recipeId = 1234;
});
it("should filter out the shoppinglistItems with the provided recipeId", () => {
const result = filterIngredientsToRemove(recipeId, shoppingList.shoppingListItems);
expect(result).toEqual([{ingredientId: 987, name: "patate", recipeId: 1234}]);
});
});
Are you setting persistence in your firebase config? Persistence is not supported in the test environment, so you can do something like this to circumvent it:
firebase.auth().setPersistence(process.env.NODE_ENV === 'test'
? firebase.auth.Auth.Persistence.NONE
: firebase.auth.Auth.Persistence.LOCAL);
I ran into this issue too. The problem seems to come from the firebaseui constructor, specifically this line of code in my app:
new firebaseui.auth.AuthUI(this.firebase.auth())
What I did to solve it was initialize the ui object only when actually using it to sign on, not just as a static (typescript) variable. This let me run jest tests that didn't try to sign on just fine.
private static ui: firebaseui.auth.AuthUI | undefined
static startAuthOnElement (selectorToUse: string, onSignedIn: () => void) {
if (this.ui === undefined) this.ui = new firebaseui.auth.AuthUI(this.firebase.auth())
// more code
}
This way all the code that doesn't call startAuthOnElement never runs the firebaseui constructor. This lets me run my jest tests just fine and auth still works in the app.

ionic 3 : Can't resolve all parameters for SQLiteObject: (?)

I'm using Ionic 3 SQLite native plugin from Here(Ionicframework.com), and Here's my constructor code :
constructor(public navCtrl: NavController,
public menu: MenuController,
translate: TranslateService,
private tts: TextToSpeech,
private sqlite: SQLite) {
this.sqlite.create({
name: 'data.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('create table IF NOT EXISTS `localflags`(`flag1` VARCHAR(10),`flag2` VARCHAR(10),`flag3` VARCHAR(10), `flag4` VARCHAR(10));', {})
.then(() => console.log('Table created!!!'))
.catch(e => console.log(e));
}).catch(e => console.log(e));
}
So, when I run it on device using "ionic cordova run android -lc" it give me this error,
Can't resolve all parameters for SQLiteObject: (?)
This code is from the ionic native documentation. This is very basic code, and I'm new to this, so I can't figure out what's wrong with this.
Any help will be appreciated. And if someone can point me to the Ionic 3 SQLite tutorials , that will be great. Thanks in Advance.
Actually, the case was, I had Done import { SQLite, SQLiteObject } from '#ionic-native/sqlite'; this in my ts file, So I thought both SQLite and SQLiteObject are needed to imported in app.module.ts file, but after reading this answer, I removed SQLiteObject from app.module.ts file and also removed injection of SQLite from the constructor and it worked.
Hope this helps someone.
I think you have to add "/ngx" on your import line
import { SQLite, SQLiteObject } from '#ionic-native/sqlite/ngx';
Besides, you don't have to add SQLiteObject in the providers array of app.module.ts file

Resources