Snowflake SQL Tutorial 166 - My Own Table Returned Zero Rows And Snowflake Called That Success

Snowflake SQL · Episode 166

In this post we are going to cover row access policies in Snowflake.

A row access policy is a named object with a body that returns true or false. You attach it to a table, and from then on every query against that table gets only the rows the body said true to. A masking policy changes what a value looks like. This one changes whether the row is in the answer at all.

We will start with a table of nine sales rows and build it up step by step. The first thing it hides is the whole table, from the role that owns it.

Every customer name and amount below is invented.

Episode 166 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

We need a table whose rows belong to different owners. The script below makes a schema for this post and a sales table with three regions in it.

Sample data
-- Sample data for this post. Every customer and amount is invented.
USE DATABASE DEMO_DB;

CREATE OR REPLACE SCHEMA DEMO_DB.ROWS_T166
  COMMENT = 'episode 166 - row access policies, dropped at the end';

USE SCHEMA DEMO_DB.ROWS_T166;

CREATE OR REPLACE TABLE DEMO_DB.ROWS_T166.SALES_T166 (
  SALE_ID  NUMBER,
  REGION   VARCHAR(10),
  CUSTOMER VARCHAR(40),
  AMOUNT   NUMBER(10,2)
);

INSERT INTO DEMO_DB.ROWS_T166.SALES_T166
       (SALE_ID, REGION, CUSTOMER, AMOUNT)
VALUES (1, 'NORTH', 'Northwind Trading',   1200.00),
       (2, 'NORTH', 'Borealis Supplies',    840.50),
       (3, 'NORTH', 'Tundra Logistics',    2310.75),
       (4, 'SOUTH', 'Meridian Foods',      1550.00),
       (5, 'SOUTH', 'Equator Imports',      620.25),
       (6, 'SOUTH', 'Palm Coast Retail',   1890.00),
       (7, 'EAST',  'Sunrise Hardware',     735.00),
       (8, 'EAST',  'Harbour Stationery',  1105.40),
       (9, 'EAST',  'Lantern Electrical',  1460.00);

Let's look at what we just created.

Query
SELECT * FROM DEMO_DB.ROWS_T166.SALES_T166 ORDER BY SALE_ID;
Result9 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT
1NORTHNorthwind Trading1200.00
2NORTHBorealis Supplies840.50
3NORTHTundra Logistics2310.75
4SOUTHMeridian Foods1550.00
5SOUTHEquator Imports620.25
6SOUTHPalm Coast Retail1890.00
7EASTSunrise Hardware735.00
8EASTHarbour Stationery1105.40
9EASTLantern Electrical1460.00

Nine rows and four columns. And here is the shape of it per region, which is the truth of this table and worth keeping in view.

Query
SELECT REGION, COUNT(*) AS HOW_MANY, SUM(AMOUNT) AS TOTAL
  FROM DEMO_DB.ROWS_T166.SALES_T166
 GROUP BY REGION
 ORDER BY REGION;
Result3 rows · 3 columns
REGIONHOW_MANYTOTAL
EAST33300.40
NORTH34351.25
SOUTH34060.25

Three regions, three rows each, and a total for each one.

And the control, before anything exists

This post is entirely about roles getting different answers, so USE ROLE has to actually change what the session can do.

Query
USE SECONDARY ROLES NONE;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
ACCOUNTADMIN{"roles":"","value":""}

Empty, and run before a single policy existed. The demo proves this again inside every role excursion, and those grids are below where they happened.

Here is the account before we start.

Query
SHOW ROW ACCESS POLICIES IN ACCOUNT;
Result0 rows · 9 columns · scroll →
created_onnamedatabase_nameschema_namekindownercommentowner_role_typeoptions
Query
SELECT COUNT(*) AS POLICIES_ALREADY_HERE
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
POLICIES_ALREADY_HERE
0

Let's make three roles and check what they can see

Two of these roles will be named in the policy. The third one never will be, and it is there to answer a question at the end of the next section.

Three roles
-- Three roles. Two of them the policy will name, one it never will.
-- The GRANT ROLE lines name a user; YOUR_USER_NAME stands in for mine.
CREATE OR REPLACE ROLE RNORTH_T166  COMMENT = 'should see NORTH rows only';
CREATE OR REPLACE ROLE RSOUTH_T166  COMMENT = 'should see SOUTH rows only';
CREATE OR REPLACE ROLE RNOBODY_T166 COMMENT = 'mentioned nowhere in any policy';

