How to ping the mysql server in Yii2 Framework - mysql

I am looking to be able to ping the MySQL server using mysql_ping() (mysqli_ping()) inside the Yii2 Framework.
I currently use the createCommand() for all my SQL queries so I do not have a good understanding of how to use the ping function outside of that scope.
I am not sure how to even grab the SQL link inside go Yii.
I do not have any test code since I am not even sure where to start.
Any help to point me in the right direction will be appreciated.

Yii DB component uses PDO, which does not have mysql_ping() equivalent. The closest what you can get is to query SELECT 1 and reconnect if exception occurred.
public function ping() {
try {
Yii::$app->db->createCommand('SELECT 1')->query();
} catch (\yii\db\Exception $exception) {
Yii::$app->db->close();
Yii::$app->db->open();
}
}
Note that reconnection implicitly may result unexpected and silent rollbacks if you're using transactions.

Related

Laravel 8 migration: DB:unprepared is not working on shared hosting server

My migrations worked as expected on the local server, but when I tried to deploy my project on the live shared hosting server and after using php artisan migrate, I got the below error.
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:692
688▕ // If an exception occurs when attempting to run a query, we'll format the error
689▕ // message to include the bindings with SQL, which will make this exception a
690▕ // lot more helpful to the developer instead of just the database's errors.
691▕ catch (Exception $e) {
➜ 692▕ throw new QueryException(
693▕ $query, $this->prepareBindings($bindings), $e
694▕ );
695▕ }
696▕ }
+7 vendor frames
8 database/migrations/2021_08_03_215015_create_user_turning_functions_table.php:14
Illuminate\Support\Facades\Facade::__callStatic("unprepared")
+21 vendor frames
30 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput),
Object(Symfony\Component\Console\Output\ConsoleOutput))
Migration:
public function up()
{
DB::unprepared("
CREATE OR REPLACE FUNCTION `get_classes`(subjects VARCHAR(140))
RETURNS varchar(200)
BEGIN
DECLARE classes VARCHAR(48);
SET classes='something here';
RETURN classes;
END");
}
public function down()
{
DB::unprepared('DROP FUNCTION IF EXISTS get_classes');
}
I am not sure where I am going wrong here or what I have to do in such a case?
I may be off base, but I will give you the answer that, if true, you don't want to hear.
You mentioned shared hosting, and once I saw your code it really stuck out for me as I have worked in the hosting industry for some time. Typically, shared hosting providers do not allow you to use stored procedures/functions at all. I have not met one that does allow it.
This is just something typically not available on shared hosting providers and would require a VPS or dedicated server.
I hope my answer is wrong and they do allow it and you can solve your issue, however you should simply ask your provider in a live chat (if possible) if they allow stored procedures. There is a strong chance that they do not.

How to handle error in sparkjava port binding

I am using sparkjava as an embedded REST server. I have made the port number user configurable, however I want to handle the case where the user has specified a port that is already in use.
The error handling section of the documentation only deals with handling routes.
Is there any way to deal with errors that occur when port() is called with a port that is already in use or otherwise invalid?
My current inelegant solution is to check with a server socket before start the class that uses Spark:
try {
ServerSocket socket = new ServerSocket(prefs.getListenPort());
socket.close();
MyListener listener = new MyListener(sightingQueue, prefs.getListenPort());
} catch (Exception e) {
// port is not valid
}
From my testing, port() doesn't throw any exception when called on an already-open port. It just terminates the program. So I guess your method is the way to go, couldn't find any inherent method.
With Spark 2.6.0 you can specify an InitExceptionHandler:
initExceptionHandler((e) -> System.out.println("Uh-oh"));
There is a release candidate that you can test out:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.6.0.RC0</version>
</dependency>`

How to wait for MySQL To Update in VB.NET?

I have been working on something that checks an MySQL Database to check something - however the program stops responding because it is constantly checking the database. Is it possible to have it wait a few seconds to recheck the database? I have tried sleep() but it is giving a strange error:
A call to PInvoke function
'Game!WindowsApplication1.Form1::Sleep' has unbalanced the
stack. This is likely because the managed PInvoke signature
does not match the
unmanaged target signature. Check that the calling convention
and parameters of the
PInvoke signature match the target unmanaged signature.
I have been looking into this for quite a while and i am in a predicament. I do need the MySQL databases to be checked very often. I tried making a web browser refresh before checking it again - but it started to lag the application.
Code:
function updateit()
' SQL Code goes here, it succeeds.
updateit() ' Update it again.
return true
end
updateit()
Your code example shows a recursive function with no base case. The result of that is always a stack overflow (an uncatchable exception in .Net).
Don't call your updateit() function from within the function itself. Instead, just write a loop to call it over and over.
Try doing your checks from a separate thread. Try dragging a BackgroundWorker onto your form and putting your check in that to make your program more responsive. I've never seen that error before though. Is it System.Threading.Thread.Sleep() or something specific to VB?
Looking at your code it looks like you've got infinite recursion. That will cause a stackoverflow... try
while(true)
'SQL code
end

LightSwitch + MySQL error: Nested Transactions are not supported

Trying to connect to and modify existing data in a MySQL table. The reading working fine but when trying to save a change, the following error occurs.
An error occurred while starting a transaction on the provider connection. See the inner exception for details.
Inner exception message:
Nested transactions are not supported.
Using MySQL Connector Net 6.4.3
Answer
I found an answer that works in my case. Add the code below to the datasource code
using System.Transactions;
namespace LightSwitchApplication
{
public partial class <ChangeThisToYourClassName>
{
private TransactionScope tx;
partial void SaveChanges_Executed()
{
tx.Complete();
}
partial void SaveChanges_Executing()
{
tx = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions {
IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
});
}
}
}
I can confirm that the hotfix works. I got lightswitch working with MySQL using mysql connector.net version 6.4.4. However, when you make your connection and choose your database you'll get this error: "The provider did not return a ProviderManifestToken string."
To fix that, click on the Advanced tab on the connection properties window. Scroll down to the security section and choose true for Persist Security Info.
This allows the entity framework to query the tables.
I created a test app with this and published to my computer and I can also do full crud operations!
Hooray.
P.S. The hotfix for the nested transactions is here: http://archive.msdn.microsoft.com/KB2534087

How to log SQL queries to a log file with CakePHP

I have a CakePHP 1.2 application that makes a number of AJAX calls using the AjaxHelper object. The AjaxHelper makes a call to a controller function which then returns some data back to the page.
I would like to log the SQL queries that are executed by the AJAX controller functions. Normally, I would just turn the debug level to 2 in config/core.php, however, this breaks my AJAX functionality because it causes the output SQL queries to be appended to the output that is returned to the client side.
To get around this issue, I would like to be able to log any SQL queries performed to a log file. Any suggestions?
I found a nice way of adding this logging functionality at this link:
http://cakephp.1045679.n5.nabble.com/Log-SQL-queries-td1281970.html
Basically, in your cake/libs/model/datasources/dbo/ directory, you can make a subclass of the dbo that you're using. For example, if you're using the dbo_mysql.php database driver, then you can make a new class file called dbo_mysql_with_log.php. The file would contain some code along the lines of the following:
App::import('Core', array('Model', 'datasource', 'dbosource', 'dbomysql'));
class DboMysqlWithLog extends DboMysql {
function _execute($sql) {
$this->log($sql);
return parent::_execute($sql);
}
}
In a nutshell, this class modifies (i.e. overrides) the _execute function of the superclass to log the SQL query before doing whatever logic it normally does.
You can modify your app/config/database.php configuration file to use the new driver that you just created.
This is a fantastic way to debug things like this, https://github.com/cakephp/debug_kit