Thursday, June 28, 2007

Top 5 best MySql practices

My opinion on MySql best practices, the new new 'chain letter' started by Ronald Bradford. As always, this is a developers point of view.

0. Make a database design. Databases generated automatically might work very well in development, but when you have large data volumes and lots of concurrent users they do not.

1. Be consistent in your choice of datatypes. I prefer to use just a subset in a system. Try to stick with SMALLINT UNSIGNED or INTEGER UNSIGNED for keys. Always use the same datatype for the same term in all tables, no joins with datatype conversion! Do not store numbers as CHAR/VARCHAR fields.

2. Make sure there are indexes supporting all searches that are part of routine system usage. If you have tables that are very small it might be better not to index them, but this should be an active decision.

3. Verify your database design with real volumes and tests covering the planned usage. A modern computer can quickly scan (without indexes) more data than you will enter by hand, so you will probably need a dump from a production system or generated data.

4.Use SQL_MODE ANSI and TRADITIONAL for new systems. For old ones, you might have to allow a less strict mode.

5. Choose your storage engine with care. Use InnoDB (and keep an eye on Falcon!!) if you need transactions, but even if you do, MYISAM migh be a good choice for some tables.

Wednesday, June 27, 2007

MySql performance in a .NET environment

The last two weeks I have been working on a .NET application using MySQL (3.21) for data storage. The application is basically a stand-alone PC application where MySql is used to store a lot of data from test equipment.

This is a bit different from what I spend most of my time on. No web site with lost of concurrent session, but instead a lot of installations of the software on local PC's. The also means we can not tune parameters on a live system, we have to set them before delivering to customers. Basically this is the main problem, since we don't know how the system will be run.

Well, if the scenario is different, the most important action was the same. Changing the field order in one of the indexes to match the queries better was our number one action, and the impact was larger than all other actions together. If your indexes are not righ, you should fix it before anything else.

An upgrade to MySql 5.41 and .net connector 5.0.7 was another obviuos task. I am a bit surprised that it was so easy. The only real problem we had was with merge tables. The initially did not work, but after we made a ALTER TABLE on all underlying tables even the merge tables were OK.

Performance improvement after upgrading was not large, but when we switched shared memory on, there was a noticeable performance improvement. The application transfers a lot of data between MySql to the applcation, mainly to produce graphs, so this should be important. We also switched both key cache and query cache on, but since we do not know how the application will be used, it is hard to determine the effect of this.

We had some problems with connections not being closed initially. But turning off connection pooling fixed this. Turning it on from the start was simply a reflex of an old web programmer, I'm afraid. Connecion pooling is not relevant in this scenario.

All in all a quite successful project. Performance is OK now, and the bottleneck is not the database, so we will look at some other changes, mainy in the graph package.

Thursday, June 21, 2007

MySql merge table problems

While upgrading fom MySql 3 to Myql 5 our only real problem was with merge tables. We have two in the system, both did not work. Createing the merge table did not give an eror, bt when we tried to select from it, we get the error message 1168:
Unable to open underlying table which is differently defined or of non-MyISAM type or doesn't exist

This kind of error message gives my the creeps. Or?? Why doesn't it say which one of the cases it is? Surely these are three different cases and it should be easy to separate them. Is it difficult to add error messages to MySql? Or a lazy programmer??

OK, we try to look at the table definition i MySql's own tool the Query browser. But if you try to do 'Edit Table' in the Query Browser, you get the following error message:
A MySql eror message was encountered. The eror message is:
Cannot fetch table information
The following error occurred:Unable to open underlying table which is differently
defined or of non-MyISAM type or doesn't exist (1168)
OK, we knew that, but we wanted to take look at the definition to check that it matches the underlying table.

OK time to check for bugs. We finally find one, saying that of our three possible causes, it is actually a fourth: the table does exist, is of MyISAM type, and definitions match. But it is of an old MyISAM version... Fix is to make an ALTER TABLE on all the underlying tables, this will fix the version also, and everything is OK.

