I am using SQLite on the project. I perform events like insert operations in database operations successfully. But I do not know how to reach the data when it brings the data. I am trying to create a list of the following code fragment. I'm waiting for your help.
GRUPLISTESI : any;
GRUPLAR(){
var sql = "SELECT * FROM 'GRUPLAR'";
this.db.executeSql(sql, {}).then((data)=>{
this.GRUPLISTESI = data["rows"]; //What should I write here?
});
}
You can access the data from your Ionic sqlite database like this:
db.executeSql("SELECT * FROM test")
.then(result => {
console.log(result.rows.item(0).id);
});
So abstract it would look like so: result.rows.item([row]).[column_label].
For some deeper examples on how to use sqlite for Ionic, you can use this repository: https://github.com/didinj/ionic3-angular4-cordova-sqlite-example
Related
I'm in the early stages of developing an app with react-native, and I need a DB implementation for for testing and development. I thought that the obvious choice would be to use simple JSON files included with the source, but the only way I see to load JSON files requires that you know the file name ahead of time. This means that the following does not work:
getTable = (tableName) => require('./table-' + tableName + '.json') // ERROR!
I cannot find a simple way to load files at runtime.
What is the proper way to add test data to a react-native app?
I cannot find a simple way to load files at runtime.
In node you can use import() though I'm not sure if this is available in react-native. The syntax would be something like:
async function getTable(tableName){
const fileName = `./table-${tableName}.json`
try {
const file = await import(fileName)
} catch(err){
console.log(err
}
}
though like I said I do not know if this is available in react-natives javascript environment so ymmv
Unfortunately dynamic import not supported by react-native but there is a way so to do this
import tableName1 from './table/tableName1.json';
import tableName2 from './table/tableName2.json';
then create own object like
const tables = {
tableName1,
tableName2,
};
after that, you can access the table through bracket notation like
getTable = (tableName) => tables[tableName];
I have a problem with a meteor publication not being reactive when using a query inside it.
Let's say I have many files, and each file has many projects, so I can go to the route:
http://localhost:3000/file/:file_id/projects
And I would like to both display the projects of the selected file and add new projects to it.
I am currently using angularjs, so the controller would look something like this:
class ProjectsCtrl {
//some setup
constructor($scope, $reactive, $stateParams){
'ngInject'
$reactive(this).attach($scope)
let ctrl = this
//retrieve current file id
ctrl.file_id = Number($stateParams.file)
//get info from DB and save it in a property of the controller
ctrl.subscribe('projects', function(){return [ctrl.file_id]}, function(){
ctrl.projects = Projects.find({file_id: ctrl.file_id}).fetch()
})
//function to add a new project
ctrl.addProject = function(){
if(ctrl.projectName){
Meteor.call('projects.insert', {name: ctrl.projectName, file_id: ctrl.file_id }, function(error, result){
if(error){
console.log(error)
}else{
console.log(result)
}
})
}
}
}
}
The publication looks something like this:
Meteor.publish('projects', function(file_id){
return Projects.find({file_id: file_id})
})
The problem is that, if I insert a new project to the DB the subscription doesn't run again, I mean the array stays the same instead of displaying the new projects I am adding.
I got many problems with this as I thought that meteor would work something like: "Oh there is a new project, let's re run the query and see if the publication change, if it does, let's return the new matching documents"... but no.
I have not found a problem similar to mine as every question regardind querys inside the publication is about how to reactively change the query (the file_id in this case) but that is not the problem here as I don't change the file_id unless I go to another route, and that triggers a new subscription.
My current solution is to expose the complete collection of projects and make the query using minimongo, but I don't know if it is a good workaround (many projects exposed uses too much memory of the browser, minimongo is not as fast as mongo... etc, I don't really know).
Your issue is that the Meteor.subscribe call doesn't know that file_id has changed. There's no reactive relationship between that argument and executing the subscription.
To fix this, whenever you are passing criteria in publish-subscribe, you must write a subscription of Collection inside a tracker.
To know more about trackers, Click here.
While I'm unsure how to do this in Angular, consider this simple Blaze template as an example:
Template.Name.onCreated(function(){
this.autorun(() => {
Meteor.subscribe('projects', file_id);
});
});
Whenever file_id changes, a new subscription is triggered, giving you the desired effect of auto pub-sub utility.
I hope this will give you some insight. It could be easily achieved via Angular JS as well.
I'm trying to export some data into a CSV file from a MySQL database using Meter/Sequelize. What I've done so far is to create a Meteor method called by the client which then call a server side function that return the data and I parse it into a csv string. My issue is returning the date client-side.
What I did
I have my CSV String server-side and I'm using FileSaver.js which can only be used client-side.
My "solution" was to create a client-side collection in which I published the String.
methods.js
run({exportParam}) {
if (!this.isSimulation) {
query.booksQuery(exportParam.sorted, exportParam.filtered, 0).then(
result => {
let CSVArr = [];
result.rows.forEach((value) => {
CSVArr.push(value.dataValues);
});
const CSVString = Baby.unparse(CSVArr,{ delimiter: ";"});<-CSV String
console.log("CSVString : ", CSVString);
Meteor.publish("CSVString", function() { <= publication
this.added("CSVCollection", Random.id(), {CSVString: CSVString});
this.ready();
});
});
}
},
And on the client-side I subscribe to the publication this way :
ExportButton.jsx
const handle = Meteor.subscribe('CSVString', {}, function() {
const exportString = myTempCollection.findOne().CSVString;
const blob = new Blob([exportString], {type:"text/plain;charset=utf
8"});
FileSaver.saveAs(blob, "test.csv");
});
My issue
It works great the first time I click my button and a CSV file is downloaded. The problem is that if I do it again I get the same file as the first one and I get this message on my console.
Ignoring duplicate publish named 'CSVString'
I'm pretty sure the problem comes from the fact that every time I click the button the same "CSVString" publication is created.
I'd like to know to know if there is a solution to this problem or if my approach is wrong.
Please let me know if you need anything else.
You are correct in assuming that you are trying to publish to the same collection every time. I think you should only do the publish once, and do that separately from inserting a record into the collection.
I am writing an Electron application and I want to display some data from a local sqlite3 database file. I am using React as my front-end framework and Redux to update the table data. However I am having trouble figuring out what's the best way to query from the .db file and update Redux with the new data. Can someone give me some insights on what is the best way to go about it?
I was able to load a .db file using the node module sqlite3 and included a javascript function as such:
var sqlite3 = require('sqlite3').verbose();
let dbSrc = 'processlist.db';
var fetchDBData = (tablename) => {
var db = new sqlite3.Database(dbSrc);
var queries = [];
db.each("SELECT * FROM " + tablename, function(err, row) {
queries.push(row);
});
db.close();
return queries;
};
Since I am using React and Redux for my front end, I was able to invoke this function by calling
window.fetchDBData(tablename);
I see jslinq, and see tds js libraries for using node and SQL together... So has anyone ever used those technologies together?
I want to be able to write linq to sql queries in a nodejs app...
I've started with JS variant of LINQ to Entities this week. Check UniMapperJS
Example
var comments = await Comment.getAll()
.where(e => e.author.endsWith("something") || e.author.startsWith("somethingElse"))
.orderByDescending("created")
.limit(10)
.skip(0)
.exec();
But cuz of limitation of JS, it was hard to figure out, how to accept variables in where because that arrow functions are parsed as string. I've solved it by "virtual" variable ($) and list of args as last param.
var comments = await Comment.getAll()
.where(e => e.author.endsWith($) || e.author.startsWith($), filter.endsWith, filter.name)
.orderByDescending("created")
.limit(10)
.skip(0)
.select(e => e.author)
.exec();
Today, JayData http://jaydata.org/ do it.
You can use the new ES6 Arrow Function syntax that looks very similar to C# (with a browser that supports it, like lastest Firefox, or a transpiler, like TypeScript or Traceur):
todoDB.Todos
.filter(todo => todo.Completed == true)
.map(todo => todo.Task )
.forEach(taskName => $('#list')
.append('Task: ' + taskName + ' completed'));
The query will be converted to a SQL Query (select Task from Todos where Completed = true) or a $filter URL parameter (http://.../?$filter=Completed%20eq%201&$select=Task), depending of the data source...
You should checkout the edge.js framework, it connects node.js with .Net. One way would be to use the built in T-SQL support in edge, and then use something like linq.js to manipulate the results.
var getTop10Products = edge.func('sql', function () {/*
select top 10 * from Products
*/});
getTop10Product(null, function (error, products) {
if (error) throw error;
console.log(products);
});
Otherwise, you could setup an EF datacontext in a .Net library and call out to that using Linq
var getTop10Product = edge.func(function () {/*
async (input) => {
using (var db = new ProductContext())
{
//Linq to EF query
var query = from b in db.Products
orderby b.Name
select b;
return query.Take(10).ToList();
}
}
*/});
I came across this question today as I was wondering the same thing, and after a little more searching I came across Squel.
Quoting directly from their website:
//this code
squel.select()
.from("students")
.field("name")
.field("MIN(test_score)")
.field("MAX(test_score)")
.field("GROUP_CONCAT(DISTINCT test_score ORDER BY test_score DESC SEPARATOR ' ')")
.group("name")
);
/* will return this SQL query as a string:
SELECT
name,
MIN(test_score),
MAX(test_score),
GROUP_CONCAT(DISTINCT test_score ORDER BY test_score DESC SEPARATOR ' ')
FROM
students
GROUP BY
name
*/
Hopefully this will help anyone who comes across this question while searching.
Good luck!
PS: <Insert standard disclaimer about not generating SQL queries in the browser...>
If you are creating client-side javascript that will send a SQL query to your database you open a whole can of worms - if the browser can dictate the SQL query, and a user can manipulate what comes from the browser, then you are vulnerable to SQL injection attacks.
Bottom line: don't use this in the browser!
This is not possible, at least if you want to create ad-hoc queries in Javascript. Linq (of any flavor) is a compiler technology. A query using Linq syntax or Linq expressions is handled by the C# or VB compiler, not directly interpreted by the database.
A conventional way to do this would be through a web service in C#, using Linq to fetch and store data, and presenting a clean API to clients. Then the client could consume the service through AJAX calls.