Mysql – Create table if not exist each time API called: bad practice

innodbMySQLperformancePHP

I'm writing a simple API in PHP with MySQL as database for a web application. I intend to put CREATE TABLE IF NOT EXIST for all tables in each API call.

I expect that I will have 5-6 tables.

I'm trying to do so for a simple reason: I will not need any extra script to run for initialization of the application – it will do it automatically on the first run.

As a drawback I expect that this can slow down API operation. However I tried to log API calls and it is still 2-3 milliseconds (in my case I did not notice any difference if there is CREATE TABLE or not).

Any thoughts?

Best Answer

So let's think forward a little. The application goes live, the tables are created and everything's lovely. Then, you have a new requirement and the tables must change. How do you code that? There's the CREATEs for environments where the code's never run, plus a bunch of ALTERs for existing environments. Now another requirement comes along. This time you have to migrate data for some reason or other. Now there are the CREATEs (for new environments), the ALTERs (for existing environments) and a whole bunch of DDL and migration logic. But wait - there's more. For really good business reasons you want the column holding the migrated data to have the same name as an existing column. How do you now tell if the database has been migrated or not? No longer do you have a metadata-only lookup. No, now you need a flag or version table to show what DDL has to run at each and every execution.

Yeah! You're a great success. Zillions of people want to use your service. Venture capitalists wheeling barrows of money to your door. Third-party organisations are begging to partner with you. The dev team's doubled (nay, trebled!) in size to handle the business opportunities and customisations. Oops. These all have to be coded in the API start-up code. Each. And. Every. One. You no longer have an API. You have the mother of all migration scripts with a fragment of business code tacked on. :sad-face: