SlideShare a Scribd company logo
DB BEST PRACTICES
         FOR WEB APPS




Patterns and Tools for Database Versioning, Migration,
           Data Loading and Data for Tests


         CodeWorks - Atlanta - 9/29/2009
WHO AM I?

Alan Pinstein
@apinstein
apinstein@mac.com
Serial Entrepreneur, current project is Neybor.com
PHP Since 3.0 (~1997), C/C++/Obj-C, Cocoa, etc
PHOCOA PHP Framework http://phocoa.com
On GitHub: http://github.com/apinstein
Atlanta Co-working:
IgnitionAlley.com 151Locust.com
AGENDA

Common DB management problems that cause
frustration and stress

Benefits of formalized solutions

Case Studies

Tools: MP, fixtures, rake, capistrano

Q&A
LIVE Q&A & POLLS


http://codeatl09.eventhive.com/

• Live, crowd-moderated questions & feedback
• Live polls
[production-db] update user set password_md5 = md5(password);
[production-db] alter table user drop column password;
COMMON DB FRUSTRATIONS

  Where should I keep track of schema changes?
  What changed since last production push?
  Did I apply this patch already to this server?
  Did I run the migrations on this copy of the app?
  Did I run the update script after updating the
  schema?
  Someone help the new developer set up the project
  on his machine...
BENEFITS OF BEST
        PRACTICES
Reproducibility

Reduction of complexity and risk

Reduced implementation time for DB changes

Increase in development throughput

Leverage from improvements in third-party tools

Community familiarity with workflows
CASE STUDY: BEFORE


$ vi updates.sql
>> alter table add column foo boolean;
$ git commit updates.sql -m “DB change”

$ ssh production@www0
$ git pull && psql -U production mydb
> i updates.sql

$ echo “” > updates.sql
CASE STUDY: BEFORE



FRAGILE process.

Quickly falls apart with 2+ devs or 2+ servers.

Branches? Fugghetaboutit.
CASE STUDY: AFTER


$   mp -n             # create new migration
$   vi migrations/20090723_163051.php
$   mp -m head
$   git commit -a -m “Added new column.”

$ rake db:clone_production
$ rake db:migrate   # test on copy of real data

$ cap deploy        # push to staging
$ cap production deploy -s tag=staging-2009-09-01.1
CASE STUDY: AFTER

Each DB change encapsulated in a single migration
script
Only code what’s unique to your app
Deployment script automatically runs all necessary
migration scripts on production database
immediately after code deploys
Nothing to remember / eliminates human factor
Easy to test, easy to reproduce
VERSIONS VS MIGRATIONS


 schema                  schema                  schema
 version    migration    version     migration   version
    1                       2                       3




 A version is the structure of a database at a point in
 time
 A migration is code that changes the database
 structure between versions
SCHEMA VERSIONING



Tracking Blocks of Changes

Sharing Changes With Others

Deploying Changes to Staging & Production
TRACKING
    SCHEMA CHANGES


Explicit

  Expressing changes as SQL or meta DDLs

Implicit

  Schema Diffs
MP: MIGRATIONS FOR PHP

 Generic migrations infrastrructure for any project

 Open Source (MIT)
 http://github.com/apinstein/mp/tree/master

   Within 3 weeks, had:
    28 public clones
    1 fork
    8 watchers

   GitHub rocks
MP ARCHITECTURE



                        user: me               schema                 schema
DB Server   clean()    db: myproj   M1->up()   version     M2->up()   version
                      (no schema)                 1                      2




                                                         M2->down()


                                               clean()
MP SETUP

$ mp -f
MP - The PHP Migrator.
No migrations dir found; initializing migrations directory
at ./migrations.
Current version: 0

$ mp -f -n
Created migration 20090805_201842 at ./migrations/
20090805_201842.php.

$ ls -1 ./migrations
20090801_175831.php
clean.php
version.txt
BASIC USAGE
$ mp -x “pgsql:dbname=myproject;user=me” -m
=> migrates to latest version

TIP: alias myproj-mp=”mp -x ‘pgsql:dbname=myproject;user=me’”

