real to_sql (#29)

real to_sql (#29)

diff --git a/lib/mini_sql/builder.rb b/lib/mini_sql/builder.rb
index b39c0aa..353749d 100644
--- a/lib/mini_sql/builder.rb
+++ b/lib/mini_sql/builder.rb
@@ -23,7 +23,7 @@ class MiniSql::Builder
     end
   end
 
-  def to_sql
+  def to_sql(hash_args = nil)
     sql = @sql.dup
 
     @sections.each do |k, v|
@@ -49,31 +49,26 @@ class MiniSql::Builder
 
       sql.sub!("/*#{k}*/", joined)
     end
-    sql
+
+    hash_args = @args.merge(hash_args) if hash_args && @args
+    hash_args ||= @args
+    if hash_args
+      @connection.param_encoder.encode(sql, hash_args)
+    else
+      sql
+    end
   end
 
   [:query, :query_single, :query_hash, :exec].each do |m|
     class_eval <<~RUBY
       def #{m}(hash_args = nil)
-        hash_args = @args.merge(hash_args) if hash_args && @args
-        hash_args ||= @args
-        if hash_args
-          @connection.#{m}(to_sql, hash_args)
-        else
-          @connection.#{m}(to_sql)
-        end
+        @connection.#{m}(to_sql(hash_args))
       end
     RUBY
   end
 
   def query_decorator(decorator, hash_args = nil)
-    hash_args = @args.merge(hash_args) if hash_args && @args
-    hash_args ||= @args
-    if hash_args
-      @connection.query_decorator(decorator, to_sql, hash_args)
-    else
-      @connection.query_decorator(decorator, to_sql)
-    end
+    @connection.query_decorator(decorator, to_sql(hash_args))
   end
 
 end
diff --git a/test/mini_sql/builder_tests.rb b/test/mini_sql/builder_tests.rb
index ab401ad..acefffb 100644
--- a/test/mini_sql/builder_tests.rb
+++ b/test/mini_sql/builder_tests.rb
@@ -101,4 +101,38 @@ module MiniSql::BuilderTests
     r = builder.query_decorator(ProductDecorator, price: 20, quantity: 3).first
     assert_equal(60, r.amount_price)
   end
+
+  def test_to_sql_without_params
+    builder = @connection.build("SELECT price, quantity AS quantity FROM products /*where*/ /*limit*/ /*order_by*/")
+    builder.where('id = :id', id: 10)
+    builder.where('is_sale = ?', true)
+    builder.limit(50)
+    builder.order_by("created_at DESC")
+
+    sql = <<~SQL.gsub(/[[:space:]]+/, " ").strip
+      SELECT price, quantity AS quantity
+      FROM products
+      WHERE (id = 10) AND (is_sale = true)
+      LIMIT 50
+      ORDER BY created_at DESC
+    SQL
+
+    assert_equal(builder.to_sql, sql)
+  end
+
+  def test_to_sql_with_params
+    builder = @connection.build("SELECT price, quantity AS quantity FROM products WHERE id = :id AND is_sale = :is_sale /*limit*/ /*order_by*/")
+    builder.limit(50)
+    builder.order_by('created_at DESC')
+
+    sql = <<~SQL.gsub(/[[:space:]]+/, " ").strip
+      SELECT price, quantity AS quantity
+      FROM products
+      WHERE id = 10 AND is_sale = true
+      LIMIT 50
+      ORDER BY created_at DESC
+    SQL
+
+    assert_equal(builder.to_sql(id: 10, is_sale: true), sql)
+  end
 end

GitHub sha: 1c998fb9

This commit appears in #29 which was merged by SamSaffron.