GRANT USAGE  ON DATABASE  DEMO_DB            TO ROLE RNORTH_T166;
GRANT USAGE  ON SCHEMA    DEMO_DB.ROWS_T166  TO ROLE RNORTH_T166;
GRANT SELECT ON TABLE     DEMO_DB.ROWS_T166.SALES_T166 TO ROLE RNORTH_T166;
GRANT USAGE  ON WAREHOUSE COMPUTE_WH         TO ROLE RNORTH_T166;
-- ... and the same four grants again for RSOUTH_T166 and for RNOBODY_T166.

GRANT ROLE RNORTH_T166  TO USER YOUR_USER_NAME;
GRANT ROLE RSOUTH_T166  TO USER YOUR_USER_NAME;
GRANT ROLE RNOBODY_T166 TO USER YOUR_USER_NAME;

Let's see what one of them holds.

Query
SELECT "privilege", "granted_on", "name"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
 ORDER BY "granted_on", "privilege";
Result4 rows · 3 columns
privilegegranted_onname
USAGEDATABASEDEMO_DB
USAGESCHEMADEMO_DB.ROWS_T166
SELECTTABLEDEMO_DB.ROWS_T166.SALES_T166
USAGEWAREHOUSECOMPUTE_WH

Four grants. Database usage, schema usage, select on the table and a warehouse to run on. Nothing clever.

And with no policy anywhere, let's check that it can read the whole table.

Query
USE ROLE RNORTH_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
RNORTH_T166{"roles":"","value":""}
Query
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166
 ORDER BY SALE_ID;
Result9 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT
1NORTHNorthwind Trading1200.00
2NORTHBorealis Supplies840.50
3NORTHTundra Logistics2310.75
4SOUTHMeridian Foods1550.00
5SOUTHEquator Imports620.25
6SOUTHPalm Coast Retail1890.00
7EASTSunrise Hardware735.00
8EASTHarbour Stationery1105.40
9EASTLantern Electrical1460.00

All nine rows. So the role is not restricted by anything yet, and whatever changes later is the policy and not the grants.

Query
USE ROLE ACCOUNTADMIN;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
ACCOUNTADMIN{"roles":"","value":""}

Now let's write the policy and attach it

A row access policy takes an argument, returns a boolean, and the body decides. Let's name two of our three roles in it.

Query
CREATE OR REPLACE ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_REGION_T166
  AS (THE_REGION VARCHAR) RETURNS BOOLEAN ->
      (CURRENT_ROLE() = 'RNORTH_T166' AND THE_REGION = 'NORTH')
   OR (CURRENT_ROLE() = 'RSOUTH_T166' AND THE_REGION = 'SOUTH');
Result1 row · 1 column
status
Row access policy 'RAP_REGION_T166' is successfully created.

Read that body. The north role gets north rows, the south role gets south rows, and nothing else is mentioned at all.

Query
SELECT "name", "kind", "owner", "options", "comment"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 5 columns
namekindowneroptionscomment
RAP_REGION_T166ROW_ACCESS_POLICYACCOUNTADMIN

DESCRIBE gives us the same shape of object as a masking policy did last post: a signature, a return type and a body.

Query
SELECT "name", "signature", "return_type", "body"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 4 columns
namesignaturereturn_typebody
RAP_REGION_T166(THE_REGION VARCHAR)BOOLEAN(CURRENT_ROLE() = 'RNORTH_T166' AND THE_REGION = 'NORTH') OR (CURRENT_ROLE() = 'RSOUTH_T166' AND THE_REGION = 'SOUTH')

Nothing is filtered yet, because the policy is not attached to anything.

Query
SELECT COUNT(*) AS ROWS_STILL_VISIBLE_TO_THE_OWNER
  FROM DEMO_DB.ROWS_T166.SALES_T166;
Result1 row · 1 column
ROWS_STILL_VISIBLE_TO_THE_OWNER
9

Now let's attach it.