For the future I think we will look into other solutions. Merge tables are very restrictive and for our purposes a view with UNON ALL would work just as well, since we already make inserts into the underlying tables and have no updates. A quic test also says that the performance is about the same. Or, possibly, we will wait for MySql 5.1 with partitions.

Tuesday, June 05, 2007

MySQL performance enhancements

I have been working on a new assignment this week, with the goal to improve performance in a .NET application using MySQL (3.21) for data storage. The application handles a lot of data in what is basically a single user system.

The main rason for the performance problems was heavy searches where indexes did not match. Simply switching the order of columns in the composite key fixed most of it.

In the old version they copied data to a temporary table, to solve the slow query problem. Once we had the indexes fixed, we could drop this solution and use the ase table in all cases. This also speeded it up a lot.

The change to MySQL 5.0 made a few other changes possible
- switch to shared memory for communication between database and application
- buffering of indexes
- query caching
which all ment further improved performance

All in all quite successful so far. Performance is OK now, and the bottleneck is not the database, so we will look at some other changes.

It has been great fun, .Net is a new environment for me, but it was quite easy to get into it.

Wednesday, May 30, 2007

More gadgeteering....

I am a great music fan, and from time to time can't stop myself from singing a song or two, mostly rock classics. Although I know a lot of lyrics, often I can't recall them all.

Now they are all out there on the net, but sometimes difficult to find. So I made a small Google custom search engine, and a gadget to go with it, like this:


Surprisingly what you can do with so little, the power of the web is amazing!

Wednesday, May 16, 2007

Pricerunner Google Gadget

Made another Google gadget the other day, this time doing a search in Pricerunner, to compare prices and products. I believe Pricerunner is a very good service, and widely used in Sweden.

The gadget looks like this:


Today it supports Pricerunner in the UK, Germany, Sweden and Denmark. Hopefully I will be able to add US and France soon.

You could also try it here.

Add Pricerunner to your Google homepage.

Thursday, May 10, 2007

Turning the result around

In many cases you don't want your the result from your SQL statement in just a plain listing, but organized in columns, or whith data grouped on status, period or whatever. This can often be accomplished with a combination of the IF function and SUM or another group function.

