Skip to content

Commit

Permalink
feat (Query): add explicit #insert(name, value) method
Browse files Browse the repository at this point in the history
Closes #77
  • Loading branch information
vladfaust committed Mar 9, 2019
1 parent 473d741 commit 6358068
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
14 changes: 14 additions & 0 deletions spec/query/insert_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ describe "Query#insert" do
end
end

context "with explicit arguments" do
it do
q = Query(User).new.insert(:created_at, "now()")

sql, params = q.build

sql.should eq <<-SQL
INSERT INTO users (created_at) VALUES (now())
SQL

params.should be_empty
end
end

context "with many arguments" do
it do
ref_uuid = UUID.random
Expand Down
22 changes: 19 additions & 3 deletions src/onyx-sql/query/insert.cr
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,21 @@ module Onyx::SQL
self
end

def insert(name : T::Field | T::Reference | String, value : String)
if name.is_a?(T::Field) || name.is_a?(T::Reference)
ensure_insert << Insert.new(T.db_column(name), value)
else
ensure_insert << Insert.new(name, value)
end

@type = :insert
self
end

private struct Insert
getter column, value

def initialize(@column : String, @value : Void*)
def initialize(@column : String, @value : Void* | String)
end
end

Expand Down Expand Up @@ -94,8 +105,13 @@ module Onyx::SQL
end; first = false

sql << insert.column
values_sql << (params_index ? "$#{params_index.value += 1}" : "?")
params.not_nil!.push(Box(DB::Any).unbox(insert.value)) if params

if value = insert.value.as?(Void*)
values_sql << (params_index ? "$#{params_index.value += 1}" : "?")
params.not_nil!.push(Box(DB::Any).unbox(value)) if params
else
values_sql << insert.value.as(String)
end
end

sql << ") VALUES (" << values_sql << ")"
Expand Down

0 comments on commit 6358068

Please sign in to comment.