$ myproj-mp -r -m
=> resets to clean, then migrates schema to latest
$ myproj-mp -m redo
=> run down() then up() on current migration
=> useful when developing migrations
$ mp -f -l
20090717_130521: Initial sql code for project
20090717_145424: Add e-commerce subsystem
20090804_145315: Add payment_method columns.
class Migration20090804_145315 extends Migration
{
     public function up()
     {
         $sql = <<<SQL
         alter table payment_method
             add column account_name text,
             add column nickname text,
             add column address_id integer,
             ADD CONSTRAINT fk_payment_method_address
                 FOREIGN KEY (address_id)
                 REFERENCES address(address_id) ON DELETE RESTRICT;
SQL;
         $this->migrator->getDbCon()->exec($sql);
     }
     public function down()
     {
         $sql = <<<SQL
         alter table payment_method
             drop column account_name,
             drop column nickname,
             drop column address_id;
SQL;
         $this->migrator->getDbCon()->exec($sql);
     }
     public function description()
     {
         return "Add payment_method columns account_name, nickname, and
address_id.";
     }
}
MP IN PRACTICE

NEVER edit a migration once it’s been relied upon by
anyone else.

  Ideally never edit once pushed to Version Control.

ALWAYS update clean.php to deal with each
migration.

ALWAYS test migrations with redo and clean.

ALWAYS test migrations against a production clone
before deployment.
MP CAVEATS
Post-schema change update scripts that rely on model code at a
certain version can break
   Migration A
      Adds blog.someFeatureField
      Runs model code to copy data from
      blog.oldFeatureField to blog.someFeatureField
   Migration B
      Removes blog.someFeatureField
  Migration A will now fail since latest model code no longer
  knows about blog.someFeatureField
Branches with migrations that can run out-of-order could be
problematic.
MP CAVEATS


Possible solutions:

  Remove migration once it’s run everywhere

  Catch errors and fail gracefully

  Write upgrade scripts without using model code.
$ php externals/mp/mp -h
migrate usage:
                                                           MP CLI
  VERSION STORAGE (must use one or the other)
  -x --dsn <PDO DSN>
    NOTE: if you supply a DSN then mp will automatically store the version number
    in your database in a table named public.mp_version.
    If you do not supply a dsn then you will need to use the -f flag to tell mp
    to use the filesystem for storage of the version.
  -f --version-in-file Store the version on the filesystem.

  COMMANDS
  -r --clean Run clean before doing anything else.
  -n --create Create a new migration.
  -s --show-version Shows the current version.
  -V --set-version <version> Set the current version number maintained by mp to
                             be <version>. Does not run migrations; used to
                             initialize mp for an existing system.
  -m --migrate <TargetVersion> or 0|up|down|head|redo
     * redo is an alias for down + up
  -l --list List all migrations in VERSION - DESCRIPTION format

  OPTIONS
  -v --verbose Verbose messages
  -q --quiet Supress all message
  -h --help Show this help
  -d --dir <MigrationDir>

Default command is "show status".
MP API
$m = new Migrator(array(
   Migrator::OPT_PDO_DSN => $dsn,
   Migrator::OPT_VERSION_PROVIDER
             => new MigratorVersionProviderDB()
 ));
$m->clean();
$m->setVersion(‘xxx’);
$m->migrateToVersion(Migrator::VERSION_HEAD);

Easily Integrate with your own framework, app, build system, etc.
   When called programmatically your infrastructure is bootstrapped,
   so you have access to all of your codebase for grabbing DB
   connections, etc.
   Optionally supply a delegate, available to clean(), up(), down()
DB BEST PRACTICES

DB Naming Conventions:
  Name: project, project_dev, project_staging
  User: user
  Password: different for each machine
Script to clone production database to local/staging

ssh -C user@host                                     
   'pg_dump                                          
      --clean --schema-only -U appUser -h 10.0.10.48 
      myProject'                                     
| psql -U appUser myProject_dev
DATA LOADING - FIXTURES


 Example - using WFFixture from phocoa php framework

   Declarative, model-aware infrastructure makes setup
   of test rigs fast and easy

   YAML for readability

   Useful for loading real baseline data as well as test
   data
BLOG EXAMPLE
  Multi-Tenant Blog App

        Blog
        name
        homePageUrl




        Post
        name
        post
        status




        Comment
        email
        comment
$fixture = <<<END
Blog:
     reasonablyOpinionatedBlog:
         name: Reasonably Opinionated
         homePageUrl: 'http://reasonablyopinionated.com'
