How I can pass this SQL Query to TypeORM? - sql

I want to sort the closest users by a user
SELECT usuario1.nickname, usuario1.name
FROM public."user" as usuario1, public."user" as usuario2
WHERE usuario1.nickname != 'Lucas' and usuario2.nickname = 'Lucas'
ORDER BY ST_Distance(usuario1.geometry, usuario2.geometry) ASC;

You can execute raw queries in Typeorm with the created connection
import {createConnection, Connection} from "typeorm";
const connection = await createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test"
});
async function getUsers() {
await connection.connect();
const users = await connection.query(`
SELECT usuario1.nickname, usuario1.name
FROM public."user" as usuario1, public."user" as usuario2
WHERE usuario1.nickname != 'Lucas' and usuario2.nickname = 'Lucas'
ORDER BY ST_Distance(usuario1.geometry, usuario2.geometry) ASC
`);
}

Related

Error: NoSuchMethodError: The getter 'sessionToken' was called on null

Hello fellow programmers!
I am starting in the world of Flutter programming.
I am following a course on Udemy, the questions are never answered by the teacher and I would not like to stop with that error.
Url
https://www.udemy.com/share/104Olo3#xtvsGS5hu0gc1eh3tVazmbv3OIlbZpdoTIVPBSMn7Aqe4JCMKpyLdiZyz4xW7vM5/
Cap: 104
I have my App in Flutter with Dart and my database developed in SQL and NodeJs.
My error is when I enter the Administrator role
When I enter I get this error
I/chatty ( 8221): uid=10154(com.agave.agave_investment_app) 1.ui identical 2 lines
I/flutter ( 8221): Error: NoSuchMethodError: The getter 'sessionToken' was called on null.
I/flutter ( 8221): Receiver: null
I/flutter ( 8221): Tried calling: sessionToken
I/flutter ( 8221): SESION TOKEN: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjExIiwiZW1haWwiOiJob2xhQGdtYWlsLmNvbSIsImlhdCI6MTYzOTAwMDMzMH0.4QqRnRMVK1X7K2ni2zU7SxACt8tAs4-ynu9WAKiHBTQ
I/chatty ( 8221): uid=10154(com.agave.agave_investment_app) 1.ui identical 2 lines
I/flutter ( 8221): SESION TOKEN: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjExIiwiZW1haWwiOiJob2xhQGdtYWlsLmNvbSIsImlhdCI6MTYzOTAwMDMzMH0.4QqRnRMVK1X7K2ni2zU7SxACt8tAs4-ynu9WAKiHBTQ
I am printing the sessionToken from the database to check that if it arrives and is correct, if it is arriving, in my provider I have this Function where it should be receiving the authorization
Future<List<Order>> getByStatus(String status) async{ //consulta para obtener todas las categorias
try {
print('SESION TOKEN: ${sessionUser.sessionToken}');
Uri url = Uri.http(_url, '$_api/findByStatus/$status');
Map<String, String> headers = {
'Content-type': 'application/json',
'Authorization': sessionUser.sessionToken
};
final res = await http.get(url, headers: headers);
if(res.statusCode == 401) {
Fluttertoast.showToast(msg: 'Sesion expirada');
new SharedPref().logout(context, sessionUser.id);
}
final data = json.decode(res.body); //se obtienen las ordenes
Order order = Order.fromJsonList(data);
return order.toList;
}
The model where 'sessionToken' comes from is this
class User {
String id;
String name;
String lastname;
String email;
String phone;
String password;
String sessionToken;
String image;
List<Rol> roles = [];
List<User> toList = [];
User({
this.id,
this.name,
this.lastname,
this.email,
this.phone,
this.password,
this.sessionToken,
this.image,
this.roles
});
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"] is int ? json['id'].toString() : json["id"],
name: json["name"],
lastname: json["lastname"],
email: json["email"],
phone: json["phone"],
password: json["password"],
sessionToken: json["session_token"] ,
image: json["image"],
roles: json["roles"] == null ? [] : List<Rol>.from(json['roles'].map((model) => Rol.fromJson(model))) ?? [],
);
User.fromJsonList(List<dynamic> jsonList) {
if (jsonList == null) return;
jsonList.forEach((item) {
User user = User.fromJson(item);
toList.add(user);
});
}
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"lastname": lastname,
"email": email,
"phone": phone,
"password": password,
"session_token": sessionToken,
"image": image,
"roles": roles,
};
}
This is my method in Visual Studio Code
async findByStatus(req, res, next) { //metodo para obtener el status de la orden
try {
const status = req.params.status;
const data = await Order.findByStatus(status);
console.log(`Status: ${JSON.stringify(data)}`);
return res.status(201).json(data);
}
catch (error) {
console.log(`Error ${error}`);
return res.status(501).json ({
message: 'Hubo un error al tratar de obtener las ordenes por estado',
error: error,
success: false
})
}
},
Table created in SQL
SELECT
O.id,
O.id_client,
O.id_address,
O.id_delivery,
O.status,
O.timestamp,
JSON_AGG(
JSON_BUILD_OBJECT(
'id', P.id,
'name', P.name,
'description', P.description,
'price', P.price,
'image1', P.image1,
'image2', P.image2,
'image3', P.image3,
'quantity', OHP.quantity
)
) AS products,
JSON_BUILD_OBJECT(
'id', U.id,
'name', U.name,
'lastname', U.lastname,
'image', U.image
) AS client,
JSON_BUILD_OBJECT(
'id', A.id,
'address', A.address,
'neighborhood', A.neighborhood,
'lat', A.lat,
'lng', A.lng
) AS address
FROM
orders AS O
INNER JOIN
users AS U
ON
O.id_client = U.id
INNER JOIN
address AS A
ON
A.id = O.id_address
INNER JOIN
order_has_products AS OHP
ON
OHP.id_order = O.id
INNER JOIN
products AS P
ON
P.id = OHP.id_product
WHERE
status = $1
GROUP BY
O.id, U.id, A.id;
I initialize sessionUser first
class OrdersProvider {
String _url = Environment.API_AGAVE;
String _api = '/api/orders';
BuildContext context;
User sessionUser;
Future init(BuildContext context, User sessionUser) async {
this.context = context;
this.sessionUser = sessionUser;
}
Future<List<Order>> getByStatus(String status) async{ //consulta para obtener todas las categorias
try {
print('SESION TOKEN: ${sessionUser.sessionToken}');
Uri url = Uri.http(_url, '$_api/findByStatus/$status');
Map<String, String> headers = {
'Content-type': 'application/json',
'Authorization': sessionUser.sessionToken
};
final res = await http.get(url, headers: headers);
if(res.statusCode == 401) {
Fluttertoast.showToast(msg: 'Sesion expirada');
new SharedPref().logout(context, sessionUser.id);
}
final data = json.decode(res.body); //se obtienen las ordenes
Order order = Order.fromJsonList(data);
return order.toList;
}
catch(e){
print('Error: $e');
return [];
}
}
What do you think can cause me this error?? Thanks in advance

Node js TypeError: Cannot read property 'nick' of undefined

The Issiue
Issue is basically if i try to combine query+variable or put it in "fake pdo" style, it does not work.
Code
if(page == "profile"){
var user = "Failed to load.";
con.query('SELECT * FROM users WHERE id = '+con.escape(parseInt(userIDRequested)), function (err, result, fields) {
//console.log(result);
user= result[0].nick;
io.emit('userinfo', { nick: user});
});
}
app.get("/user/:start", function(req, res){
page = "profile";
var user_id = req.params['start'];
pageid = user_id;
if(didshitgetupdated == false){
useridRequested = pageid;
didshitgetupdated = true;
}
res.writeHeader(200, {"Content-Type": "text/html"});
let btlib = btNetLib(res);
btlib.btSend(navbar);
btlib.btSendFile("profile/index.html");
finishConnection(res);
})
but for some reason i get this:
TypeError: Cannot read property 'nick' of undefined
at Query.<anonymous> (D:\bricktalenode\bricktale.js:36:29)
at Query.<anonymous> (D:\bricktalenode\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (D:\bricktalenode\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
at Query.EofPacket (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
at Protocol._parsePacket (D:\bricktalenode\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (D:\bricktalenode\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (D:\bricktalenode\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (D:\bricktalenode\node_modules\mysql\lib\protocol\Protocol.js:38:16)
Things i tried
making a if condition to check it
(did not helped)
connecting database using another thing
i used same query(changed variable for php though) in php to access, query is ok, so issue on my node.js code then.
waiting for some time ( did not helped)
parse int
nothing really helped that i done
but for some reason i get stuff correctly using console.log(result);
but i cant fetch them using the code.
The results
[ RowDataPacket {
nick: '[MODERATED 5]',
id: 5,
password: 'fdaf40dc5531c0acf82911892f552f0a',
banned: 0,
coins: 0,
registerdate: 2021-05-10T02:55:45.000Z,
status: 'BETA STATUS',
rank: 'Player',
rep: 1,
token: 'token',
lastonline: '2021-05-10 03:05:08',
lastdaily: 2021-05-19T07:04:34.000Z } ]
but i cannot access it
app.get("/user", function(req, res){
page = "profile";
res.writeHeader(200, {"Content-Type": "text/html"});
let btlib = btNetLib(res);
btlib.btSend(navbar);
btlib.btSendFile("profile/index.html");
var sql = 'SELECT * FROM users WHERE id = ?';
con.query(sql, req.query.id, function (err, result) {
if (err) throw err;
setInterval(() => {
var bricklet;
bricklet = result[0].nick;
console.log(bricklet);
io.emit('userinfo', { nick: bricklet});
},150);
});
finishConnection(res);
})
moving stuff inside of my app.get solved it.

Difference between where and like in CLEARDB

I'm trying a simple nodejs login system and want to use the following query:
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
But it simply doesn't return anything so I had to do it like this:
'SELECT * from admin_cred where username like "%'+username+'%" AND password like "%'+password+'%"'
This is the code segment:
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
// 'SELECT * from admin_cred where username like "%'+username+'%" AND password like
"%'+password+'%"'
);
Can anyone point out why the first query is not working?
And the difference bertween the two statements?
N.B: This is the first time i'm using cleardb on heroku and a few things seems different from MySql. Everything else in the code works so I've narrowed the problem down
EDIT 1
I just noticed that the second query is running even though the password was wrong
UPDATE 1
Here is the node js code as requested:
class auth {
constructor(app, database) {
this.login(app, database);
}
//http://localhost:8000/api/auth/v1/login
login(app, database) {
app.post("/api/auth/v1/login", async (request, response) => {
const username = request.body.username;
const password = request.body.password;
try {
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?'", [username]
);
console.log(result);
if(result.length > 0){
if(password === result[0].password){
response.json({
loggedIn:"true",
data: username
})
}else{
response.json({
loggedIn:"false",
data: "wrong username or pass"
})
}
}else{
response.json({
loggedIn:"false",
data:"username doesnt exist"
})
}
} catch (error) {
console.log(error);
}
});
}
}
And here is the post request from ReactJs:
const handleLogin = async (e) =>{
e.preventDefault();
const admin = {username, password};
const response = await axios.post(
"http://localhost:8000/api/auth/v1/login",
admin
);
if(response.length > 0){
console.log("response: " + response);
}else{
console.log("no response")
}
};
Use:
const result = await database.query(
'SELECT * FROM admin_cred WHERE username = "?" AND password = "?"', [username, password]
);
Tip: never use LIKE for authentication queries and try to encrypt passwords.

Does TypeORM supports raw SQL queries for input and output?

I would like to know if there is a feature of TypeORM that supports raw sql queries for Insert Update Delete Select etc..
According to this issue comment, TypeORM enables you to use any queries to your heart's content. using entityManager.query() Here is the documentation.
UPDATE
Link above is outdated, try this instead entity-manager-api.
const rawData = await manager.query(`SELECT * FROM USERS`);
2020 UPDATE, entityManager.query() basing the entityManager off the EntityManager class, was not working for me so had to do this:
import { getManager } from 'typeorm';
const entityManager = getManager();
const someQuery = await entityManager.query(`
SELECT
fw."X",
fw."Y",
ew.*
FROM "table1" as fw
JOIN "table2" as ew
ON fw."X" = $1 AND ew.id = fw."Y";
`, [param1]);
https://orkhan.gitbook.io/typeorm/docs/working-with-entity-manager
try out this (April, 2022, typeorm ^0.3.6)
import { DataSource } from "typeorm";
(async () => {
const AppDatasource = new DataSource({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "root",
database: "your-database",
synchronize: false,
logging: false,
entities: ['src/entity/**/*.ts']
})
const appDataSource = await AppDataSource.initialize();
const queryRunner = await appDataSource.createQueryRunner();
var result = await queryRunner.manager.query(
`SELECT * FROM your-table LIMIT 100`
);
await console.log(result)
})()
You can use deprecated getConnection or repo instance:
const db = this.repo.manager; // or getConnection().manager
const users = await db.query(`SELECT * FROM "users";`);
const [{ total }] = await db.query(`SELECT COUNT(*) as total FROM "users";`);
// users.length === Number(total);
Metadata allows you to get table properties dynamically
// utilities...
const usersTableMeta = db.connection.getMetadata(UserEntity); // or getConnection().getMetadata(UserEntity);
const usersTable = `"${usersTableMeta.tableName}"`
// data...
const users = await db.query(`SELECT * FROM ${usersTable};`);
const admins = await db.query(`
SELECT id, name FROM ${usersTable}
WHERE ${usersTable}.role = 'admin';
`);

How to run a BigQuery Script by Google App Scripts after a table is updated by another BigQuery script?

I have developed a quite code heavy and data heavy query for Google BigQuery which is why I have chosen to run it in multiple scripts (and create multiple tables). What I want is to run script b (and create table b) when tabel a is updated (by script a). I see only the option to set time events and I'm not that experienced with javascripting. Can someone provide an example?
Thanks in advance!
Guido
function saveQueryToTable() {
var sql = 'query-a';
var projectId = 'xxx';
var datasetId = 'xxx';
var tableId = 'xxx';
var job = {
configuration: {
query: {
query: sql,
writeDisposition:'WRITE_APPEND',
allowLargeResults: 'TRUE',
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
}
}
}
};
var queryResults = BigQuery.Jobs.insert(job, projectId);
Logger.log(queryResults.status);
}
function saveQueryToTable() {
var sql = 'query-b';
var projectId = 'xxx';
var datasetId = 'xxx';
var tableId = 'xxx';
var job = {
configuration: {
query: {
query: sql,
writeDisposition:'WRITE_APPEND',
allowLargeResults: 'TRUE',
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
}
}
}
};
var queryResults = BigQuery.Jobs.insert(job, projectId);
Logger.log(queryResults.status);
}