How to safely detele a record? - orm

CONTEXT
I created an app which handles todos. I want to be able to delete todos based on an id I get from the url
import vweb
struct App {
vweb.Context
}
[post]
["/todo/:id/delete"]
pub fn (mut app App) delete_todo_response(id string) vweb.Result {
db := sqlite.open("dist/database.db") or {
return app.redirect("/todo")
}
db.exec_none('DELETE FROM todo WHERE id = $id') // id is not escaped
}
fn main() {
vweb.run<App>(80)
}
PROBLEM
As you can see, the id is not escaped. I feel this is not the ideal and secure way to do this.
QUESTIONS
How one can escape values using exec(), exec_one() or exec_none()?
Is the ORM capable of deleting a record for me based on a struct, like this is possible with select and insert?

As far as I know, there is no standard way to escape sqlite queries.
However, you can indeed use the ORM.
If you declare your Todo struct, this should do :
sql db {
delete from Todo where id == id
}

Related

Return selected fields only React Native / GraphQL / Amplify

I have the following basic list query in GraphQL:
API.graphql(graphqlOperation(listSomething,{filter: filter})).then(({ data: { something } }) => {
// Returns the entire object
})
This will return an array containing entire objects, but as I've seen on multiple GraphQL tutorials, I'd like to take advantage of the utility of only returning / plucking select fields for obvious reasons. However there isn't a lot of information out there on GraphQL + RN + Amplify. So how would I re-write this query to only return the attribute id for instance? Or is that something that I have to define as a resolver in the graphql / queries.js file? I'm using autogenerated queries so it sort of feels like an anti-pattern to add your own queries to that file — Correct me if I'm wrong.
Thanks!
I'm still at an early stage of getting familiar with AWS, so please take this with a grain of salt.
Your auto generated queries.js will contain a listSomething query, that looks something like this:
export const listTodos = /* GraphQL */ `
query ListTodos(
$filter: ModelTodoFilterInput
$limit: Int
$nextToken: String
) {
listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
userID
name
description
createdAt
updatedAt
}
nextToken
}
}
`;
I created a new folder called /src/customGraphQL and created a file called customListTodos.js. I copied there the auto generated query, changed the query name, and removed the fields I didn't need.
export const customListTodos = /* GraphQL */ `
query CustomListTodos(
$filter: ModelTodoFilterInput
$limit: Int
$nextToken: String
) {
listTodos(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
name
description
}
nextToken
}
}
`;
I only changed the query's name, but kept the inner function's name as listTodos, so I'm running a customised version of that query. If the original API is pushed to AWS, you can import and use the custom query:
import {customListTodos} from './src/customGraphQL/customListTodos';
...
API.graphql(graphqlOperation(customListTodos ...
This worked for me. Making a custom queries file was pretty simple and I was able to limit the object to just returning the _version.
export const getUserVersion = /* GraphQL */ `
query GetUserVersion($id: ID!) {
getUser(id: $id) {
_version
}
}
`;
Then in my .js file I could call the function this way:
const getUserVersionResponse = await API.graphql(
graphqlOperation(getUserVersion, { id })
);

How to add a semi colon ; automatically to each generated sql statement using jOOQ

I'm trying to add a semi colon ; to every jOOQ generated sql statement as I'm writing multiple DDL and insert statement to an output file.
I found a similar question here suggesting using an ExecuteListener here https://jooq-user.narkive.com/6adKecpt/adding-semicolon-at-the-end-of-sql-statement.
My setup is now as follows (using Groovy):
private DSLContext createDSLContext() {
def configuration = new DefaultConfiguration()
configuration.settings = new Settings()
.withRenderFormatted(true)
.withRenderKeywordCase(RenderKeywordCase.LOWER)
.withRenderQuotedNames(RenderQuotedNames.ALWAYS)
.withStatementType(StatementType.STATIC_STATEMENT)
configuration.set(
new DefaultExecuteListenerProvider(new DefaultExecuteListener() {
#Override
void renderEnd(ExecuteContext ctx) {
ctx.sql(ctx.sql() + ";")
}
}),
new DefaultExecuteListenerProvider(new DefaultExecuteListener() {
#Override
void start(ExecuteContext ctx) {
println "YEAH!!!"
}
}))
// return configuration.dsl();
return DSL.using(configuration)
}
but is not adding the semi colon, nor is it getting in the renderEnd method at all.
I added another execute listener to print something at the start (as I have seen in other examples) but it is also never called..
My code looks like:
file.withWriter { writer ->
// Drop schema objects.
DEFAULT_SCHEMA.tables.each {
switch (it.type) {
case TABLE:
writer.writeLine(dsl.dropTableIfExists(it).SQL)
break
case VIEW:
writer.writeLine(dsl.dropViewIfExists(it).SQL)
break
}
}
writer.writeLine("")
// Create schema objects.
def ddlStatements = dsl.ddl(DEFAULT_SCHEMA)
ddlStatements.each {
writer.writeLine(it.SQL)
writer.writeLine("")
}
// Insert data.
def insert = dsl.insertInto(Tales.CUSTOMER).columns(Tales.CUSTOMER.fields())
customers.each {insert.values(it) }
writer.writeLine(insert.SQL)
}
The ExecuteListener lifecycle is only triggered when you execute your queries with jOOQ. You're not doing that, you're just calling Query.getSQL()
You could wrap your queries into DSLContext.queries(Query...), and jOOQ will separate the statements using ; when you call Queries.getSQL() when you call Queries.toString(). Of course, that's not reliable, the behaviour of toString() might change in the future, which is why it would make sense to offer methods like Queries.getSQL() and the likes: https://github.com/jOOQ/jOOQ/issues/11755
For the time being, why not just add the semi colon manually to the writer in your code?

Where do I execute native SQL queries in Loopback 4?

I'm new to Loopback 4 and I've been trying to execute a native SQL query. I found how to do it, the thing is that don't have any clue of WHERE to put it in my code in order for it to work... here's the documentation I found.
I need to know where should I put this:
const result = await repository.execute('SELECT * FROM Products');
in my Loopback project, which has many files. My goal is to make a REST endpoint like /products/[name] with [name] being a parameter inserted dynamically to the SQL query.
You can do it in your controller class as per loopback docs https://loopback.io/doc/en/lb4/Controller.html. As you will define the REST endpoint in the controller itself you can also do the insertion there using repository.execute() e.g.
#get('/products/{name}')
async doSomething(
#param.path.string('name') name: string,
): Promise<Product> {
const sql = `SELECT * FROM some_table WHERE some_field="${name}"`;
await this.productRepository.execute(sql)
--- other lines of code & return value --
}
Personally, I would implement it as a new Repository method.
Let's say your model is called Product, then you should have src/repositories/product.repository.ts file exporting ProductRepository class already present in your project. (You can run lb4 repository to create it.)
export class Product extends DefaultCrudRepository<
Product,
typeof Product,
Product Relations
> {
constructor(#inject('datasources.db') dataSource: DbDataSource) {
super(Product, dataSource);
}
// your custom method
async selectByName(name: string): Promise<Product[]> {
const rawItems = await repository.execute('SELECT * FROM Products');
// would you like to convert raw data into Product instances?
return rawItems.map(it => new Product(it));
}
}
Then you can call this new custom repository method from your controller in the same way as you would call e.g. repository.find(filter).

Golang access raw Podio field values

Hi Podio people (and maybe more specifically Andreas),
I'm trying to dig deeper into the Golang API library but bumping into my rookie Golang skills.
After doing a client.getItems(...) call I wish to loop over the fields inside of the items and only grab relevant portions. The end goal is that I can create a very much simplified json object like this
{
1000: "John", // key = app field id, value = text
5490: [{item_id: 4031294, app_id: 94392}], // relations
5163: [1,2,5] // categories
}
However I cannot seem to get a hold of the item.Fields nested Values struct {}. I tried using reflect but without any luck.
Could someone help me complete this code please?
for _, field := range item.Fields {
switch field.PartialField.Type {
case "text":
simpleValue := field.Values.Value // not working as I can't access Value in struct {}
}
}
Greetings,
PJ
Try a type assertion
myTexts := field.Values.([]TextValue)
You can also check for a valid assertion so your program doesn't panic
myTexts, assertionSucceeded := field.Values.([]TextValue)

Parsing Expression Tree To Sqlstring - Not Reinventing the wheel

I need to parse an expressiontree to get a sql where clause.
Aren't there any classes in the .NET FX or any third party library which already have this abilities ?
I mean Linq2SQL, EntityFramework , all of them have to do this, so does anyone know, if there is something that can be reused instead of reinventing the wheel?
MyType.Where(Func<TEntity,bool>((entity)=>entity.Id == 5)))
now i need to get the corresponding string representing a where clause:
where abc.Id = "5"
this is just an simple example. it should also work with logical conjunctions.
I know I can create the expressiontree and parse it on my own, but i think there could be something already existing, which I'm missing
You could create an ExpressionVisitor with the sole purpose of finding and processing the where calls. Making this task very easy to handle.
e.g.,
public class WhereCallVisitor : ExpressionVisitor
{
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var method = node.Method;
if (method.Name == "Where" && method.DeclaringType == typeof(Queryable))
{ // we are in a Queryable.Where() call
ProcessWhereCall(node);
}
return base.VisitMethodCall(node);
}
private void ProcessWhereCall(MethodCallExpression whereCall)
{
// extract the predicate expression
var predicateExpr = ((dynamic)whereCall.Arguments[1]).Operand as LambdaExpression;
// do stuff with predicateExpr
}
// p.s., dynamic used here to simplify the extraction
}
Then to use it:
var query = from row in table
where row.Foo == "Bar"
select row.Baz;
var visitor = new WhereCallVisitor();
visitor.Visit(query.Expression);