SlideShare a Scribd company logo
1 of 14
ORMs
Ikenna Okpala
21st Jan. 2015
Go London User Group:
January Meetup
ORM
● Object Relational Mapping
○ Convert data between two different type
systems
○ In memory representation of domain objects
(better abstractions of reality)
ORMs thus far….
● Hailed as worthwhile at first
● Tagged unusable by some as time went on
● Some assumptions made that cost dearly
● Leading to some hot debates.
● But they are still around.
Why?
● Structure / Modularity(The M in MVC, Object Representation / Relational Mapping)
● Agnostic Database Integration (configs)
● Boilerplate Reduction (Spaghetti, Complex Queries, DRY)
● Providing hooks Tx lifecycle (Before/After)
● Easier data validation (Maintaining Data integrity)
● Sensible Defaults (Better naming, Connascence/Cognizance etc)
● RAW SQL strings have a high chance of compiling
with semantic errors and @ runtime.
How?
● Support for popular databases
● CRUD
● SQL Generation
● Relationships / Association Traversals
● Tx hooks
● Schema Migration
● Managing Cache (???)
Go’s Philosophy
● As it Affects ORMs
○ Duality (Class / Type)
○ Non existence of a type hierarchy
■ Struct embedding (Composition)
■ Plumbing not encouraged
■ they don't have to announce their
relationships
Go ORMs
❖ jinzhu/gorm
❖ coopernurse/gorp
❖ astaxie/beedb now
beego/orm
❖ go-xorm/xorm
❖ coocood/qbs
❖ upper.io/db
❖ eaigner/hood
❖ Not regarded as ORMs
➢ jmoiron/sqlx
➢ eaigner/jet
➢ jaekwon/go-modeldb
database/sql
package models
// Author model
type Author struct {
ID int64 `db:"ID"json:"id"`
Name string `db:"display_name"json:"name"`
NickName string `db:"user_nicename"json:"nickname"`
Email string `db:"user_email"json:"email"`
URL string `db:"user_url"json:"url"`
}
db, _ := sql.Open("mysql", os.Getenv("SQL_MYSQL_DSN")")
database/sql
db.Exec(
"INSERT INTO author (display_name, user_nicename, email, url) VALUES (?, ?, ?)",
"Foo", "Bar", 'we@gfb.com', 'gfb.com/author/1'
)
row := db.QueryRow("SELECT id, display_name, user_nicename, email, url FROM users WHERE id = ?", 1)
row.Scan(&author.ID, &author.Name, &author.NickName, &author.Email, &author.URL)
db.Exec(
"UPDATE author SET display_name=?, user_nicename=?, email=?, url=? WHERE id = ?",
&author.ID, &author.Name, &author.NickName, &author.Email, &author.URL
)
db.Exec(
"DELETE FROM author WHERE id = ?",
author.ID
)
coopernurse/gorp
1. Supports MySQL, PostgresSQL, SQLite
2. CRUD
3. SQL migrations
a. dbmap.CreateTables()
b. dbmap.CreateTablesIfNotExists()
4. Hooks (PostGet,PreInsert ,PostInser,PreUpdat,PostUpdat,PreDelet,PostDelete)
5. Bind arbitrary SQL queries to a struct
6. Bind slice to SELECT query results without type assertions
7. Use positional or named bind parameters in custom SELECT queries
8. more..
var posts []Post
_, err = dbmap.Select(&posts, "select * from posts order by post_id")
jmoiron/sqlx
1. Is not regarded as an ORM from the authors view (I kind of disagree and agree to some extent)
2. Supports MySQL, PostgresSQL, SQLite
3. CRUD
4. Bind arbitrary SQL queries to a struct
a. Scannability (scan safety)
b. sql = fmt.Sprintf(`SELECT * FROM comments WHERE comment_approved <> 'spam'
AND comment_post_ID IN (%s)`, pIDs)
err = db.Unsafe().Select(&comments, sql)
5. A lot more flexible and better for legacy database
jinzhu/gorm
1. Supports MySQL, PostgreSQL, SQLite
2. Heavily influenced by Activerecord
3. CRUD
authors := []Author{}
err = db.Select(&authors, "SELECT * FROM author")
db.Save(&Author{Name: "Foo", NickName: "Bar", Email: 'we@gfb.com', URL: 'gfb.com/author/1'})
author.FirstName = "Big"
db.Save(author)
db.Delete(author)
4. Schema migrations
a. db.AutoMigrate(&Author{})
b. db.CreateTable(&Author{})
c. db.DropTable(&User{}) and db.DropTableIfExists(&User{})
5. Polymorphism and more...
6. Legacy DB support not great, A lot better for starting from scratch
Noteworthy
● Serialization is implemented the same way on all
● Be careful of go struct tags opaque strings which
happily compile with semantic errors and can fail
at runtime all too easily.
● Easily write verbose code
● Do all your logic outside your Go Structs (DAO)
● Avoid using YAML, JSON or XML for
configuration (Deployment is a bit steep) Use ENV
instead.
Thanks
@ikenna_okpala

More Related Content

What's hot

JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder RubyNick Sieger
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
Compiling EdgeQL
Compiling EdgeQLCompiling EdgeQL
Compiling EdgeQLEdgeDB
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
QA Fest 2015. Яков Крамаренко. Polyglot automation
QA Fest 2015. Яков Крамаренко. Polyglot automation QA Fest 2015. Яков Крамаренко. Polyglot automation
QA Fest 2015. Яков Крамаренко. Polyglot automation QAFest
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesRaimonds Simanovskis
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPeter Eisentraut
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoNina Zakharenko
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Kenji Tanaka
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical StuffPetr Dvorak
 

What's hot (20)

Node.js
Node.jsNode.js
Node.js
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Compiling EdgeQL
Compiling EdgeQLCompiling EdgeQL
Compiling EdgeQL
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Seeking Clojure
Seeking ClojureSeeking Clojure
Seeking Clojure
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Ggug spock
Ggug spockGgug spock
Ggug spock
 
QA Fest 2015. Яков Крамаренко. Polyglot automation
QA Fest 2015. Яков Крамаренко. Polyglot automation QA Fest 2015. Яков Крамаренко. Polyglot automation
QA Fest 2015. Яков Крамаренко. Polyglot automation
 
Spock
SpockSpock
Spock
 
Using Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databasesUsing Ruby on Rails with legacy Oracle databases
Using Ruby on Rails with legacy Oracle databases
 
Python in 90 minutes
Python in 90 minutesPython in 90 minutes
Python in 90 minutes
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQL
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
 

Similar to Go ORM comparison and best practices

Cloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsCloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsPushkar Chivate
 
PostgreSQL - Object Relational Database
PostgreSQL - Object Relational DatabasePostgreSQL - Object Relational Database
PostgreSQL - Object Relational DatabaseMubashar Iqbal
 
Graph Databases in the Microsoft Ecosystem
Graph Databases in the Microsoft EcosystemGraph Databases in the Microsoft Ecosystem
Graph Databases in the Microsoft EcosystemMarco Parenzan
 
Presentation sql server to oracle a database migration roadmap
Presentation    sql server to oracle a database migration roadmapPresentation    sql server to oracle a database migration roadmap
Presentation sql server to oracle a database migration roadmapxKinAnx
 
Domain oriented development
Domain oriented developmentDomain oriented development
Domain oriented developmentrajmundr
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersMichael Rys
 
IT talk SPb "Full text search for lazy guys"
IT talk SPb "Full text search for lazy guys" IT talk SPb "Full text search for lazy guys"
IT talk SPb "Full text search for lazy guys" DataArt
 
ERRest - The Next Steps
ERRest - The Next StepsERRest - The Next Steps
ERRest - The Next StepsWO Community
 
no sql presentation
no sql presentationno sql presentation
no sql presentationchandanm2
 
Modeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeModeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeDavid Boike
 
Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)Michael Rys
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Big data technology unit 3
Big data technology unit 3Big data technology unit 3
Big data technology unit 3RojaT4
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020Thodoris Bais
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021Thodoris Bais
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applicationsbrandonsavage
 
