pg-promise: Transactions: Handling missing properties - node.js

This is the query I pass into a batch transaction:
INSERT INTO table VALUES(${id}, ${name}, ${crtd});
The input array may or may not contain one of the keys, say ${crtd}.
This throws Error: property 'crtd' does not exist and the entire batch fails.
I still want this row to be inserted, containing only {id} and {name}. The ${crtd} is a nullable column too.
In the below, 'l' is the input json missing the key ${crtd}.
db.tx(t=>t.batch(valuesArray.map(l=>t.none(query, l)))) So, the only way to do this is additional logic that checks for missing keys and adds them?
How to handle this?

Related

flux query: filter out all records related to one matching the condition

I'm trying to filter an influx DB query (using the nodeJS influxdb-client library).
As far as I can tell, it only works with "flux" queries.
I would like to filter out all records that share a specific attribute with any record that matches a particular condition. I'm filtering using the filter-function, but I'm not sure how I can continue from there. Is this possible in a single query?
My filter looks something like this:
|> filter(fn:(r) => r["_value"] == 1 and r["button"] == "1" ) and I would like to leave out all the record that have the same r["session"] as any that match this filter.
Do I need two queries; one to get those r["session"]s and one to filter on those, or is it possible in one?
Update:
Trying the two-step process. Got the list of r["session"]s into an array, and attempting to use the contains() flux function now to filter values included in that array called sessionsExclude.
Flux query section:
|> filter(fn:(r) => contains(value: r["session"], set: ${sessionsExclude}))
Getting an error unexpected token for property key: INT ("102")'. Not sure why. Looks like flux tries to turn the values into Integers? The r["session"] is also a String (and the example in the docs also uses an array of Strings)...
Ended up doing it in two queries. Still confused about the Strings vs Integers, but casting the value as an Int and printing out the array of r["session"] within the query seems to work like this:
'|> filter(fn:(r) => not contains(value: int(v: r["session"]), set: [${sessionsExclude.join(",")}]))'
Added the "not" to exclude instead of retain the values matching the array...

Is there any possibility to search an asset with partial id

In hyperledger-fabric node js sdk.
Is there any possibility to search an asset with partial id?
for example my id is 'abc123'.
I can search with bc12 or abc or 123..and get the matching results.
Using stub.GetStateByRange(startKey, endKey) it is possible to retrieve results on a partial key, if they key has a specific form.
For eg.
the following keys could be used to successfully with a range query in the chaincode to retrieve a list of results, to match key abc123
a
ab
abc
abc1
abc12
abc123
However, a key without the same initial characters will not work. Eg. bc12 or 123.
The below function documentation gives a good idea of how the GetStateByRange function can be used.
// GetStateByRange returns a range iterator over a set of keys in the
// ledger. The iterator can be used to iterate over all keys
// between the startKey (inclusive) and endKey (exclusive).
// However, if the number of keys between startKey and endKey is greater than the
// totalQueryLimit (defined in core.yaml), this iterator cannot be used
// to fetch all keys (results will be capped by the totalQueryLimit).
// The keys are returned by the iterator in lexical order. Note
// that startKey and endKey can be empty string, which implies unbounded range
// query on start or end.
// Call Close() on the returned StateQueryIteratorInterface object when done.
// The query is re-executed during validation phase to ensure result set
// has not changed since transaction endorsement (phantom reads detected).
GetStateByRange(startKey, endKey string) (StateQueryIteratorInterface, error)
The answer by Clyde is the correct one to your question.
But, if you intend to perform complex queries in your code and you are in a position to refactor your data modelling, maybe you can set the information you must filter in some field inside your model (instead of or in addition to the ID itself) and perform rich queries against that field.
To do this, you must enable CouchDB as the state DB in your peers if haven't done it yet. Then you can query the DB and perform rich queries against your model fields.
Of course, this is not the answer to your question, but it may fit better to your use case if you are in a position to perform this kind of changes.

Is it possible to combine 'field' and table record inside 'select' in JOOQ?

I'm using an auto incremental session variable temporary column, to get some kind of sequence for a specific sort-order. The query looks something like this:
return ctx.select(
field("rowNumber"),
TABLE.ID
).from(/* Get an inner query here */)
.where(TABLE.ID.eq(someValue))
.orderBy(field("rowNumber").asc());
But, when I try to execute the above query, it returns the following error:
Unknown column 'TABLE.ID' in 'field list'
The only way I can make it work, is when TABLE.ID is passed as field("ID") inside ctx.select().
Is it so that JOOQ doesn't support specifying the column(s) using a combination of TableRecord and field("column")?
Turns out, it is possible to do so. Apparently, the improper aliasing might have had something to do with the issue. Solved it like this:
TABLE t = TABLE.as("t");
return ctx.select(
field("rowNumber"),
t.ID
).from(getInnerQuery().asTable("t"))
.where(t.ID.eq(someValue))
.orderBy(field("rowNumber").asc());

Fetching Data from Database using Strings not IDs

Whenever we save data to the database, there is always a corresponding ID which we use to fetch the data from that specific column.
sql_con.execute("SELECT FROM DBNAME WHERE ID = ?", id)
The above code only allows us to fetch data based from the ID. The problem is that the above code only accepts 1 supplied binding. In my database, I used sets of strings as the ID for each column, which means that the binding of my IDs are more than 1. And, those sets of strings have different bindings (or character count).
How do I modify the code in above, so I could input strings as my ID, preventing it from receiving the specific error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.
Thank you in advance. I use Python 3.xx and in-built module sqlite3. Database is in .db file format and is a disk-based database.
I found the answer for my own question, by asking someone else.
For you to resolve this problem with the bindings of the input, just simply convert the parameter into a tuple.
OLD CODE:
sql_con.execute("SELECT FROM DBNAME WHERE ID = ?", id)
INTO THIS...
NEW CODE:
sql_con.execute("SELECT * FROM DBNAME WHERE ID = ?", (id,))
Hope it helps.

How to remove id from select active record?

Query on console
User.select('email','dob')
returns,
[#<User:0x000000084a9b08 id: nil, email: "xyz#zyx.com">,
Why am I getting id attributes in rails 4? How to get rid of this?
Pluck only returns the values if you want keys and values then
try this:
User.select('email','dob').as_json(:except => :id)
In my case the desired result was a JSON object. So, inside the as_json method
you can exclude any column you desire
(additionally you can invoke object methods or access associated tables as well)
This will give you desired output
User.pluck(:email, :dob)

Resources