Showing posts with label MySQL. Show all posts

Sunday, October 11, 2026

MySQL Community Engagement Starts at the Bug Tracker


Earlier this year, Oracle outlined a welcome series of community initiatives—introducing new developer forums, active Slack channels, and expanded collaboration frameworks. For those of us who care deeply about the MySQL ecosystem, seeing renewed attention on community participation is genuinely encouraging. At the same time, for operators and DBAs managing production fleets, enthusiasm is tempered by a practical question: how do these initiatives translate to the place where production issues are solved daily—the bug tracker?

Having spent 15 years in MySQL Support triaging and verifying bugs, my foremost thought is one of gratitude and respect for Oracle’s server engineers, architects, and leads. Delivering milestones like MySQL 8.4 LTS and the 9.x innovation track while maintaining stability across InnoDB, the optimizer, and replication is demanding work. Absorbing community bug verification on top of active sprint deliverables and CVE patches is an immense responsibility, and their commitment to engine stability deserves sincere recognition.

At the same time, the scale of the challenge is visible on the tracker itself. A quick search on bugs.mysql.com today shows over 400 reports sitting in "Open" status—meaning they have yet to receive initial verification or triage. Behind each of those 400+ tickets is significant unbilled labor from community DBAs and engineers isolating edge cases, scrubbing proprietary schemas, and scripting deterministic MTR (MySQL Test Run) reproductions. When comprehensive submissions wait in an unacknowledged queue, reporters understandably wonder whether their contribution registered.

If this new chapter of community engagement is to flourish, the bug tracker is the ideal place to anchor it. The community does not expect immediate patches—even a brief note from an engineer confirming an issue has been reviewed or queued for verification validates that effort and keeps goodwill strong.

To my fellow DBAs and developers: please keep filing. Clean, reproducible test cases and real-world telemetry have been the foundation of MySQL's reliability for two decades. Let us continue sharing clean MTR scripts, reporting rigorously, and supporting the engineering teams maintaining the engine we all rely on.

---

P.S. For anyone looking at the archive dates: yes, this is my first post here since 2011. It took an important moment in the MySQL community to bring me out of blogging retirement, but it feels good to be writing again. More field notes, triage scripts, and internals deep dives to follow.


(Disclaimer: These thoughts represent solely my personal reflections as a long-time MySQL practitioner and community member, not those of my current or former employers. If I am misinformed or not fully up to date on recent internal triage workflows, please feel free to correct me in the comments or on LinkedIn.)

Monday, February 21, 2011

MySQL: Bulk import and logging the warnings to a file

Platform: Any UNIX*

If you are working on a small set of data or with fewer tables and if you notice that the DML statements such as INSERT, UPDATE, and LOAD DATA INFILE as well as DDL statements such as CREATE TABLE and ALTER TABLE operation has generated few warnings then you can just execute the “SHOW WARNINGS” SQL command to display the exact warning messages generated during the last DML operation.
But “SHOW WARINGS” shows nothing if the last statement used a table and generated no messages.
SHOW WARNINGS shows the error, warning, and note messages that resulted from the last statement that generated messages in the current session.
“SHOW WARINGS” can certainly help you in grabbing the warnings but what if you are loading a huge dump file or performing a batch operation and at the middle of load operation MySQL reports that the last DML completed with 500000 warnings? Certainly not sounds good if you are serious about your data.

Query OK, 3000000000 rows affected, 500000 warnings (xxxxx.xxx xxxx)
Records: 3000000000 Duplicates: 0 Warnings: 500000


So how do you grab those warnings?
You can use the --show-warnings parameter with the “mysql” command line utility which causes warnings to be shown after each statement if there are any. This option applies to interactive and batch mode.

/path/to/mysql --show-warnings –uUserName –pPassword DBNAME < /path/to/dump_file.sql >> /path/to/load_warnings.log 2>&1
The 2>&1 will write standard output and standard errors to a file (/path/to/load_warnings.log)

You may not see warnings
(i) If max_error_count is set to 0. In this case, warning_count still indicates how many warnings have occurred, but none of the messages are stored.
(ii) if sql_notes session variable is set to 0 to cause Note-level warnings not to be recorded.