Query
ALTER TABLE DEMO_DB.ROWS_T166.SALES_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_REGION_T166 ON (REGION);
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT POLICY_NAME, POLICY_KIND, REF_COLUMN_NAME, POLICY_STATUS
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         REF_ENTITY_NAME   => 'DEMO_DB.ROWS_T166.SALES_T166',
         REF_ENTITY_DOMAIN => 'TABLE'));
Result1 row · 4 columns
POLICY_NAMEPOLICY_KINDREF_COLUMN_NAMEPOLICY_STATUS
RAP_REGION_T166ROW_ACCESS_POLICYNULLACTIVE

The table carries the policy and its status reads ACTIVE. We will come back to that NULL under REF_COLUMN_NAME later, because it is not the typo it looks like.

And now the owner gets nothing

Let's run the same SELECT as before, as ACCOUNTADMIN, which owns the table and owns the policy.

Query
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166
 ORDER BY SALE_ID;
Result0 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT

Column headings and nothing underneath. Not an error, not stars, not a refusal. An empty answer.

Query
SELECT COUNT(*) AS ROWS_THE_OWNER_CAN_SEE
  FROM DEMO_DB.ROWS_T166.SALES_T166;
Result1 row · 1 column
ROWS_THE_OWNER_CAN_SEE
0
Query
SELECT REGION, COUNT(*) AS HOW_MANY
  FROM DEMO_DB.ROWS_T166.SALES_T166
 GROUP BY REGION
 ORDER BY REGION;
Result0 rows · 2 columns
REGIONHOW_MANY

The reason is in the body. It names RNORTH_T166 and RSOUTH_T166, and ACCOUNTADMIN is neither of those, so the body returns false for every row in the table.

Absent, not redacted

This is the difference from a masking policy in one line. A masked row is still a row. A row this policy says no to is simply not in the answer, and the owner of the table is not exempt from it.

Now let's run that same statement as three roles

Nothing below changes by one character except the role in the session.

The north role

Query
USE ROLE RNORTH_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
RNORTH_T166{"roles":"","value":""}
Query
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166
 ORDER BY SALE_ID;
Result3 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT
1NORTHNorthwind Trading1200.00
2NORTHBorealis Supplies840.50
3NORTHTundra Logistics2310.75

Three rows, all north. The policy let through exactly the rows its body said yes to. And the count agrees with the select, which is worth checking rather than assuming.

Query
SELECT COUNT(*) AS WHAT_THE_COUNT_SAYS
  FROM DEMO_DB.ROWS_T166.SALES_T166;
Result1 row · 1 column
WHAT_THE_COUNT_SAYS
3

And now the part that is quiet about itself

Let's ask that same role for some aggregates.

Query
SELECT COUNT(*)                                   AS ROWS_COUNTED,
       COUNT(DISTINCT REGION)                     AS REGIONS_VISIBLE,
       MIN(SALE_ID)                               AS LOWEST_ID,
       MAX(SALE_ID)                               AS HIGHEST_ID,
       SUM(AMOUNT)                                AS TOTAL_VISIBLE
  FROM DEMO_DB.ROWS_T166.SALES_T166;
Result1 row · 5 columns
ROWS_COUNTEDREGIONS_VISIBLELOWEST_IDHIGHEST_IDTOTAL_VISIBLE
31134351.25

One region visible, the lowest and highest id it can see, and a total. Compare that total with the per-region grid in the first section: it is the real north total, to the penny.

The quiet part

That number is correct, and nothing in the grid says it is a subset. An aggregate over a table with a row access policy on it is computed over the rows you can see, and it comes back looking exactly like an aggregate over the whole table. It is a right answer to a question nobody asked.

And asking for one specific row by its key does not help.

Query
SELECT SALE_ID, REGION, CUSTOMER
  FROM DEMO_DB.ROWS_T166.SALES_T166
 WHERE SALE_ID = 4;
Result0 rows · 3 columns
SALE_IDREGIONCUSTOMER

Empty. Sale 4 is in the table, as the first section shows. The policy does not refuse the question. It makes it unanswerable.

The south role

Query
USE ROLE RSOUTH_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
RSOUTH_T166{"roles":"","value":""}
Query
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166
 ORDER BY SALE_ID;
Result3 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT
4SOUTHMeridian Foods1550.00
5SOUTHEquator Imports620.25
6SOUTHPalm Coast Retail1890.00
Query
SELECT COUNT(*) AS WHAT_THE_SOUTH_ROLE_COUNTS
  FROM DEMO_DB.ROWS_T166.SALES_T166;
