Skip to content
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

Fix double-escaping and single-quote handling. #20

Merged
merged 1 commit into from
Oct 18, 2011
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions lib/cassandra-cql/statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,27 +54,27 @@ def execute(bind_vars=[], options={})
res
end
end

def finish
true
end

def self.escape(obj)
obj.gsub("'", "\\\\'")
obj.gsub("'", "''")
end

def self.quote(obj)
if obj.kind_of?(Array)
obj.map { |member| quote(member) }.join(",")
elsif obj.kind_of?(String)
"'" + escape(obj) + "'"
"'" + obj + "'"
elsif obj.kind_of?(Fixnum)
obj
else
raise Error::UnescapableObject, "Unable to escape object of class #{obj.class}"
end
end

def self.cast_to_cql(obj)
if obj.kind_of?(Array)
obj.map { |member| cast_to_cql(member) }
Expand Down
23 changes: 18 additions & 5 deletions spec/statement_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@

describe "escape" do
it "should escape quotes" do
Statement.escape("'").should eq("\\'")
Statement.escape("\'").should eq("\\'")
Statement.escape("\\'").should eq("\\\\'")
Statement.escape(%q{'}).should eq(%q{''})
Statement.escape(%q{\'}).should eq(%q{\''})
Statement.escape(%q{''}).should eq(%q{''''})
end
end

Expand All @@ -133,10 +133,10 @@
context "with an array" do
it "should return a comma-separated list" do
Statement.quote([1, 2, 3]).should eq("1,2,3")
Statement.quote(["a", "b'", "c"]).should eq("'a','b\\'','c'")
Statement.quote(["a", "b''", "c"]).should eq("'a','b''','c'")
end
end

context "with an unsupported object" do
it "should raise an exception" do
expect {
Expand Down Expand Up @@ -248,6 +248,19 @@
Statement.sanitize("use keyspace ? with randomness (?)", ["test", "stuff"]).should eq("use keyspace 'test' with randomness ('stuff')")
}.to_not raise_error(Error::InvalidBindVariable)
end

it "should not double-escape the single quotes in your string" do
Statement.sanitize(
"insert into keyspace (key, ?) values (?)", ["vanilla", %Q{I\'m a string with \'cool\' quotes}]
).should eq("insert into keyspace (key, 'vanilla') values ('I''m a string with ''cool'' quotes')")
end

it "should handle numbers and stuff appropriately" do
Statement.sanitize(
"insert into keyspace (key, ?) values (?)", [488, 60.368]
).should eq("insert into keyspace (key, 488) values ('60.368')")
end

end
end

Expand Down