##On EE
ttp://www.experts-exchange.com/Database/MySQL/Q_26835461.html


Friday, January 22, 2010

Cannot create Windows service for MySQL.Error:0

Platform: Windows


People often checks MySQL's download section and when they notice that there is new version of MySQL released they just can't wait for a second & starts downloading it so that they can install it on their windows box for testing purpose. Ok fine, download is completed its time to install it. Couple of successful "NEXT" and In the last step they
encounter a error message such as
"Cannot create Windows service for MySQL.Error:0"

We are so intelligent ppl that we don't want to take any help from our colleague..
And what we do is we just delete the directory in which new installation has been done & starts the installation
wizard one-more time in the hope that this time we gonna install it.

Again the result is same "Cannot create Windows service for MySQL.Error:0"

So why are we getting error that too at the last step? one common thought is "there must be something wrong
or some sort of bug in the new release"

How to resolve this error?
The primary reason for this error is that you haven't properly uninstalled the 
previously installed MySQL server & in the installation wizard  last step was
 to create  the service with the name "MySQL" and which has the same name as that 
 of the existing service (default is "MySQL").

Solution for this error is to first stop the service if it is running and then remove 
the service.

C:\>NET STOP MYSQL
The MySQL
service is stopping.
The MySQL service was stopped successfully.

Once the service is stopped, it can be removed with the SC utility:
C:\>SC DELETE MYSQL

[SC]
DeleteService SUCCESS

With the previous service stopped and removed, you can now run the MySQL Configuration Wizard again to configure and start the new MySQL service.




Thursday, January 14, 2010

MySQL: Copy tables (Only structure and NO DATA) using stored procedure

Last week some one asked how to Copy the tables (Only structure and NO DATA..also no other DB objects) from one schema to another on EE. This can be easily done from command line but user wanted to do this thru stored procedure.
http://www.experts-exchange.com/Database/MySQL/Q_25024073.html
So I came with a very small MySQL procedure which was doing as needed by the user. I'm not sure whether this is the best way to do this but "There is always room for improvement."
 
DELIMITER $$

DROP PROCEDURE IF EXISTS `CopySchema`$$
CREATE PROCEDURE `CopySchema`(sourceSchema VARCHAR(64),targetSchema VARCHAR(64))


BEGIN

DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;
DECLARE my_table VARCHAR(64);

DECLARE my_cur CURSOR FOR
SELECT TABLE_NAME AS myTable
 FROM information_schema.TABLES
WHERE information_schema.TABLES.TABLE_SCHEMA=sourceSchema AND TABLE_TYPE = 'BASE TABLE';


DECLARE CONTINUE HANDLER FOR NOT FOUND


SET no_more_rows = TRUE;
SET @tmp_sql= CONCAT("CREATE DATABASE IF NOT EXISTS ",targetSchema);
PREPARE s1 FROM @tmp_sql;
EXECUTE s1;
DEALLOCATE PREPARE s1;


OPEN my_cur;
select FOUND_ROWS() into num_rows;

the_loop: LOOP
    FETCH my_cur
      INTO my_table;

     IF no_more_rows THEN
         CLOSE my_cur;
         LEAVE the_loop;
     END IF;


     SET @tmp_sql= CONCAT("CREATE TABLE IF NOT EXISTS ",targetSchema,'.',my_table,' LIKE ',sourceSchema,'.',my_table);
      PREPARE s1 FROM @tmp_sql;
      EXECUTE s1;
     DEALLOCATE PREPARE s1;

     SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;

SELECT CONCAT('Summary: ', loop_cntr, ' tables copied from schema "',sourceSchema,'" to "',targetSchema,'"') AS "Schema copying";


END$$
DELIMITER ;

Usage:

call CopySchema('dba','dba_dummy');


Friday, October 30, 2009

MySQL - Extract numbers out of a string

I recently came across a fascinating request on Experts Exchange where a user needed to extract numbers from a text string. While this is a simple one-liner in many programming languages, solving it directly inside a SQL SELECT query can be a bit tricky.
To help them out, I built a lightweight, custom MySQL function that gets the job done perfectly. While it works great, there is always room for improvement—so I'd love to hear how you would optimize it!


 
[code]  
DELIMITER $$