Result1 row · 1 column
WHAT_THE_SOUTH_ROLE_COUNTS
3

Three rows, all south. So that one statement is three different tables so far, depending on who runs it.

And the role the policy never mentions

Query
USE ROLE RNOBODY_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
RNOBODY_T166{"roles":"","value":""}
Query
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166
 ORDER BY SALE_ID;
Result0 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT
Query
SELECT COUNT(*) AS ROWS_FOR_A_ROLE_NOT_IN_THE_POLICY
  FROM DEMO_DB.ROWS_T166.SALES_T166;
Result1 row · 1 column
ROWS_FOR_A_ROLE_NOT_IN_THE_POLICY
0

Nothing, the same as the owner. It does hold SELECT on the table, and it can still read the table's shape.

Query
SELECT "name", "type", "null?"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result4 rows · 3 columns
nametypenull?
SALE_IDNUMBER(38,0)Y
REGIONVARCHAR(10)Y
CUSTOMERVARCHAR(40)Y
AMOUNTNUMBER(10,2)Y

All four column names. So a role can know everything about the structure of a table and see none of its rows.

Query
USE ROLE ACCOUNTADMIN;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
ACCOUNTADMIN{"roles":"","value":""}

What happens when we delete a row we cannot see?

This is the part I would put a warning on. The sales table is never written to, so let's make a second table for this and put the same policy on it.

A writable table
-- A second table, so the sales table is never written to.
CREATE OR REPLACE TABLE DEMO_DB.ROWS_T166.WRITABLE_T166 (
  SALE_ID  NUMBER,
  REGION   VARCHAR(10),
  CUSTOMER VARCHAR(40)
);

INSERT INTO DEMO_DB.ROWS_T166.WRITABLE_T166 (SALE_ID, REGION, CUSTOMER)
VALUES (1, 'NORTH', 'Northwind Trading'),
       (2, 'NORTH', 'Borealis Supplies'),
       (3, 'SOUTH', 'Meridian Foods'),
       (4, 'SOUTH', 'Equator Imports');

GRANT SELECT, INSERT, UPDATE, DELETE
   ON TABLE DEMO_DB.ROWS_T166.WRITABLE_T166 TO ROLE RNORTH_T166;
Query
SELECT * FROM DEMO_DB.ROWS_T166.WRITABLE_T166 ORDER BY SALE_ID;
Result4 rows · 3 columns
SALE_IDREGIONCUSTOMER
1NORTHNorthwind Trading
2NORTHBorealis Supplies
3SOUTHMeridian Foods
4SOUTHEquator Imports
Query
ALTER TABLE DEMO_DB.ROWS_T166.WRITABLE_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_REGION_T166 ON (REGION);
Result1 row · 1 column
status
Statement executed successfully.

Four rows in it, two north and two south. Now let's see what the north role makes of it.

Query
USE ROLE RNORTH_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
RNORTH_T166{"roles":"","value":""}
Query
SELECT SALE_ID, REGION, CUSTOMER
  FROM DEMO_DB.ROWS_T166.WRITABLE_T166
 ORDER BY SALE_ID;
Result2 rows · 3 columns
SALE_IDREGIONCUSTOMER
1NORTHNorthwind Trading
2NORTHBorealis Supplies

Two rows, as expected. Now let's delete one it cannot see.

Query
DELETE FROM DEMO_DB.ROWS_T166.WRITABLE_T166 WHERE SALE_ID = 3;
Result1 row · 1 column
number of rows deleted
0
Query
SELECT "number of rows deleted" AS ROWS_DELETED
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
ROWS_DELETED
0

Nought rows deleted. No error, no warning, no refusal of any kind.

Now let's delete one it can see.

Query
DELETE FROM DEMO_DB.ROWS_T166.WRITABLE_T166 WHERE SALE_ID = 2;
Result1 row · 1 column
number of rows deleted
1
Query
SELECT "number of rows deleted" AS ROWS_DELETED
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
ROWS_DELETED
1

One. Same statement shape, same role, same table. The only difference between those two runs is the number in the WHERE clause, and the only thing that tells them apart afterwards is the row count.