No SQL, No problem - using MongoDB in Ruby
No SQL, No problem - using MongoDB in RubyNo SQL, No problem - using MongoDB in Ruby
No SQL, No problem - using MongoDB in Rubysbeam
 

Similar to Go ORM comparison and best practices (20)

Cloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure toolsCloud architectural patterns and Microsoft Azure tools
Cloud architectural patterns and Microsoft Azure tools
 
PostgreSQL - Object Relational Database
PostgreSQL - Object Relational DatabasePostgreSQL - Object Relational Database
PostgreSQL - Object Relational Database
 
Graph Databases in the Microsoft Ecosystem
Graph Databases in the Microsoft EcosystemGraph Databases in the Microsoft Ecosystem
Graph Databases in the Microsoft Ecosystem
 
Presentation sql server to oracle a database migration roadmap
Presentation    sql server to oracle a database migration roadmapPresentation    sql server to oracle a database migration roadmap
Presentation sql server to oracle a database migration roadmap
 
Domain oriented development
Domain oriented developmentDomain oriented development
Domain oriented development
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for Developers
 
IT talk SPb "Full text search for lazy guys"
IT talk SPb "Full text search for lazy guys" IT talk SPb "Full text search for lazy guys"
IT talk SPb "Full text search for lazy guys"
 
