how to sanitize sql.js inputs? - javascript

I am using sql.js to manage the SQLite file I created for an electron app. My issue is that I want to make sure all the inputs are sanitized. As of now, I am using statements like so:
const SQL = await sqljs();
const db = new SQL.Database();
// These values are just examples and will be user inputs through electron.
let id = 1;
let name = 'row name';
db.run(`INSERT INTO tableName VALUES (${}, 'hello');`);
I'm pretty sure that this way is unsafe and can cause SQL injections. What can I do to prevent such a problem? Thank you kindly.

You can use bound parameters. These are values that are passed to the database engine and not parsed as part of a SQL statement:
let id = 1;
let name = 'row name';
/* Either pass in a dictionary to use named bound parameters */
db.run("INSERT INTO tableName VALUES(:id, :name)", { ':id': id, ':name': name });
/* Or an array to use positional bound parameters */
db.run("INSERT INTO tableName VALUES(?, ?)", [id, name]);
More information is available in the SQLite documentation, as well as sqljs documentation.

Related

typeorm get repository from name

To create REST API for any entity.
Can I use table name instead of Entity for queryBuilder?
const repository = getRepository("Table_Name"); // instead of Entity, I want use string `Any Table name`.
repository.createQueryBuilder( ... )
.leftJoin(['TableA', 'TableB'])
.orderBy("TableA.name")
.offset(5)
.limit(10);
I think you are looking to find the correct entity name given that you already know the name of the database table.
Assuming you have only one database to connect to, you can do something like this:
const tableName = "Table_Name";
const entityMetadata = getConnection().entityMetadatas.find((metadata) => metadata.tableName === tableName);
const repository = getRepository(entityMetadata.name);
For your TableA and TableB, I guess you can follow the same logic.

How can I access a specific attribute of a specific document in a mongoDB collection?

To summarize, I am working with 2 collections - 'usercollection' and 'groupcollection' and I would like to associate users with groups. I don't want to have 2 copies of all the user documents so I have a unique ID attribute for each user that I want to use to associate specific users with specific groups. This is all running on a localhost webserver so I'm getting the input from an html page with a form in it where you enter 'username' and 'groupname'. I tried using the .distinct() function with query as 'username' and the target field/attribute as 'uid'.
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
// Set query and options for searching usercollection
var query = {"username" : userName};
const fieldName = "uid";
// Set our collections
var users = db.get('usercollection');
// Get UID corresponding to username
var uidToAdd = users.distinct(fieldName, query);
This is what I attempted (with some other lines that aren't relevant taken out) but it just returned a null object so I'm at a bit of a loss. Also, I'm still a beginner with nodejs/javascript/mongoDB so the more informative the answer the better! When I do the same code in the mongo shell I can get the actual value of the 'uid' attribute so I really don't know what's going wrong
I am not sure I am following you. But if I understood correctly, if you want to make a relationship between 'usercollection' and 'groupcolletion', you can simply create those 2 collections and each user in 'usercollection' should have a field with 'groupid' as a reference. In this way, you can access 'groupcollection' easily.
Here is an example with using mongoose.
In User model
...
groupId: {
type: mongoose.Schema.Types.ObjectID
ref: "Group"
}
...
Later you can also use 'populate' to fetch 'Group' information.
...
let data = await User.findById(id).populate('groupId');
...

Is there a way to shorten the code of getting one user from postgres DB in node.js?

I use node.js and pg library (node-postgres) to interact with database.
This is the code I use to retrieve one user of specific ID:
const { rows: users } = await db.query("SELECT * FROM users WHERE id = $1", [id]);
const user = users[0];
Even if there is only one record postgres always returns an array, so I retrieve this first item in the second line.
Is there a way to shorten this code if there is only one user? Like make it one line instead of two.
You can directly get the first user object by destructuring the rows array
const { rows: [user] } = await db.query(...)

postgres: relation does not exist when the table clearly exists when calling from node.js

so I psql'd and created table users;
CREATE TABLE users (
id integer NOT NULL,
username text
);
I am able to grab rows by doing SELECT * FROM users;
However, when I use node.js with the library module pg to make calls I get the infamous relation does not exist.
const createQuery = {text: "INSERT INTO users(id, username) VALUES($1)",values: values}
const { rows } = await db.query(createQuery);
I wasn't running into this issue before a complete server migration.
The most likely option is that the table was created in a different schema than the default schema that you are using from node.js.
You can search the schema your table belongs to by querying table information_schema.tables:
select table_schema from information_schema.tables where table_name = 'users';
With this information at hand, you can now qualify your table name with the proper schema name in the query that you are running from node.js. Assuming that the schema name is myschema, you would go:
INSERT INTO myschema.users(id, username) VALUES($1)
By default when you don't specify any schema, postgres points out to public schema. Please use schema name/ database name as along with the table name. Make sure you have provided proper configurations of the database within your code. If the configurations are proper and even you no need to provided schema alias within the query.

Using variables in a node.js mysql-node query

I am running a mysql query with WHERE, I would like to include my input prompt variable, input how would I go about doing so? my current query is like so,
var connect = connection.query('SELECT url FROM Sonic_url WHERE name='
+ input //<where I'm confused
, function(err, rows, fields) {
You can just include it the way you did, but that will give you an unescaped query which is open to sql - injection. To prevent you from this, you can use mysql.format
var sql = mysql.format("SELECT url FROM Sonic_url WHERE name=?", [input]);
var connection = connection.query(sql, function(err,rows,fields) {});

Categories