Query
SELECT SALE_ID, REGION, CUSTOMER
  FROM DEMO_DB.ROWS_T166.WRITABLE_T166
 ORDER BY SALE_ID;
Result1 row · 3 columns
SALE_IDREGIONCUSTOMER
1NORTHNorthwind Trading

And now let's take the policy off as the owner and look at the actual table.

Query
USE ROLE ACCOUNTADMIN;
Result1 row · 1 column
status
Statement executed successfully.
Query
ALTER TABLE DEMO_DB.ROWS_T166.WRITABLE_T166
  DROP ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_REGION_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT SALE_ID, REGION, CUSTOMER
  FROM DEMO_DB.ROWS_T166.WRITABLE_T166
 ORDER BY SALE_ID;
Result3 rows · 3 columns
SALE_IDREGIONCUSTOMER
1NORTHNorthwind Trading
3SOUTHMeridian Foods
4SOUTHEquator Imports
Query
SELECT COUNT(*) AS ROWS_LEFT_IN_THE_WRITABLE_TABLE
  FROM DEMO_DB.ROWS_T166.WRITABLE_T166;
Result1 row · 1 column
ROWS_LEFT_IN_THE_WRITABLE_TABLE
3

Three rows survived, and sale 3 is one of them. That is the row the first delete named by key. The delete did not fail. It matched nothing, because the row was not in scope.

The one to take away

A row you cannot see is a row you cannot delete, and the row count is the only thing that tells you. If your code checks for an error rather than checking how many rows it changed, it will think that delete worked.

Now the pattern you will actually use

Naming roles in a body does not scale, and every change means editing the policy. The usual pattern is to look the roles up in a table instead.

A mapping table
-- A mapping table, and one role deliberately mapped to two regions.
CREATE OR REPLACE TABLE DEMO_DB.ROWS_T166.MAP_T166 (
  ROLE_NAME   VARCHAR(40),
  REGION_NAME VARCHAR(10)
);

INSERT INTO DEMO_DB.ROWS_T166.MAP_T166 (ROLE_NAME, REGION_NAME)
VALUES ('RNORTH_T166', 'NORTH'),
       ('RSOUTH_T166', 'SOUTH'),
       ('RSOUTH_T166', 'EAST');
Query
SELECT ROLE_NAME, REGION_NAME
  FROM DEMO_DB.ROWS_T166.MAP_T166
 ORDER BY ROLE_NAME, REGION_NAME;
Result3 rows · 2 columns
ROLE_NAMEREGION_NAME
RNORTH_T166NORTH
RSOUTH_T166EAST
RSOUTH_T166SOUTH

Three rows, and the south role is mapped to two regions.

Now a policy whose body is a subquery against that table.

Query
CREATE OR REPLACE ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_MAPPED_T166
  AS (THE_REGION VARCHAR) RETURNS BOOLEAN ->
      EXISTS (SELECT 1
                FROM DEMO_DB.ROWS_T166.MAP_T166
               WHERE ROLE_NAME   = CURRENT_ROLE()
                 AND REGION_NAME = THE_REGION);
Result1 row · 1 column
status
Row access policy 'RAP_MAPPED_T166' is successfully created.

Before we can attach it, one question. Can a table hold two of these?

Query
ALTER TABLE DEMO_DB.ROWS_T166.SALES_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_MAPPED_T166 ON (REGION);
Query failed — Snowflake returned an error
003549 (23505): Object SALES_T166 already has a ROW_ACCESS_POLICY. Only one ROW_ACCESS_POLICY is allowed at a time.

003549. Only one row access policy at a time, so one table holds one. Let's swap them over.

Query
ALTER TABLE DEMO_DB.ROWS_T166.SALES_T166
  DROP ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_REGION_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
ALTER TABLE DEMO_DB.ROWS_T166.SALES_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_MAPPED_T166 ON (REGION);
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT POLICY_NAME, POLICY_KIND, REF_COLUMN_NAME, POLICY_STATUS
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         REF_ENTITY_NAME   => 'DEMO_DB.ROWS_T166.SALES_T166',
         REF_ENTITY_DOMAIN => 'TABLE'));
Result1 row · 4 columns
POLICY_NAMEPOLICY_KINDREF_COLUMN_NAMEPOLICY_STATUS
RAP_MAPPED_T166ROW_ACCESS_POLICYNULLACTIVE

