Openerp create function doesn't execute query - postgresql

Following is my create function for roster module. The problem is that only update query is not working. The query is working fine when it run alone in pgadmin but in here it doesn't. Both Select and Insert queries are working fine.
(I know using cr.execute is not a good practice but I am in little bit hurry with deadlines).
def create(self, cr, uid, values, context=None):
#rec_id=values['id']
sub_day=values['roster_day']
ros_time=values['time_slot']
emp = values['employee']
dept = values['department_id']
sub_emp = values['sub_employee']
#sub_day = datetime.datetime.strptime(sub_day, '%Y-%m-%d')
cr.execute("""SELECT ra.id , ra.emp_id FROM roster_allocation ra, roster_days_allocation rda
WHERE rda.roster_allocation_connection=ra.id and
rda.allocation_start_day='%s' and
rda.roster_time_list=%d and
ra.emp_id=%d"""%(sub_day,ros_time,emp))
exers=cr.fetchone()[0]
cr.execute("""INSERT INTO roster_allocation (write_uid,emp_id,department_id) VALUES(%d,%d,%d)""" %(context['uid'], sub_emp, dept))
print "Employee for substitution record inserted successfully"
cr.execute("""UPDATE roster_days_allocation SET roster_allocation_connection = (SELECT MAX(ra.id) FROM roster_allocation ra, roster_substitution rs
WHERE ra.emp_id=rs.sub_employee)
WHERE allocation_start_day = '%s' AND roster_time_list = %d AND roster_allocation_connection = %d""" %(sub_day, ros_time,exers))
print "Employee for substitution record updated successfully"
return super(roster_substitution, self).create(cr, uid, values, context=context)

I have edited UPDATE query and even though it's not the best practice, it worked.
cr.execute (SELECT MAX(ra.id) FROM roster_allocation ra, roster_substitution rs
WHERE ra.emp_id=rs.sub_employee)
val=cr.fetchone()
cr.execute("""UPDATE roster_days_allocation SET roster_allocation_connection = %d
WHERE allocation_start_day = '%s' AND roster_time_list = %d AND roster_allocation_connection = %d""" %(val,sub_day, ros_time,exers))

Related

Delete statement not executed in postgresql

I am creating a transaction where I want to update a user in one table and delete some data in another that belongs to that user. But only the first query is executed, not the second one. In the delete statement in the second query code is a comma-separated std::string.
pqxx::connection c(connectionString);
try {
pqxx::work w(c);
pqxx::result r;
c.prepare("user", "update user set started = null, finished = null, task = $1 where id = $2");
r = w.prepared("user")(task)(email).exec();
c.prepare("belongings", "delete from belongings where id in " \
"(select id from info where code in ($1) and id = $2)");
r = w.prepared("belongings")(code)(id).exec();
w.commit();
}
I read this SO-thread that explain how to run multiple queries before commit(). So I must be making a mistake in the second delete statement but can't find the reason.
The code parameter is interpreted as a single literal. You can try to use the alternative syntax of any(array expression), e.g.:
code = "{abc,def}"; // instead of code = "'abc','def'"
...
c.prepare("belongings", "delete from belongings where id in " \
"(select id from info where code = any ($1) and id = $2)");
r = w.prepared("belongings")(code)(id).exec();

Column is not updating in postgresql

I tried to update my table like below:
$query = "select *
FROM sites s, companies c, tests t
WHERE t.test_siteid = s.site_id
AND c.company_id = s.site_companyid
AND t.test_typeid = '20' AND s.site_id = '1337'";
$queryrow = $db->query($query);
$results = $queryrow->as_array();
foreach($results as $key=>$val){
$update = "update tests set test_typeid = ? , test_testtype = ? where test_siteid = ?";
$queryrow = $db->query($update,array('10','Meter Calibration Semi Annual',$val->site_id));
}
The above code is working good. But in update query , The column test_typeid is not updated with '10'. Column test_typeid is updating with empty value. Other columns are updating good. I dont know why this column test_typeid is not updating? And the column test_typeid type is integer only. I am using postgreSql
And My table definition is:
What i did wrong with the code. Kindly advice me on this.
Thanks in advance.
First, learn to use proper JOIN syntax. Never use commas in the FROM clause; always use proper explicit JOIN syntax.
You can write the query in one statement:
update tests t
set test_typeid = '10',
test_testtype = 'Meter Calibration Semi Annual'
from sites s join
companies c
on c.company_id = s.site_companyid
where t.test_siteid = s.site_id and
t.test_typeid = 20 and s.site_id = 1337;
I assume the ids are numbers, so there is no need to use single quotes for the comparisons.