Apache Solr for begginers
Apache Solr for begginersApache Solr for begginers
Apache Solr for begginers
 
ERRest - The Next Steps
ERRest - The Next StepsERRest - The Next Steps
ERRest - The Next Steps
 
mongodb_DS.pptx
mongodb_DS.pptxmongodb_DS.pptx
mongodb_DS.pptx
 
no sql presentation
no sql presentationno sql presentation
no sql presentation
 
Modeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeModeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught Me
 
Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)Introducing U-SQL (SQLPASS 2016)
Introducing U-SQL (SQLPASS 2016)
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Big data technology unit 3
Big data technology unit 3Big data technology unit 3
Big data technology unit 3
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
 
Data Abstraction for Large Web Applications
Data Abstraction for Large Web ApplicationsData Abstraction for Large Web Applications
Data Abstraction for Large Web Applications
 
No SQL, No problem - using MongoDB in Ruby
No SQL, No problem - using MongoDB in RubyNo SQL, No problem - using MongoDB in Ruby
No SQL, No problem - using MongoDB in Ruby
 

Recently uploaded

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 

Recently uploaded (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 

Go ORM comparison and best practices

  • 1. ORMs Ikenna Okpala 21st Jan. 2015 Go London User Group: January Meetup
  • 2. ORM ● Object Relational Mapping ○ Convert data between two different type systems ○ In memory representation of domain objects (better abstractions of reality)
  • 3. ORMs thus far…. ● Hailed as worthwhile at first ● Tagged unusable by some as time went on ● Some assumptions made that cost dearly ● Leading to some hot debates. ● But they are still around.
  • 4. Why? ● Structure / Modularity(The M in MVC, Object Representation / Relational Mapping) ● Agnostic Database Integration (configs) ● Boilerplate Reduction (Spaghetti, Complex Queries, DRY) ● Providing hooks Tx lifecycle (Before/After) ● Easier data validation (Maintaining Data integrity) ● Sensible Defaults (Better naming, Connascence/Cognizance etc) ● RAW SQL strings have a high chance of compiling with semantic errors and @ runtime.
  • 5. How? ● Support for popular databases ● CRUD ● SQL Generation ● Relationships / Association Traversals ● Tx hooks ● Schema Migration ● Managing Cache (???)
  • 6. Go’s Philosophy ● As it Affects ORMs ○ Duality (Class / Type) ○ Non existence of a type hierarchy ■ Struct embedding (Composition) ■ Plumbing not encouraged ■ they don't have to announce their relationships
  • 7. Go ORMs ❖ jinzhu/gorm ❖ coopernurse/gorp ❖ astaxie/beedb now beego/orm ❖ go-xorm/xorm ❖ coocood/qbs ❖ upper.io/db ❖ eaigner/hood ❖ Not regarded as ORMs ➢ jmoiron/sqlx ➢ eaigner/jet ➢ jaekwon/go-modeldb
  • 8. database/sql package models // Author model type Author struct { ID int64 `db:"ID"json:"id"` Name string `db:"display_name"json:"name"` NickName string `db:"user_nicename"json:"nickname"` Email string `db:"user_email"json:"email"` URL string `db:"user_url"json:"url"` } db, _ := sql.Open("mysql", os.Getenv("SQL_MYSQL_DSN")")
  • 9. database/sql db.Exec( "INSERT INTO author (display_name, user_nicename, email, url) VALUES (?, ?, ?)", "Foo", "Bar", 'we@gfb.com', 'gfb.com/author/1' ) row := db.QueryRow("SELECT id, display_name, user_nicename, email, url FROM users WHERE id = ?", 1) row.Scan(&author.ID, &author.Name, &author.NickName, &author.Email, &author.URL) db.Exec( "UPDATE author SET display_name=?, user_nicename=?, email=?, url=? WHERE id = ?", &author.ID, &author.Name, &author.NickName, &author.Email, &author.URL ) db.Exec( "DELETE FROM author WHERE id = ?", author.ID )
  • 10. coopernurse/gorp 1. Supports MySQL, PostgresSQL, SQLite 2. CRUD 3. SQL migrations a. dbmap.CreateTables() b. dbmap.CreateTablesIfNotExists() 4. Hooks (PostGet,PreInsert ,PostInser,PreUpdat,PostUpdat,PreDelet,PostDelete) 5. Bind arbitrary SQL queries to a struct 6. Bind slice to SELECT query results without type assertions 7. Use positional or named bind parameters in custom SELECT queries 8. more.. var posts []Post _, err = dbmap.Select(&posts, "select * from posts order by post_id")
  • 11. jmoiron/sqlx 1. Is not regarded as an ORM from the authors view (I kind of disagree and agree to some extent) 2. Supports MySQL, PostgresSQL, SQLite 3. CRUD 4. Bind arbitrary SQL queries to a struct a. Scannability (scan safety) b. sql = fmt.Sprintf(`SELECT * FROM comments WHERE comment_approved <> 'spam' AND comment_post_ID IN (%s)`, pIDs) err = db.Unsafe().Select(&comments, sql) 5. A lot more flexible and better for legacy database
  • 12. jinzhu/gorm 1. Supports MySQL, PostgreSQL, SQLite 2. Heavily influenced by Activerecord 3. CRUD authors := []Author{} err = db.Select(&authors, "SELECT * FROM author") db.Save(&Author{Name: "Foo", NickName: "Bar", Email: 'we@gfb.com', URL: 'gfb.com/author/1'}) author.FirstName = "Big" db.Save(author) db.Delete(author) 4. Schema migrations a. db.AutoMigrate(&Author{}) b. db.CreateTable(&Author{}) c. db.DropTable(&User{}) and db.DropTableIfExists(&User{}) 5. Polymorphism and more... 6. Legacy DB support not great, A lot better for starting from scratch
  • 13. Noteworthy ● Serialization is implemented the same way on all ● Be careful of go struct tags opaque strings which happily compile with semantic errors and can fail at runtime all too easily. ● Easily write verbose code ● Do all your logic outside your Go Structs (DAO) ● Avoid using YAML, JSON or XML for configuration (Deployment is a bit steep) Use ENV instead.