Now let's wear the south role, which the mapping gives two regions.

Query
USE ROLE RSOUTH_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
RSOUTH_T166{"roles":"","value":""}
Query
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166
 ORDER BY SALE_ID;
Result6 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT
4SOUTHMeridian Foods1550.00
5SOUTHEquator Imports620.25
6SOUTHPalm Coast Retail1890.00
7EASTSunrise Hardware735.00
8EASTHarbour Stationery1105.40
9EASTLantern Electrical1460.00

Six rows, south and east. Two regions out of one role, and the policy body never changed.

Query
SELECT REGION, COUNT(*) AS HOW_MANY
  FROM DEMO_DB.ROWS_T166.SALES_T166
 GROUP BY REGION
 ORDER BY REGION;
Result2 rows · 2 columns
REGIONHOW_MANY
EAST3
SOUTH3

And here is the fact that makes the pattern work

Let's ask that same role to read the mapping table directly.

Query
SELECT ROLE_NAME, REGION_NAME
  FROM DEMO_DB.ROWS_T166.MAP_T166
 ORDER BY ROLE_NAME;
Query failed — Snowflake returned an error
002003 (42S02): SQL compilation error:
Object 'DEMO_DB.ROWS_T166.MAP_T166' does not exist or not authorized. Your primary role RSOUTH_T166 must have at least one privilege granted on TABLE DEMO_DB.ROWS_T166.MAP_T166.

002003. It cannot. It was never granted anything on that table.

Whose rights the body runs with

So the body read a table the caller cannot see at all. A policy body runs with the policy's rights, not the caller's. That is the whole reason a mapping table is usable: the mapping itself stays private while it decides what everybody gets.

Query
USE ROLE ACCOUNTADMIN;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
ACCOUNTADMIN{"roles":"","value":""}

Can a policy go on a view?

Yes. Let's make a view and a third policy for it.

Query
CREATE OR REPLACE VIEW DEMO_DB.ROWS_T166.SALES_VIEW_T166 AS
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166;
Result1 row · 1 column
status
View SALES_VIEW_T166 successfully created.
Query
CREATE OR REPLACE ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_VIEW_T166
  AS (THE_REGION VARCHAR) RETURNS BOOLEAN ->
      CURRENT_ROLE() = 'ACCOUNTADMIN';
Result1 row · 1 column
status
Row access policy 'RAP_VIEW_T166' is successfully created.
Query
ALTER VIEW DEMO_DB.ROWS_T166.SALES_VIEW_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_VIEW_T166 ON (REGION);
Result1 row · 1 column
status
Statement executed successfully.

And the catalogue reports it with the entity domain reading VIEW.

Query
SELECT POLICY_NAME, POLICY_KIND, REF_ENTITY_NAME, REF_ENTITY_DOMAIN, POLICY_STATUS
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         POLICY_NAME => 'DEMO_DB.ROWS_T166.RAP_VIEW_T166'));
Result1 row · 5 columns
POLICY_NAMEPOLICY_KINDREF_ENTITY_NAMEREF_ENTITY_DOMAINPOLICY_STATUS
RAP_VIEW_T166ROW_ACCESS_POLICYSALES_VIEW_T166VIEWACTIVE

So where would you look to find out it is there?

Last post, DESCRIBE TABLE grew a policy name column and named the masking policy. Let's try the same thing here, with a row access policy attached.

Query
DESCRIBE TABLE DEMO_DB.ROWS_T166.SALES_T166;
Result4 rows · 13 columns · scroll →
Thirteen columns, and policy name is the eleventh — scroll right
nametypekindnull?defaultprimary keyunique keycheckexpressioncommentpolicy nameprivacy domainwrite default
SALE_IDNUMBER(38,0)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL
REGIONVARCHAR(10)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL
CUSTOMERVARCHAR(40)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL
AMOUNTNUMBER(10,2)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL

A real NULL under policy name on all four columns. DESCRIBE TABLE does not mention a row access policy at all.

POLICY_REFERENCES does know about it.

