Doctrine Create New Entity From Legacy Database Shell Script
Aug 18, 2016 · 2 minute readCategory: doctrine
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
readonly DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )";
cd $DIR;
set -e
set -u
set -o pipefail
standardIFS="$IFS"
IFS=$'\n\t'
echo "
===========================================
$(hostname) $0 $@
===========================================
"
#Usage
if (( $# < 1 ))
then
echo "
Usage:
./$0 [tableToCreateEntityFrom] {bundle - defaults to AppBundle}
"
exit 1
fi
#Parameters
tableToCreateEntityFrom=$1
bundle=${2:-AppBundle}
camelCaseEntityName=$(echo "$tableToCreateEntityFrom" | sed -r 's/(^|_)([a-z])/\U\2/g')
newDb=NEW_DB_NAME_HERE
oldDb=OLD_DB_NAME_HERE
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
( SELECT COLUMN_NAME
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!