My Blog

contains PHP and other web related content. (Sometimes there are some off topic things - don't freak out!)

Archive for the ‘mysql’ Category

How about profiling your mysql queries… later?

Friday, February 19th, 2010

So the other night I was thinking about using xdebug on my PHP code. I then totally had a brain explosion: I’m always forgetting to profile my MySQL queries. ‘Explain’ is a great command for this. However, as the lazy programmer I am, I don’t know if I’m always going to do this on all of my queries. In an attempt to save myself time, I started brainstorming an idea.

What if I extended my MySQL class to capture unique queries so I could run explain on them later?

You should profile your queries when you write them

Well, you really should. Check out the Explain Mysql Page for more information on how to do this. However, this is not always possible.

  1. You may be using a 3rd party or open source software application. Then, you didn’t write the queries.
  2. You FUBAR’d and forgot to do this – or got lazy – or blamed deadlines for being sloppy.

Either way, you may not have been able to do the optimization ahead of time.

Collect your queries

So the next thought I had was to extend my database classes to capture these queries. My goal is to grab all of the queries that are uniquely ran on my site and profile them.

Depending on the constants used in the query, however, each query may be different so you’ll just be logging all of your queries. Prepared statements may help cut down on this – but you still need to capture some of the input. So, your logging mechanism has now become more complex.

For those non-prepared statements, I think you could use tools like PHP’s Similar Text function to determine if the query is indeed different enough to be logged.

Automate it

The last thought I had is to automate the process. Wait until there is a significant amount of new queries (or queries you’ve marked to be re-analyzed) to be explained. Then, have the process run during the middle of the night. All of the explains are ran on the queries and the complete result is sent to your email address. This way, the next morning, you can have your coffee while optimizing your statements! woo!

Your thoughts

Does something like this already exist? Is this a good way to retroactively deal with the situation? I’m curious what you think.

Exploring MySQL in Eclipse PDT

Monday, February 15th, 2010

As you probably know by now, I’m a huge fan of Eclipse PDT. Well, I wanted to stop using MySQL GUI tools for a bit and explore Eclipse tools.

Get the SQL Explorer Plugin


The first thing to do is to get the Eclipse SQL Explorer plugin. You can get that at the update URL:
http://eclipsesql.sourceforge.net/

Install this software like you normally would. Accept the license and you’re ready to go with the plugin. I would recommend letting Eclipse restart after the installation.

Eclipse Uses JDBC

Eclipse uses JDBC connections to connect to MySQL. You can get this on the MySQL connectors page:
Connector

Simply unzip the connector into your Eclipse program directory and move on.

Open Eclipse

Next, Open eclipse (if its not already open.) First step is to choose the SQL Explorer perspective. This can be done by going to the Window menu, clicking Open Perspective and choosing Other. Then, select the perspective from the list.

Now, create a connection profile. This is done by clicking on the Create New Connection Profile link. From here, name your connection, choose your adapter and fill in the proper credentials. (If you’re not familiar with this style credentials, you can visit this website: http://www.connectionstrings.com

What if I can’t find my Driver in the list?

There is a good chance that the driver may not be in the list by default.
Follow the following steps.

1) On the connection profile screen, click the ‘Add/Edit’ button
2) Select the MysQL driver in the list.
3) Click the Edit button on the right hand side.
4) If you do not see your driver in the list of Java Class Paths, click on the Extra Class Path tab.
5) Browse to find your most recent driver download and select that jar file.
6) Click on the list drivers button. com.mysql.jdbc.Driver should appear in the Driver Class Name box. If not, select it.
7) Click OK and then OK again to return to the connection profile box

Now you should be able to use the MySQL driver from the list.

Browsing the Database

After configuring the connection profile, you should see it in your list of connections. Once you expand it and double click the user, you will be prompted to enter your password (as well as choose some other connection profile options).

From here, you’re good to go! You can browse the databases in the Database Structure tab, you can edit SQL in the SQL Editor tab, etc.

Display unix timestamp in a date format in MySQL

Sunday, August 30th, 2009

Every once in a while, I forget about the built in awesomeness of MySQL. Today, I was looking at a unix timestamp from PHP in one of the fields and was wondering what that date was. Derr, use from_unixtime function!

1
SELECT from_unixtime(dateField) FROM tableName;

Quick Reference: Simple MySQL Performance Monitoring

Tuesday, April 7th, 2009

There are a few quick ways to monitor MySQL performance. This isn’t much of an in-depth reference, just a quick reminder. Lets look:

mysqladmin status

Shows a quick status:

mysqladmin status
Uptime: 102594  Threads: 1  Questions: 39  Slow queries: 0  Opens: 12  Flush tables: 1  Open tables: 0  Queries per second avg: 0.000

