MyBatis3Migrations.docx
《MyBatis3Migrations.docx》由会员分享,可在线阅读,更多相关《MyBatis3Migrations.docx(18页珍藏版)》请在冰点文库上搜索。
MyBatis3Migrations
MyBatis3–SchemaMigrationSystem
UserGuide
⇨NOTE:
ThisguideisnotaboutmigratingfromolderversionsofMyBatis.Itisamanualaboutatoolthatwillchangethewayyoumanagechangestoyourdatabase.
Introduction
Evolvingdatabaseshasbeenoneofthemajorchallengesforsoftwaredevelopment.Oftentimes,regardlessofoursoftwaredevelopmentmethodology,thedatabasefollowsadifferentchangemanagementprocess.Despiteourbestefforts,fewtoolsandpracticeshavebeenabletochangethat.ThetoolsofthepasthavebeenGUIcentric,proprietaryforaparticulardatabaseand/orcarriedasteeplicensecost.Yet,attheendofthedaytheysufferedfromthesamechallenges.
Recently,afewtoolsarrivedandchangedallofthat.Theydidsobyembracingsimplicityandafewsimplerulesfordatabaseevolutiontofollow.AcoupleofgoodexamplesareRailsMigrationsanddbdeploy.Bothtoolsaresimilarinpurpose,butquitedifferentinimplementation.TheMyBatisSchemaMigrationSystemdrawsfrombothandseekstobethebestmigrationtoolofitskind.
Goals
Toachieveagooddatabasechangemanagementpractice,weneedtoidentifyafewkeygoals.
Thus,theMyBatisSchemaMigrationSystem(orMyBatisMigrationsforshort)seeksto:
∙Workwithanydatabase,neworexisting
∙Leveragethesourcecontrolsystem(e.g.Subversion)
∙Enableconcurrentdevelopersorteamstoworkindependently
∙Allowconflictsveryvisibleandeasilymanageable
∙Allowforforwardandbackwardmigration(evolve,devolverespectively)
∙Makethecurrentstatusofthedatabaseeasilyaccessibleandcomprehensible
∙Enablemigrationsdespiteaccessprivilegesorbureaucracy
∙Workwithanymethodology
∙Encouragesgood,consistentpractices
Installation
Installationissimplyamatterofunzippingthepackagetoadirectoryofyourchoosing.Therearegenerallytwowaystoworkwiththistool:
∙Unzipittoacentrallocation.AddMIGRATIONS_HOMEtoyourenvironmentvariables,andaddMIGRATIONS_HOMEtoyourpath.Thisisacommonoption,popularamongsimilartoolslikeAntorMaven.
∙Unzipitintoadirectoryinyourworkspaceforaprojectthatyou’recurrentlyworkingon,thuskeepingallofthedependenciesandthetoolversionisolatedwithintheproject.It’sasmallframework,andthisoptionhastheadvantageofportabilityandzerosetupfordevelopersnewtotheproject.
What’sIncluded?
TheMyBatisMigrationspackageissmallandsimple.Thefollowingisthecontentsoftheunzippedpackage:
./lib/mybatis-3-core-3.0.0.188.jar
./migrate
.migrate.cmd
ThesingleMyBatisJARfileistheonlydependencythatMyBatisMigrationshas.Thetwoscriptfilesdothesamething,butasyoucansee,oneisfor*nixshellsandtheotherisforWindows(Note:
cygwinusersshouldstillcallthe.cmdversion).
The‘migrate’Command
TheentireMigrationssystemcanbeaccessedthroughthisonesimplecommand.Youcanaccessthebuilt-inhelpbytyping:
migrate--help
Callingthemigratecommandwithnooptionsorinvalidoptionsalsoproducesthehelpmessage.Here’stheoutputofthehelpcommand:
Usage:
migratecommand[parameter][--path=][--env=]
--path=Pathtorepository.Defaultcurrentworkingdirectory.
--env=Environmenttoconfigure.Defaultenvironmentis'development'.
--forceForcesscripttocontinueevenifSQLerrorsareencountered.
--helpDisplaysthisusagemessage.
--traceShowsadditionalerrordetails(ifany).
Commands:
initCreates(ifnecessary)andinitializesamigrationpath.
bootstrapRunsthebootstrapSQLscript(seescripts/bootstrap.sqlformore).
newCreatesanewmigrationwiththeprovideddescription.
upRunallunappliedmigrations.
downUndoesthelastmigrationappliedtothedatabase.
versionMigratesthedatabaseupordowntothespecifiedversion.
pendingForceexecutespendingmigrationsoutoforder(notrecommended).
statusPrintsthechangelogfromthedatabaseifthechangelogtableexists.
scriptGeneratesadeltamigrationscriptfromversionv1tov2(undoifv1>v2).
We’llgothrougheachofthesecommandsindetail,butfirst,let’stalkaboutlifecycle.
TheMyBatisMigrationsLifecycle
Databasechangemanagementisdifficultatthebestoftimes,sotomakethesituationbetter,it’simportanttohaveagooddatabaseevolutionstrategy.ThatemployedbyMyBatisMigrationstargetsafewkeygoals:
∙Consistent–Theschemashouldbepredictableoneverymachineit’screatedon.
∙Repeatable–Theschemacanbedestroyedandrecreatedapredictableway.
∙Reversible–Changesshouldbeabletoberolledback,orundone.
∙Versioned–Theversionoftheschemashouldbeidentifiable(viaqueryortool).
∙Auditable–Theschemaevolutionshouldbeauditableandthechangestoitlogged.
∙Automated–Theevolution(ordevolution)oftheschemashouldbefullyautomated.
∙Serial–Theevolutioninthedatabaseshouldneverbranchorevolveconditionally.
∙ImmutableChanges–Nopastappliedalterorevolutionofthedatabaseshouldbemodified,insteadanewchangeshouldbecreated.
∙ConcurrentlyModifiable–Theschemashouldbesafelymodifiablebymultiplepeopleorteamsinawaythatencouragesteamwork,communicationandeasyidentificationofconflicts,withoutdependingontextcomparisons(diff)oranyparticularsourcecontrolfeature(conflicts),butshouldworkverywellwithsourcecontrolsystems.
Thus,thelifecycleofaschemamanagedwithMyBatisMigrationsisasfollows:
1.InitializeRepository
2.Bootstrapdatabaseschema
3.Createanewmigration(ormanymigrations)
4.Applymigrations
Optionalstepsinclude:
∙Revertmigrationsifnecessarytoresolveconflicts
∙Applypendingmigrationsoutoforderifit’ssafetodoso
∙Generatemigrationscriptstoberun“offline”inenvironmentsthatarebeyondyourcontrol
∙Getthestatusofthesystematanytime
Thefollowingcommanddiscussionswillprovidemoredetailabouthowthislifecycleworks.
init
Theinitcommandinitializesanew‘migrationpath’,alsocalleda‘repository’(ofmigrationscripts).Regardlessofwhetheryourworkingwithanewdatabaseoranexistingone,you’llruninittocreatetheworkspaceinwhichyou’llplaceeverythingyouneedtomanagedatabasechange.Runningthiscommandwillcreatethedirectoryspecifiedbythe--pathoption(whichisthecurrentworkingdirectorybydefault).
Here’sanexampleofrunningtheinitcommand:
/$migrate--path=/home/cbegin/testdbinit
IfIwasalreadyinthe/home/cbegin/testdbdirectory,Icouldsimplyrun:
/home/cbegin/testdb$migrateinit
Whenthecommandiscompleted,thedirectorywillcontainthefollowingsub-directories:
./drivers
PlaceyourJDBCdriver.jaror.zipfilesinthisdirectory.Uponrunningamigration,thedriverswillbedynamicallyloaded.
./environments
Intheenvironmentsfolderyouwillfind.propertiesfilesthatrepresentyourdatabaseinstances.Bydefaultadevelopment.propertiesfileiscreatedforyoutoconfigureyourdevelopmenttimedatabaseproperties.Youcanalsocreatetest.propertiesandproduction.propertiesfiles.Detailsaboutthepropertiesthemselvesfollowlaterinthisdocument.Theenvironmentcanbespecifiedwhenrunningamigrationbyusingthe--env=option(withoutthepathor".properties"part).
Thedefaultenvironmentis"development".Thepropertiesfileisselfdocumented,buthereitisforreference:
##Basetimezonetoensuretimesareconsistentacrossmachines
time_zone=GMT+0:
00
##Thecharactersetthatscriptsareencodedwith
#script_char_set=UTF-8
##JDBCconnectionproperties.
driver=
url=
username=
password=
#Nameofthetablethattrackschangestothedatabase
changelog=CHANGELOG
#Ifsettotrue,eachstatementisisolated
#initsowntransaction.Otherwisetheentire
#scriptisexecutedinonetransaction.
auto_commit=false
#Thiscontrolshowstatementsaredelimited.
#Bydefaultstatementsaredelimitedbyan
#endoflinesemicolon.Somedatabasesmay
#(e.g.MSSQLServer)mayrequireafullline
#delimitersuchasGO.
delimiter=;
full_line_delimiter=false
#Thisignoresthelinedelimitersand
#simplysendstheentirescriptatonce.
#UsewithJDBCdriversthatcanacceptlarge
#blocksofdelimitedtextatonce.
send_full_script=false
#Customdriverpathtoavoidcopyingyourdrivers
#driver_path=
./scripts
ThisdirectorycontainsyourmigrationSQLfiles.ThesearethefilesthatcontainyourDDLtobothupgradeanddowngradeyourdatabasestructure.Bydefault,thedirectorywillcontainthescripttocreatethechangelogtable,plusoneemptyexamplemigrationscript.Tocreateanewmigrationscript,usethe"new"command.Torunallpendingmigrations,usethe"up"command.Toundothelastmigrationapplied,usethe"down"commandetc.
bootstrap
Ifyou’reworkingfromanexistingdatabase,youneedtostartfromaknownstate.There’snopointintryingtorewindtimeandshoehornyourexistingdatabaseintoaseriesofmigrationscripts.It’smorepracticaltojustacceptthecurrentstateofyourdatabaseschemaandidentifythisasthestartingpoint.Thebootstrapscriptandcommandexistforthisreason.Inthescriptsdirectoryyou’llfindbootstrap.sql.YoucanputyourexistingDDLscriptinthisfile.Ifyoudon’thaveaDDLscript,youcanexportyourexistingdatabaseschemaandputitinthebootstrapfile.You’llwanttocleanitupsothatitdoesn’tcontainanythingspecifictoanyoneenvironment,butotherwisealmostanyscriptshouldwork.WatchoutforDDLthatcontainsconditionalelementsorbranchinglogicthatcouldgeneratemultipleschemas.Whilethisissome