Codeception grabRecord failing - yii2

Using Yii2 2.0.12, php 5.6.24 and codeception 2.3.3
On a recent upgrade a set of acceptance tests that have always worked up to now, failed. The upgrade was a standard composer update to the latest versions. The test scenario is as follows:
Test adding a record via a form
Grab the new record to verify
Test adding a second record via a form
Grab the new record to verify
The second grab fails in that it returns an empty record. I've traced this back to the 'queryInternal' method of the 'Command' object and there is a correctly formed PDO statement which performs the correct query but returns an empty result. I've tried breaking before the PDO->execute() and performing the query in MySQL. The query works but the PDO statement fails.
the code of the Cept test script is:
$I->wantTo('Do successive grabs');
$I->amOnPage('index.php?r=portfolio%2Fcreate');
$I->see('Create Portfolio');
$I->fillField('Name','Test Portfolio 1');
$I->click('Create');
$r = $I->grabRecord('app\models\Portfolio' , ['name' => 'Test Portfolio 1']);
$I->amOnPage('index.php?r=portfolio%2Fcreate');
$I->see('Create Portfolio');
$I->fillField('Name','Test Portfolio 2');
$I->click('Create');
$r = $I->grabRecord('app\models\Portfolio' , ['name' => 'Test Portfolio 2']);
The second "grabRecord" produces an empty record. Anyone else have a similar problem?

This seems to have been caused by the change in the 'cleanup' option in 2.2.6. Changing this value to false in the .yml file seems to clear the problem, although I'm not sure why.

Related

JSP page is running MySQL query twice on Tomcat

I am getting this weird problem where a MySQL insert is happening twice. I kept pairing down the code until I had the simplest version, but it's still happening. Has anyone seen this before? This is on a Tomcat server.
Below is my super-simplified code. When I run this, two entries appear in the table withe same value. The strange thing is it seems to run the whole page twice, because if I do a select quickly enough I can see the first entry by itself, then seconds later the second entry appears. When I timestamp the rows, they are 1-ish seconds different.
"jdbc:mysql://127.0.0.1/mydatabase",
"myusername",
"mypassword"
);
java.sql.Statement statement = connection.createStatement();;
statement.execute("INSERT INTO tbl_test (Value) VALUES ('Test value')");
%>
Additional info:
Also if I execute a select statement after the insert and select the complete contents of the table, only the first entry shows up. But when I look in the database, there are two entires. So it's like the whole jsp page finishes running, then runs again silently in the background.
Here is an expanded version of the code that allows you to choose the input value for the database, so you can try this out on the fly and see what's happening:
<%
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection = java.sql.DriverManager.getConnection(
"jdbc:mysql://***/***",
"***",
"***!"
);
java.sql.Statement statement = connection.createStatement();
String Value = request.getParameter("Value");
statement.execute("INSERT INTO tbl_test (Value) VALUES ('" + Value + "');");
java.sql.ResultSet rs = statement.executeQuery("SELECT * FROM tbl_test;");
while (rs.next()) {
%><%=rs.getString("ID")%>=<%=rs.getString("Value")%><BR><%
}
%>
You can try out this code at:
http://familychurch.life/familychurch/test.jsp?Value=Whatever
(Replace "Whatever" with the value you want to insert.)
Run it once and you'll see the value inserted once. But run it a second time, and you will see that the value you entered before is now in the table twice.
It turns out the problem was caused by a Chrome extension (Video Downloader for FaceBook™). It must have been reloading the page silently in the background.
Special shout-out to #RiggsFolly for helping me figure it out!

Ruby MySQL output conflicting on different servers

I have coded a Ruby IRC bot which is on github (/ninjex/rubot) which is having some conflicting output with MySQL on a dedicated server I just purchased.
Firstly we have the connection to the database in the MySQL folder (in .gitignore) which looks similar to the following code block.
#con = Mysql.new('localhost', 'root', 'pword', 'db_name')
Then we have an actual function to query the database
def db_query
que = get_message # Grabs query from user i.e,./db_query SELECT * FROM words
results = #con.query(que) # Send query through the connection i.e, #con.query("SELECT * FROM WORDS")
results.each {|x| chan_send(x)} # For each row returned, send it to the channel via
end
On my local machine, when running the command:
./db_query SELECT amount, user from words WHERE user = 'Bob' and word = 'hello'
I receive the output in IRC in an Array like fashion: ["17", "Bob"] Where 17 is amount and Bob is the user.
However, using this same function on my dedicated server results in an output like: 17Bob I have attempted many changes in the code, as well as try to parse the data into it's own variable, however it seems that 17Bob is coming out as a single variable, making it impossible to parse into something like an array, which I could then use to send the data correctly.
This seems odd to me on both my local machine and the dedicated server, as I was expecting the output to first send 17 to the IRC and then Bob like:
17
Bob
For all the functions and source you can check my github /Ninjex/rubot, however you may need to install some gems.
A few notes:
Make sure you are sanitizing query via get_message. Or you are opening yourself up to some serious security problems.
Ensure you are using the same versions of the mysql gem, ruby and MySql. Differences in any of these may alter the expected output.
If you are at your wits end and are unable to resolve the underlying issue, you can always send a custom delimiter and use it to split. Unfortunately, it will muck up the case that is actually working and will need to be stripped out.
Here's how I would approach debugging the issue on the dedicated machine:
def db_query
que = get_sanitized_message
results = #con.query(que)
require 'pry'
binding.pry
results.each {|x| chan_send(x)}
end
Add the pry gem to your Gemfile, or gem install pry.
Update your code to use pry: see above
This will open up a pry console when the binding.pry line is hit and you can interrogate almost everything in your running application.
I would take a look at results and see if it's an array. Just type results in the console and it will print out the value. Also type out results.class. It's possible that query is returning some special result set object that is not an array, but that has a method to access the result array.
If results is an array, then the issue is most likely in chan_send. Perhaps it needs to be using something like puts vs print to ensure there's a new line after each message. Is it possible that you have different versions of your codebase deployed? I would also add a sleep 1 within the each block to ensure that this is not related to your handling of messages arriving at the same time.