Post:
     rant1:
         Blog: reasonablyOpinionatedBlog
         name: Database Migration is Hard
         post: Database Migration is Hard...
         status: structureTypeId: <?php BlogStatus::NOT_YET_PUBLISHED ?>
         Comment: # to-many
             - email: rudecommenter@blah.com
               comment: this post sucks
             - email: apinstein@mac.com
               comment: you suck!
     rant2:
         Blog:   # to-one
             name: Some Other Blog
             homePageUrl: http://someotherblog.com
         name: Cantankerous rant on php 3
         post: PHP3 is so old...
         status: structureTypeId: <?php BlogStatus::PUBLISHED ?>
END;
$results = WFFixture::WFFixture()->loadFromYaml($fixture);
$this->rant1 = $results['rant1'];
WORKFLOW INTEGRATION




 AUTOMATE!!!

 Use build tools: phing, rake, capistrano etc
RAKE FOR
               DB MANAGEMENT
rake db:backup_production           # Backup production DB - for safety before
                                      deployment only
rake   db:clone_production          # Restore Production DB to Local DB
rake   db:create                    # Create Database
rake   db:drop                      # Drop Database
rake   db:export:features           # Export all feature data for later reloading.
rake   db:export:geographies        # Export all geography data for later reloading.
rake   db:import:development_data   # Load useful data for doing development.
rake   db:import:features           # Load feature data.
rake   db:import:geographies        # Load geography data.
rake   db:migrate                   # Migrate to latest db version
rake   db:migrate:check             # Verify project is already set up for MP.
rake   db:migrate:clean             # Clean database.
rake   db:migrate:head              # Update to latest version.
rake   db:migrate:rebuild           # Rebuild db from clean state and update to
                                      latest version.
rake db:model:rebuild               # Rebuild model (reverse om convert-conf) from
                                      existing database state.
rake db:rebuild                     # Rebuild the entire database, reload baseline
                                      data, and rebuild the propel ORM model.
MP ROADMAP




Support for pinning migrations to specific VCS tags?

Support for manifesting irreversible migrations?
Questions?

More Related Content

PDF
BenchFlow: A Platform for End-to-end Automation of Performance Testing and An...
PDF
Towards Holistic Continuous Software Performance Assessment
PDF
Collecting and Leveraging a Benchmark of Build System Clones to Aid in Qualit...
PPTX
PHP North-East - Automated Deployment
PDF
Virtual CD4PE Workshop
PDF
Workflow Engine Performance Benchmarking with BenchFlow
PPTX
Virtual Bolt Workshop - March 16, 2020
PPTX
C++ for the Web
BenchFlow: A Platform for End-to-end Automation of Performance Testing and An...
Towards Holistic Continuous Software Performance Assessment
Collecting and Leveraging a Benchmark of Build System Clones to Aid in Qualit...
PHP North-East - Automated Deployment
Virtual CD4PE Workshop
Workflow Engine Performance Benchmarking with BenchFlow
Virtual Bolt Workshop - March 16, 2020
C++ for the Web

What's hot (20)

PDF
Preparing your code for Java 9
PDF
Effective CMake
PPTX
CI from scratch with Jenkins (EN)
PDF
Architecting the Future: Abstractions and Metadata - CodeStock
PDF
makefiles tutorial
PDF
CMake - Introduction and best practices
ODP
Pipeline based deployments on Jenkins
RTF
Readme
PDF
Version Control with Subversion
PDF
Analysis of merge requests in GitLab using PVS-Studio for C#
PDF
Dependencies Managers in C/C++. Using stdcpp 2014
PDF
Java 10 New Features
PDF
Hyper-pragmatic Pure FP testing with distage-testkit
PDF
Puppet evolutions
PDF
ScalaUA - distage: Staged Dependency Injection
PDF
Java fx smart code econ
KEY
groovy & grails - lecture 9
PDF
The Play Framework at LinkedIn
PDF
Gradle in 45min
Preparing your code for Java 9
Effective CMake
CI from scratch with Jenkins (EN)
Architecting the Future: Abstractions and Metadata - CodeStock
makefiles tutorial
CMake - Introduction and best practices
Pipeline based deployments on Jenkins
Readme
Version Control with Subversion
Analysis of merge requests in GitLab using PVS-Studio for C#
Dependencies Managers in C/C++. Using stdcpp 2014
Java 10 New Features
Hyper-pragmatic Pure FP testing with distage-testkit
Puppet evolutions
ScalaUA - distage: Staged Dependency Injection
Java fx smart code econ
groovy & grails - lecture 9
The Play Framework at LinkedIn
Gradle in 45min
Ad

