I'm looking for a solution to make the database name of my webSQL query a variable , if it's possible, I have not found any clue yet.
I'm working on transformation of .json to webSql.
Here's some parts of my code :
$(document).ready(function() {
CreateTable();
$.getJSON('dataMultiTable.json',function(data){
console.log(data);
$.each(data.People, function(index, People){
InsertData(baseUtilisateur,People.nom,People.prenom,People.tel,People.email,People.adresse);
});
});
return false;
});
function CreateTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS baseUtilisateur (id INTEGER PRIMARY KEY AUTOINCREMENT, prenom TEXT, nom TEXT,tel TEXT,email TEXT,adresse TEXT)");
});
}
function InsertData(entryNom,entryPrenom,entryTel,entryMail,entryAdresse) {
var insertStatement = "INSERT INTO baseUtilisateur (prenom,nom,tel,email,adresse) VALUES (?,?,?,?,?)";
db.transaction(function(tx) {
tx.executeSql(insertStatement,[entryPrenom,entryNom,entryTel,entryMail,entryAdresse]);
});
}
So can I make the 'baseUtilisateur' a variable ?
I already have tried to use the ? , [] which is used in the insert into query for the values but it doesnt work.
Thanks,
Related
Given these schemas:
model awayinfo {
PlayerID Int #id
IsAway Boolean
playerinfo playerinfo #relation(fields: [PlayerID], references: [ID])
}
model playerinfo {
name String #db.VarChar(15)
ID Int #id #unique #default(autoincrement())
awayinfo awayinfo?
}
How would I create a prisma SQL update for the awayinfo table if the only identifier I have would be the Name of a player and not the ID?
what I tried:
I try to pass something into the WHERE part as seen below:
const result = await prisma.awayinfo.update({
where: {
PlayerID: {
name: name
}
},
data: {
IsAway: true,
}
});
but it always gives me the Error:
Invalid `prisma.awayinfo.update()` invocation:
Argument PlayerID: Got invalid value
{
name: 'Dummy'
}
on prisma.updateOneawayinfo. Provided Json, expected Int.
I got pretty desperate and even tried wonky selects like this one
const result = await prisma.awayinfo.update({
where: {
PlayerID: {
playerinfo: {
Where: {
name: name
},
select: {ID: true},
}}
}, .....
but obviously this would not work aswell.
I wonder what I am missing here and I cannot find any example of a condition within the WHERE clause in the prisma documentation
There are two issues here, the first is in your Prisma schema/data model and the second is in your query.
Making name unique
Firstly, if you want to uniquely identify a record in the playerinfo table with just the name property, this property must be unique. Otherwise, it's not possible for your database (and Prisma) to know which player info record to update in case there are multiple records with the same name property.
Update your schema accordingly:
model playerinfo {
name String #unique #db.VarChar(15)
ID Int #id #unique #default(autoincrement())
awayinfo awayinfo?
}
Rewriting the update query
Since the where condition in your update references a property playerinfo model, that is where you should begin your query. Here's what it looks like:
const data = await prisma.playerinfo.update({
where: {
name: name
},
data: {
awayinfo: {
update: {
IsAway: true
}
}
}
})
I am new to mobile development and I would like to perform simple queries like deleting a row a specific from my sqlite table. But It doesnt work.The row still exits in my database table
This is my code:
export default class App extends Component{
constructor(props){
super(props);
db = SQlite.openDatabase(
{
name: 'gad.db',
createFromLocation: 1,
},
this.successToOpenDB,
this.failToOpenDB,
);
}
successToOpenDB()
{
db.transaction(tx =>
{
tx.executeSql("DELETE FROM songs WHERE content='content2' ", [] ,(tx, results) =>
{
console.log('DELETION OK');
},
(tx, error) =>
{
console.log("DELETION KO");
});
});
}
failToOpenDB(err){
console.log(err);
alert("not connected to database");
}
Please anyone help.
Thanks in advance
Must be some issue with primary key, if primary key is your condition to delete,
or "content" here.
First try to retrieve primary key of the row you want to delete, and store in
some state maybe:
var deleted= results.rows.item(length-1).ID
I have primary key as ID, so I am now able to get required row.
also, after delete query you can check any rows affected or not in promise returned as follows:
(tx, results) => {
if( results.rowsAffected >0) {
//then proceed ahead.
}
}
I'm using Vue alongside with Apollo in order to query a GraphQL endpoint in my project. Everything's fine but I want to start programming generic components to ease and fasten the development.
The thing is, in most views, I use the Smart Query system.
For instance, I use :
apollo: {
group: {
query: GROUP_QUERY,
variables () { return { id: this.groupId } },
skip () { return this.groupId === undefined },
result ({ data }) {
this.form.name = data.group.name
}
}
}
With the GROUP_QUERY that is :
const GROUP_QUERY = gql`
query groupQuery ($id: ID) {
group (id: $id) {
id
name
usersCount
userIds {
id
username
}
}
}
`
So my group variable in my apollo smart query has the same name as the query itself group (id: $id). It is this mechanism that is quite annoying for what I try to achieve. Is there a way to avoid that default mechanism ?
I'd like for instance to be able to give a generic name such as record, and it would be records for queries that potentially return multiple records.
With that, I would be able to make generic components or mixins that operate either on record or records.
Or have I to rename all my queries to record and records which would be annoying later on in case of troubleshooting with error messages ?
Or maybe there's another way to achieve that and I didn't think about it ?
Thanks in advance.
You can, in fact, rename the variable of Apollo smart queries using the update option, as seen here in the Vue Apollo documentation. Your example would look like:
apollo: {
record: {
query: GROUP_QUERY,
variables () { return { id: this.groupId } },
update: (data) => data.group,
skip () { return this.groupId === undefined },
result ({ data }) {
this.form.name = data.group.name
}
}
}
You should notice that the Apollo object will create a record variable in your component, and the update statement shows where to get the group for the record.
By doing so :
const GROUP_QUERY = gql`
query groupQuery ($id: ID) {
record: group (id: $id) {
id
name
usersCount
userIds {
id
username
}
}
}
`
If the GROUP_QUERY is used at several places, the result will be accessible under the record name, because it is defined as an alias over group.
See documentation for Aliases.
Still a little new to Node but this is driving me nuts. I have looked around but cannot find an existing answer that has helped me yet. I know I'm missing something stupid I'm sure. My elements appear to be mapping correctly. I have triple checked my columns and my values. I've even taken the SQL query from my debug session in Visual Studio code and run it directly in DBVis, no issues. But for some reason when I run this in Node I always get "Error: SQLITE_RANGE: bind or column index out of range". Are there any known issues with mapping elements in node and SQLite Im unfamiliar with?? Im using the map function and sql function in other places and it seems to be working fine. Just not here.
Here is the relevant code.
exports.createUserGoogle = createUserGoogle;
function createUserGoogle(jsonObj, cb) {
var sql = "Begin;"
+"Insert into userGoogle (googleId,token,name,email,photoid) values ($googleid,$googleToken,$name,$email,$photoid);"
+"Commit;";
doSQL(sql, mapDataElements(jsonObj), cb);
}
My mapping function
function mapDataElements(jsonObj) {
dataObj = {};
for (key in jsonObj) {
dataObj['$' + key] = jsonObj[key];
}
console.log('mapDataElements: Mapped as: ' + JSON.stringify(dataObj));
return dataObj;
}
My Standard SQL Promise function
function doSQL(sqlStr, bindings, cb) {
var p = new Promise((resolve, reject) => {
db.serialize(() => {
db.run(sqlStr, bindings, (err) => {
if (err) {
console.log('SQL failed: ' + JSON.stringify(bindings));
reject(err);
}
else {
console.log('SQL succeeded: ' + sqlStr);
resolve();
}
});
});
});
p.then(
(data) => {
console.log('Doing callback');
cb('success');
},
(err) => {
cb(null, err);
}
);
}
Also here are what my mapped elements look like (slightly edited for security):
mapDataElements: Mapped as: {"$googleid":"mylongnumber","$googleToken":"myreallylongtokenvalue","$name":"My name","$email":"my.email#gmail.com","$photoid":1}
Any my table if it helps
CREATE TABLE userGoogle(
pk_google INTEGER NOT NULL PRIMARY KEY,
googleId TEXT,
token TEXT,
name TEXT,
email TEXT,
photoid int,
FOREIGN Key(photoid) References photo(pk_photo)
);
I solved similar problem by using db.exec() instead of db.run(). As db.exec() doesn't accept parameters I had to make correct sql query string myself.
I´m working with datatables for a meteor app.
My problem is that when some fields change all the table is rendered again, if I´m on page two on the table or I order by field, the table is rendered again and I´m back on the beginning.
My code:
Template.adminpage.rendered = function() {
$('#userData').dataTable({
"bDestroy":true,
"aaSorting": [[ 0, "desc" ]],
"bAutoWidth":false,
"bFilter": false,
"aoColumns": [
{ "bVisible": false },
null,
null,
null,
null,
null,
null,
null
],
"aaData": Template.adminpage.arrayUsersAdmin()
});
}
Array that populates the table:
Template.adminpage.arrayUsersAdmin=function() {
var adminUsers = allUserData.find({roles: 'basic'});
var arrayUserAdmin = [];
var count=0;
adminUsers.forEach(function(user) {
var idColumn = user._id;
var dateColumn=moment(user.createdAt).format("MMM Do HH:mm");
var usernameColumn=username;
var emailColumn=email;
arrayUserAdmin[count]=[
idColumn,
dateColumn,
usernameColumn,
emailColumn
];
count++;
});
return arrayUserAdmin;
}
Collection on the server:
if(Meteor.users.find({_id: this.userId}, {roles: 'admin'})){
Meteor.publish("allUserData", function () {
var self = this;
var handle = Meteor.users.find({}).observeChanges({
added: function(id, fields){
self.added("allUsersCollection", id, fields);
},
changed: function(id, fields){
self.changed("allUsersCollection", id, fields);
},
removed: function(id){
self.removed("allUsersCollection", id);
}
});
self.ready();
this.onStop(function() {
handle.stop();
});
});
}
Thanks for your time.
You can pass reactive: false as an option to find, which disables the underlying addition of a dependency, like so:
Template.adminpage.arrayUsersAdmin=function() {
var adminUsers = allUserData.find({roles: 'basic'}, reactive: false);
// Your code
return arrayUserAdmin;
}
This behaviour is documented here
Alternatively, if you would like the individual fields to update, you will have to add them in yourself. To do this, you can use allUserDate.find({roles: 'basic'}).observe. This will require you, however, to edit the HTML directly, and is quite messy. A better alternative would be to change your table structure entirely - don't use a data table, use a vanilla HTML table, and sort the data with minimongo queries.
Regardless, you can use observe like so:
allUserData.find({roles: 'basic'}).observe({
changed: function(newDocument, oldDocument) {
// Update table
}
});