mysqladmin processlist

Show the active processes and what they’re doing:

mysqladmin processlist
+----+------+----------------+----+---------+------+-------+------------------+
| Id | User | Host           | db | Command | Time | State | Info             |
+----+------+----------------+----+---------+------+-------+------------------+
| 25 | root | localhost:3185 |    | Query   | 0    |       | show processlist |
+----+------+----------------+----+---------+------+-------+------------------+

mysqladmin extended

This is short for extended-status, which shows you pretty much everything you want to know about the current system.

mysqladmin extended
+-----------------------------------+----------+
| Variable_name                     | Value    |
+-----------------------------------+----------+
| Aborted_clients                   | 0        |
| Aborted_connects                  | 8        |
| Binlog_cache_disk_use             | 0        |
| Binlog_cache_use                  | 0        |

| Threads_connected                 | 1        |
| Threads_created                   | 1        |
| Threads_running                   | 1        |
| Uptime                            | 102658   |
+-----------------------------------+----------+

Add iterations or relative comparisons with ‘-i’ and ‘-r’. For example, the following updates the list every 10 seconds with relative numbers (shows change well).

mysqladmin extended -i10 -r

Other Resources

MySQL.com’s explanation of some performance monitoring options
MyTop – top clone for mysql

PHP Bitwise User Authorization

Tuesday, January 27th, 2009

After looking at the Windows model for controlling file access, I realized I could also do that for user authorization control.

The code is pretty self explanatory, but after, you’ll find a quick rundown.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
$ADMIN = 1;
$SUPERUSER = 2;
$SECTION1LEADER = 4;
$SECTION2LEADER = 8;
 
$myTestUser = $SUPERUSER + $SECTION1LEADER + $SECTION2LEADER;
 
if ($ADMIN & $myTestUser) {
    print 'got into admin<br />';
}
if ($SECTION1LEADER & $myTestUser) {
    print 'section 1<br />';
}
if ($SECTION2LEADER & $myTestUser) {
    print 'section 2<br />';
}
if ($SUPERUSER & $myTestUser) {
    print 'got into superuser<br />';
}
if ($myTestUser) {
    print 'is normal user.<br />';
}

First off, the capital lettered variables are our section permission markers. These need to expand by the power of 2. This way, our bitwise operators work out well.

Next, our test user’s permissions are the summation of all the sections/permissions that they should have access to. Its important to note that $ADMIN might be better labeled as $ADMINSECTION to not give the idea of hierarchy, but just access.

Now, when checking access to the sections, we just use the bitwise and operator. See how we use just one qualifier? This is nicer coding (because of the access additions earlier) than older code ideas:

1
2
3
4
$isADMIN = true;
if ($isADMIN || || $isSuperUser || $section1LeaderAccess) {
    print 'section 1!';
}

The one thing that I had to get over was the notion of a hierarchy in the actual values. Really, the hierarchy is business rule based, so the actual values do not matter. For example, if the $admin variable is less than the $superuser, I would think that it would mean the $admin was above. But technically, in our model, we could develop a $superadmin which could be 128 – without having to re-architect the whole system.

The only thing that keeps tripping me up is how to add a new permission, and then auto apply them to each user with so and so setting. So, for example, every $admin user should also have access to the new $section3leader variable. Is there a better way to code around this than doing an update query like this?

1
update userPermission set permission = permission+128 where permission & 1 > 0

Seems like there would be a better way to do it… any thoughts?

PDO – can you handle identical prepared statements?

Monday, December 1st, 2008

I’ve been wondering if I should be concerned about re-preparing a prepared statement when using PDO. Right now, I use code like this when preparing a statement:

1
2
3
4
5
6
7
8
9
10
	public function prep($statement)
	{
		if ($statement != $this->_lastPrepared) {
			/**
			 * Store our clear text statement, and then our object
			 */
			$this->_lastPrepared = $statement;
			$this->_ps = $this->db->prepare($statement);
		}
	}

I end up storing the last statement and do a quick compare. My concern comes from MySQL’s admission of this:
“If a prepared statement with the given name already exists, it is deallocated implicitly before the new statement is prepared.”

So, not knowing the internal workings of PDO, I wonder how they handle it. Do they…

  • Create each prepared statement with the same name, causing them to be deallocated each time
  • Create each one with a random name, so that there are never any deallocations unless you unset the statement?

Anyone have any insight?

  • twitter loader

Follow me on twitter: @aaronsaray

The views on this website are my own and do not reflect the opinions of my employer or clients.
Creative Commons License Home | Open Source | Book | Music | Art | Bio | Resume | Contact
My Baby