Similar to Patterns and Tools for Database Versioning, Migration, Data Loading and Test Data. (20)

PDF
Introduction to WP-CLI: Manage WordPress from the command line
PPTX
Getting started with agile database migrations for java flywaydb
PDF
Phinx talk
PDF
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
ODP
Handling Database Deployments
PPT
Evolutionary db development
PPTX
Automated Deployment
PDF
PgConf US 2015 - ALTER DATABASE ADD more SANITY
PPTX
Chef arista devops days a'dam 2015
PDF
plProxy, pgBouncer, pgBalancer
PDF
Deploying TYPO3 Neos websites using Surf
PDF
Lean Php Presentation
PDF
Web development automatisation for fun and profit (Artem Daniliants)
PDF
Painless Perl Ports with cpan2port
PPTX
Vitta Minicurso Laravel - Hackathon League of Legends
PPTX
drupal ci cd concept cornel univercity.pptx
PPT
Php classes in mumbai
PDF
IR Journal (itscholar.codegency.co.in).pdf
PDF
What's New In Laravel 5
PDF
Development Setup of B-Translator
Introduction to WP-CLI: Manage WordPress from the command line
Getting started with agile database migrations for java flywaydb
Phinx talk
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Handling Database Deployments
Evolutionary db development
Automated Deployment
PgConf US 2015 - ALTER DATABASE ADD more SANITY
Chef arista devops days a'dam 2015
plProxy, pgBouncer, pgBalancer
Deploying TYPO3 Neos websites using Surf
Lean Php Presentation
Web development automatisation for fun and profit (Artem Daniliants)
Painless Perl Ports with cpan2port
Vitta Minicurso Laravel - Hackathon League of Legends
drupal ci cd concept cornel univercity.pptx
Php classes in mumbai
IR Journal (itscholar.codegency.co.in).pdf
What's New In Laravel 5
Development Setup of B-Translator
Ad

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Encapsulation theory and applications.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Machine learning based COVID-19 study performance prediction
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Big Data Technologies - Introduction.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
“AI and Expert System Decision Support & Business Intelligence Systems”
Encapsulation theory and applications.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Machine learning based COVID-19 study performance prediction
Building Integrated photovoltaic BIPV_UPV.pdf
cuic standard and advanced reporting.pdf
A Presentation on Artificial Intelligence
NewMind AI Weekly Chronicles - August'25 Week I
Big Data Technologies - Introduction.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
NewMind AI Monthly Chronicles - July 2025
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Advanced methodologies resolving dimensionality complications for autism neur...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Patterns and Tools for Database Versioning, Migration, Data Loading and Test Data.

  • 1. DB BEST PRACTICES FOR WEB APPS Patterns and Tools for Database Versioning, Migration, Data Loading and Data for Tests CodeWorks - Atlanta - 9/29/2009
  • 2. WHO AM I? Alan Pinstein @apinstein apinstein@mac.com Serial Entrepreneur, current project is Neybor.com PHP Since 3.0 (~1997), C/C++/Obj-C, Cocoa, etc PHOCOA PHP Framework http://phocoa.com On GitHub: http://github.com/apinstein Atlanta Co-working: IgnitionAlley.com 151Locust.com
  • 3. AGENDA Common DB management problems that cause frustration and stress Benefits of formalized solutions Case Studies Tools: MP, fixtures, rake, capistrano Q&A
  • 4. LIVE Q&A & POLLS http://codeatl09.eventhive.com/ • Live, crowd-moderated questions & feedback • Live polls
  • 5. [production-db] update user set password_md5 = md5(password); [production-db] alter table user drop column password;
  • 6. COMMON DB FRUSTRATIONS Where should I keep track of schema changes? What changed since last production push? Did I apply this patch already to this server? Did I run the migrations on this copy of the app? Did I run the update script after updating the schema? Someone help the new developer set up the project on his machine...
  • 7. BENEFITS OF BEST PRACTICES Reproducibility Reduction of complexity and risk Reduced implementation time for DB changes Increase in development throughput Leverage from improvements in third-party tools Community familiarity with workflows
  • 8. CASE STUDY: BEFORE $ vi updates.sql >> alter table add column foo boolean; $ git commit updates.sql -m “DB change” $ ssh production@www0 $ git pull && psql -U production mydb > i updates.sql $ echo “” > updates.sql
  • 9. CASE STUDY: BEFORE FRAGILE process. Quickly falls apart with 2+ devs or 2+ servers. Branches? Fugghetaboutit.
  • 10. CASE STUDY: AFTER $ mp -n # create new migration $ vi migrations/20090723_163051.php $ mp -m head $ git commit -a -m “Added new column.” $ rake db:clone_production $ rake db:migrate # test on copy of real data $ cap deploy # push to staging $ cap production deploy -s tag=staging-2009-09-01.1
  • 11. CASE STUDY: AFTER Each DB change encapsulated in a single migration script Only code what’s unique to your app Deployment script automatically runs all necessary migration scripts on production database immediately after code deploys Nothing to remember / eliminates human factor Easy to test, easy to reproduce
  • 12. VERSIONS VS MIGRATIONS schema schema schema version migration version migration version 1 2 3 A version is the structure of a database at a point in time A migration is code that changes the database structure between versions
  • 13. SCHEMA VERSIONING Tracking Blocks of Changes Sharing Changes With Others Deploying Changes to Staging & Production
  • 14. TRACKING SCHEMA CHANGES Explicit Expressing changes as SQL or meta DDLs Implicit Schema Diffs
  • 15. MP: MIGRATIONS FOR PHP Generic migrations infrastrructure for any project Open Source (MIT) http://github.com/apinstein/mp/tree/master Within 3 weeks, had: 28 public clones 1 fork 8 watchers GitHub rocks
  • 16. MP ARCHITECTURE user: me schema schema DB Server clean() db: myproj M1->up() version M2->up() version (no schema) 1 2 M2->down() clean()
  • 17. MP SETUP $ mp -f MP - The PHP Migrator. No migrations dir found; initializing migrations directory at ./migrations. Current version: 0 $ mp -f -n Created migration 20090805_201842 at ./migrations/ 20090805_201842.php. $ ls -1 ./migrations 20090801_175831.php clean.php version.txt
  • 18. BASIC USAGE $ mp -x “pgsql:dbname=myproject;user=me” -m => migrates to latest version TIP: alias myproj-mp=”mp -x ‘pgsql:dbname=myproject;user=me’” $ myproj-mp -r -m => resets to clean, then migrates schema to latest $ myproj-mp -m redo => run down() then up() on current migration => useful when developing migrations $ mp -f -l 20090717_130521: Initial sql code for project 20090717_145424: Add e-commerce subsystem 20090804_145315: Add payment_method columns.
  • 19. class Migration20090804_145315 extends Migration { public function up() { $sql = <<<SQL alter table payment_method add column account_name text, add column nickname text, add column address_id integer, ADD CONSTRAINT fk_payment_method_address FOREIGN KEY (address_id) REFERENCES address(address_id) ON DELETE RESTRICT; SQL; $this->migrator->getDbCon()->exec($sql); } public function down() { $sql = <<<SQL alter table payment_method drop column account_name, drop column nickname, drop column address_id; SQL; $this->migrator->getDbCon()->exec($sql); } public function description() { return "Add payment_method columns account_name, nickname, and address_id."; } }
  • 20. MP IN PRACTICE NEVER edit a migration once it’s been relied upon by anyone else. Ideally never edit once pushed to Version Control. ALWAYS update clean.php to deal with each migration. ALWAYS test migrations with redo and clean. ALWAYS test migrations against a production clone before deployment.
  • 21. MP CAVEATS Post-schema change update scripts that rely on model code at a certain version can break Migration A Adds blog.someFeatureField Runs model code to copy data from blog.oldFeatureField to blog.someFeatureField Migration B Removes blog.someFeatureField Migration A will now fail since latest model code no longer knows about blog.someFeatureField Branches with migrations that can run out-of-order could be problematic.
  • 22. MP CAVEATS Possible solutions: Remove migration once it’s run everywhere Catch errors and fail gracefully Write upgrade scripts without using model code.
  • 23. $ php externals/mp/mp -h migrate usage: MP CLI VERSION STORAGE (must use one or the other) -x --dsn <PDO DSN> NOTE: if you supply a DSN then mp will automatically store the version number in your database in a table named public.mp_version. If you do not supply a dsn then you will need to use the -f flag to tell mp to use the filesystem for storage of the version. -f --version-in-file Store the version on the filesystem. COMMANDS -r --clean Run clean before doing anything else. -n --create Create a new migration. -s --show-version Shows the current version. -V --set-version <version> Set the current version number maintained by mp to be <version>. Does not run migrations; used to initialize mp for an existing system. -m --migrate <TargetVersion> or 0|up|down|head|redo * redo is an alias for down + up -l --list List all migrations in VERSION - DESCRIPTION format OPTIONS -v --verbose Verbose messages -q --quiet Supress all message -h --help Show this help -d --dir <MigrationDir> Default command is "show status".
  • 24. MP API $m = new Migrator(array( Migrator::OPT_PDO_DSN => $dsn, Migrator::OPT_VERSION_PROVIDER => new MigratorVersionProviderDB() )); $m->clean(); $m->setVersion(‘xxx’); $m->migrateToVersion(Migrator::VERSION_HEAD); Easily Integrate with your own framework, app, build system, etc. When called programmatically your infrastructure is bootstrapped, so you have access to all of your codebase for grabbing DB connections, etc. Optionally supply a delegate, available to clean(), up(), down()
  • 25. DB BEST PRACTICES DB Naming Conventions: Name: project, project_dev, project_staging User: user Password: different for each machine Script to clone production database to local/staging ssh -C user@host 'pg_dump --clean --schema-only -U appUser -h 10.0.10.48 myProject' | psql -U appUser myProject_dev
  • 26. DATA LOADING - FIXTURES Example - using WFFixture from phocoa php framework Declarative, model-aware infrastructure makes setup of test rigs fast and easy YAML for readability Useful for loading real baseline data as well as test data
  • 27. BLOG EXAMPLE Multi-Tenant Blog App Blog name homePageUrl Post name post status Comment email comment
  • 28. $fixture = <<<END Blog: reasonablyOpinionatedBlog: name: Reasonably Opinionated homePageUrl: 'http://reasonablyopinionated.com' Post: rant1: Blog: reasonablyOpinionatedBlog name: Database Migration is Hard post: Database Migration is Hard... status: structureTypeId: <?php BlogStatus::NOT_YET_PUBLISHED ?> Comment: # to-many - email: rudecommenter@blah.com comment: this post sucks - email: apinstein@mac.com comment: you suck! rant2: Blog: # to-one name: Some Other Blog homePageUrl: http://someotherblog.com name: Cantankerous rant on php 3 post: PHP3 is so old... status: structureTypeId: <?php BlogStatus::PUBLISHED ?> END; $results = WFFixture::WFFixture()->loadFromYaml($fixture); $this->rant1 = $results['rant1'];
  • 29. WORKFLOW INTEGRATION AUTOMATE!!! Use build tools: phing, rake, capistrano etc
  • 30. RAKE FOR DB MANAGEMENT rake db:backup_production # Backup production DB - for safety before deployment only rake db:clone_production # Restore Production DB to Local DB rake db:create # Create Database rake db:drop # Drop Database rake db:export:features # Export all feature data for later reloading. rake db:export:geographies # Export all geography data for later reloading. rake db:import:development_data # Load useful data for doing development. rake db:import:features # Load feature data. rake db:import:geographies # Load geography data. rake db:migrate # Migrate to latest db version rake db:migrate:check # Verify project is already set up for MP. rake db:migrate:clean # Clean database. rake db:migrate:head # Update to latest version. rake db:migrate:rebuild # Rebuild db from clean state and update to latest version. rake db:model:rebuild # Rebuild model (reverse om convert-conf) from existing database state. rake db:rebuild # Rebuild the entire database, reload baseline data, and rebuild the propel ORM model.
  • 31. MP ROADMAP Support for pinning migrations to specific VCS tags? Support for manifesting irreversible migrations?