-
Notifications
You must be signed in to change notification settings - Fork 87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bulk import #168
Bulk import #168
Changes from 9 commits
814de94
d1b2134
93b6e67
6435d63
85c36a0
73e7de5
1a03145
54dd5b7
c74d126
e0e1be4
84364d9
2d15769
bbd2f7f
2425ad2
87009d5
acc4a6e
4b10e27
87268a0
f6dcf2a
e3e525a
371d0b4
9fe4bcb
5b31b80
027be38
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
require "../../spec_helper" | ||
|
||
{% for adapter in GraniteExample::ADAPTERS %} | ||
module {{adapter.capitalize.id}} | ||
describe "{{ adapter.id }} .import" do | ||
it "should import 3 new objects" do | ||
to_import = [ | ||
Parent.new(name: "ImportParent1"), | ||
Parent.new(name: "ImportParent2"), | ||
Parent.new(name: "ImportParent3"), | ||
] | ||
Parent.import(to_import) | ||
Parent.all("WHERE name LIKE ?", ["Import%"]).size.should eq 3 | ||
end | ||
end | ||
end | ||
{% end %} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -76,6 +76,44 @@ class Granite::Adapter::Mysql < Granite::Adapter::Base | |
end | ||
end | ||
|
||
def import(table_name : String, primary_name : String, fields, model_array, **options) | ||
params = [] of DB::Any | ||
now = Time.now.to_utc | ||
fields.reject! { |field| field === "id" } if primary_name === "id" | ||
|
||
statement = String.build do |stmt| | ||
stmt << "INSERT" | ||
stmt << " IGNORE" if options["on_duplicate_key_ignore"]? | ||
stmt << " INTO #{quote(table_name)} (" | ||
stmt << fields.map { |field| quote(field) }.join(", ") | ||
stmt << ") VALUES " | ||
|
||
model_array.each do |model| | ||
model.updated_at = now if model.responds_to? :updated_at | ||
model.created_at = now if model.responds_to? :created_at | ||
next unless model.valid? | ||
stmt << '(' | ||
stmt << Array.new(fields.size, '?').join(',') | ||
params.concat fields.map { |field| model.to_h[field] } | ||
stmt << ")," | ||
end | ||
end.chomp(',') | ||
|
||
if update_keys = options["on_duplicate_key_update"]? | ||
statement += " ON DUPLICATE KEY UPDATE " | ||
update_keys.each do |key| | ||
statement += "#{quote(key)}=VALUES(#{quote(key)}), " | ||
end | ||
statement = statement.chomp(", ") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. does mysql not have an There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
end | ||
|
||
log statement, params | ||
|
||
open do |db| | ||
db.exec statement, params | ||
end | ||
end | ||
|
||
private def last_val | ||
return "SELECT LAST_INSERT_ID()" | ||
end | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -76,6 +76,47 @@ class Granite::Adapter::Pg < Granite::Adapter::Base | |
end | ||
end | ||
|
||
def import(table_name : String, primary_name : String, fields, model_array, **options) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. your def import(table_name : String, primary_name : String, fields, model_array : Array(self), *, update_on_duplicate_key = false) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That would mean i would need to have a defined param for each options right? As of now there is There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can probably have the best of both worlds using a crystal overloaded method signature. If you need, here are the docs on overloading There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don’t have strong opinions on this either. I just noticed a rubyism that might be able to be cleaned up with some crystal. |
||
params = [] of DB::Any | ||
now = Time.now.to_utc | ||
fields.reject! { |field| field === "id" } if primary_name === "id" | ||
index = 0 | ||
|
||
statement = String.build do |stmt| | ||
stmt << "INSERT" | ||
stmt << " INTO #{quote(table_name)} (" | ||
stmt << fields.map { |field| quote(field) }.join(", ") | ||
stmt << ") VALUES " | ||
|
||
model_array.each do |model| | ||
model.updated_at = now if model.responds_to? :updated_at | ||
model.created_at = now if model.responds_to? :created_at | ||
next unless model.valid? | ||
stmt << '(' | ||
stmt << fields.map_with_index { |_f, idx| "$#{index + idx + 1}" }.join(',') | ||
params.concat fields.map { |field| model.to_h[field] } | ||
stmt << ")," | ||
index += fields.size | ||
end | ||
end.chomp(',') | ||
|
||
if update_keys = options["on_duplicate_key_update"]? | ||
statement += " ON CONFLICT (#{quote(primary_name)}) DO UPDATE SET " | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This seems right, but would you mind explaining the behavior in a terse comment for future maintainers? (And me...) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yea, I plan on updating the READ me with info on how to use everything. But basic this was part of Postgres' 9.5 version: https://www.postgresql.org/docs/9.5/static/sql-insert.html It's basic the PostGres version of MySQL From the docs: INSERT INTO distributors (did, dname)
VALUES (5, 'Gizmo Transglobal'), (6, 'Associated Computing, Inc')
ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname; Is basic saying if there is a conflict on the |
||
update_keys.each do |key| | ||
statement += "#{quote(key)}=EXCLUDED.#{quote(key)}, " | ||
end | ||
statement = statement.chomp(", ") | ||
elsif options["on_duplicate_key_ignore"]? | ||
statement += " ON CONFLICT DO NOTHING" | ||
end | ||
|
||
log statement, params | ||
|
||
open do |db| | ||
db.exec statement, params | ||
end | ||
end | ||
|
||
private def last_val | ||
return "SELECT LASTVAL()" | ||
end | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
module Granite::ORM::Querying | ||
class NotFound < Exception | ||
end | ||
end | ||
|
||
macro extended | ||
macro __process_querying | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,9 +7,20 @@ module Granite::ORM::Transactions | |
@updated_at : Time? | ||
@created_at : Time? | ||
|
||
# The import class method will run a batch INSERT statement for each model in the array | ||
# the array must contain only one model class | ||
# invalid model records will be skipped | ||
def self.import(model_array : Array(self), **options) | ||
begin | ||
@@adapter.import(table_name, primary_name, fields, model_array, **options) | ||
rescue err | ||
raise DB::Error.new(err.message) | ||
end | ||
end | ||
|
||
# The save method will check to see if the primary exists yet. If it does it | ||
# will call the update method, otherwise it will call the create method. | ||
# This will update the timestamps apropriately. | ||
# This will update the timestamps appropriately. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🥇 |
||
def save | ||
return false unless valid? | ||
|
||
|
@@ -91,7 +102,7 @@ module Granite::ORM::Transactions | |
end | ||
end | ||
|
||
module ClassMethods | ||
module ClassMethods | ||
def create(**args) | ||
create(args.to_h) | ||
end | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The unless primary_auto references above/below here can be removed once #169 gets merged, since fields will cover it by default.
Probably also be able to remove the primary_auto param since that is only reason i needed it.