Query
SELECT POLICY_NAME, POLICY_KIND, REF_ENTITY_NAME, REF_ENTITY_DOMAIN, REF_COLUMN_NAME
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         POLICY_NAME => 'DEMO_DB.ROWS_T166.RAP_MAPPED_T166'));
Result1 row · 5 columns
POLICY_NAMEPOLICY_KINDREF_ENTITY_NAMEREF_ENTITY_DOMAINREF_COLUMN_NAME
RAP_MAPPED_T166ROW_ACCESS_POLICYSALES_T166TABLENULL

There it is, against the table. But look at REF_COLUMN_NAME: a real NULL again.

Why that column is empty

That is not an omission. When we wrote ON (REGION) we were passing REGION to the policy as an argument, not attaching the policy to that column. The policy is on the table, so there is no column name to report.
The NULL here comes from an INFORMATION_SCHEMA function, which returns a real SQL NULL. A missing value in SHOW output comes back as an empty string instead, which is why some grids in this series show an empty cell where others show the word NULL.

And now six more refusals

Two refusals have already happened on this page: the second policy on one table, and the role that could not read the mapping table. Six more are worth running on purpose, and the first two differ in when they arrive.

First, a policy whose argument is a number.

Query
CREATE OR REPLACE ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_WRONGTYPE_T166
  AS (THE_AMOUNT NUMBER) RETURNS BOOLEAN ->
      THE_AMOUNT > 1000;
Result1 row · 1 column
status
Row access policy 'RAP_WRONGTYPE_T166' is successfully created.

Created, happily. Now let's attach it to a text column.

Query
ALTER TABLE DEMO_DB.ROWS_T166.WRITABLE_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_WRONGTYPE_T166 ON (REGION);
Query failed — Snowflake returned an error
003554 (42601): SQL compilation error: Column 'REGION' data type 'VARCHAR(10)' does not match with Row access policy data type 'NUMBER(38,0)'.

003554, and the message names both types. So the type check happens when you attach, not when you create.

Query
SELECT COUNT(*) AS POLICIES_ON_THE_WRITABLE_TABLE
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         REF_ENTITY_NAME   => 'DEMO_DB.ROWS_T166.WRITABLE_T166',
         REF_ENTITY_DOMAIN => 'TABLE'));
Result1 row · 1 column
POLICIES_ON_THE_WRITABLE_TABLE
0

And nothing landed. Now a body that returns a number instead of a boolean.

Query
CREATE OR REPLACE ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_NOTBOOL_T166
  AS (THE_REGION VARCHAR) RETURNS BOOLEAN ->
      LENGTH(THE_REGION);
Query failed — Snowflake returned an error
090207 (42601): Declared return type 'BOOLEAN' is incompatible with actual return type 'NUMBER(18,0)'

090207, and this one is refused at CREATE. The object never existed.

Query
SELECT COUNT(*) AS NOTBOOL_POLICY_ROWS
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
NOTBOOL_POLICY_ROWS
0

Next, dropping a policy while a table still carries it.

Query
DROP ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_MAPPED_T166;
Query failed — Snowflake returned an error
003531 (23001): SQL compilation error: Policy RAP_MAPPED_T166 cannot be dropped/replaced as it is associated with one or more entities.

003531, the same code a masking policy gave last post for the same mistake.

Query
SELECT COUNT(*) AS MAPPED_POLICY_STILL_THERE
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
MAPPED_POLICY_STILL_THERE
1

Still there. Now three smaller ones. A policy that does not exist.

Query
ALTER TABLE DEMO_DB.ROWS_T166.WRITABLE_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.NO_SUCH_POLICY_T166 ON (REGION);
Query failed — Snowflake returned an error
002003 (02000): SQL compilation error:
Row access policy 'DEMO_DB.ROWS_T166.NO_SUCH_POLICY_T166' does not exist or not authorized. Your primary role ACCOUNTADMIN must have at least one privilege granted on POLICY DEMO_DB.ROWS_T166.NO_SUCH_POLICY_T166.

Detaching a policy a table never had.

Query
ALTER TABLE DEMO_DB.ROWS_T166.WRITABLE_T166
  DROP ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_VIEW_T166;
Query failed — Snowflake returned an error
003548 (55000): Policy RAP_VIEW_T166 is not attached to TABLE WRITABLE_T166.

003548, and it names both objects, which makes it easy to see what you got wrong.

And a column that does not exist.

Query
ALTER TABLE DEMO_DB.ROWS_T166.WRITABLE_T166
  ADD ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_REGION_T166 ON (NO_SUCH_COLUMN_T166);
