How to query/scan a table in DynamoDB using AND and OR in the same statement using python? - python-3.x

I want to query a table on DynamoDB and using python. The thing with this query is that I want to use an AND and OR condition in the same query. I want the query to retrieve values from one column when the value is B or C.
I have the following table:
domain validation_A validation_B validation_C
--------- ----------------- --------------- ---------------
drene.com pass pass pass
drene.com pass true pass
drene.com fail pass pass
In regular SQL expression I will use:
Select *
from
ValidationTable
where
domain = 'drene.com' and
validation_A = 'pass' and
(validation_B = 'pass' or validation_B = 'true')
I do not know how to do this in DynamoDB / Pythom
I tried the following:
response = table.scan(
IndexName="Date-index",
FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') || Attr('validation_B').eq('true'))
)
But it is not working
I need the query bring me the first 2 rows.

Use | instead of ||
response = table.scan(
IndexName="Date-index",
FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') | Attr('validation_B').eq('true'))

Related

How to log parameters instead of placeholders using sqlx with Postgres?

I'm using sqlx for the first time today.
I'm having really hard time understanding my SQL errors because I cannot copy & paste logged queries in my IDE because the parameters are not converted from placeholders.
It prints:
SELECT * from players where team_id = $1 AND id = $2
but I would like the below instead:
SELECT * from players where team_id = 'ABC' AND id = '123'
How to do this?

Django Rest : AssertionError: Cannot combine a unique query with a non-unique query

I'm trying to get a queryset with unique instances of a model project. when I try to combine multiple querysets with & operator like:
projects = (q1_projects & q2_projects & q3_projects)
I get this error:
AssertionError: Cannot combine a unique query with a non-unique query.
As quoted by ruddra
You can use union() to combine different querysets like this:
q1_projects = Model.objects.filter(...)
q2_projects = Model.objects.filter(...)
q3_projects = Model.objects.filter(...)
projects = q1_projects.union(q2_projects, q3_projects)
That will give same result as:
projects = q1_projects & q2_projects & q3_projects
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the all=True argument.
But if you want to order_by on the ForeignKey, you have to use select()
I got the same error below:
AssertionError: Cannot combine a unique query with a non-unique query.
When combining the query with distinct() and the query without distinct() with "|"(bitwise or) as shown below:
qs1 = Food.objects.distinct().filter(name='Apple') # With "distinct()"
qs2 = Food.objects.filter(name='Orange') # Without "distinct()"
result = qs1 | qs2 # Here
So, I used union() instead of "|"(bitwise or) as shown below, then the error was solved:
qs1 = Food.objects.distinct().filter(name='Apple')
qs2 = Food.objects.filter(name='Orange')
result = qs1.union(qs2) # Here

How to Update oracle table using Python passing arguments

I need to pass 2 arguments to my update statement.
I first get the distinct ID's from TBL1 into a List as below. This works fine
unit_no=[]
sql = """SELECT DISTINCT(ID) FROM TBL1"""
tmp_cursor=self.DB_conn.cursor()
for rec in tmp_cursor.execute(self.orcl_query1)
unit_no.append(rec)
Then, I get a values from another table using the above result. This also is working fine.
while i < len(unit_no):
sql = 'SELECT COL1 FROM TBL2 WHERE ID = :1)
tmp_cursor1=self.DB_conn.cursor()
tmp_cursor1.execute(sql,unit_no[i])
for result in tmp_cursor1
input1=result
sql = """update tbl1 set col1 = :1 where id = :2"""
tmp_cursor2=self.DB_conn.cursor()
tmp_cursor2.execute(sQL,col1, unit_no[i])
I am getting error - function takes at most 2 arguments (3 given), for the above line.
How do I pass 2 values as input to the update statement

Need help fetching data from a column

Sorry for this but I'm real new to sqlite: i've created a database from an excel sheet I had, and I can't seem to fetch the values of the column I need
query = """ SELECT GNCR from table"""
cur.execute(query)
This actually works, but
query = """ SELECT ? from table"""
cur.execute(query, my_tuple)
doesn't
Here's my code:
def print_col(to_print):
db = sqlite3.connect('my_database.db')
cur = db.cursor()
query = " SELECT ? FROM my_table "
cur.execute(query, to_print)
results = cur.fetchall()
print(results)
print_col(('GNCR',))
The result is:
[('GNCR',), ('GNCR',), ('GNCR',), ('GNCR',), [...]]
instead of the actual values
What's the problem ? I can't figure it out
the "?" character in query is used for parameter substitution. Sqlite will escape the parameter you passed and replace "?" with the send text. So in effect you query after parameter substitution will be SELECT 'GNCR' FROM my_table where GNCR will be treated as text so you will get the text for each row returned by you query instead of the value of that column.
Basically you should use the query parameter where you want to substitute the parameter with escaped string like in where clause. You can't use it for column name.

Dynamic variable parameter in static mysql query using groovy soap ui

I would like to generate the query that results for the BeneficiaryID 'ABC123' along with some other inputs if they were also given. Suppose if the currency value is given, I would like to include the Currency condition as well in the JOIN query, so as well the Category. I have the following code snippet in the SOAP UI Groovy script.
query= " CORR.BeneficiaryID LIKE 'ABC123'"
if (currencyValue!=""){
query=query + " and CORR.Currency LIKE '${currencyValue}'"
}
if (CategoryValue!=""){
query=query + " and CORR.Category LIKE '${CategoryValue}'"
}
log.info("Query" + query)
Outputrows = sql.rows("select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
from BENEFICIARY CORR \
JOIN LOCATION LOC on CORR.UID=LOC.UID and ${query}
log.info("Output rows size" + Outputrows.size())
When currency and category are not given, I would like to have the following query run and get me the results.
select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
from BENEFICIARY CORR \
JOIN LOCATION LOC on CORR.UID=LOC.UID and CORR.BeneficiaryID LIKE 'ABC123'
and when the currency and category are given(say USD & Commercial), then the following query.
select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
from BENEFICIARY CORR \
JOIN LOCATION LOC on CORR.UID=LOC.UID and CORR.BeneficiaryID LIKE 'ABC123' and CORR.Currency LIKE 'USD' and CORR.Category LIKE 'Commercial'
All I could see on the result for Outputrows.size() is zero(0).
Can you please correct me where am I doing wrong.
Thanks.
Here is changed script.
Since the issue to just build query, only putting that part remove sql execution part as that is not really the issue.
//Define the values or remove if you get those value from somewhere else
//Just put them here to demonstrate
//You may also try by empty value to make sure you are getting the right query
def currencyValue = 'USD'
def categoryValue = 'Commercial'
def query = 'select CORR.Preferred as preferred, CORR.Category as category,CORR.Currency as currency from BENEFICIARY CORR JOIN LOCATION LOC on CORR.UID = LOC.UID and CORR.BeneficiaryID LIKE \'ABC123\''
currencyValue ? (query += " and CORR.Currency LIKE '${currencyValue}'") : query
categoryValue ? (query += " and CORR.Category LIKE '${categoryValue}'") : query
log.info "Final query is \n ${query}"
You can just pass query to further where you need to run the sql, say sql.rows(query)
You may quickly try Demo

Resources