Codeignighter Record wont insert

Using CI for the first time and i'm smashing my head with this seemingly simple issue. My query wont insert the record.
In an attempt to debug a possible problem, the insert code has been simplified but i'm still getting no joy.
Essentially, i'm using;
$data = array('post_post' => $this->input->post('ask_question'));
$this->db->insert('posts', $data);
I'm getting no errors (although that possibly due to disabling them in config/database.php due to another CI related trauma :-$ )
Ive used
echo print $this->db->last_query();
to get the generated query, shown as below:
INSERT INTO `posts` (`post_post`) VALUES ('some text')
I have pasted this query into phpMyAdmin, it inserts no problem. Ive even tried using $this->db->query() to run the outputted query above 'manually' but again, the record will not insert.
The scheme of the DB table 'posts' is simply two columns, post_id & post_post.
Please, any pointers on whats going on here would be greatly appreciated...thanks
OK..Solved, after much a messing with CI.
Got it to work by setting persistant connection to false.
$db['default']['pconnect'] = FALSE;
sigh
Things generally look ok, everything you have said suggests that it should work. My first instinct would be to check that what you're inserting is compatible with your SQL field.
Just a cool CI feature; I'd suggest you take a look at the CI Database Transaction class. Transactions allow you to wrap your query/queries inside a transaction, which can be rolled back on failure, and can also make error handling easier:
$this->db->trans_start();
$this->db->query('INSERT INTO posts ...etc ');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
// generate an error... or use the log_message() function to log your error
}
Alternatively, one thing you can do is put your Insert SQL statement into $this->db->query(your_query_here), instead of calling insert. There is a CI Query feature called Query Binding which will also auto-escape your passed data array.
Let me know how it goes, and hope this helps!

CI: Session Variables and json_encode

I have values I've added to my session that I'd like to pass into an query as follows:
$eventTypeID = $this->session->userdata('eventtypeID');
$this->session->unset_userdata('eventtypeID');
$venueCityID = $this->session->userdata('venuecityID');
$this->session->unset_userdata('venuecityID');
echo json_encode($this->event_model->getSearchEvents($eventTypeID, $venueCityID));
The issue I'm running into is that last line (echo json_encode...) will not run when the prior variables are extracted/unset. If I comment out the variables, and run simply:
echo json_encode($this->event_model->getSearchEventsAll());
Then all works well. Can someone tell my why json_encode doesn't seem to play well with sessions and how I may be able to get this to work? Thanks!
EDITED
After much frustration, it now appears the issue may not be with the session, but is instead with outputting my query:
$this->db->_compile_select();
$q = $this->db->get();
echo $this->db->last_query();
All used to work fine, and I was able to "intercept" the query to see what was being called, but now when using _compile & last_query, nothing happens????
Run json_last_error() to see if any errors were encountered encoding the data. See the example on the docs page for proper usage:
http://www.php.net/manual/en/function.json-last-error.php
We're not certain what $this->event_model->getSearchEvents($eventTypeID, $venueCityID) returns VS $this->event_model->getSearchEvents(), but there should definitely not be any problems related to the use of variables.
As always, try var_dump() on the output (try before decoding) and see what the differences are between the two return values of the function. You might even be encountering an error within the function itself that's stopping execution - make sure error_reporting() is on full-blast.

Why doesn't a new table column show up in the query results in CakePHP?

I have added a new column to my table Attributes which already has (id , form_id(foreign key),type,label,size,sequence no,instr)
where instr is the new column i have added.
My application is in CakePHP and MySQL.
I have used the following code to insert into the table Attributes But the field instr alone not inserted.
function saveFieldname($data)//from untitledfieldname
{
$this->data['Attribute']['form_id'] = $this->find( 'all', array(
'fields' => array('Form.id'),
'order' => 'Form.id DESC'
));
$this->data['Attribute']['form_id'] = $this->data['Attribute']['form_id'][0]['Form']['id'];
$this->data['Attribute']['label'] = 'Label';
$this->data['Attribute']['size'] ='50';
$this->data['Attribute']['instr'] ='Fill';
$this->data['Attribute']['type'] = $data['Attribute']['type'];
$this->data['Attribute']['sequence_no'] = $data['Attribute']['sequence_no'];
$this->Attribute->save($this->data);
}
Please suggest me..
The information about the structure of your table is probably cached. Remove the content of "app/tmp/cache/models" and try it again.
Note that in development the debug level in app/config/core.php is usually set to > 1. This means you should never run into the issue in development because Cake will not cache. However, in production, debug is set to 0 in core.php, thus causing cake to start caching.
To add to that, I had removed the cache files in app/tmp/cache/models as dhofstet specified on my production CakePHP app and the find queries were still not grabbing my new column.
--
As well as clearing the model cache files, I set the debug level to 2 on my production site and did page refresh then set it back to 0 and it got it working again. I know this is an ugly approach, but it fixed it for me when no other methods were working.