For example get your sales per customer grouped by period:
SELECT customer_no AS CUSTNO, cust_name AS CUSTNAME,
sum(if(period = '200701',amount,0) as Jan_Amount,
sum(if(period = '200702',amount,0) as Jan_Amount
FROM otd.salestrans_hist s
WHERE period IN ('200701','200702')
GROUP BY customer_no, cust_name

Or number of open and closed records in each class:
SELECT class, sum(if(status='Open',1,0)) as open,
sum(if(status='Closed',1,0)) as closed
FROM table_name
GROUP BY class

In the examples I have used the MySQL IF function. You could also use CASE, which is SQL standard.

Wednesday, April 25, 2007

Indexing, indexing and indexing....

Saw this table definition in a system I was working on:

CREATE TABLE session_role (
Session_sessionId bigint(20) NOT NULL,
activeRoles_roleId varchar(255) NOT NULL,
PRIMARY KEY(Session_sessionId,activeRoles_roleId),
UNIQUE KEY activeAccounts_actorId (activeRoles_roleId),
KEY `FK38CC06CCF5B03D50` (Session_sessionId),
KEY `FK38CC06CC4085AE4` (activeRoles_roleId),
CONSTRAINT `FK38CC06CC4085AE4` FOREIGN KEY (activeRoles_roleId)
REFERENCES role(roleId),
CONSTRAINT `FK38CC06CCF5B03D50` FOREIGN KEY (Session_sessionId)
REFERENCES session (sessionId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This is four indexes for a two-column table! Of course nobody has actually written this, this is generated by JBoss/Hibernate, with a MySQL database used for storing data. Be very careful with code generators....

Wednesday, April 11, 2007

Google gadget

I have spent some time on a Google gadget, Shopping List, and now it is released.


Helps you remeber what to buy. It can also be printed and sent via mail, Gmail or other.


Click the link below to add to your Google homepage.

It is amazing what you can do with a little javascript and html. The small format also makes it necessary to think about your design.

Add "Shopping List" to your Google homepage

Thursday, March 22, 2007

More EJB questions

Our EJB project is moving forward.. My sceptisism is growing... Some questionable points:

Session beans is where most, if not all our business logic goes. But session beans are nut pure java classes. They are based on some arcitectural ideas, which are not obviuosly good:

  1. Communication with RMI and serialized java objects. This is probably a bad idea in most cases, a solution that is not only java specific but also has problems with different java versions. Basically it is based on that both sides have the same java classes. And then there is
  2. Putting your logic in separate threads. A good idea if your session beans work with a large number of java clients, but probably a bad idea if your clients are servlets or message driven beans. In that case it will give you more thread handling overhead and little gain.

Entity beans have disappeared, instead we have got the new EntityManager. This of course means much faster development, but what is the cost? In my opinion the Data Access Object pattern is a good one, since it means that you have all your database access for one object in one place. With the EnityManager you can easily end up with SQL statements scattered all over your application. Where did the object orientation go?

Another point is constructions like this:

customer.getOrders().add(new Order(.....))

this would mean that to add a new order, you first fetch all existing orders from a customer before adding a new one. A framework that encourages this kind of solutions is not a good one.

Thursday, March 08, 2007

Started with EJB3

I have just started on a new project, where we will use EJB 3.0. I am very sceptical to the EJB concept, because some of the worst systems I have seen use EJB. Complicated to write, very hard to maintain and with very bad performance, mostly because they generate a lot of database traffic.

Version 3.0 is a big improvement, that's for sure. But is it better than the old POJO way, with Database Access Objects and SQL/JDBC? That remains to see. Development is so far fast, but will performance be OK? If everything goes OK, we will roll out the system in thousands of installations. We can not make performance tuning when the systems are up and running, which according to my experience is necessary on EJB systems. The performance has to be ok from day one.

Tuesday, December 12, 2006

LOAD XML submitted

I have been working on an addition to MySQL the latest month's or so, adding XML import to MySQL. This weekend I decided that the version was good enough to submit to MySQL. You can find it at http://lists.mysql.com/internals/34169. Good enough to submit yes, probably not good enough for production, but feedback would be good.

But all in all I am quite satisfied with it.
- focus is on easy-of-use, with automatic matching of tags and attributes to field names
- support for three different xml formats: using tags for field values, using attributes or the format used by oth MySQL tools (not a good format, but anyway..)
- works very much like th CSV file load that has been a feature of MySQL for very long

I can think of some additions, like support for binary fields (probably does not work today), better handling of character encoding etc, improved handling of the SET clause etc. But then, there are always improvements that could be made, and probably there are others that I have not thought of that are more important.

Monday, November 06, 2006

Tsql2mysql update

Released a new version of the procedure converter from SQL Server to MySQL. The changes are driven by user requests.

I have added support for temporary table creation: in SQL server you create a temporary table by adding INTO #temptable to your select. This is converted to MySQL CREATE TEMPORARY TABLE and the # is dropped.

Also some minor changes, like support for very large SQL statements, better pretty-printing and improved support for CASE statements.

Friday, October 06, 2006

MySQL Developer Certification

Received the final papers about my MySQL 5.0 Developers certification. Seems we are only two certified in Sweden so far, feels strange to be one of the few. But probably most people working with MySQL don't bother about certifying.

Supporting the procedure converter

Had a support question on the T-SQL to MySQL procedure converter. Seems like the first (current) version crashes when SQL statements are very long. Made a fix, and also improved the printing of long lines. Don't know if I am going to release it as is, or add more pretty-rpinting perheps. Also noticed that my support case uses + for string concatenation, which is not converted by the current version.

Thursday, September 21, 2006

Some comments on the procedure converter

The T-SQL to MySQL procedure converter is of course developed based on what I needed when I made it. I have made it as a window's executable because we run the system on windows (guess that is common with SQL Server installations...). There is no fancy user interface (in fact no user interface at all) because I didn't need it etc.

T-SQL constructs not handled:
  • String concatenation: since + is used in T-SQL both for concatenation strings and for addition you need to know the datatype of the arguments to know if it should be converted. The tool does no attempt to do this, even if some cases (text constants, declared variables or parameters) would be quite easy.
  • GOTO's and labels: The code I converted contains a lot of GOTO's. A very common construction is:
    SELECT /UPDATE/DELETE/INSERT
    ....
    SELECT @p_err_num = @@ERROR
    IF (@p_err_num <> 0) GOTO OnError
    COMMIT TRANSACTION
    GOTO Done
    OnError:
    ROLLBACK TRANSACTION
    Done:
    RETURN( @p_err_num )

    I don't want to convert this! The MySQL/ANSI error handler is so much better, and there is no GOTO. So, the goto's and lables will be commented out and you will have to convert it by hand.
  • Dateadd: MySql has the same functionality in the date_add function, but parameter order is different. Since function calls can be nested, the tool would need to parse the code more than it does to be able to fix this. This is on my list, but not yet implemented.
  • Select TOP: This corresponds to the MySQL LIMIT clause. But since T-SQL allows parameters perhaps using the SET SQL_SELECT_LIMIT would be better. On the other hand this would be complicated in cursors.. Since we have only very few procedures where this is used, we do it by hand so far. Perhaps in a coming release...
  • Dynamic SQL: T-SQL execute could be replaced by MySQL PREPARE/ EXCUTE/ DROP PREPARE but the command would be a text string, and the tool does not, and should not, convert text strings. Probably you should check why you are using dynamic SQL in your code, and consider using another approach, or convert the text strings to MySQL by hand. Dynamic SQL is advanced and should only be used if you really need it.


Erik

Monday, September 18, 2006

T-SQL to MySQL procedure converter released

Yesterday evening I finally released the procedure converter at Sourceforge.net. I am quite satisfied with the result, it covers quite a lot. But the user interface is virtuallt non-existant, and the parsing needs some improvement. The problem is that for more complex conversion tasks (like shifting order for function parameters) I would need better parsing of the source code.

Features:
  1. converts CREATE PROCEDURE/FUNCTION syntax
  2. adds semi-colon at the end of statements
  3. converts IF and WHILE statements to MySQL syntax
  4. sorts the code in the correct order, with declarations at the top and instructions
  5. after that
  6. removes @, [ and ] from identifiers
  7. converts comments to MySQL syntax (a space in the 3rd position for -- comments)
  8. adds a CONTINUE HANDLER FOR NOT FOUND if the procedure contains cursors
  9. comments out GOTO and labels (you will have to restructure this yourself, since there is no GOTO in MySQL stored procedures)
  10. converts some data types (nvarchar, identity, smalldatetime, money, smallmoney)
  11. Converts function with a direct MySQL correspondence (getdate, getutcdate, len, replicate)
Limitations
  1. No conversion of GOTO:s and labels
  2. no MySQL error handling added

Wednesday, September 06, 2006

More Conversion tool problems

My conversion tool is getting better, soon time to release.

What makes it possible is really that T-SQL is such a poor language, not much to take care of. But that is also the problem, since som features are far from perfect, T-SQL code contains a lot of complicated constructs, like error handling with goto's, and checking @@error efter every SQL statement. Converting that to MySQL would make horrible code, in a system where much better error handling is available. But there is currently no GOTO in MySQL...

So that will be unsolved, GOTO's and labels etc. Also references to SQL Server specific system tables, views, procedures and varibles will be largely unconverted.

Monday, September 04, 2006

Conversion of Microsoft T-SQL to MySQL

Spent some time on a tool for converting T-SQL stored procedures to MySQL during the weekend. It is looking quite good, but new problems keep popping up all the time. Like the differences in WHILE statement syntax, different naming of database objects etc.

Guess at some time I will have to be satisfied with a tool that leaves som problems unsolved, but not quite yet... I'll spend some more time on it before I release it.

Tuesday, August 29, 2006

Should databases always be normalized?

I posted a comment on this subject today. My point is not that normalization is not good as a rule, but rather that there are times that you could optimized your design by deviating from the model.

The example seems to be such a case, where you avoid having a table with very many records by storing the data in a list (violates first normal form). More about this later...

You could also take a look at Denormalization.