How to display an understandable error from sqlite expo? - sql

I'm creating an app in React-native and I use expo-SQLite for the database.
Unfortunately, I have a problem in my db request and I don't understand the error sent from sqlite.
Could you please help me ?
This is my code:
db.transaction(tx => {
tx.executeSql(
`create table if not exists Espace (id_espace integer primary key autoincrement,name text not null unique)`, [], (tx, results) => {
console.log("Create table Espace");
}
);
});
db.transaction(tx => {
tx.executeSql(
`INSERT INTO Indicator (title, display_order, type, hidden, graphic_type, id_espace) VALUES ('?','?','?','?','?','?')`, [title,display_order,type, hidden, graphic_type, espace], (_, {rows}) =>{
console.log('Put Indicator: ' + title + type + display_order + hidden + graphic_type + espace);
},
(error)=>{
console.log(error);
return true;
}
);
});
When I try to create an indicator my console display this error from sqlite:
WebSQLTransaction {
"_complete": false,
"_error": null,
"_running": true,
"_runningTimeout": false,
"_sqlQueue": Queue {
"first": undefined,
"last": undefined,
"length": 0,
},
"_websqlDatabase": WebSQLDatabase {
"_currentTask": TransactionTask {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
"_db": SQLiteDatabase {
"_closed": false,
"_name": "diplea.db",
},
"_running": true,
"_txnQueue": Queue {
"first": Object {
"item": TransactionTask {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
},
"last": Object {
"item": TransactionTask {
"errorCallback": [Function anonymous],
"readOnly": false,
"successCallback": [Function anonymous],
"txnCallback": [Function anonymous],
},
},
"length": 1,
},
"exec": [Function anonymous],
"version": "1.0",
}
It means nothing to me ... could you tell me a way to understand it? Or maybe what is wrong in my code ...
Thanks in advance !

What you are seeing is the Transaction itself, not the error.
According to Expo's SQLite docs, the error callback of Transaction.executeSql takes two arguments:
error (function) -- Called if an error occured executing this particular query in the transaction. Takes two parameters: the transaction itself, and the error object.
You want your error callback to look like this:
tx.executeSql(
...,
...,
...,
(_, error) => {
console.log(error);
return true;
}
);

Related

Vuex store changes not reactive in components

I have a basic store for inserting and deleting from an array
state: {
assessmentTypes : []
},
mutations: {
setAssessmentTypes(state, assessmentTypes) {
assessmentTypes.forEach(assessmentType => {
state.assessmentTypes.push(assessmentType);
});
},
removeAssessmentType ( state, assessmentTypeId ) {
let assessmentTypeIndex = state.assessmentTypes.map(assessmentType => assessmentType.id).indexOf(assessmentTypeId);
state.assessmentTypes.splice(assessmentTypeIndex, 1)
}
}
I get the state assessmentTypes in computed property in one of my components.
computed:{
assessmentTypes : {
get () {
return this.$store.state.assessmentTypes;
}
}
The problem is I am looping the array in dom for listing a div, but the computed property is not reactive. When I delete or insert a new object into/from the array (through actions), the dom is not rerendering.
Object structure
{
"id": "T7pLDdjmFWAqGiuqB",
"name": "bbb",
"code": "BBB",
"properties": {
combinationOfAssessments: false,
staffCanCreateInstance: false
},
"identifyingContext": {
"semId": "2",
"batchId": "54",
"staffId": "155",
"subjectId": "966",
"subbatchId": "391"
},
"permissions": {
"hod": "1",
"staff": "1"
},
"isActive": "1",
"createdBy": null,
"createdUserName": null,
"createdByUserType": null,
"createdDate": null,
"updatedDate": null,
"updatedBy": null,
"updatedUserName": null,
"updatedByUserType": null,
"propertiesValue": null
}

fetch unable to get response from json server API endpoint

json server is up and running..API response from Browser GET request is working fine.. but from fetch i always got error "Network Request Failed" ... this code is for react-native on expo environment
i also tried by replacing localhost with corresponding ip.. still didn't work for me.. where am i getting stucked?
#base url
export const baseUrl = "http://localhost:3002/";
fetchPosts reducer
return fetch(baseUrl + "posts")
.then(
(response) => {
if (response.ok) {
return response;
} else {
var error = new Error(
"Error " + response.status + ": " + response.statusText
);
error.response = response;
throw error;
}
},
(error) => {
var errmess = new Error(error.message);
throw errmess;
}
)
.then((response) => response.json())
.then((posts) => dispatch(addPosts(posts)))
.catch((error) => dispatch(postsFailed(error.message)));
logger output in console
action POSTS_LOADING # 17:09:00.842
prev state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": "Network request failed",
"isLoading": false,
"posts": Array [],
},
}
action Object {
"type": "POSTS_LOADING",
}
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": true,
"posts": Array [],
},
}
action POSTS_FAILED # 17:09:00.928
prev state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": null,
"isLoading": true,
"posts": Array [],
},
}
action Object {
"payload": "Network request failed",
"type": "POSTS_FAILED",
}
next state Object {
"highlights": Object {
"errMess": null,
"highlights": Array [],
"isLoading": true,
},
"posts": Object {
"errMess": "Network request failed",
"isLoading": false,
"posts": Array [],
},
}

