|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "cases/helper_cockroachdb" |
| 4 | +require "models/post" |
| 5 | +require "models/comment" |
| 6 | + |
| 7 | +module CockroachDB |
| 8 | + class AostTest < ActiveRecord::TestCase |
| 9 | + def test_simple_aost |
| 10 | + time = 2.days.ago |
| 11 | + re_time = Regexp.quote(time.iso8601) |
| 12 | + assert_match(/from "posts" as of system time '#{re_time}'/i, Post.aost(time).to_sql) |
| 13 | + assert_match(/from "posts" as of system time '#{re_time}'/i, Post.where(name: "foo").aost(time).to_sql) |
| 14 | + end |
| 15 | + |
| 16 | + def test_reset_aost |
| 17 | + time = 1.second.from_now |
| 18 | + assert_match(/from "posts"\z/i, Post.aost(time).aost(nil).to_sql) |
| 19 | + end |
| 20 | + |
| 21 | + def test_aost_with_join |
| 22 | + time = Time.now |
| 23 | + assert_match( |
| 24 | + /FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" AS OF SYSTEM TIME '#{Regexp.quote time.iso8601}'/, |
| 25 | + Post.joins(:comments).aost(time).to_sql |
| 26 | + ) |
| 27 | + end |
| 28 | + |
| 29 | + def test_aost_with_subquery |
| 30 | + time = 4.seconds.ago |
| 31 | + assert_match(/from \(.*?\) subquery as of system time '#{Regexp.quote time.iso8601}'/i, Post.from(Post.where(name: "foo")).aost(time).to_sql) |
| 32 | + end |
| 33 | + |
| 34 | + def test_only_time_input |
| 35 | + time = 1.second.ago |
| 36 | + expected = "SELECT \"posts\".* FROM \"posts\" AS OF SYSTEM TIME '#{time.iso8601}'" |
| 37 | + assert_equal expected, Post.aost(time).to_sql |
| 38 | + assert_raises(ArgumentError) { Post.aost("no time") } |
| 39 | + assert_raises(ArgumentError) { Post.aost(true) } |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + class AostNoTransactionTest < ActiveRecord::TestCase |
| 44 | + # AOST per query is not compatible with transactions. |
| 45 | + self.use_transactional_tests = false |
| 46 | + |
| 47 | + def test_aost_with_multiple_queries |
| 48 | + time = 1.second.ago |
| 49 | + queries = capture_sql { |
| 50 | + Post.aost(time).limit(2).find_each(batch_size: 1).to_a |
| 51 | + } |
| 52 | + queries.each do |
| 53 | + assert_match /FROM \"posts\" AS OF SYSTEM TIME '#{Regexp.quote time.iso8601}'/, _1 |
| 54 | + end |
| 55 | + end |
| 56 | + end |
| 57 | +end |
0 commit comments