IT training whats new in ecto 2 0 1 khotailieu

73 66 0
  • Loading ...
    Loading ...
    Loading ...

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Tài liệu liên quan

Thông tin tài liệu

Ngày đăng: 12/11/2019, 22:34

TableofContents Foreword Introduction EctoisnotyourORM Schemalessqueries Schemalesschangesets Dynamicqueries Multitenancywithqueryprefixes Aggregatesandsubqueries Improvedassociationsandfactories Manytomanyandcasting Manytomanyandupserts 10 ComposabletransactionswithEcto.Multi 11 ConcurrenttestswiththeSQLSandbox Foreword Foreword InJanuary2017,wewillcelebrate5yearssincewedecidedtoinvestinElixir Backin2012, JoséValim,ourco-founderandpartner,presentedustheideaofaprogramminglanguage thatwouldbeexpressive,embraceproductivityinitstooling,andleveragetheErlangVMto notonlytackletheproblemsinwritingconcurrentsoftwarebutalsotobuildfault-tolerantand distributedsystems Elixircontinued,insomesense,tobeariskyprojectformonths Wewerecertainlyexcited aboutspreadingfunctional,concurrentanddistributedprogrammingconceptstomoreand moredevelopers,hopingitwouldleadtoapositiveimpactonthesoftwaredevelopment industry,butdevelopingalanguageisalong-termeffortthatmayneverbecomeconcrete Duringthesummerof2013,othercompaniesanddevelopersstartedtoshowintereston Elixir Weheardaboutcompaniesusingitinproduction,moredevelopersbeganto contributeandcreatetheirownprojects,differentpublisherswerewritingbooksonthe language,andsoon SucheventsgaveustheconfidencetoinvestmoreinElixirandbring thelanguagetoversion1.0 OnceElix-ir1.0waslaunchedinSeptember2014,weturnedourfocustothewebplatform WetidiedupPlug,thebuildingblockforwritingwebapplicationsinElixir Wealsofocused intensivelyonEcto,bringingittoversion1.0togetherwiththeEctoteam,andthenworked alongsideChrisMcCordandteamtogetthefirstmajorPhoenixreleaseout Duringthistime wealsostartedother Today,boththecommunityandouropensourceprojectsareshowingsteadyandhealthy growth Elixirisastablelanguagewithcontinuousimprovementslandedinminorversions PlugcontinuestobeasolidfoundationforframeworkssuchasPhoenix Ecto,however, requiredmorethanasmallnudgeintherightdirection Werealizedthatweneededtoletgo ofold,harmfulhabitsandmakeEctolessofanabstractionlayerandmoreofatoolyou controlandapplytodifferentproblems Foreword ThisbookisthefinaleffortbehindEcto2.0 Itshowcasesthenewdirectionwehaveplanned forEcto,thestructuralimprovementsmadebytheEctoteamandmanyofitsnewfeatures Wehopeyouwillenjoyit Afterall,itistimetoletgoofpasthabits Havefun, -ThePlataformatecteam Foreword CONTACTUS Introduction Introduction Ecto2.0isasubstantialdeparturefromearlierversions Insteadofthinkingaboutmodels, Ecto2.0aimstoprovidedevelopersawiderangeofdata-centrictools Therefore,inorderto useEcto2.0effectively,wemustlearnhowtowieldthosetoolsproperly That'sthegoalof thisbook Thisbook,however,isnotanintroductiontoEcto IfyouhaveneverusedEctobefore,we recommendyoutogetstartedwithEcto'sdocumentationandlearnmoreaboutrepositories, queries,schemasandchangesets Weassumethereaderisfamiliarwiththesebuilding blocksandhowtheyrelatetoeachother ThefirstchaptersofthebookwillcoverthebiggestconceptualchangesinEcto2.0 Wewill talkaboutrelationalmappersin"EctoisnotyourORM"andthenexploreSchemaless QueriesandtherelationshipbetweenSchemasandChangesets Afterwewilltakeadeeperlookintoqueries,discussinghowEcto2.0makesiteasierto builddynamicqueries,howtotargetdifferentdatabasesviaqueryprefixes,aswellasthe newaggregateandsubqueryfeatures Thenwewillgobacktoschemasanddiscusstheschema-relatedenhancementsthatare partofEcto2.0,suchastheimprovedassociationsupport, many_to_many associationsand Ecto's2.1upsertsupport Finally,wewillexplorebrandnewtopics,likethenewEctoSQLSandbox,thatallows developerstoruntestsagainstthedatabaseconcurrently,aswellas Ecto.Multi,which makesworkingwithtransactionssimplerthanever Acknoledgements Introduction WewanttothanktheEctoteamfortheirfantasticworkbehindEcto:EricMeadows-Jönsson, JamesFish,JoséValimandMichałMuskała Wealsothankeveryonewhohascontributed toEcto,beitwithcode,documentation,bywritingarticles,givingpresentations,organizing workshops,etc Finallyweappreciateeveryonewhohasreviewedourbetaeditionsandsentusfeedback: AdamRutkowski,AlkisTsamis,ChristianvonRoques,CurtisEkstrom,EricMeadowsJönsson,KevinBaird,KevinRankin,MichaelMadrid,MichałMuskała,RaphaelVidal,Steve Pallen,TobiasPfeifferandWojtekMach EctoisnotyourORM EctoisnotyourORM Dependingonyourperspective,thisisaratherboldorobviousstatementtostartthisbook Afterall,Elixirisnotanobject-orientedlanguage,soEctocan'tbeanObject-relational Mapper However,thisstatementisslightlymorenuancedthanitlooksandthereare importantlessonstobelearnedhere OisforObjects Atitscore,objectscouplestateandbehaviourtogether Inthesame user object,youcan havedata,likethe user.name,aswellasbehaviour,likeconfirmingaparticularuser accountvia user.confirm() Whilesomelanguagesenforcedifferentsyntaxesbetween accessingdata( user.name withoutparentheses)andbehaviour( user.confirm() with parentheses),otherlanguagesfollowtheUniformAccessPrincipleinwhichanobjectshould notmakeadistinctionbetweenthetwosyntaxes EiffelandRubyarelanguagesthatfollow suchprinciple Elixirfailsthe"couplingofstateandbehaviour"test InElixir,weworkwithdifferentdata structuressuchastuples,lists,mapsandothers Behaviourcannotbeattachedtodata structures Behaviourisalwaysaddedtomodulesviafunctions Whenthereisaneedtoworkwithstructureddata,Elixirprovidesstructs Structsdefinea setoffields Astructwillbereferencedbythenameofthemodulewhereitisdefined: defmoduleUserdo defstruct[:name,:email] end user=%User{name:"JohnDoe",email:"john@example.com"} EctoisnotyourORM Onceauserstructiscreated,wecanaccessitsemailvia user.email However,structsare onlydata Itisimpossibletoinvoke user.confirm() onaparticularstructinawayitwill executecoderelatedtoe-mailconfirmation Althoughwecannotattachbehaviourtostructs,itispossibletoaddfunctionstothesame modulethatdefinesthestruct: defmoduleUserdo defstruct[:name,:email] defconfirm(user)do #Confirmtheuseremail end end Evenwiththedefinitionabove,itisimpossibleinElixirtoconfirmagivenuserbycalling user.confirm() Instead,the User prefixisrequiredandthe user structmustbeexplicitly givenasargument,asin User.confirm(user) Attheendoftheday,thereisnostructural couplingbetweenthe user structandthefunctionsinthe User module HenceElixirdoes nothavemethods,ithasfunctions Withouthavingobjects,Ectocertainlycan'tbeanORM However,ifweletgooftheletter "O"forasecond,canEctostillbearelationalmapper? Relationalmappers AnObject-RelationalMapperisatechniqueforconvertingdatabetweenincompatibletype systems,commonlydatabases,toobjects,andback Similarly,EctoprovidesschemasthatmapsanydatasourceintoanElixirstruct When appliedtoyourdatabase,Ectoschemasarerelationalmappers Therefore,whileEctoisnot arelationalmapper,itcontainsarelationalmapperaspartofthemanydifferenttoolsit offers Forexample,theschemabelowtiesthefields name, email, inserted_at and updated_at tofieldssimilarlynamedinthe users table: EctoisnotyourORM defmoduleMyApp.Userdo useEcto.Schema schema"users"do field:name field:email timestamps() end end Theappealbehindschemasisthatyoudefinetheshapeofthedataonceandyoucanuse thisshapetoretrievedatafromthedatabaseaswellascoordinatechangeshappeningon thedata: MyApp.User |>MyApp.Repo.get!(13) |>Ecto.Changeset.cast([name:"newname"],[:name,:email]) |>MyApp.Repo.update! Byrelyingontheschemainformation,Ectoknowshowtoreadandwritedatawithoutextra inputfromthedeveloper Insmallapplications,thiscouplingbetweenthedataandits representationisdesired However,whenusedwrongly,itleadstocomplexcodebasesand subparsolutions ItisimportanttounderstandtherelationshipbetweenEctoandrelationalmappersbecause saying"EctoisnotyourORM"doesnotautomaticallysaveEctoschemasfromsomeofthe downsidesmanydevelopersassociateORMswith HerearesomeexamplesofissuesoftenassociatedwithORMsthatEctodevelopersmay runintowhenusingschemas: ProjectsusingEctomayend-upwith"GodSchemas",commonlyreferredas"God Models","FatModels"or"CanonicalModels"insomelanguagesandframeworks Such schemascouldcontainhundredsoffields,oftenreflectingbaddecisionsdoneatthe datalayer Insteadofprovidingonesingleschemawithfieldsthatspanmultiple concerns,itisbettertobreaktheschemaacrossmultiplecontexts Forexample, insteadofasingle MyApp.User schemawithdozensoffields,considerbreakingitinto MyApp.Accounts.User, MyApp.Purchases.User andsoon Eachstructwithfields exclusivetoitsenclosingcontext Developersmayexcessivelyrelyonschemaswhensometimesthebestwaytoretrieve datafromthedatabaseisintoregulardatastructures(likemapsandtuples)andnot pre-definedshapesofdatalikestructs Forexample,whendoingsearches,generating 10 ... adapter: Ecto. Adapters.Postgres, username:"postgres", password:"postgres", database:"demo", hostname:"localhost", pool_size: 10 Anddefineamigration: #priv/repo/migrations / 20 1 6 01 0 10 0 000 0_create_sample.exs... contributeandcreatetheirownprojects,differentpublisherswerewritingbooksonthe language,andsoon Sucheventsgaveustheconfidencetoinvestmore in Elixirandbring thelanguagetoversion 1 .0 OnceElix-ir 1 .0 waslaunched in September 20 14 ,weturnedourfocustothewebplatform... OnceElix-ir 1 .0 waslaunched in September 20 14 ,weturnedourfocustothewebplatform WetidiedupPlug,thebuildingblockforwritingwebapplications in Elixir Wealsofocused intensivelyon Ecto, bringing it toversion 1 .0 togetherwiththe Ecto team,andthenworked alongsideChrisMcCordandteamtogetthefirstmajorPhoenixreleaseout
- Xem thêm -

Xem thêm: IT training whats new in ecto 2 0 1 khotailieu , IT training whats new in ecto 2 0 1 khotailieu