Doctrine Create New Entity From Legacy Database Shell Script

Here is a nice little script I have just written to help me with migration of a legacy application onto a Symfony based architecture, including Doctrine for entities.

In this scenario I have created a new database and am importing tables across from the legacy database as I bring them into the application.

The process is a little tricky and unfortunately I figured it out, then went on holiday and came back having totally forgotten how to do it. So I wrote a nice script to document and automate the process for me.

Here is the script:

#!/usr/bin/env bash
cd $DIR;
set -e
set -u
set -o pipefail
echo "
$(hostname) $0 $@

if (( $# < 1 ))
    echo "


./$0 [tableToCreateEntityFrom] {bundle - defaults to AppBundle}

    exit 1



camelCaseEntityName=$(echo "$tableToCreateEntityFrom" | sed -r 's/(^|_)([a-z])/\U\2/g')



mysql $newDb -e \"

    drop table if exists $newDb.$tableToCreateEntityFrom;

    create table $newDb.$tableToCreateEntityFrom like $oldDb.$tableToCreateEntityFrom;

    insert into $newDb.$tableToCreateEntityFrom select * from $oldDb.$tableToCreateEntityFrom ORDER BY
        FROM information_schema.COLUMNS
        WHERE (TABLE_SCHEMA = '$oldDb')
          AND (TABLE_NAME = '$tableToCreateEntityFrom')
          AND (COLUMN_KEY = 'PRI')
    ) DESC limit 0,500;

$DIR/../bin/console doctrine:mapping:import "$bundle" annotation --filter="^$camelCaseEntityName\$"

$DIR/../bin/console doctrine:generate:entities "$bundle":"$camelCaseEntityName" --no-backup

The script will take a single parameter which is the table name. If not importing to AppBundle, you can also specify a bundle name.

It will then create the Upper Camel Case version of the table name (as used by Doctrine).

Then it runs some SQL which will drop and recreate the table and then import the most recent 500 rows from that table as defined by the primary key.

Finally, we do a couple of doctrine commands to create the annotation class and then create the getters and setters. Notice the use of regex to prevent bringing in anything other than an exact match on the table name.

I think this is pretty slick and makes me love Doctrine that little bit more, hope you find it useful too!

Tags: doctrinesymfonybashmysql