# LogicTest: local-opt

# TODO(radu): when we no longer have a heuristic planner, merge this file with
# the rest of the prepare tests.

statement ok
CREATE TABLE t (k INT PRIMARY KEY, str STRING)

statement ok
INSERT INTO t SELECT i, to_english(i) FROM generate_series(1, 5) AS g(i)

statement error PREPARE AS OPT PLAN is a testing facility that should not be used directly
PREPARE a AS OPT PLAN 'xx'

statement ok
SET allow_prepare_as_opt_plan = ON

statement ok
PREPARE a AS OPT PLAN '
(Root
  (Scan [ (Table "t") (Cols "k,str") ])
  (Presentation "k,str")
  (NoOrdering)
)'

query IT rowsort
EXECUTE a
----
1  one
2  two
3  three
4  four
5  five

statement ok
PREPARE b AS OPT PLAN '
(Root
  (Sort
    (Select
      (Scan [ (Table "t") (Cols "k,str") ])
      [
        (Eq
          (Mod (Var "k") (Const 2))
          (Const 1)
        )
      ]
    )
  )
  (Presentation "k,str")
  (OrderingChoice "+str")
)'

query IT
EXECUTE b
----
5  five
1  one
3  three

statement ok
PREPARE e AS OPT PLAN '
(Root
  (Explain
    (Select
      (Scan [ (Table "t") (Cols "k,str") ])
      [
        (Eq
          (Mod (Var "k") (Const 2))
          (Const 1)
        )
      ]
    )
    [
      (Options "opt,verbose")
      (ColList [ (NewColumn "text" "string") ])
      (Props (MinPhysProps))
    ]
  )
  (Presentation "text")
  (NoOrdering)
)'

query T
EXECUTE e
----
select
 ├── columns: k:1 str:2
 ├── stats: [rows=333.333333, distinct(1)=333.333333, null(1)=0]
 ├── cost: 1050.03
 ├── key: (1)
 ├── fd: (1)-->(2)
 ├── prune: (2)
 ├── scan test.public.t
 │    ├── columns: k:1 str:2
 │    ├── stats: [rows=1000, distinct(1)=1000, null(1)=0]
 │    ├── cost: 1040.02
 │    ├── key: (1)
 │    ├── fd: (1)-->(2)
 │    └── prune: (1,2)
 └── filters
      └── (k % 2) = 1 [outer=(1)]

# Only root may use PREPARE AS OPT PLAN.

user testuser

statement ok
SET allow_prepare_as_opt_plan = ON

statement error user testuser does not have SELECT privilege on relation t
SELECT * FROM t

statement error PREPARE AS OPT PLAN may only be used by root
PREPARE a AS OPT PLAN '
(Root
  (Scan [ (Table "t") (Cols "k") ])
  (Presentation "k")
  (NoOrdering)
)'

# Ensure we error even when the string matches a previously prepared statement.
statement error PREPARE AS OPT PLAN may only be used by root
PREPARE b AS OPT PLAN '
(Root
  (Scan [ (Table "t") (Cols "k,str") ])
  (Presentation "k,str")
  (NoOrdering)
)'
