diff --git a/spec/granite_orm/querying/count_spec.cr b/spec/granite_orm/querying/count_spec.cr new file mode 100644 index 00000000..d79bd296 --- /dev/null +++ b/spec/granite_orm/querying/count_spec.cr @@ -0,0 +1,22 @@ +require "../../spec_helper" + +{% for adapter in GraniteExample::ADAPTERS %} + {% model_constant = "Parent#{adapter.camelcase.id}".id %} + + describe "{{ adapter.id }} #count" do + it "returns 0 if no result" do + count = {{ model_constant }}.count + count.should eq 0 + end + + it "returns a number of the all records for the model" do + 2.times do |i| + {{ model_constant }}.new(name: "model_#{i}").tap(&.save) + end + + count = {{ model_constant }}.count + count.should eq 2 + end + end + +{% end %} diff --git a/src/granite_orm/querying.cr b/src/granite_orm/querying.cr index 10e8f2e2..a01d58cf 100644 --- a/src/granite_orm/querying.cr +++ b/src/granite_orm/querying.cr @@ -92,6 +92,11 @@ module Granite::ORM::Querying end end + # count returns a count of all the records + def count : Int32 + scalar "select count(*) from #{@@table_name}", &.to_s.to_i + end + def exec(clause = "") @@adapter.open { |db| db.exec(clause) } end