query T nosort
SELECT show_trgm(str) FROM (VALUES
    (''),
    ('a'),
    ('ab'),
    ('abc'),
    ('abcd'),
    ('Приветhi'),
    (NULL)
  ) tbl(str)
----
{}
{"  a"," a "}
{"  a"," ab","ab "}
{"  a"," ab",abc,"bc "}
{"  a"," ab",abc,bcd,"cd "}
{"  п"," пр","hi ",вет,етh,иве,при,рив,тhi}
NULL

# Test that we sort the output trigrams.
query T
SELECT show_trgm('dcba')
----
{"  d"," dc","ba ",cba,dcb}

# Test that we downcase the input string.
query T
SELECT show_trgm('Foo')
----
{"  f"," fo",foo,"oo "}

# Test that we de-duplicate the output trigrams.
query T
SELECT show_trgm('aaaa')
----
{"  a"," aa","aa ",aaa}

# Test that we split at word boundaries.
query T
SELECT show_trgm('a b,c|d_e3 bl  ')
----
{"  a","  b","  c","  d","  e"," a "," b "," bl"," c "," d "," e3","bl ","e3 "}

# Test the similarity builtin.
query F nosort
SELECT similarity(a, b) FROM (VALUES
    ('', ''),
    ('foo', ''),
    ('', 'foo'),
    ('foo', NULL),
    (NULL, 'foo'),
    (NULL, NULL),
    ('foo', 'bar'),
    ('foo', 'far'),
    ('foo', 'for'),
    ('foo', 'foo')
  ) tbl(a, b)
----
0
0
0
NULL
NULL
NULL
0
0.142857142857143
0.333333333333333
1

query F nosort
SELECT similarity(a, b) FROM (VALUES
    ('f', 'bfr'),
    ('foo', 'foobar'),
    ('', 'blah'),
    ('blah', '')
  ) tbl(a, b)
----
0
0.375
0
0

query F nosort
SELECT similarity(a, b) FROM (VALUES
    ('FOO', 'foo'),
    ('foobar', 'foo'),
    ('foobar', 'barfoo'),
    ('blorp', 'z')
  ) tbl(a, b)
----
1
0.375
0.16666666666666666
0

# Similarity is commutative.
query F nosort
SELECT similarity(a, b) FROM (VALUES
    ('foo', 'foobar'),
    ('foobar', 'foo'),
    ('FOO', 'foo'),
    ('foo', 'FOO'),
    ('blorp', 'z'),
    ('z', 'blorp')
  ) tbl(a, b)
----
0.375
0.375
1
1
0
0

query T
SHOW pg_trgm.similarity_threshold
----
0.3

# Test the text % text similarity threshold operator. This operator runs
# the same algorithm as similarity(), and checks if the result is greater than
# the value in pg_trgm.similarity_threshold, which defaults to .3.
query BBBB
SELECT 'FOO' % 'foo', 'foobar' % 'foo', 'foobar' % 'barfoo', 'blorp' % 'z'
----
true  true  false  false

# Change similarity threshold and try again.
statement ok
SET pg_trgm.similarity_threshold=.1

query BBBB
SELECT 'FOO' % 'foo', 'foobar' % 'foo', 'foobar' % 'barfoo', 'blorp' % 'z'
----
true  true  true  false

# Change similarity threshold and try again.
statement ok
SET pg_trgm.similarity_threshold=1

query BBBB
SELECT 'FOO' % 'foo', 'foobar' % 'foo', 'foobar' % 'barfoo', 'blorp' % 'z'
----
true  false  false  false

# Sanity check the error message.
query error pq: 2.00 is out of range for similarity_threshold
SET pg_trgm.similarity_threshold = 2.0