DROP FUNCTION IF EXISTS `uExtractNumberFromString`$$ 
CREATE FUNCTION `uExtractNumberFromString`(in_string varchar(50)) RETURNS INT NO SQL
BEGIN

DECLARE ctrNumber varchar(50);
DECLARE finNumber varchar(50) default ' ';
DECLARE sChar varchar(2);
DECLARE inti INTEGER default 1;

IF length(in_string) > 0 THEN
WHILE(inti <= length(in_string)) DO
    SET sChar= SUBSTRING(in_string,inti,1);
    SET ctrNumber= FIND_IN_SET(sChar,'0,1,2,3,4,5,6,7,8,9');

    IF ctrNumber > 0 THEN
       SET finNumber=CONCAT(finNumber,sChar);
    ELSE
       SET finNumber=CONCAT(finNumber,'');
    END IF;
    SET inti=inti+1;
END WHILE;
RETURN CAST(finNumber AS SIGNED INTEGER) ;
ELSE
  RETURN 0;
END IF;

END$$

[/code]

select uExtractNumberFromString('12;e1hhsak123s12');
12112312

Tuesday, October 06, 2009

Client does not support authentication protocol requested by server; consider upgrading MySQL client


Reference: MySQL Manual

If you are trying to evaluate some free open source application available on various websites(which are especially developed using PHP) and when the application try to access newer version of MySQL server you may end up seeing a error message like below


Client does not support authentication protocol requested by server; consider upgrading MySQL client


 Reason for this unwanted welcome message is that In older versions of PHP, the mysql extension does not support the authentication protocol used in MySQL 4.1.1 and higher. This is true regardless of the PHP version being used. If you wish to use the mysql extension with MySQL 4.1 or newer, you may need to follow one of the options discussed above for configuring MySQL to work with old clients. The mysqli extension (stands for "MySQL, Improved"; added in PHP 5) is compatible with the improved password hashing employed in MySQL 4.1 and higher, and no special configuration of MySQL need be done to use this MySQL client library.
 MySQL >=4.1 uses an authentication protocol based on a password hashing algorithm that is not compatible with that used by older (< 4.1) clients.


There are several ways through which you can resolve this type of issues


- Tell the server to use the older password hashing algorithm
   (i) Start mysqld with the --old-passwords option(also, you can place old-passwords in my.cnf/my.ini under mysqld group).
   (ii) Assign an old-format password to each account that has had its password updated to the longer 4.1 format. You can identify these accounts with the following query: 
 mysql> SELECT Host, User, Password FROM mysql.user
                            -> WHERE LENGTH(Password) > 16;
For each account record displayed by the query, use the Host and User values and assign a password using the OLD_PASSWORD() function and either SET PASSWORD or UPDATE



For further options please take a look at the manual page
http://dev.mysql.com/doc/refman/5.1/en/old-client.html

Friday, August 07, 2009

MySQL - Restoring a single table from nightly backup (mysqldump generated file)

Very often we get the requests from customer to restore a "tiny" table from the nightly backup into the development/staging environment. This request need to be done on urgent basis as its just a matter of a one table and customer don't want to restore entire database of 10GB so the restoration might take less than 5 min - this is how most of the customer/managers thinks and they are abs right as why should it take more time for a single table?. This can be addressed by playing with the privileges and with the help of parameters available to 'mysql' command line utility

Steps to restore single table from dump file

# Create a user & GRANT him all rights on the table which need to be restored
# Start importing as show below

mysql -uRestUser -pSecret --force --one-database DB_NAME < /path/to/dumpfile.sql

ResetUser - "user" created for restoring single table

--one-database - Ignore statements except those for the default database named on the command line