Postgres insert syntax error

My SQL query looks like this:
product = 'Huggies Little Movers Diaper Pants for Boys Size 5 (60 Count)'
retailer = 'Target'
query = """SELECT * FROM product_info WHERE product_name = %s AND retailer = %s""" % (product, retailer)
conn = psycopg2.connect("dbname='test1' user='postgres' host='localhost' password='123'")
cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cur.execute(query)
When i execute that i get a error saying:
psycopg2.ProgrammingError: syntax error at or near "Basic"
I am not sure why my syntax is wrong
Your statement;
query = """SELECT * FROM product_info WHERE product_name = %s AND retailer = %s""" % (product, retailer)
...builds a complete string from the query and parameters without any quoting around your strings, which makes the entire string invalid SQL which fails at execute;
SELECT * FROM product_info
WHERE product_name = Huggies Little Movers Diaper Pants for Boys Size 5 (60 Count)
AND retailer = Target
What you're probably trying to do is parameterizing your query which is instead done in execute by passing the parameters in a tuple;
query = """SELECT * FROM product_info WHERE product_name = %s AND retailer = %s"""
...
cur.execute(query, (product, retailer))

Parametrized query inside mysqli class

I am using Mertol Kasanan's class for running parametrized queries -
http://liveplanet.googlecode.com/svn-history/r132/trunk/db/DB.php
I am very satisfied with the script except for some issues that I don't seem to put my finger on.
As it states in the brief tutorial in the class's description the method for running the query is:
$result = $db->query('SELECT * FROM `users` WHERE id = ? AND user_type = ? LIMIT ?',$id,$user_type,$limit);
Can anybody figure out how to run a query without defining any parameter as it seems that
$result = $db->query('SELECT * FROM `users` WHERE id = 'y' ");
neither
$result = $db->query('SELECT * FROM `users` WHERE id = 'y' ", '');
do not do the trick as it returns a binding error;
A workaround would be
$result = $db->query('SELECT * FROM `users` WHERE 1 = ? AND id = 'y' ", 1);
Is there a neater way to run my query?
I don't need parameters as the query gets it's values from a safe source inside a class.
Edit:
Let's say I have this:
if($HC == 'C'){
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat != 'D' GROUP BY pic LIMIT ?";
$query = $this->dbs->query($sql,$this->user,$this->user_head,4);
$results = $this->dbs->numRows($query);
if($results < 3){
$sql = "SELECT * FROM `photo` WHERE `user` = ?i AND `pic` != ?s ORDER BY id ASC LIMIT ?";
$query = $this->dbs->query($sql, $this->user,$this->user_head,4);
}
}else{
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat = ?s ORDER BY RAND() LIMIT ?";
$query = $this->dbs->query($sql,$this->user,$this->user_head,$HC,4);
$results = $this->dbs->numRows($query);
}
Now, in order to get the data from the right query I can either define $data->getAll under each query - but that would mean repeating my code or I could try extracting the data from the last defined $query result - which I do not know how to do.
I know that there may be a better way of doing this but I am trying to improve my coding style as I think the safemysql class would need some improvements even if that would mean a bit more documentation.
I could try using $db->getAll instead of $db->query but, as far as I know, I cannot use numRows on GetAll.
As a matter of fact, this class is totally unusable. And the problem you mentioned is a least one.
It seems that someone who wrote it, never used this class in a real life project.
So, if you want a class which works and works way better, go for SafeMysql, as it will do exactly what you want:
$data = $db->getAll("SELECT * FROM `users` WHERE status = 'y'");
(note that you've got your data already, without any further code)
Nevertheless, you have to understand that the following statement of yours
I don't need parameters as the query gets it's values from a safe source inside a class.
is wrong.
It's OK to use a hard-coded value as you wrote it, but if you were intended to use a "safe" variable - it ought to be added via placeholder. Otherwise your query remains error-prone and unsafe.
So, it have to be
$id = 1; // "safe" variable
$data = $db->getRow("SELECT * FROM `users` WHERE id = ?i", $id);
To answer edited question. Not sure if it's what you need, but here is the code. It wu
if($HC == 'C')
{
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat != 'D' GROUP BY pic LIMIT ?";
$data = $this->dbs->getAll($sql,$this->user,$this->user_head,4);
if (count($data) < 3) {
$sql = "SELECT * FROM `photo` WHERE `user` = ?i AND `pic` != ?s ORDER BY id ASC LIMIT ?";
$data = $this->dbs->query($sql, $this->user,$this->user_head,4);
}
} else {
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat = ?s ORDER BY RAND() LIMIT ?";
$data = $this->dbs->query($sql,$this->user,$this->user_head,$HC,4);
}

crytal report count total records

Im using query in crystal report like:
if({?User Name}) <>"ALL"
then
{COMN_USER_RESP_LINK_T.APPL_USER_NAME}={?User Name}
else
{COMN_USER_RESP_LINK_T.APPL_USER_NAME} ={COMN_USER_RESP_LINK_T.APPL_USER_NAME}
and
{COMN_USER_RESP_LINK_T.ENABLED}="Y"
this is actual query in sql:
SELECT
C.APPL_USER_NAME,
A.RESP_NAME,
B.MENU_NAME,
B.DESCRIPTION,
B.MODULE_NAME,
C.APPL_RESP
FROM COMN_RESPONSIBILITY_T A,
COMN_RESP_MENU_LINK_T B,
COMN_USER_RESP_LINK_T C
WHERE A.COMP_CODE = B.COMP_CODE
AND B.COMP_CODE = C.COMP_CODE
AND C.COMP_CODE = A.COMP_CODE
AND A.RESP_NAME = B.RESP
AND C.APPL_RESP = A.RESP_NAME
AND B.ENABLED = 'Y'
AND C.APPL_USER_NAME = c.APPL_USER_NAME
CASE #ACCT_CODE_FROM
WHEN 'ALL' THEN C.APPL_USER_NAME
ELSE #ACCT_CODE_FROM
END
ORDER BY APPL_USER_NAME,
RESP_NAME
I should select user name in parameter field(?user name), if I select ALL then I have to show all records ({COMN_USER_RESP_LINK_T.APPL_USER_NAME})
is the above query correct?
I would probably rephrase that as something like:
SELECT C.APPL_USER_NAME, A.RESP_NAME, B.MENU_NAME, B.DESCRIPTION,
B.MODULE_NAME, C.APPL_RESP
FROM COMN_RESPONSIBILITY_T A
INNER JOIN COMN_RESP_MENU_LINK_T B ON A.COMP_CODE = B.COMP_CODE
AND A.RESP_NAME = B.RESP
INNER JOIN COMN_USER_RESP_LINK_T C ON B.COMP_CODE = C.COMP_CODE
AND C.APPL_RESP = A.RESP_NAME
WHERE ((#ACCT_CODE_FROM = 'ALL') AND (B.ENABLED = 'Y'))
OR (C.APPL_USER_NAME = #ACCT_CODE_FROM)
ORDER BY APPL_USER_NAME, RESP_NAME
This gets you the details for either:
when ALL is selected, all accounts that are enabled; or
just the user code entered
i don't read your code because it is very dirty! but i think you can use SelectionFormula in crystal report. Certainly you can set it in code :
crystalReportViewer1.SelectionFormula ="(({?User Name}= 'ALL') AND ({B.ENABLED} = 'Y'))
OR ({C.APPL_USER_NAME} = #ACCT_CODE_FROM)"