Query failed — Snowflake returned an error
000904 (42000): SQL compilation error: error line 2 at position 62
invalid identifier 'NO_SUCH_COLUMN_T166'

000904, invalid identifier. That one is a typo, not a rule.

One last thing: let's take the policies off again

Let's detach both of them.

Query
ALTER TABLE DEMO_DB.ROWS_T166.SALES_T166
  DROP ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_MAPPED_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
ALTER VIEW DEMO_DB.ROWS_T166.SALES_VIEW_T166
  DROP ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_VIEW_T166;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT COUNT(*) AS REFERENCES_LEFT
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         REF_ENTITY_NAME   => 'DEMO_DB.ROWS_T166.SALES_T166',
         REF_ENTITY_DOMAIN => 'TABLE'));
Result1 row · 1 column
REFERENCES_LEFT
0

And read the table one more time.

Query
SELECT SALE_ID, REGION, CUSTOMER, AMOUNT
  FROM DEMO_DB.ROWS_T166.SALES_T166
 ORDER BY SALE_ID;
Result9 rows · 4 columns
SALE_IDREGIONCUSTOMERAMOUNT
1NORTHNorthwind Trading1200.00
2NORTHBorealis Supplies840.50
3NORTHTundra Logistics2310.75
4SOUTHMeridian Foods1550.00
5SOUTHEquator Imports620.25
6SOUTHPalm Coast Retail1890.00
7EASTSunrise Hardware735.00
8EASTHarbour Stationery1105.40
9EASTLantern Electrical1460.00

All nine rows, exactly as the first section had them. Nothing in the table ever changed except the one row we deleted out of the other table on purpose.

With nothing attached, the drop that was refused goes through.

Query
DROP ROW ACCESS POLICY DEMO_DB.ROWS_T166.RAP_MAPPED_T166;
Result1 row · 1 column
status
RAP_MAPPED_T166 successfully dropped.

And here is the account at the end, after the roles, the tables, the view and the schema have gone too.

Query
SHOW ROW ACCESS POLICIES IN ACCOUNT;
Result0 rows · 9 columns · scroll →
created_onnamedatabase_nameschema_namekindownercommentowner_role_typeoptions
Query
SELECT COUNT(*) AS MY_POLICIES_LEFT
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
 WHERE "name" LIKE '%\\_T166' ESCAPE '\\';
Result1 row · 1 column
MY_POLICIES_LEFT
0
Query
SELECT COUNT(*) AS MY_ROLES_LEFT
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
MY_ROLES_LEFT
0
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
ACCOUNTADMIN{"roles":"ORGADMIN","value":"ALL"}

Counts of 0, and the control put back the way we found it.

Key points

  • A row access policy has a boolean body and is attached to a table with ALTER TABLE ... ADD ROW ACCESS POLICY ... ON (col).
  • A row the body says no to is absent, not redacted, and the owner of the table is not exempt.
  • One unchanged statement gave three roles three different tables, and a role the policy never mentions gets nothing.
  • Aggregates are computed over the rows you can see and never say so. The restricted total on this page is the real regional total.
  • DELETE on a row you cannot see reports 0 rows deleted and raises nothing. The count is the only tell.
  • A body can be an EXISTS subquery against a mapping table, and the body runs with the policy's rights, not the caller's.
  • One table holds one row access policy. A second one is 003549.
  • A policy can go on a view as well, and POLICY_REFERENCES reports the entity domain as VIEW.
  • DESCRIBE TABLE says nothing about it. Only POLICY_REFERENCES knows, and even there REF_COLUMN_NAME is NULL, because ON (col) names an argument.
Next in this series

In the next post we look at tags and object tagging, which label an object rather than filtering it — including a value that stayed on an object after its own tag stopped allowing it.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.36.101) running the demo script for this episode. USE SECONDARY ROLES NONE was set and proved off before the first policy existed and again inside every role excursion, and those proofs are on the page where they happened. Every customer name and amount is invented. The sales table is never written to; a separate table takes the one delete. The grants that name a user are written here with a stand-in name. Everything created here was dropped here and the closing counts are on the page. Nothing is timed and no performance claims are made anywhere in this series. Behaviour follows the Snowflake CREATE ROW ACCESS POLICY documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.