Dynamic table names in pg-promise - pg-promise

I would like to dynamically select the table in a pg-promise query. The following code does not work, any help is appreciated!
return db.any('SELECT * from $1', table_name)
The error message I get is:
error: error: syntax error at or near
I am not sure if I should be using a helper, as described in this link:
https://vitaly-t.github.io/pg-promise/helpers.TableName.html

The direct approach is via SQL Names:
await db.any('SELECT * from $1:name', [table]);
// or
await db.any('SELECT * from ${table:name}', {table});
And with the schema:
await db.any('SELECT * from $1:name.$2:name', [schema, table]);
// or
await db.any('SELECT * from ${schema:name}.${table:name}', {schema, table});
A more generic approach is via TableName:
const tn = new pgp.helpers.TableName({schema, table});
await db.any('SELECT * from $1', [tn]);
// or
await db.any('SELECT * from ${tn}', {tn});

Related

multiple arguments in sqflite flutter

I want to search database based on the keyword. if it title or content contains the keyword then return the data. but it send backs nothing.
static Future<List<Note>> searchDocuments(String? keyword) async {
final database = await DatabaseHelper.database();
List<Map<String, dynamic>> allDocuments = await database.rawQuery(
'SELECT * FROM docs WHERE title=? and content=?',
['$keyword%', '$keyword%']);
checked - doesn't work.
This works.
await database.rawQuery(
'SELECT * FROM docs WHERE title LIKE ? OR content LIKE ?',
['%$keyword%', '%$keyword%']);
await database.rawQuery(
'SELECT * FROM docs WHERE title="$keyword" AND content="$keyword"');

How to combine 2 or more Sqflite queries with logical operators?

Im currently trying to combine the results of 2 queries in flutter. These are the queries:
Future<List> filterExercises({
List<String> equipmentFilter,
List<String> muscleFilter,
int custom, //0 = false, 1 = true
int recent, //0 = false, 1 = true
String orderBy,
}) async {
Database db = await initDatabase();
final muscleRes = await db.query(
'exercises',
where: "targetMuscle IN (${('?' * (muscleFilter.length)).split('').join(', ')})",
whereArgs: muscleFilter,
);
final equipmentRes = await db.query(
'exercises',
where: "equipment IN (${('?' * (equipmentFilter.length)).split('').join(', ')})",
whereArgs: equipmentFilter,
);
return finalResult; //need to combine the results with a logical AND somehow
}
I know there's the option the use a rawQuery with logical OR / AND, but that doesn't work for my case.
It should be possible for the user to select different attributes and thus filter the list. Im looking for a way to pass arguments to this function and query my table accordingly to the passed arguments but I already fail when merging the first two queries.
How to add a logical AND to these two queries?
And furthermore: How to add even more attributes with a logical AND and order the final result?
I managed to find a way to the first question:
List<String> muscleFilter = ['Chest', 'Biceps'];
List<String> equipmentFilter = ['Machine', 'Cable'];
return db.rawQuery('''
select * from exercises
where targetMuscle in (${('?' * (muscleFilter.length)).split('').join(', ')})
and equipment in (${('?' * (equipmentFilter.length)).split('').join(', ')})
''',
muscleFilter + equipmentFilter
);

Node-postgres prepared statements with conditional arguments

Is there a way to query something where you hava many conditions that can be undefined (not required)
const c = {
id?: number
type?: string
}
const sql = `SELECT * FROM smth WHERE id=$1 AND type=$2`
query(sql , [c.id, c.type])
You could use
const sql = `SELECT * FROM smth WHERE ($1::int IS NULL OR id=$1) AND ($2::text IS NULL OR type=$2)`;
but in general this is the place where query builder libraries are the appropriate solution.

Multiple arguments in sqllite in flutter

I would like to know how to pass multiple arguments to a raw query in sqllite.
My code is below
query() async {
// get a reference to the database
Database db = await DatabaseHelper.instance.database;
// raw query
List<Map> result = await db.rawQuery('SELECT * FROM my_table WHERE name=?', ['Peter']);
// print the results
result.forEach((row) => print(row));
}
In the above code i am passing one argument 'Peter' but what if I want to pass multiple arguments, for example:
List<Map> result = await db.rawQuery('SELECT * FROM my_table WHERE name=? and last_name=? and year=?', ['Peter'], ['Smith'],[2019]);
If I do the code above, I get error "Too many positional arguments: 2 expected, but 4 found." can someone show me how to pass multiple arguments to a query in sqllite flutter?
I'm assuming you're using sqflite.
You need to put all your arguments into one list and not multiple.
The code below should work like this:
List<Map> result = await db.rawQuery(
'SELECT * FROM my_table WHERE name=? and last_name=? and year=?',
['Peter', 'Smith', 2019]
);
For more examples how to use raw queries see their examples on their pub.dev page.
Or if you want to use the query function you can do it like this:
String strVal = 'str';
int intVal = 0;
String likeVal = 'str';
final List<Map<String, dynamic>> maps = await db.query('my_table',
where: "col1 LIKE ? and col2 = ? and col3 = ?",
whereArgs: ['$likeVal%', strVal, intVal],
orderBy: 'id',
limit: 10);

Error when using "ALL" operator when execute query

I need to execute following query using phalcon framework:
"SELECT id FROM table GROUP BY id HAVING '31' = ALL(array_agg(status))"
How can I execute this query using phalcon?
When I do following:
Model::query()
->columns(['id'])
->groupBy('id')
->having('31 = ALL(array_agg(status))')
->execute();
I get this error message:
Syntax error, unexpected token ALL, near to '(array_agg(status)) ', when parsing: SELECT id FROM [SomeNameSpace\Model] GROUP BY [id] HAVING 31 = ALL(array_agg(status)) (137)
I'm not 100% sure which Postgres functions are supported, but you can try like this:
Model::query()
->columns([
'id',
'ALL(array_agg(status)) AS statusCounter'
])
->groupBy('id')
->having('31 = statusCounter')
->execute();
Notice that I moved the aggregation functions in the select, rather in having clause.
UPDATE: here is an example of very custom query. Most functions used are not supported and it's sometimes cleaner just to write a simple SQL query and bind the desired Model to it:
public static function findNearest($params = null)
{
// A raw SQL statement
$sql = '
SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
* COS(RADIANS(X(coords)))
* COS(RADIANS(Y(coords)) - RADIANS(:lng))
+ SIN(RADIANS(:lat))
* SIN(RADIANS(X(coords)))))
AS distance_in_km
FROM object_locations
ORDER BY distance_in_km ASC
LIMIT 0,5;
';
// Base model
$model = new ObjectLocations();
// Execute the query
return new \Phalcon\Mvc\Model\Resultset\Simple(
null,
$model,
$model->getReadConnection()->query($sql, $params)
);
}
// How to use:
\Models\ObjectLocations::findNearest([
'lat' => 42.4961756,
'lng' => 27.471543300000008
])
You need to add ALL as dialect extension. Check this topic for example https://forum.phalconphp.com/discussion/16363/where-yearcurrenttimestamp-how-to-do-this