Sort icon not changing in Datatable server side processing

When I use server side processing in datatable the sorting works but the sort icon does not change and stays in same direction. Below is the code snippet of my datatable configuration.
$('#dtSearchResult').DataTable({
"filter": false,
"pagingType": "simple_numbers",
"orderClasses": false,
"order": [[0, "asc"]],
"info": true,
"scrollY": "450px",
"scrollCollapse": true,
"bLengthChange": false,
"searching": true,
"bStateSave": false,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": VMCreateExtraction.AppSecurity.websiteNode() + "/api/Collection/SearchCustIndividual",
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "ccUid", "value": ccUid });
//Below i am getting the echo that i will be sending to Server side
var echo = null;
for (var i = 0; i < aoData.length; i++) {
switch (aoData[i].name) {
case 'sEcho':
echo = aoData[i].value;
break;
default:
break;
}
}
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
success: function (msg, a, b) {
$.unblockUI();
var mappedCusNames = $.map(msg.Table, function (Item) {
return new searchGridListObj(Item);
});
var data = {
"draw": echo,
"recordsTotal": msg.Table2[0].TOTAL_NUMBER_OF_RECORDS,
"recordsFiltered": msg.Table1[0].FILTERED_RECORDS,
"data": mappedCusNames
};
fnCallback(data);
$("#dtSearchResult").show();
ko.cleanNode($('#dtSearchResult')[0]);
ko.applyBindings(VMCreateExtraction, $('#dtSearchResult')[0]);
}
})
},
"aoColumns": [{
"mDataProp": "C_UID"
}, {
"mDataProp": "C_LAST_NAME"
}, {
"mDataProp": "C_FIRST_NAME"
}, {
"mDataProp": "C_USER_ID"
}, {
"mDataProp": "C_EMAIL"
}, {
"mDataProp": "C_COMPANY"
}],
"aoColumnDefs": [{ "defaultContent": "", "targets": "_all" },
//I create a link in 1 st column
]
});
There is some configuration that I am missing here. I read on datatable forums and the only issue highlighted by people was that draw should be same as what we send on server side.
For anyone looking for an answer to this. Sad but i had to write my own function as below:
function sortIconHandler(thArray, sortCol, sortDir) {
for (i = 0; i < thArray.length; i++) {
if (thArray[i].classList.contains('sorting_asc')) {
thArray[i].classList.remove('sorting_asc');
thArray[i].classList.add("sorting");
}
else if (thArray[i].classList.contains('sorting_desc')) {
thArray[i].classList.remove('sorting_desc');
thArray[i].classList.add("sorting");
}
if (i == sortCol) {
if (sortDir == 'asc') {
thArray[i].classList.remove('sorting');
thArray[i].classList.add("sorting_asc");
}
else {
thArray[i].classList.remove('sorting');
thArray[i].classList.add("sorting_desc");
}
}
}
}
tharrray-> The array of all row headers(You can just write a jquery selector for this).
sortCol->Column on which sort is clicked (Datatable param iSortCol_0)
sortDir -> Sorting direction (Datatable param sSortDir_0)
I know this is an old thread, but make sure you don't have an .off() somewhere associated with the tables capture group in jQuery. I had a click event that (for some reason) I attached an off function to.. Took me 3 days to find it.