--force - Parameter would force the import to continue even if an SQL error occurs( mainly due to the privileges as the new user don't have the privilege on other tables)





Thursday, July 30, 2009

Step-by-Step guide for Installing MySQL on RHEL5

Installation of MySQL Server on Linux (RedHat Enterprise Linux 5)

The recommended way to install MySQL on RPM-based Linux distributions is by using the RPM packages. The RPMs that MySQL/Sun provide to the community should work on all versions of Linux that support RPM packages and use glibc 2.3. You can download it from http://mirrors.sunsite.dk/mysql/downloads/mysql/5.1.html

Checking if MySQL is already installed & would be uninstalling it to install latest MySQL version

[root@localhost mysql]# rpm -qa | grep -i '^mysql-'
MySQL-python-1.2.1-1
mysql-5.0.22-2.1.0.1
mysql-server-5.0.22-2.1.0.1
mysql-connector-odbc-3.51.12-2.2

Un-installing older version of MySQL

[root@localhost mysql]# rpm --nodeps -ev MySQL-python-1.2.1-1
[root@localhost mysql]# rpm --nodeps -ev mysql-5.0.22-2.1.0.1
[root@localhost mysql]# rpm --nodeps -ev mysql-server-5.0.22-2.1.0.1
warning: /var/log/mysqld.log saved as /var/log/mysqld.log.rpmsave
[root@localhost mysql]# rpm --nodeps -ev mysql-connector-odbc-3.51.12-2.2
[root@localhost mysql]#


First, using a web browser or wget utility, you should download the server RPM from the location: http://www.mysql.com/Downloads/MySQL-*.rpm
Once you download the packages, install it as shown below.


[root@localhost mysql]# ls -la
total 39572
drwxr-xr-x 2 root root 4096 Jul 26 17:26 .
drwxr-xr-x 3 root root 4096 Jul 26 16:40 ..
-rw-r--r-- 1 root root 6664128 Jun 11 14:07 MySQL-client-community-5.0.83-0.rhel5.i386.rpm
-rw-r--r-- 1 root root 10616677 Jun 11 14:17 MySQL-devel-community-5.0.83-0.rhel5.i386.rpm
-rw-r--r-- 1 root root 19613508 Jun 11 14:26 MySQL-server-community-5.0.83-0.rhel5.i386.rpm
-rw-r--r-- 1 root root 3532055 Jun 11 14:31 MySQL-shared-compat-5.0.83-0.rhel5.i386.rpm

Here is brief details of packages that we are going to install

MySQL-server-community-5.0.83-0.rhel5.i386.rpm: The MySQL server. You need this unless you only want to connect to a MySQL server running on another machine.
MySQL-client-community-5.0.83-0.rhel5.i386.rpm: The standard MySQL client programs. You probably always want to install this package.
MySQL-devel-community-5.0.83-0.rhel5.i386.rpm: The libraries and include files that are needed if you want to compile other MySQL clients, such as the Perl modules.
MySQL-shared-compat-5.0.83-0.rhel5.i386.rpm: This package includes the shared libraries for MySQL 3.23, 4.0, and so on, up to the current release. It contains single-threaded and thread-safe libraries. Install this package instead of
MySQL-shared if you have applications installed that are dynamically linked against older versions of MySQL but you want to upgrade to the current version without breaking the library dependencies.


To perform a standard minimal installation, you can only install the server and client RPMs and for complete installation you have to install all the packages.



[root@localhost mysql]# rpm -ivh MySQL-*.rpm
Preparing... ########################################### [100%]
1:MySQL-shared-compat ########################################### [ 25%]
2:MySQL-client-community ########################################### [ 50%]
3:MySQL-devel-community ########################################### [ 75%]
4:MySQL-server-community ########################################### [100%]
PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:
/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h localhost.localdomain password 'new-password'

Alternatively you can run:
/usr/bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default. This is
strongly recommended for production servers.

See the manual for more instructions.

Please report any problems with the /usr/bin/mysqlbug script!

The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licenses at http://shop.mysql.com
Starting MySQL..[ OK ]
Giving mysqld 2 seconds to start
[root@localhost mysql]#


The server RPM places data under the /var/lib/mysql directory. The RPM also creates a login account for a user named mysql (if one does not exist) to use for running the MySQL server, and creates the appropriate entries in /etc/init.d/ to start the server automatically at boot time.


If you want to install the MySQL RPM on older Linux distributions that do not support initialization scripts in /etc/init.d (directly or via a symlink), you should create a symbolic link that points to the location where your initialization scripts actually are installed. For example, if that location is /etc/rc.d/init.d, use these commands before installing the RPM to create /etc/init.d as a symbolic link that points there:
shell> cd /etc
shell> ln -s rc.d/init.d .

However, all current major Linux distributions should support the new directory layout that uses /etc/init.d, because it is required for LSB (Linux Standard Base) compliance.
If the RPM files that you install include MySQL-server, the mysqld server should be up and running after installation. You should be able to start using MySQL.



Securing the Server


[root@localhost mysql]# /usr/bin/mysql_secure_installation




NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!


In order to log into MySQL to secure it, we'll need the current
password for the root user. If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!


By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
... Success!

Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
... Success!

Cleaning up...



All done! If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!


[root@localhost mysql]#




Test mysql connectivity

Type the following command to connect to MySQL server:


[root@localhost mysql]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 5.0.83-community MySQL Community Edition (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Tuesday, July 28, 2009

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Platform: Linux/Unix

If you come across below errors when trying to connect MySQL then there might be couple of reasons behind it.




-bash-3.2$ mysql --user=root --password
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

One of the reason could be that MySQL server isn't running. So how do you check whether or not MySQL is running? try running below shell command and see what it reports


-bash-3.2$ ps -e|grep mysqld
30878 ? 00:00:00 mysqld_safe
30939 ? 00:58:06 mysqld
-bash-3.2$



If you see at least 2 process are running/listed from the above command then it is confirmed that MySQL is running.

What if you don't see any process(as shown below)? then the MySQL services is not at all running then try to start it and watch for errors(you can check error log for same) and resolve them before making an attempt to start.
-bash-3.2$ ps -e|grep mysqld
-bash-3.2$

Starting MySQL(easiest way :-))

/etc/init.d/mysql start
If there are no errors, re-enter the process status(ps) command once again & if the service is now running, then try connecting to MySQL and If still you are receiving the error then another reason(wasn't first one) could be if the location of the Unix socket has been changed or is different from the default location.

It might be that the location of the socket file has been changed so first one has to check the MyQL config file (/etc/my.cnf) and locate the the value for the socket parameter(you may see two socket details - for client and mysqld groups).
-bash-3.2$ more /etc/my.cnf |grep socket
socket=/var/lib/mysql/mysql.sock
-bash-3.2$

It could be that the value for the --socket option is set at the command-line when MySQL is started is different than what the client mysql is expecting in that case you have to either change the socket file path in the config file or you will have to supply the socket parameter with its path for the the client
-bash-3.2$ mysql --user=root --password --socket=/var/lib/mysql/mysql.sock
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 421830
Server version: 5.0.45 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Wednesday, June 24, 2009

Step-by-Step guide for Installing MySQL on Windows

You can download the MySQL database from the MySQL website http://www.mysql.com by clicking on the downloads tab. Scroll down to the MySQL database server & standard clients section and select the latest production release of MySQL, 5.1.35 at the time of writing.

Installation of MySQL Server


Unzip the setup file and execute the downloaded MSI file. Follow the instructions below exactly when installing MySQL Server:



Click on the "setup"




Perform a typical installation








<!--[if !vml]--><!--[endif]-->


Check box to configure MySQL Server

If you checked the Configure the MySQL Server now check box on the final dialog of the MySQL
Server installation, then the MySQL Server Instance Configuration Wizard will automatically start.
Follow the instructions below carefully to configure your MySQL Server to run correctly with
EventSentry.




Select Detailed Configuration



I was installing it on my local machine where other applications & tools are running I decided to opt "developer machine" but it is recommended that you use a Dedicated MySQL Server Machine for your MySQL database, if this is not an option then select "Server Machine".

If you selected Dedicated MySQL Server Machine and your MySQL service does not start after the wizard completes, then try to re-run the wizard (or re-install) MySQL, but this time select the Server Machine option.



I have checked "Multifunctional databases" as I wanted MyISAM as default storage engine but if you want you can select "Transactional Database Only", this will make sure that InnoDB is the main storage engine. If you have checked 3rd option then only myISAM engine would be available



Select the drive where the database files will be stored.
Select the drive on the fastest drive(s) on your server








It is recommended that you leave the default port 3306 in place, however
EventSentry will also work with non-standard ports if necessary.








It is highly recommended that you run the MySQL Server as a Windows
service(you can disable this if you want to start it manually whenever required) and include the binary directory in the search path.



Specify a secure root password, you may want to check the box Enable root access
from remote machines if you plan on administering your MySQL server
from your workstation or other servers.


If you are getting an error message after clicking the Next button, then please enable port 3306
in the Windows XP Firewall Settings






Done!!!

But if you are installing MySQL on a Windows XP workstation, or any other computer that has a firewall enabled, and the wizard fails with an error message similar to the one shown below (Can't connect to MySQL server on 'localhost'), then you will have to exclude the MySQL daemon from your firewall configuration



On Windows XP, you can exclude MySQL from the firewall by following the steps below:
1. Navigate to Start -> Settings -> Control Panel -> Windows Firewall




2. In the resulting dialog, enter the information as shown in the screenshot




After clicking OK twice, return to the MySQL error message and select Retry. MySQL should now be able to create the instance correctly.
<!--[if !vml]--><!--[endif]-->

Sunday, June 21, 2009

MySQL - Syncing slave with the master

Manual procedure of syncing slave with he master

Below commands to be run on Slave

1. Check the slave status and Stop the slave its is running


mysql> show slave status\G

mysql> stop slave;

2. Get the dump of master server


shell> time mysqldump --opt -master_server_ip --master-data=1 --triggers --routines --databases DB1 DB2 DB3 DBn | gzip > /path/to/dumpfile.gz


3. Once the above dump is over, you can start importing


shell> time gunzip –c /path/to/dumpfile.gz | mysql





Once the above import is done, start slave on slave server<!--[endif]-->




mysql> show slave status\G

mysql> start slave;


In production environment you can do this kind of sync activity by taking a maitenance window/down time during the dump process(mysqldump command)




Saturday, June 20, 2009

MySQL - Restoring a single database from a backup file contaning multiple databases

Sometime (rather I would say most of the time) you may need to restore a single/specific database from the nightly backup but unfortunately your nightly backup contains all the other databases and restoring all the databases is not the solution as we may end up losing some of the data which might be added to the databases after the nightly backup. Fortunately there is one option "--one-database" available in the 'mysql' command line utility which comes into our rescue.


In order to restore a single database from the nightly backup you can use the --one-database or -o option when restoring
shell>mysql --one-database required_db < /path/to/backup.sql


Friday, June 19, 2009

MySQL - Renaming database

You would hear a big "NO" if you ask some some one about the command to RENAME the DATABASE.

Sometime ago MySQL tried to include the SQL command(This statement was added in MySQL 5.1.7) to rename the database "RENAME {DATABASE | SCHEMA} db_name TO new_db_name;"

but was found to be dangerous and was removed in MySQL 5.1.23. It was intended to enable upgrading pre-5.1 databases to use the encoding implemented in 5.1 for mapping database names to database directory names . However, use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.

Then is there any workaround for this? yes there couple of ways to do this.. below suggestion are given by some of MySQL experts on online forums which I'm including here


A) use mysqldump to dump the database, create the new
database, reload the dump file into the new database, then drop the old
database.  That is, in effect, a database rename, although (I suspect)
it can cause problems if you have foreign key relationships that refer
to the table names in the original database.


B) Another approach is to create the new database, and then, for each
table in the original database, use RENAME TABLE orig_db.t TO new_db.t
to move the table from one database to the other.  Then drop the old
database.

C) Some ppl suggest this way ( NOT A SAFE-WAY though if you have mixed engines)

