Useful SQL
- Published
- Tags
- #sql#notes
List RLS
sql
SELECT * FROM pg_policies WHERE schemaname = 'public';
SELECT * FROM pg_policies WHERE schemaname = 'public' AND tablename = 'products';
SELECT * FROM pg_policies WHERE schemaname = 'public' AND tablename = 'categories';
List all tables
sql
SELECT tablename
FROM pg_catalog.pg_tables
WHERE schemaname = 'public';
Alter RLS loop
sql
CREATE TABLE IF NOT EXISTS tables_to_update (name text);
INSERT INTO tables_to_update (name) VALUES
('dye_materials'), ('dye_recipe_materials'), ('dye_recipes'), ('product_variants'),
('fabrics'), ('product_variant_fabrics'), ('categories'), ('collections'),
('favorite_products'), ('collection_products'), ('category_products'),
('product_variant_dye_recipes'), ('roles'), ('user_roles'), ('users'), ('products'), ('billings');
DO
$$
DECLARE
table_name text;
BEGIN
FOR table_name IN (SELECT name FROM tables_to_update)
LOOP
EXECUTE format('DROP POLICY IF EXISTS "Admins can select all %s" ON %s;', table_name, table_name);
EXECUTE format('DROP POLICY IF EXISTS "Admins can insert all %s" ON %s;', table_name, table_name);
EXECUTE format('DROP POLICY IF EXISTS "Admins can update all %s" ON %s;', table_name, table_name);
EXECUTE format('DROP POLICY IF EXISTS "Admins can delete all %s" ON %s;', table_name, table_name);
EXECUTE format('DROP POLICY IF EXISTS "Public %s are viewable by everyone" ON %s;', table_name, table_name);
END LOOP;
END
$$;
DROP TABLE tables_to_update;
Check RLS enabled:
sql
SELECT relrowsecurity FROM pg_class WHERE relname = 'categories';
Join User, roles, user roles:
sql
SELECT u.*, ur.*, r.*,r.id as role_id
FROM users u
JOIN user_roles ur ON u.id = ur.user_id
JOIN roles r ON ur.role_id = r.id;