Getting undefined for fnGetData() in DataTables

What I want is to get row data when users click on the table's tbody but I keep getting undefined for these datatables functions.
Data comes from a node-mysql module. And for testing purposes, after the table is initialized and data's propertly arrived I've set:
"fnDrawCallback" : function() {
console.log('this:' + this);
console.log('oTable.fnGetData():' + oTable.fnGetData());
console.log('JSON.stringify(oTable.fnGetData():' + JSON.stringify(oTable.fnGetData()));
console.log('JSON.stringify(oTable.fnGetData():' + JSON.stringify(oTable.fnGetData()[0]));
console.log('oTable.fnGetData()[0]:' + oTable.fnGetData()[0]);
},
The result is this:
this:[object Object] tables_offline.js:40
oTable.fnGetData():[object Object],[object Object],[object Object] tables_offline.js:41
JSON.stringify(oTable.fnGetData():[{"id":1,"age":"23","vol":26227,"tlg":4.93,"r":18.15},{"id":2,"age":"13","vol":6378,"tlg":3.97,"r":16.76},{"id":3,"age":"54","vol":131626,"tlg":6.49,"r":11.1}] tables_offline.js:42
JSON.stringify(oTable.fnGetData()[0]:{"id":1,"age":"23","vol":26227,"tlg":4.93,"r":18.15} tables_offline.js:43
oTable.fnGetData()[0]:[object Object]
It's not an array... Maybe this is the weird thing.
I've tried debugging with chrome, setting
$('#myTable').on('click', 'tr', function(){
var oTable = $('#myTable').DataTable();
debugger;
});
And here's a screenshot of what's coming from the variable oTable. I'm not sure but shouldn't I be able to see the functions right there? I can't query something like oTable.fnGetData() 'cause it's undefined.
Let me know if you need something else from my side in order for you to help me.
EDIT
What I want basicaly is to get row data when users click on the table's tbody. I can't get there since oTable = $('#myTable').DataTable(); oTable.fnGetData()' throws undefined.
I'll try to clarify a bit more.
tables_offline.js is the file that loads the datatable, there I define my oTable variable. While searching for help I came across this post (I'm using mData for the columns definition) and I'm not sure if this is the case but it may help.
I make use of fnDrawCallback just for testing oTable in the console, it's not part of the original code.
var oTable = $("#myTable").dataTable({
'fnServerParams': function (aoData) {
aoData.push({ "name": "startDate", "value": startDate });
aoData.push({ "name": "endDate", "value": endDate });
},
'sAjaxSource': '/url',
'sAjaxDataProp': '',
'bProcessing': true,
'sDom':'t',
"aoColumns": [
{ "bVisible": false, "mDataProp": "pcrc_id"},
{ "sWidth": "25%","sTitle": "age", "mDataProp": "pcrc"},
{ "sWidth": "25%","sTitle": "Vol", "mDataProp": "volumen"},
{ "sWidth": "25%","sTitle": "tlg", "mDataProp": "tlg"},
{ "sWidth": "25%","sTitle": "r", "mDataProp": "reitero",
"mRender": function ( data, type, full ) {
return data + '%';
}
}
],
"oLanguage": {
"sUrl": "/javascripts/i18n/dataTables.Spanish.json"
},
"aaSorting": [[ 0, "desc" ]],
"bSort": false,
"bInfo" : false,
"bPaginate": false,
"fnDrawCallback" : function() {
console.log('this:' + this);
console.log('oTable.fnGetData():' + oTable.fnGetData());
console.log('JSON.stringify(oTable.fnGetData():' + JSON.stringify(oTable.fnGetData()));
console.log('JSON.stringify(oTable.fnGetData()[0]:' + JSON.stringify(oTable.fnGetData()[0]));
console.log('oTable.fnGetData()[0]:' + oTable.fnGetData()[0]);
},
"bFilter": false
});
EDIT 2
New screenshot after accesing oTable when a row's clicked. If I dig deep into context I see the data but it's the full thing, not just the row clicked. I'd like to use a function to get clicked row data.
Remove the fnDrawCallback stuff, I think it's distracting you from the actual problem.
Try this:
var oTable = $("#myTable").dataTable({
'fnServerParams': function (aoData) {
aoData.push({ "name": "startDate", "value": startDate });
aoData.push({ "name": "endDate", "value": endDate });
},
'sAjaxSource': '/url',
'sAjaxDataProp': '',
'bProcessing': true,
'sDom':'t',
"aoColumns": [
{ "bVisible": false, "mDataProp": "pcrc_id"},
{ "sWidth": "25%","sTitle": "age", "mDataProp": "pcrc"},
{ "sWidth": "25%","sTitle": "Vol", "mDataProp": "volumen"},
{ "sWidth": "25%","sTitle": "tlg", "mDataProp": "tlg"},
{ "sWidth": "25%","sTitle": "r", "mDataProp": "reitero",
"mRender": function ( data, type, full ) {
return data + '%';
}
}
],
"oLanguage": {
"sUrl": "/javascripts/i18n/dataTables.Spanish.json"
},
"aaSorting": [[ 0, "desc" ]],
"bSort": false,
"bInfo" : false,
"bPaginate": false,
"bFilter": false
});
oTable.$('tr').click( function () {
var data = oTable.fnGetData( this );
console.log(data);
} );
Note that the oTable var is still in scope so you don't need to use var oTable = $('#myTable').DataTable().
This example is copied verbatim from the Datatables API documentation

BigQuery + javascript (tabledata.insertAll)

Here is my code:
function runQuery(){
var json = JSON.stringify({"string": "eight", "number": "8", "id": "8"});
var body = {
"kind": "bigquery#tableDataInsertAllRequest",
"rows": [
{
"insertId": "8",
"json": json
}
]
};
var request = gapi.client.bigquery.tabledata.insertAll({
'projectId': project_id,
'datasetId': 'newTest',
'tableId': 'newTable',
'content': body
});
request.execute(function(response){
console.log(response);
});
}
But this code return error: No records present in table data append request. (400)
Can somebody help me?
Problem solved:
var request = gapi.client.bigquery.tabledata.insertAll({
'projectId': projectId,
'datasetId': datasetId,
'tableId': tableId,
"kind": "bigquery#tableDataInsertAllRequest",
"rows":[
{
"insertId": "10",
"json": {"id": "10", "string": "ten", "number": "10"}
}
]
});
Spent a lot of time on the same issue.
dbepcepk's answer resulted in the error:
"Error: Invalid JSON payload received. Unknown name "rows": Cannot bind query parameter. 'rows' is a message type. Parameters can only be bound to primitive types."
Here is how I got around it:
Note the JSON Key "resource" defining the TableDataInsertAllRequest object
const request ={
"projectId": projectId,
"datasetId": datasetId,
"tableId": tableId,
"resource":{
"kind": "bigquery#tableDataInsertAllRequest",
"skipInvalidRows": false,
"ignoreUnknownValues": false,
"templateSuffix":"",
"rows": [{"json": {"test":true}]
}
}
client.tabledata.insertAll(
request,
(err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
You can't append data to the sample data set. Create your own to perform your inserts.