i) Bring down MySQL if it is running
ii) rename database directory using OS commands
iii) Bring up MySQL

Wednesday, June 17, 2009

MySQL - initcap function

Sometime back I was looking for a built-in initcap/ucfirst function in MySQL but unfortunately couldn't find such string functions so decided to write my own.. thanks to the MySQL community member who corrected the bug in my function & posted it back.


DELIMITER $$

DROP FUNCTION IF EXISTS `test`.`initcap`$$

CREATE FUNCTION `initcap`(x char(30)) RETURNS char(30) CHARSET utf8
BEGIN
SET @str='';
SET @l_str='';
WHILE x REGEXP ' ' DO
SELECT SUBSTRING_INDEX(x, ' ', 1) INTO @l_str;
SELECT SUBSTRING(x, LOCATE(' ', x)+1) INTO x;
SELECT CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(@l_str,1,1)),LOWER(SUBSTRING(@l_str,2)))) INTO @str;
END WHILE;
RETURN LTRIM(CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(x,1,1)),LOWER(SUBSTRING(x,2)))));
END$$

DELIMITER ;



Usage:

select initcap('umesh kumar shastry');

Umesh Kumar Shastry

select initcap('ashutosh s');

Ashutosh S

select initcap('rahul giri');

Rahul Giri

