SQLite update query is not updating table data with phonegap3.1 - sqlite

I am new user for SQLite. I am using phonegap3.1 foe android. I have an issue while updating user table. Below is the code that I am using:
var db = window.openDatabase("riazdb", "1.0", "Demo", 200000);
var userName = "user1";
db.transaction(function(tx) {
tx.executeSql('UPDATE user SET auto_login = "true" WHERE name = ?', [userName], userUpdateSuccess, userUpdateError);
}, userUpdateError);
function userUpdateSuccess(tx, results) {
console.log("affected rows : "+results.rowsAffected);
}
function userUpdateError(err) {
console.log("userUpdateError");
}
I am getting response as a success with results.rowsAffected = 1.
Can somebody tell me that what am I doing wrong.
Thanks

I had the exact same scenario.
Take a look in your onSuccess callback. If there is an unhanded exception thrown from your onSuccess handler, you will see the success happen, you will see rowsAffected == 1. However I suspect that the exception in the success handler causes phonegap to never WRITE the results to the table.
HTH

Related

problem in Flutter with Sqflite exception

I have a problem with my code, I wrote simple flutter app which is f note app, and I have included SQLite as a database , I run the app at first via the emulator and everything went cool , but when I tried to run it on my real device (which is an android device), the database did not respond (i.e I could not add new notes to the database ) and when I went back to run my app via the emulator .. the app did the same thing I found in my real device and in console I found this error
Error: Can't use 'SqfliteDatabaseException' because it is declared more than once.
I need help Please
I saw your code and the problem is that the exception you get is probably related to this one:
PlatformException(sqlite_error, UNIQUE constraint failed: Notetable.id
And it's because you need to manage the unicity of your primary key when you insert a new row. You can have a look at this SO question for a quick reference.
So just to quickly make your code working I've made this changes (please take this code only for reference, write a better one):
void createDataBase(Database db,int newVersion) async{
await db.execute('CREATE TABLE IF NOT EXISTS $noteTable ($col_id INTEGER PRIMARY KEY ,'+
'$col_title TEXT , $col_description TEXT , $col_date TEXT,$col_priority INTEGER)');
}
And
Future<int> insertData(myNote note)async{
var mdatabase = await database;
var _newNoteMap = note.convertToMap();
_newNoteMap['id'] = null;
var result = await mdatabase.insert(noteTable, _newNoteMap);
return result;
}
Pay attention that you always call a DB insert even when you update an existing note.
UPDATE: added additional modification (not listed before)
in databaseObject.dart
Map<String,dynamic> convertToMap(){
var mapObject = Map<String,dynamic>();
mapObject["id"] = _id;
mapObject["title"] = _title;
mapObject["description"] = _description;
mapObject["date"] = _date;
mapObject["priority"] = _priority;
return mapObject;
}
in Note.dart
if(res >= 1){
showAlertDialog('Status', "New note added successfully and the value of result is $res");
}

What is the Partiton Key value when it's null?

I've got records that were the result of bad data where the Partition Key is null and I need to clean them up, but I've been unsuccessful so far.
Here's what I've tried:
var scriptResult = await _dbClient.ExecuteStoredProcedureAsync<dynamic>(
GetStoredProcLink("BulkDelete"),
new RequestOptions() { PartitionKey = new PartitionKey(""), EnableScriptLogging = true },
"select * from c where c.documentDbType = "SomeValue"");
I've also tried used Undefined.Value as the parameter to new PartitionKey().
I ripped the stored proc from here and haven't changed anything yet.
Note: This is a partitioned collection if it was not obvious (by /companyId)
I just hit this issue when migrating to new database level throughput provision. This is syntax that got me up and running again when my models did not contain the specified partition Key property:
new RequestOptions() {
PartitionKey = new PartitionKey(Undefined.Value)
}
Ref:
https://www.lytzen.name/2016/12/06/find-docs-with-no-partitionkey-in-azure.html
Null, Undefined, and empty string are all different values in Cosmos DB. You need something like: new RequestOptions { PartitionKey = new PartitionKey(null) }

If one of the multiple adds in a saveChangesAsync fails do the others get added?

I have this function in my application. If the insert of Phrase fails then can someone tell me if the Audit entry still gets added? If that's the case then is there a way that I can package these into a single transaction that could be rolled back.
Also if it fails can I catch this and then still have the procedure exit with an exception?
[Route("Post")]
[ValidateModel]
public async Task<IHttpActionResult> Post([FromBody]Phrase phrase)
{
phrase.StatusId = (int)EStatus.Saved;
UpdateHepburn(phrase);
db.Phrases.Add(phrase);
var audit = new Audit()
{
Entity = (int)EEntity.Phrase,
Action = (int)EAudit.Insert,
Note = phrase.English,
UserId = userId,
Date = DateTime.UtcNow,
Id = phrase.PhraseId
};
db.Audits.Add(audit);
await db.SaveChangesAsync();
return Ok(phrase);
}
I have this function in my application. If the insert of Phrase fails
then can someone tell me if the Audit entry still gets added?
You have written your code in a correct way by calling await db.SaveChangesAsync(); only one time after doing all your modifications on the DbContext.
The answer to your question is: No, the Audit will not be added if Phrase fails.
Because you are calling await db.SaveChangesAsync(); after doing all your things with your entities, Entity Framework wil generate all the required SQL Queries and put them in a single SQL transaction which makes the whole queries as an atomic operation to your database. If one of the generated query e.g. Auditgenerated query failed then the transaction will be rolled back. So every modification that have been done to your database will be removed and so Entity Framework will let your database in a coherent state.

DynamoDB table is getting created but can not insert new items

I am using the boto DynamoDBV2 interface for a script to create and populate a table in the DynamoDB. My code for it looks something like this -
my_table = Table.create(table_name, schema=[HashKey('key', data_type=STRING)], connection = self.connection)
my_table.put_item(data={
'key': 'somekey',
'value': value
})
I have created the connection, and when I run it, the table is created properly and I can see it in the AWS console. But I am getting the error "Requested Resource not found" when trying to put values in the table.
I also tried reading table separately and then insert values like this -
Table.create(table_name, schema=[HashKey('key', data_type=STRING)], connection = self.connection)
my_table = Table(table_name, self.connection)
my_table.put_item(data={
'key': 'somekey',
'value': value
})
but still getting the same error on the second line. What am I missing ?
The problem is that you need to wait a little bit after the table is created before inserting items. You can use the waitFor() event to find when the table finishes to be created.
Example with AWS Node SDK:
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB();
const createTableParams = {
// parameters...
}
dynamodb.createTable(createTableParams, (err, data) => {
if (err) return console.log(err, err.stack);
const params = {
TableName: 'MY_TABLE'
};
dynamodb.waitFor('tableExists', params, (err, data) => {
if (err) console.log(err, err.stack);
else insertData();
});
});
Your table will not be immediately ready on creation, you have to wait for it to become active before writing to it. I found a Java code sample that illustrates how to do this, but the problem is not language-specific, it applies to any DynamoDB client.
You can see this in the AWS Management Console as the "Status" of the table, to confirm or deny this theory.

Protractor + CucumberJS MySQL Query

Currently my automation framework uses protractor from cucumberJS. We use chai as promised as a assertion library, and I have recently come across a need to do direct mysql queries against a database.
How would I structure a step-definition to be able to get a query, and use the query results within the same step? My current struggles are the asynchronous way protractor is being run, causing me to perform the query after the step requiring the query results happens, and also the scope of which to pass the JSON Object that is created as a result of the query.
this.loginWithMysqlUser = function(uname) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : '*******',
password : '*******',
database : '*******'
});
connection.connect();
connection.query('SELECT * FROM prot_users WHERE username = ?', [uname], function(err, rows) {
if(err) throw err;
mysqlUser = {
username: rows[0].username,
password: rows[0].password
};
});
connection.end();
loginpage.login(mysqlUser);
};
This function resides on loginpage declaration.
So typically your cucumber test script would like:
Feature: As an admin I would like to check if a customer has an
account
Scenario: Check that customer name is registered in DB
Given that I am logged in as admin
And I wish to check that customer (foo) is registered
Then I expect following details from DB query:
| username | password | database |
| foo | bar | mysql |
with step definitions for:
Given(/^that I am logged in as admin$/, function(callback){
..
logic goes here
..
});
And(/^I wish to check that customer (foo) is registered$/,
function(username, callback){
// create connection with db as described
// with supplied username
// Use a promise to create mySQL connection
// and queries DB based on username as described
// on successful resolution set DBResult to results
// for username, password and database
// on error set DBResult to undefined
});
Then(/^I expect following details from DB query$/, function(data,
callback)
{
var rows = data.raw;
// extract values of input table cells into DBExpect using
// rows[0].username
// rows[0].password
// rows[0].database
// Check equality of DBResult and DBExpect objects
..
expect.isFulfilled(DBResult).toEqual(DBExpect).notify(callback);
});
I ended up containing all of the logic for the login and functions that needed to work with the data within the connection.query function.
Seemed to work ok, and protractor was able to be called from within that query function.

Resources