SlideShare a Scribd company logo
1 of 51
Download to read offline
Intermediate
SQL with Ecto
Dennis Beatty

@dnsbty
GET https://mybusiness.googleapis.com/v4/
{parent=accounts/*/locations/*}/reviews
defmodule GMB.Reviews.Review do
use Ecto.Schema
schema "reviews" do
field :id, :string
field :author, :string
field :rating, :integer
field :reply, :string
field :created_at, :utc_datetime
field :updated_at, :utc_datetime
field :deleted_at, :utc_datetime
end
end
(ArgumentError) field/association :id
is already set on schema
defmodule GMB.Reviews.Review do
use Ecto.Schema
@primary_key {:id, :string, []}
schema "reviews" do
field :author, :string
field :comment, :string
field :rating, :integer
field :reply, :string
field :created_at, :utc_datetime
field :updated_at, :utc_datetime
field :deleted_at, :utc_datetime
end
end
defmodule GMB.Repo.Migrations.CreateReviews do
use Ecto.Migration
def change do
create table(:reviews) do
add :author, :string, null: false, default: ""
add :rating, :integer, null: false, default: 0
add :comment, :string, null: false, default: ""
add :reply, :string, null: false, default: ""
add :created_at, :naive_datetime, null: false, default: "epoch"
add :updated_at, :naive_datetime, null: false, default: "epoch"
add :deleted_at, :naive_datetime, null: false, default: "epoch"
end
end
end
defmodule GMB.Reviews.Review do
use Ecto.Schema
@primary_key {:id, :string, []}
schema "reviews" do
field :author, :string
field :comment, :string
field :rating, :integer
field :reply, :string
field :created_at, :utc_datetime
field :updated_at, :utc_datetime
field :deleted_at, :utc_datetime
end
end
defmodule GMB.Repo.Migrations.CreateReviews do
use Ecto.Migration
def change do
create table(:reviews, primary_key: false) do
add :id, :string, primary_key: true
add :author, :string, null: false, default: ""
add :rating, :integer, null: false, default: 0
add :comment, :string, null: false, default: ""
add :reply, :string, null: false, default: ""
add :created_at, :naive_datetime, null: false, default: "epoch"
add :updated_at, :naive_datetime, null: false, default: "epoch"
add :deleted_at, :naive_datetime, null: false, default: "epoch"
end
end
end
🎉
User
id - Integer
first_name - String
last_name - String
email - String
Group
id - Integer
name - String
description - String
slug - String
Member
user_id - Integer
group_id - Integer
role - String
defmodule SirAlex.Groups.Member do
use Ecto.Schema
alias SirAlex.Groups.{Group, User}
@primary_key false
schema "members" do
field :role, :string, default: "member"
belongs_to :group, Group
belongs_to :user, User
timestamps()
end
end
defmodule SirAlex.Repo.Migrations.CreateMembers do
use Ecto.Migration
def change do
create table(:members, primary_key: false) do
add :group_id, references(:groups), primary_key: true
add :user_id, references(:users), primary_key: true
add :role, :string, null: false, default: "member"
timestamps()
end
end
end
defmodule SirAlex.Accounts.User do
schema "users" do
...
many_to_many :groups, Group, join_through: Member
...
end
end
iex> user.groups
[%Group{}]
🎉
⭐⭐⭐⭐⭐
defmodule GMB.Reviews do
alias GMB.Repo
alias GMB.Reviews.Review
def save_reviews(reviews) do
Enum.map(reviews, &save_review/1)
end
def save_review(attrs) do
%Review{}
|> Review.changeset(attrs)
|> Repo.insert()
end
end
INSERT INTO “reviews"
(“author”,"comment",
“created_at",“id",
"rating","reply")
VALUES
('Dennis','Elixir is awesome’,
‘2018-02-24T07:15:19.730704Z','s929u9dswrf9348',
5,'Yeah, it is!');
• Check out a DB connection from the pool

• Send review data to the DB

• Wait for response from DB

• Release the DB connection back to the pool
• Check out a DB connection from the pool

• Send review data to the DB

• Wait for response from DB

• Release the DB connection back to the pool
INSERT INTO “reviews"
(“author”,"comment",
“created_at",“id",
"rating","reply")
VALUES
('Dennis','Elixir is awesome’,
‘2018-02-24T07:15:19.730704Z','s929u9dswrf9348',
5,'Yeah, it is!’),
(‘Brett','Best BBQ place around.’,
‘2018-02-21T03:26:01.359302Z','sldfi304jslfi3l',
5,’Thanks!’);
defmodule GMB.Reviews do
alias GMB.Repo
alias GMB.Reviews.Review
def save_reviews(reviews) do
Enum.map(reviews, &save_review/1)
end
def save_review(attrs) do
%Review{}
|> Review.changeset(attrs)
|> Repo.insert()
end
end
defmodule GMB.Reviews do
alias GMB.Repo
alias GMB.Reviews.Review
def save_reviews(reviews) do
Repo.insert_all(Review, reviews)
end
end
No validation?! 😱
🎉
** (Postgrex.Error) ERROR 23505
(unique_violation): duplicate key
value violates unique constraint
"reviews_pkey"
def save_reviews(reviews) do
opts = [on_conflict: :nothing]
Repo.insert_all(Review, reviews, opts)
end
🎉
def save_reviews(reviews) do
opts = [on_conflict: :replace_all]
Repo.insert_all(Review, reviews, opts)
end
** (Postgrex.Error) ERROR 42601
(syntax_error): ON CONFLICT DO UPDATE
requires inference specification or
constraint name
def save_reviews(reviews) do
opts = [
on_conflict: :replace_all,
conflict_target: :id
]
Repo.insert_all(Review, reviews, opts)
end
🎉
def save_reviews(reviews) do
opts = [
on_conflict: [set: [comment: "updated"]],
conflict_target: :id
]
Repo.insert_all(Review, reviews, opts)
end
😎
def save_reviews(reviews) do
query = from r in Review, update: [set: [comment:
fragment("EXCLUDED.comment")]]
opts = [
on_conflict: query,
conflict_target: :id
]
Repo.insert_all(Review, reviews, opts)
end
🎉
https://goo.gl/DMof8Q
Under the Hood
• Get next val from sequence*

• Insert row with value from sequence

• If unique constraint error, run ON CONFLICT clause
reviews = [
%{
author: "Dennis",
comment: "Elixir is awesome",
created_at: #DateTime<2018-02-24 09:10:21.752944Z>,
id: "s929u9dswrf9348",
rating: 5,
reply: "Yeah, it is!"
},
%{
author: "Brett",
comment: "I wish I'd found Elixir sooner",
created_at: #DateTime<2018-02-24 09:10:21.754933Z>,
id: "wod938wlfu",
rating: 5,
reply: "Too bad"
}
]
iex> Reviews.save_reviews(reviews)
{2, nil}
def save_reviews(reviews) do
query = from r in Review, update: [set:
[comment: fragment("EXCLUDED.comment")]]
opts = [
on_conflict: query,
conflict_target: :id,
returning: true
]
Repo.insert_all(Review, reviews, opts)
end
iex> Reviews.save_reviews(reviews)
{2,
[
%GMB.Reviews.Review{
__meta__: #Ecto.Schema.Metadata<:loaded, "reviews">,
author: "Dennis",
comment: "Elixir is awesome",
created_at: #DateTime<2018-02-24 09:10:21.752944Z>,
deleted_at: #DateTime<1970-01-01 00:00:00.000000Z>,
id: "s929u9dswrf9348",
rating: 5,
reply: "Yeah, it is!",
updated_at: #DateTime<1970-01-01 00:00:00.000000Z>
},
%GMB.Reviews.Review{
__meta__: #Ecto.Schema.Metadata<:loaded, "reviews">,
author: "Brett",
comment: "I wish I'd found Elixir sooner",
created_at: #DateTime<2018-02-24 09:10:21.754933Z>,
deleted_at: #DateTime<1970-01-01 00:00:00.000000Z>,
id: "wod938wlfu",
rating: 5,
reply: "Too bad",
updated_at: #DateTime<1970-01-01 00:00:00.000000Z>
}
]}
podium.com/jobs
Further Reading
• Plataformatec - What’s New in Ecto 2.1

http://pages.plataformatec.com.br/ebook-whats-new-in-ecto-2-0

• Ecto Docs! 

https://hexdocs.pm/ecto/Ecto.html

• @dnsbty on twitter

More Related Content

What's hot

Introducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React AppsIntroducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React AppsSencha
 
Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]automician
 
2013-06-25 - HTML5 & JavaScript Security
2013-06-25 - HTML5 & JavaScript Security2013-06-25 - HTML5 & JavaScript Security
2013-06-25 - HTML5 & JavaScript SecurityJohannes Hoppe
 
Joomla! Components - Uma visão geral
Joomla! Components - Uma visão geralJoomla! Components - Uma visão geral
Joomla! Components - Uma visão geralFábrica Livre
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in MagentoDivante
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Craig Francis
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1Sharon Liu
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013Michelangelo van Dam
 
WordPress overloading Gravityforms using hooks, filters and extending classes
WordPress overloading Gravityforms using hooks, filters and extending classes WordPress overloading Gravityforms using hooks, filters and extending classes
WordPress overloading Gravityforms using hooks, filters and extending classes Paul Bearne
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
Writing DSLs with Parslet - Wicked Good Ruby Conf
Writing DSLs with Parslet - Wicked Good Ruby ConfWriting DSLs with Parslet - Wicked Good Ruby Conf
Writing DSLs with Parslet - Wicked Good Ruby ConfJason Garber
 

What's hot (20)

Factory Girl
Factory GirlFactory Girl
Factory Girl
 
Zend framework 04 - forms
Zend framework 04 - formsZend framework 04 - forms
Zend framework 04 - forms
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React AppsIntroducing ExtReact: Adding Powerful Sencha Components to React Apps
Introducing ExtReact: Adding Powerful Sencha Components to React Apps
 
Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]Better Bullshit Driven Development [SeleniumCamp 2017]
Better Bullshit Driven Development [SeleniumCamp 2017]
 
2013-06-25 - HTML5 & JavaScript Security
2013-06-25 - HTML5 & JavaScript Security2013-06-25 - HTML5 & JavaScript Security
2013-06-25 - HTML5 & JavaScript Security
 
Joomla! Components - Uma visão geral
Joomla! Components - Uma visão geralJoomla! Components - Uma visão geral
Joomla! Components - Uma visão geral
 
Dsl
DslDsl
Dsl
 
Design patterns in Magento
Design patterns in MagentoDesign patterns in Magento
Design patterns in Magento
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
20220112 sac v1
20220112 sac v120220112 sac v1
20220112 sac v1
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 
Data Validation models
Data Validation modelsData Validation models
Data Validation models
 
Sql
SqlSql
Sql
 
WordPress overloading Gravityforms using hooks, filters and extending classes
WordPress overloading Gravityforms using hooks, filters and extending classes WordPress overloading Gravityforms using hooks, filters and extending classes
WordPress overloading Gravityforms using hooks, filters and extending classes
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Writing DSLs with Parslet - Wicked Good Ruby Conf
Writing DSLs with Parslet - Wicked Good Ruby ConfWriting DSLs with Parslet - Wicked Good Ruby Conf
Writing DSLs with Parslet - Wicked Good Ruby Conf
 

Similar to Intermediate SQL with Ecto - LoneStar ElixirConf 2018

Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsEleanor McHugh
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialYi-Ting Cheng
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Say Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick SuttererSay Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick SuttererRuby Meditation
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2pyjonromero
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)RORLAB
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2RORLAB
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developersLuiz Messias
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Pedro Cunha
 

Similar to Intermediate SQL with Ecto - LoneStar ElixirConf 2018 (20)

Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
Merb Router
Merb RouterMerb Router
Merb Router
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
Clean Code
Clean CodeClean Code
Clean Code
 
Say Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick SuttererSay Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick Sutterer
 
Intro to Rails 4
Intro to Rails 4Intro to Rails 4
Intro to Rails 4
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
 
Active Support Core Extension (2)
Active Support Core Extension (2)Active Support Core Extension (2)
Active Support Core Extension (2)
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Phoenix for laravel developers
Phoenix for laravel developersPhoenix for laravel developers
Phoenix for laravel developers
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 

Recently uploaded

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
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.
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
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
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
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
 
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
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
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
 
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
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 

Recently uploaded (20)

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
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...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
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...
 
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
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
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
 
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 ...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
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
 

Intermediate SQL with Ecto - LoneStar ElixirConf 2018

  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 8. defmodule GMB.Reviews.Review do use Ecto.Schema schema "reviews" do field :id, :string field :author, :string field :rating, :integer field :reply, :string field :created_at, :utc_datetime field :updated_at, :utc_datetime field :deleted_at, :utc_datetime end end (ArgumentError) field/association :id is already set on schema
  • 9. defmodule GMB.Reviews.Review do use Ecto.Schema @primary_key {:id, :string, []} schema "reviews" do field :author, :string field :comment, :string field :rating, :integer field :reply, :string field :created_at, :utc_datetime field :updated_at, :utc_datetime field :deleted_at, :utc_datetime end end
  • 10. defmodule GMB.Repo.Migrations.CreateReviews do use Ecto.Migration def change do create table(:reviews) do add :author, :string, null: false, default: "" add :rating, :integer, null: false, default: 0 add :comment, :string, null: false, default: "" add :reply, :string, null: false, default: "" add :created_at, :naive_datetime, null: false, default: "epoch" add :updated_at, :naive_datetime, null: false, default: "epoch" add :deleted_at, :naive_datetime, null: false, default: "epoch" end end end
  • 11. defmodule GMB.Reviews.Review do use Ecto.Schema @primary_key {:id, :string, []} schema "reviews" do field :author, :string field :comment, :string field :rating, :integer field :reply, :string field :created_at, :utc_datetime field :updated_at, :utc_datetime field :deleted_at, :utc_datetime end end
  • 12. defmodule GMB.Repo.Migrations.CreateReviews do use Ecto.Migration def change do create table(:reviews, primary_key: false) do add :id, :string, primary_key: true add :author, :string, null: false, default: "" add :rating, :integer, null: false, default: 0 add :comment, :string, null: false, default: "" add :reply, :string, null: false, default: "" add :created_at, :naive_datetime, null: false, default: "epoch" add :updated_at, :naive_datetime, null: false, default: "epoch" add :deleted_at, :naive_datetime, null: false, default: "epoch" end end end
  • 13. 🎉
  • 14. User id - Integer first_name - String last_name - String email - String Group id - Integer name - String description - String slug - String Member user_id - Integer group_id - Integer role - String
  • 15. defmodule SirAlex.Groups.Member do use Ecto.Schema alias SirAlex.Groups.{Group, User} @primary_key false schema "members" do field :role, :string, default: "member" belongs_to :group, Group belongs_to :user, User timestamps() end end
  • 16. defmodule SirAlex.Repo.Migrations.CreateMembers do use Ecto.Migration def change do create table(:members, primary_key: false) do add :group_id, references(:groups), primary_key: true add :user_id, references(:users), primary_key: true add :role, :string, null: false, default: "member" timestamps() end end end
  • 17. defmodule SirAlex.Accounts.User do schema "users" do ... many_to_many :groups, Group, join_through: Member ... end end
  • 19. 🎉
  • 21.
  • 22. defmodule GMB.Reviews do alias GMB.Repo alias GMB.Reviews.Review def save_reviews(reviews) do Enum.map(reviews, &save_review/1) end def save_review(attrs) do %Review{} |> Review.changeset(attrs) |> Repo.insert() end end
  • 23. INSERT INTO “reviews" (“author”,"comment", “created_at",“id", "rating","reply") VALUES ('Dennis','Elixir is awesome’, ‘2018-02-24T07:15:19.730704Z','s929u9dswrf9348', 5,'Yeah, it is!');
  • 24. • Check out a DB connection from the pool • Send review data to the DB • Wait for response from DB • Release the DB connection back to the pool
  • 25. • Check out a DB connection from the pool • Send review data to the DB • Wait for response from DB • Release the DB connection back to the pool
  • 26. INSERT INTO “reviews" (“author”,"comment", “created_at",“id", "rating","reply") VALUES ('Dennis','Elixir is awesome’, ‘2018-02-24T07:15:19.730704Z','s929u9dswrf9348', 5,'Yeah, it is!’), (‘Brett','Best BBQ place around.’, ‘2018-02-21T03:26:01.359302Z','sldfi304jslfi3l', 5,’Thanks!’);
  • 27. defmodule GMB.Reviews do alias GMB.Repo alias GMB.Reviews.Review def save_reviews(reviews) do Enum.map(reviews, &save_review/1) end def save_review(attrs) do %Review{} |> Review.changeset(attrs) |> Repo.insert() end end
  • 28. defmodule GMB.Reviews do alias GMB.Repo alias GMB.Reviews.Review def save_reviews(reviews) do Repo.insert_all(Review, reviews) end end No validation?! 😱
  • 29. 🎉
  • 30. ** (Postgrex.Error) ERROR 23505 (unique_violation): duplicate key value violates unique constraint "reviews_pkey"
  • 31.
  • 32.
  • 33. def save_reviews(reviews) do opts = [on_conflict: :nothing] Repo.insert_all(Review, reviews, opts) end
  • 34. 🎉
  • 35. def save_reviews(reviews) do opts = [on_conflict: :replace_all] Repo.insert_all(Review, reviews, opts) end ** (Postgrex.Error) ERROR 42601 (syntax_error): ON CONFLICT DO UPDATE requires inference specification or constraint name
  • 36. def save_reviews(reviews) do opts = [ on_conflict: :replace_all, conflict_target: :id ] Repo.insert_all(Review, reviews, opts) end
  • 37. 🎉
  • 38. def save_reviews(reviews) do opts = [ on_conflict: [set: [comment: "updated"]], conflict_target: :id ] Repo.insert_all(Review, reviews, opts) end
  • 39.
  • 40. 😎
  • 41.
  • 42. def save_reviews(reviews) do query = from r in Review, update: [set: [comment: fragment("EXCLUDED.comment")]] opts = [ on_conflict: query, conflict_target: :id ] Repo.insert_all(Review, reviews, opts) end
  • 43. 🎉
  • 45. Under the Hood • Get next val from sequence* • Insert row with value from sequence • If unique constraint error, run ON CONFLICT clause
  • 46. reviews = [ %{ author: "Dennis", comment: "Elixir is awesome", created_at: #DateTime<2018-02-24 09:10:21.752944Z>, id: "s929u9dswrf9348", rating: 5, reply: "Yeah, it is!" }, %{ author: "Brett", comment: "I wish I'd found Elixir sooner", created_at: #DateTime<2018-02-24 09:10:21.754933Z>, id: "wod938wlfu", rating: 5, reply: "Too bad" } ]
  • 48. def save_reviews(reviews) do query = from r in Review, update: [set: [comment: fragment("EXCLUDED.comment")]] opts = [ on_conflict: query, conflict_target: :id, returning: true ] Repo.insert_all(Review, reviews, opts) end
  • 49. iex> Reviews.save_reviews(reviews) {2, [ %GMB.Reviews.Review{ __meta__: #Ecto.Schema.Metadata<:loaded, "reviews">, author: "Dennis", comment: "Elixir is awesome", created_at: #DateTime<2018-02-24 09:10:21.752944Z>, deleted_at: #DateTime<1970-01-01 00:00:00.000000Z>, id: "s929u9dswrf9348", rating: 5, reply: "Yeah, it is!", updated_at: #DateTime<1970-01-01 00:00:00.000000Z> }, %GMB.Reviews.Review{ __meta__: #Ecto.Schema.Metadata<:loaded, "reviews">, author: "Brett", comment: "I wish I'd found Elixir sooner", created_at: #DateTime<2018-02-24 09:10:21.754933Z>, deleted_at: #DateTime<1970-01-01 00:00:00.000000Z>, id: "wod938wlfu", rating: 5, reply: "Too bad", updated_at: #DateTime<1970-01-01 00:00:00.000000Z> } ]}
  • 51. Further Reading • Plataformatec - What’s New in Ecto 2.1
 http://pages.plataformatec.com.br/ebook-whats-new-in-ecto-2-0 • Ecto Docs! 
 https://hexdocs.pm/ecto/Ecto.html • @dnsbty on twitter