select initcap('alam seraj');

Alam Seraj

select initcap('atul kaushik');

Atul Kaushik


Monday, June 15, 2009

MySQL - Thread stack overrun

Sometime you may come across a situation wherein a stored procedure(in mycase it was uGetBussinessDays which was working perfectly until this morning is now throwing a Thread stack overrun error) when called throws Thread stack overrun error.

Typically the error message would look like:

Error Code : 1436
Thread stack overrun: 6444 bytes used of a 131072 byte stack, and 128000 bytes needed. Use 'mysqld -O thread_stack=#' to specify a bigger stack.


According to the MySQL manual "The default (192KB) is large enough for normal operation. If the thread stack size is too small, it limits the complexity of the SQL statements that the server can handle, the recursion depth of stored procedures, and other memory-consuming actions" .

To resolve this issue you need to increase the default value of parameter thread_stack (128 in my my-small.cnf) to something 258K in your MySQL configuration file
.

MySQL - Get bussiness/Off days

MySQL Version >5.0

Ever wondered how would you get a list of business dates/Off dates from a specific date range in MySQL? here is a simple way to do so...

DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`uGetBussinessDays`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `uGetBussinessDays`(in_sDate DATE, in_eDate DATE)
READS SQL DATA
BEGIN
DECLARE l_sDate DATE;
SET l_sDate = in_sDate;
DROP TABLE IF EXISTS _tblBussinessDays;
DROP TABLE IF EXISTS _tblHolidaysDays;
CREATE TEMPORARY TABLE _tblBussinessDays(BussinessDays date);
CREATE TEMPORARY TABLE _tblHolidaysDays(Offdays date);
IF ( in_sDate > in_eDate ) THEN
SELECT "Invalid dates supplied";
END IF;
WHILE l_sDate <= in_eDate DO IF (DAYNAME(l_sDate) = 'Sunday' ) THEN INSERT INTO _tblHolidaysDays VALUES(l_sDate); ELSEIF ( DAYNAME(l_sDate) = 'Saturday' ) THEN INSERT INTO _tblHolidaysDays VALUES(l_sDate); ELSE INSERT INTO _tblBussinessDays VALUES(l_sDate); END IF; SET l_sDate = DATE_ADD(l_sDate,INTERVAL 1 DAY); END WHILE; SELECT BussinessDays FROM _tblBussinessDays; SELECT Offdays FROM _tblHolidaysDays; END$$ DELIMITER ;



## Now call above procedure to get a list of Bussiness days/Off days

call uGetBussinessDays('2009-06-01','2009-06-11');

BussinessDays
==========
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-08
2009-06-09
2009-06-10
2009-06-11


Offdays
======
2009-06-06
2009-06-07

Thursday, June 11, 2009

Relocating MySQL DATADIR under Unix -

To relocate a database directory under Unix, use the following procedure:

a) Bring down MySQL server if it is running
b) Create the directories that will be new datadir
c) chown the directory to the mysql:mysql user
d) copy the files from the old datadir to the new location. (If you are using InnoDB then make sure that the files named ib_log* etc. are not copied to the newer location).
e) Make sure that the files and directories are owned by mysql user
f) Make changes in the my.cnf to point to the new datadir.
g) Bring up MySQL server You can verify this by creating a new database and verify that the files for this database are getting created in the new datadir

NOTE: The same procedure applies when you are relocating DATADIR under Windows.