Okay, here's the SQL code to create your PostgreSQL database schema. I've made a few common-sense assumptions (like NOT NULL for certain fields) and added a trigger for the last_update column in the USERS table.
sql
-- Enable pgcrypto for UUID generation if you ever need it (optional, not used in this schema)
-- CREATE EXTENSION IF NOT EXISTS "pgcrypto";
-- =============================================================================
-- USERS Table
-- =============================================================================
CREATE TABLE users (
id INTEGER PRIMARY KEY, -- As requested "we edit this manually?", so not SERIAL.
-- Consider using SERIAL if you want auto-incrementing IDs managed by the DB.
name VARCHAR(100) NOT NULL,
last_update TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP -- Sets on insert
);
-- Comment on the manual ID management for USERS:
COMMENT ON COLUMN users.id IS 'Primary key, managed manually as per requirement. Consider SERIAL if auto-increment is desired.';
-- Optional: Trigger to automatically update `last_update` on any row update
CREATE OR REPLACE FUNCTION update_last_update_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.last_update = NOW(); -- Or CURRENT_TIMESTAMP
RETURN NEW;
END;
$$ language 'plpgsql';
CREATE TRIGGER users_last_update_trigger
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION update_last_update_column();
-- =============================================================================
-- EVENT Table
-- (Create before tables that reference it, like EVENT_USERS)
-- =============================================================================
CREATE TABLE event (
id SERIAL PRIMARY KEY, -- Using SERIAL for auto-incrementing integer ID
name VARCHAR(255) NOT NULL, -- Assuming a reasonable default length if not specified
location VARCHAR(255), -- Assuming a reasonable default length
start_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
end_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
CONSTRAINT chk_event_times CHECK (end_time >= start_time) -- Ensures end_time is not before start_time
);
COMMENT ON TABLE event IS 'Stores information about events.';
COMMENT ON COLUMN event.id IS 'Auto-incrementing primary key for events.';
-- =============================================================================
-- WEEK_STATUSES Table
-- =============================================================================
CREATE TABLE week_statuses (
user_id INTEGER NOT NULL,
start_day DATE NOT NULL, -- Using DATE as it's a "start_day" implies no time component needed.
-- If time is needed, use TIMESTAMP WITHOUT TIME ZONE.
status BYTEA, -- For BLOB data. The 48*7=336 is a good note for application logic.
PRIMARY KEY (user_id, start_day),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE
-- ON DELETE CASCADE: If a user is deleted, their week statuses are also deleted.
-- ON UPDATE CASCADE: If a user's ID changes (unlikely for a PK), update here.
);
COMMENT ON TABLE week_statuses IS 'Stores weekly status information for users.';
COMMENT ON COLUMN week_statuses.start_day IS 'The first day (e.g., Monday) of the week this status applies to.';
COMMENT ON COLUMN week_statuses.status IS 'Binary status data, expected to be 336 bytes (48*7).';
-- =============================================================================
-- EVENT_USERS Table (Junction Table)
-- =============================================================================
CREATE TABLE event_users (
event_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (event_id, user_id),
FOREIGN KEY (event_id) REFERENCES event(id) ON DELETE CASCADE ON UPDATE CASCADE,
-- ON DELETE CASCADE: If an event is deleted, its user associations are removed.
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE
-- ON DELETE CASCADE: If a user is deleted, their event associations are removed.
);
COMMENT ON TABLE event_users IS 'Junction table linking users to events they are associated with (e.g., attending).';
-- =============================================================================
-- Optional: Indexes for Foreign Keys (often beneficial for performance)
-- PostgreSQL automatically creates indexes for PRIMARY KEY and UNIQUE constraints.
-- For foreign keys, it's often good to add them manually if they aren't already part of a composite PK.
-- In this schema:
-- - week_statuses.user_id is part of its PK.
-- - event_users.event_id is part of its PK.
-- - event_users.user_id is part of its PK.
-- So, explicit indexes on FK columns might not be strictly necessary here unless specific query patterns demand it.
-- Example of an index you might add if you frequently query users by name:
-- CREATE INDEX IF NOT EXISTS idx_users_name ON users(name);
-- Example of an index for events by start time:
-- CREATE INDEX IF NOT EXISTS idx_event_start_time ON event(start_time);
-- =============================================================================
-- To connect to a specific database (e.g., 'mydatabase') after creating it:
-- \c mydatabase
-- To list tables:
-- \dt
-- To describe a table (e.g., users):
-- \d users
Explanation and Key Decisions:
USERS Table:
id INTEGER PRIMARY KEY: As per your comment "we edit this manually?", I've used INTEGER and not SERIAL. This means you are responsible for providing unique IDs when inserting users. If you prefer auto-incrementing IDs, change INTEGER PRIMARY KEY to SERIAL PRIMARY KEY.
last_update TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP: This sets the last_update to the current time when a new user is inserted.
Trigger for last_update: I've added a standard PostgreSQL trigger (update_last_update_column function and users_last_update_trigger) to automatically update the last_update field whenever a row in the users table is updated.
WEEK_STATUSES Table:
user_id INTEGER NOT NULL: Foreign key to users.id.
start_day DATE NOT NULL: I've used DATE because "start_day" implies it's just the date (e.g., the Monday of a week). If you need to store the time component as well, change this to TIMESTAMP WITHOUT TIME ZONE.
status BYTEA: This is PostgreSQL's type for binary large objects (BLOBs). The length constraint (336 bytes) isn't enforced by BYTEA itself in the schema definition but should be handled by your application logic.
FOREIGN KEY ... ON DELETE CASCADE ON UPDATE CASCADE: If a referenced user is deleted, their corresponding week statuses are also deleted. If a user's ID is updated (less common for PKs), it's reflected here.
EVENT Table:
id SERIAL PRIMARY KEY: SERIAL creates an auto-incrementing integer, which is common for primary keys.
name VARCHAR(255) and location VARCHAR(255): Used VARCHAR(255) as a common default length. Adjust if needed.
start_time, end_time TIMESTAMP WITHOUT TIME ZONE: Standard for date and time.
CONSTRAINT chk_event_times CHECK (end_time >= start_time): A useful check constraint to ensure data integrity.
Table:
How to use this:
Create a Database (if you haven't already):
sql
CREATE DATABASE my_app_db;
Connect to your Database:
Using psql command-line tool:
bash
psql -U your_postgres_user -d my_app_db
Or using a GUI tool like pgAdmin or DBeaver.
Run the SQL Script:
Copy and paste the entire SQL code block above into your psql session or SQL editor connected to my_app_db and execute it.
This will set up the tables and relationships as you've described.
User
can you make this specific to supabase?
Assistant
Okay, making this specific to Supabase involves a few considerations, primarily around:
Authentication (auth.users): Supabase has a built-in auth.users table. Your USERS table might be a "profile" table linked to auth.users, or it might be an entirely separate concept. The "we edit this manually?" for USERS.id is unusual if it's tied to Supabase auth. I'll provide the schema as requested but add notes on how you might integrate with auth.users.
Row Level Security (RLS): This is crucial in Supabase for securing your data. You'll need to define RLS policies.
Timestamps: Supabase often uses TIMESTAMPTZ (timestamp with time zone) and defaults like now() or current_timestamp. Your datetime maps to TIMESTAMP WITHOUT TIME ZONE. I'll stick to your specification but note this.
UUIDs: While your schema uses INTEGER or SERIAL for IDs, Supabase often encourages UUIDs, especially for tables linked to auth.users (whose id is a UUID).
Here's the SQL, suitable for the Supabase SQL Editor, with Supabase-specific considerations:
sql
User
we're deliberately making all data public, so there's no need for auth
Assistant
Okay, if all data is intended to be publicly accessible and modifiable via the API without any user-specific authentication or authorization checks, the RLS policies become very permissive.
Here's the Supabase SQL schema tailored for this "fully public" scenario:
sql
User
can i disable editing on the users table for everyone except the admin?
Assistant
Okay, let's adjust the RLS policies for the users table to make it read-only for everyone except "admins," while keeping other tables fully public for reads and writes.
To define an "admin," we need a way to identify them. A common method in Supabase is to use custom claims in the JWT. Let's assume you have a way to set a custom claim like is_admin: true in the app_metadata or user_metadata of an authenticated admin user.
If you don't have JWT claims for roles, another common method is to have a separate table (e.g., admin_users) that lists the auth.uid() of users who are admins, and your RLS policy would check against that table. For simplicity, I'll demonstrate with a JWT claim.
Assumed Admin Identification:
We'll assume an admin user has a JWT claim app_metadata.is_admin = true. You can access this in RLS policies using (auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE.
Here's the updated SQL:
sql
User
will this query work as a supabase migration?
Assistant
Yes, the SQL code you've provided is well-structured and uses standard PostgreSQL syntax that will work perfectly as a Supabase migration file.
Here's how you would typically use it with the Supabase CLI and some best practices:
How to Use as a Supabase Migration:
Ensure Supabase CLI is Installed and Project is Linked:
If you haven't already, install the Supabase CLI: npm install supabase --save-dev (or globally).
Log in: supabase login
Link your project: supabase link --project-ref <your-project-ref> (get <your-project-ref> from your Supabase project's dashboard URL).
Create a New Migration File:
In your project's root directory (where your supabase folder is), run:
bash
supabase migration new initial_schema_setup
(You can replace initial_schema_setup with any descriptive name for your migration).
This will create a new SQL file in the supabase/migrations/ directory, typically named something like YYYYMMDDHHMMSS_initial_schema_setup.sql.
Paste Your SQL Code:
Open the newly created .sql file.
Delete any boilerplate content that might be in it.
Paste the entire SQL script you provided (the one that creates tables, the trigger, and RLS policies) into this file.
Save the file.
Apply the Migration (Locally - Recommended First):
If you're running Supabase locally (supabase start):
bash
supabase migration up
This will apply the migration to your local Supabase instance. Check your local Supabase Studio (usually at http://localhost:54323) or connect with a PSQL client to verify the tables, trigger, and RLS policies are created correctly.
Deploy the Migration (to Linked Supabase Project):
Once you've tested it locally and are satisfied:
bash
supabase db push
This command pushes unapplied local migrations to your linked Supabase cloud project.
FOREIGN KEY ... ON DELETE CASCADE ON UPDATE CASCADE: Similar to WEEK_STATUSES, ensures referential integrity.
-- Supabase Schema
-- Run this in your Supabase project's SQL Editor
-- (Database > SQL Editor > New Query)
-- =============================================================================
-- USERS Table
-- "we edit this manually?" for id. This is unusual if linking to Supabase auth.
-- If this IS for Supabase authenticated users, consider making it a `profiles`
-- table with an `id UUID PRIMARY KEY REFERENCES auth.users(id)`.
-- For now, creating as per your specific request.
-- =============================================================================
CREATE TABLE public.users (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
last_update TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Add a comment to clarify the manual ID management
COMMENT ON TABLE public.users IS 'Stores user information. ID is manually managed as per specification. If for authenticated users, consider linking to auth.users and using UUIDs.';
COMMENT ON COLUMN public.users.id IS 'Primary key, managed manually. For Supabase auth integration, this would typically be a UUID referencing auth.users.id.';
-- Trigger to automatically update `last_update` on any row update
CREATE OR REPLACE FUNCTION public.handle_user_update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.last_update = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER; -- SECURITY DEFINER is often used in Supabase for triggers
CREATE TRIGGER on_user_update
BEFORE UPDATE ON public.users
FOR EACH ROW
EXECUTE FUNCTION public.handle_user_update_timestamp();
-- =============================================================================
-- EVENT Table
-- =============================================================================
CREATE TABLE public.event (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
location VARCHAR(255),
start_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
end_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
-- Optional: Consider adding a created_at timestamp, common in Supabase
-- created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()) NOT NULL,
CONSTRAINT chk_event_times CHECK (end_time >= start_time)
);
COMMENT ON TABLE public.event IS 'Stores information about events.';
COMMENT ON COLUMN public.event.id IS 'Auto-incrementing primary key for events.';
-- =============================================================================
-- WEEK_STATUSES Table
-- =============================================================================
CREATE TABLE public.week_statuses (
user_id INTEGER NOT NULL,
start_day DATE NOT NULL, -- DATE is appropriate for a "day"
status BYTEA, -- For BLOB data (336 bytes)
-- Optional: Consider adding a created_at/updated_at timestamp
-- created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()) NOT NULL,
PRIMARY KEY (user_id, start_day),
FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE CASCADE
);
COMMENT ON TABLE public.week_statuses IS 'Stores weekly status information for users.';
COMMENT ON COLUMN public.week_statuses.start_day IS 'The first day (e.g., Monday) of the week this status applies to.';
COMMENT ON COLUMN public.week_statuses.status IS 'Binary status data, expected by application to be 336 bytes.';
-- =============================================================================
-- EVENT_USERS Table (Junction Table)
-- =============================================================================
CREATE TABLE public.event_users (
event_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
-- Optional: Consider adding a timestamp for when the user joined the event
-- joined_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()) NOT NULL,
PRIMARY KEY (event_id, user_id),
FOREIGN KEY (event_id) REFERENCES public.event(id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE CASCADE
);
COMMENT ON TABLE public.event_users IS 'Junction table linking users to events.';
-- =============================================================================
-- IMPORTANT: ROW LEVEL SECURITY (RLS)
-- By default, tables in Supabase are NOT accessible via the API unless RLS is enabled
-- AND policies are defined.
-- Below are EXAMPLES. You'll need to tailor them to your app's logic.
-- =============================================================================
-- Enable RLS for all tables
ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.week_statuses ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_users ENABLE ROW LEVEL SECURITY;
-- EXAMPLE RLS POLICIES (ADAPT THESE TO YOUR NEEDS!)
-- For USERS table:
-- Option 1: If `users` is a public profile anyone can read, but only the user (or admin) can update.
-- This assumes `users.id` could somehow be linked to an authenticated user, which is tricky with manual INTEGER IDs.
-- If `users.id` directly mapped to `auth.uid()`, it would be: `USING (id = auth.uid())`
-- Given the current schema, a policy might be based on `name` or an admin role, which is less typical.
-- For simplicity, let's assume for now a very open or very restricted policy, as linking `users.id` to `auth.uid()` is not direct.
-- Policy: Allow authenticated users to read all users (example, adjust)
-- CREATE POLICY "Allow authenticated read access to users"
-- ON public.users FOR SELECT
-- TO authenticated
-- USING (true);
-- Policy: Allow users to update their own record (NEEDS A WAY TO IDENTIFY "OWNER")
-- This is where the manual `INTEGER id` for `users` becomes difficult with Supabase auth.
-- If you had a `user_auth_id UUID` column in `users` referencing `auth.users.id`:
-- CREATE POLICY "Allow individual user update access"
-- ON public.users FOR UPDATE
-- TO authenticated
-- USING (user_auth_id = auth.uid())
-- WITH CHECK (user_auth_id = auth.uid());
-- For EVENT table:
CREATE POLICY "Allow authenticated read access to events"
ON public.event FOR SELECT
TO authenticated
USING (true);
CREATE POLICY "Allow admin or specific role to insert events" -- Placeholder for your logic
ON public.event FOR INSERT
TO authenticated -- Or a specific role
WITH CHECK (true); -- Add your actual conditions, e.g., check for an 'admin' role
CREATE POLICY "Allow admin or specific role to update events" -- Placeholder for your logic
ON public.event FOR UPDATE
TO authenticated -- Or a specific role
USING (true) -- Add your actual conditions
WITH CHECK (true); -- Add your actual conditions
CREATE POLICY "Allow admin or specific role to delete events" -- Placeholder for your logic
ON public.event FOR DELETE
TO authenticated -- Or a specific role
USING (true); -- Add your actual conditions
-- For WEEK_STATUSES table:
-- Users can manage their own week statuses.
-- This assumes `week_statuses.user_id` can be matched to the authenticated user.
-- Again, tricky with the current `users.id` being a manual INTEGER.
-- IF `users.id` was linked to `auth.users.id` (e.g., `users.id` was a UUID FK to `auth.users`),
-- and `week_statuses.user_id` referred to that `users.id`, then:
-- CREATE POLICY "Allow individual access to own week_statuses"
-- ON public.week_statuses FOR ALL
-- TO authenticated
-- USING (user_id = (SELECT id FROM public.users WHERE auth_id_column = auth.uid())) -- Hypothetical auth_id_column
-- WITH CHECK (user_id = (SELECT id FROM public.users WHERE auth_id_column = auth.uid()));
-- A simpler (but less secure if users.id isn't well-managed) policy if direct auth linking is not set up:
CREATE POLICY "Allow users to manage their own week_statuses based on user_id"
ON public.week_statuses FOR ALL
TO authenticated
USING (EXISTS (SELECT 1 FROM public.users u WHERE u.id = week_statuses.user_id /* AND u.some_auth_identifier = auth.uid() */)) -- The comment part is key for true ownership
WITH CHECK (EXISTS (SELECT 1 FROM public.users u WHERE u.id = week_statuses.user_id /* AND u.some_auth_identifier = auth.uid() */));
-- For EVENT_USERS table:
-- Users can see their own event associations. Event organizers might add/remove.
CREATE POLICY "Allow users to see their event participation"
ON public.event_users FOR SELECT
TO authenticated
USING (EXISTS (SELECT 1 FROM public.users u WHERE u.id = event_users.user_id /* AND u.some_auth_identifier = auth.uid() */));
CREATE POLICY "Allow authenticated users to join/leave events (basic)"
ON public.event_users FOR INSERT
TO authenticated
WITH CHECK (EXISTS (SELECT 1 FROM public.users u WHERE u.id = event_users.user_id /* AND u.some_auth_identifier = auth.uid() */));
CREATE POLICY "Allow users to remove themselves from events"
ON public.event_users FOR DELETE
TO authenticated
USING (EXISTS (SELECT 1 FROM public.users u WHERE u.id = event_users.user_id /* AND u.some_auth_identifier = auth.uid() */));
-- =============================================================================
-- Notes on Supabase Integration:
-- =============================================================================
-- 1. `auth.users` Table:
-- Supabase has `auth.users` for authentication. Its `id` is a `UUID`.
-- If your `public.users` table is meant to store profiles for these authenticated users,
-- it's highly recommended to:
-- a. Rename `public.users` to something like `public.profiles`.
-- b. Change `profiles.id` to `id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE`.
-- c. Remove the manual ID management and the `last_update` trigger (or adapt it if still needed).
-- Supabase `auth.users` has an `updated_at` field.
-- This makes RLS policies much cleaner using `auth.uid()` to check ownership.
-- 2. Timestamps:
-- Your schema uses `TIMESTAMP WITHOUT TIME ZONE`. Supabase examples often use
-- `TIMESTAMPTZ` (timestamp with time zone) with `DEFAULT timezone('utc'::text, now())`.
-- This is generally better for applications with users in different timezones.
-- Example: `created_at TIMESTAMPTZ DEFAULT timezone('utc'::text, now()) NOT NULL`.
-- 3. UUIDs for Primary Keys:
-- For tables like `event`, using `UUID` for `id` (e.g., `id UUID PRIMARY KEY DEFAULT gen_random_uuid()`)
-- can be beneficial, especially if IDs are generated client-side or for better global uniqueness.
-- This requires enabling the `pgcrypto` extension if not already (Supabase usually has it):
-- `CREATE EXTENSION IF NOT EXISTS "pgcrypto" WITH SCHEMA public;` (Run this once per project if needed)
-- 4. RLS Policies are CRITICAL:
-- The example RLS policies above are just starting points.
-- You MUST define policies that accurately reflect who should access/modify what.
-- Without RLS enabled and proper policies, your tables might be fully open or fully closed via the API.
-- Test your RLS policies thoroughly.
Key Supabase-Specific Changes and Considerations:
Schema Qualification: All tables are created in the public schema (e.g., public.users). This is standard.
auth.users and public.users:
I've kept your public.users table with its manual INTEGER ID as requested.
Crucially, I've added extensive comments explaining that if this table is for users who authenticate via Supabase, it should ideally be a profiles table linked to auth.users.id (which is a UUID). This would simplify RLS significantly. The current structure makes owner-based RLS on USERS and related tables more complex.
Timestamp Trigger: The trigger function handle_user_update_timestamp uses SECURITY DEFINER. This is a common practice in Supabase for trigger functions that modify data, though its necessity depends on the exact privileges.
Row Level Security (RLS):
Enabled RLS:ALTER TABLE ... ENABLE ROW LEVEL SECURITY; is added for all tables.
Example Policies: I've provided basic RLS policy examples. These are critical and you MUST customize them.
The policies highlight the difficulty of linking actions to auth.uid() when public.users.id is a manual integer not directly tied to auth.users.id. I've included commented-out parts showing how it would look if users.id (or an alternative column) was linked to auth.uid().
Policies generally grant access TO authenticated users. You might also have policies for TO anon (anonymous users) or specific roles.
Notes Section: Added a comprehensive notes section at the end re-iterating the points about auth.users integration, TIMESTAMPTZ, UUIDs, and the importance of RLS.
To Use This:
Go to your Supabase project dashboard.
Navigate to SQL Editor (under the "Database" section).
Click "New query".
Paste the entire SQL script into the editor.
Click "RUN".
After running, immediately focus on defining and testing your RLS policies to secure your data according to your application's access rules. The current RLS examples are very basic and likely need significant adjustment.
-- Supabase Schema - ALL DATA PUBLIC
-- Run this in your Supabase project's SQL Editor
-- (Database > SQL Editor > New Query)
-- =============================================================================
-- USERS Table
-- ID is manually managed.
-- =============================================================================
CREATE TABLE public.users (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
last_update TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
COMMENT ON TABLE public.users IS 'Stores user information. All data is public. ID is manually managed.';
-- Trigger to automatically update `last_update` on any row update
CREATE OR REPLACE FUNCTION public.handle_user_update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.last_update = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER; -- Using SECURITY DEFINER is a common Supabase pattern for triggers
CREATE TRIGGER on_user_update
BEFORE UPDATE ON public.users
FOR EACH ROW
EXECUTE FUNCTION public.handle_user_update_timestamp();
-- =============================================================================
-- EVENT Table
-- =============================================================================
CREATE TABLE public.event (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
location VARCHAR(255),
start_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
end_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
CONSTRAINT chk_event_times CHECK (end_time >= start_time)
);
COMMENT ON TABLE public.event IS 'Stores information about events. All data is public.';
-- =============================================================================
-- WEEK_STATUSES Table
-- =============================================================================
CREATE TABLE public.week_statuses (
user_id INTEGER NOT NULL,
start_day DATE NOT NULL,
status BYTEA,
PRIMARY KEY (user_id, start_day),
FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE CASCADE
);
COMMENT ON TABLE public.week_statuses IS 'Stores weekly status information for users. All data is public.';
COMMENT ON COLUMN public.week_statuses.status IS 'Binary status data, expected by application to be 336 bytes.';
-- =============================================================================
-- EVENT_USERS Table (Junction Table)
-- =============================================================================
CREATE TABLE public.event_users (
event_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (event_id, user_id),
FOREIGN KEY (event_id) REFERENCES public.event(id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE CASCADE
);
COMMENT ON TABLE public.event_users IS 'Junction table linking users to events. All data is public.';
-- =============================================================================
-- ROW LEVEL SECURITY (RLS) - CONFIGURED FOR FULLY PUBLIC ACCESS
-- =============================================================================
-- IMPORTANT: By enabling RLS and using the policies below,
-- you are making all data in these tables readable AND MODIFIABLE
-- by ANYONE (anonymous or authenticated) through the Supabase API.
-- Ensure this is your intended behavior.
-- Enable RLS for all tables (required for API access, even if public)
ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.week_statuses ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_users ENABLE ROW LEVEL SECURITY;
-- RLS POLICIES FOR FULLY PUBLIC ACCESS (READ AND WRITE)
-- For USERS table:
CREATE POLICY "Allow public full access to users"
ON public.users FOR ALL -- ALL means SELECT, INSERT, UPDATE, DELETE
TO anon, authenticated -- Grant to anonymous and any authenticated user
USING (true) -- Condition for which rows are affected (true = all rows)
WITH CHECK (true); -- Condition for INSERT/UPDATE (true = allow all)
-- For EVENT table:
CREATE POLICY "Allow public full access to events"
ON public.event FOR ALL
TO anon, authenticated
USING (true)
WITH CHECK (true);
-- For WEEK_STATUSES table:
CREATE POLICY "Allow public full access to week_statuses"
ON public.week_statuses FOR ALL
TO anon, authenticated
USING (true)
WITH CHECK (true);
-- For EVENT_USERS table:
CREATE POLICY "Allow public full access to event_users"
ON public.event_users FOR ALL
TO anon, authenticated
USING (true)
WITH CHECK (true);
-- =============================================================================
-- Final Considerations for "Fully Public"
-- =============================================================================
-- 1. Data Modification: With `FOR ALL ... USING (true) WITH CHECK (true)` policies
-- for `anon` and `authenticated` roles, anyone who can reach your Supabase API
-- endpoint can read, insert, update, and delete data in these tables.
-- If you only want public READ access, change `FOR ALL` to `FOR SELECT`.
-- Example for public read-only:
-- CREATE POLICY "Allow public read access to users"
-- ON public.users FOR SELECT
-- TO anon, authenticated
-- USING (true);
-- (And you would then need separate, more restrictive policies for INSERT, UPDATE, DELETE,
-- or handle modifications outside the public API, e.g., directly in the database
-- or via a backend service with its own authentication).
-- 2. "Edit Manually" for USERS.id: Since the `users.id` is manual, whoever
-- inserts users (whether via API or directly) is responsible for ensuring its uniqueness
-- as it's the PRIMARY KEY.
-- 3. Rate Limiting/Abuse: For a truly public and writable API, consider implementing
-- rate limiting or other abuse prevention mechanisms at a higher level (e.g., API gateway,
-- Supabase's built-in limits, or custom logic if needed) if you anticipate high traffic
-- or potential misuse.
Key Changes for "Fully Public":
No Auth-Specific Logic: All references to auth.users, auth.uid(), or user-specific ownership in RLS have been removed.
RLS Policies:
RLS is still enabled on all tables. This is necessary for Supabase to allow API access to them.
The policies are now FOR ALL (meaning SELECT, INSERT, UPDATE, DELETE) and granted TO anon, authenticated with USING (true) and WITH CHECK (true).
TO anon: Allows access for unauthenticated API requests.
TO authenticated: Allows access for any authenticated API requests (even if the authentication isn't used for specific row-level checks).
USING (true): For SELECT, UPDATE, DELETE, this means the policy applies to all rows.
WITH CHECK (true): For INSERT, UPDATE, this means any data is allowed to be written (no additional validation at the RLS policy level).
Comments: Updated comments to reflect the public nature of the data.
Final Considerations: Added a section highlighting the implications of fully public writable data and suggesting FOR SELECT if only public read is desired.
How to Use:
Go to your Supabase project dashboard.
Navigate to SQL Editor.
Click "New query".
Paste the entire SQL script.
Click "RUN".
VERY IMPORTANT WARNING:
The RLS policies above make your data completely open for anyone to read and modify via your Supabase API. Ensure this is truly what you intend. If you only want public read access, and modifications should be restricted, you should change FOR ALL to FOR SELECT in the policies, and then handle inserts/updates/deletes through other means (e.g., database console, a secured backend function, or more restrictive RLS policies for specific roles if you introduce them later).
-- Supabase Schema - USERS table editable only by ADMINS, others public
-- Run this in your Supabase project's SQL Editor
-- =============================================================================
-- USERS Table
-- ID is manually managed.
-- =============================================================================
CREATE TABLE public.users (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
last_update TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
COMMENT ON TABLE public.users IS 'Stores user information. Publicly readable. Editable only by admins. ID is manually managed.';
-- Trigger to automatically update `last_update` on any row update
CREATE OR REPLACE FUNCTION public.handle_user_update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.last_update = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER on_user_update
BEFORE UPDATE ON public.users
FOR EACH ROW
EXECUTE FUNCTION public.handle_user_update_timestamp();
-- =============================================================================
-- EVENT Table
-- =============================================================================
CREATE TABLE public.event (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
location VARCHAR(255),
start_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
end_time TIMESTAMP WITHOUT TIME ZONE NOT NULL,
CONSTRAINT chk_event_times CHECK (end_time >= start_time)
);
COMMENT ON TABLE public.event IS 'Stores information about events. All data is public.';
-- =============================================================================
-- WEEK_STATUSES Table
-- =============================================================================
CREATE TABLE public.week_statuses (
user_id INTEGER NOT NULL,
start_day DATE NOT NULL,
status BYTEA,
PRIMARY KEY (user_id, start_day),
FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE CASCADE
);
COMMENT ON TABLE public.week_statuses IS 'Stores weekly status information for users. All data is public.';
COMMENT ON COLUMN public.week_statuses.status IS 'Binary status data, expected by application to be 336 bytes.';
-- =============================================================================
-- EVENT_USERS Table (Junction Table)
-- =============================================================================
CREATE TABLE public.event_users (
event_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (event_id, user_id),
FOREIGN KEY (event_id) REFERENCES public.event(id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE CASCADE
);
COMMENT ON TABLE public.event_users IS 'Junction table linking users to events. All data is public.';
-- =============================================================================
-- ROW LEVEL SECURITY (RLS)
-- =============================================================================
-- Enable RLS for all tables
ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.week_statuses ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_users ENABLE ROW LEVEL SECURITY;
-------------------------------------------------------------------------------
-- RLS POLICIES FOR public.users
-------------------------------------------------------------------------------
-- Policy 1: Allow public read access to users table for everyone
CREATE POLICY "Allow public read access to users"
ON public.users FOR SELECT
TO anon, authenticated -- Grant to anonymous and any authenticated user
USING (true); -- Condition for which rows are visible (true = all rows)
-- Policy 2: Allow admin users to INSERT into the users table
-- Assumes admin users have a JWT claim: app_metadata.is_admin = true
CREATE POLICY "Allow admin insert access to users"
ON public.users FOR INSERT
TO authenticated -- Only authenticated users can potentially be admins
WITH CHECK (
(auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE
);
-- Policy 3: Allow admin users to UPDATE the users table
CREATE POLICY "Allow admin update access to users"
ON public.users FOR UPDATE
TO authenticated
USING ( -- This determines which rows can be updated by the policy
(auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE
)
WITH CHECK ( -- This validates the new/updated row data
(auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE
);
-- Policy 4: Allow admin users to DELETE from the users table
CREATE POLICY "Allow admin delete access to users"
ON public.users FOR DELETE
TO authenticated
USING (
(auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE
);
-------------------------------------------------------------------------------
-- RLS POLICIES FOR OTHER TABLES (Fully Public Read/Write)
-------------------------------------------------------------------------------
-- For EVENT table:
CREATE POLICY "Allow public full access to events"
ON public.event FOR ALL
TO anon, authenticated
USING (true)
WITH CHECK (true);
-- For WEEK_STATUSES table:
CREATE POLICY "Allow public full access to week_statuses"
ON public.week_statuses FOR ALL
TO anon, authenticated
USING (true)
WITH CHECK (true);
-- For EVENT_USERS table:
CREATE POLICY "Allow public full access to event_users"
ON public.event_users FOR ALL
TO anon, authenticated
USING (true)
WITH CHECK (true);
-- =============================================================================
-- Notes on Admin Identification:
-- =============================================================================
-- The policies for INSERT, UPDATE, DELETE on `public.users` rely on a JWT claim:
-- `(auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE`
--
-- To make this work:
-- 1. When an admin user is created or promoted, you need to set this custom claim
-- in their `app_metadata`. This can be done:
-- a. Via a Supabase Edge Function (e.g., an "on user create" Auth Hook).
-- b. Using the Supabase Management API (requires `service_role` key).
-- c. Manually via the Supabase Dashboard (Authentication -> Users -> Edit User -> User Metadata).
-- User Metadata is fine too, just change `app_metadata` to `user_metadata` in policies.
-- `app_metadata` is generally preferred for roles as users cannot modify it themselves.
--
-- Alternative Admin Check (using a separate admin table):
-- If you prefer not to use JWT claims, you could create an `admins` table:
-- CREATE TABLE public.admins (user_id UUID PRIMARY KEY REFERENCES auth.users(id));
-- And then your RLS check would be:
-- EXISTS (SELECT 1 FROM public.admins WHERE user_id = auth.uid())
-- This requires admins to be actual Supabase authenticated users.
--
-- Service Role Key:
-- Remember, if you (or a backend process) use the `service_role` key to interact
-- with the database, RLS policies are bypassed. These RLS policies are for controlling
-- access via the public API (e.g., from a frontend client or an API consumer
-- using an `anon` or user-specific JWT).
Explanation of Changes for users Table RLS:
ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;: Still essential.
Public Read Policy:
sql
CREATE POLICY "Allow public read access to users"
ON public.users FOR SELECT
TO anon, authenticated
USING (true);
This allows anyone (anonymous or any authenticated user) to SELECT (read) all rows from the users table.
Admin Insert Policy:
sql
CREATE POLICY "Allow admin insert access to users"
ON public.users FOR INSERT
TO authenticated
WITH CHECK (
(auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE
);
FOR INSERT: This policy applies to INSERT operations.
TO authenticated: Inserts can only be attempted by authenticated users (as anonymous users won't have the is_admin JWT claim).
WITH CHECK (...): This condition must be true for the INSERT to be allowed. It checks if the JWT of the authenticated user making the request has app_metadata.is_admin set to true.
Admin Update Policy:
sql
CREATE POLICY "Allow admin update access to users"
ON public.users FOR UPDATE
TO authenticated
USING ( (auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE )
WITH CHECK ( (auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE );
FOR UPDATE: Applies to UPDATE operations.
TO authenticated: Updates can only be attempted by authenticated users.
USING (...): This clause defines which existing rows this policy applies to for an update operation. If the user is an admin, this policy applies to all rows for them to potentially update.
WITH CHECK (...): This clause validates the new data being written during an update. In this case, it re-confirms the user is an admin. For simple "admin can update anything" scenarios, USING and WITH CHECK often have the same condition.
Admin Delete Policy:
sql
CREATE POLICY "Allow admin delete access to users"
ON public.users FOR DELETE
TO authenticated
USING (
(auth.jwt() -> 'app_metadata' ->> 'is_admin')::boolean IS TRUE
);
FOR DELETE: Applies to DELETE operations.
TO authenticated: Deletes can only be attempted by authenticated users.
USING (...): This condition must be true for the DELETE to be allowed on a row. It checks if the user is an admin.
How Admins Will Work:
An "admin" user will need to authenticate with Supabase.
Their JWT token must contain the is_admin: true claim within app_metadata (or user_metadata if you prefer, just adjust the policy).
When this admin user makes API requests to INSERT, UPDATE, or DELETE data in the public.users table, these policies will allow the operations.
Any other user (anonymous or authenticated non-admin) will only be able to SELECT data from public.users. Attempts to modify will be denied by RLS.
The other tables (event, week_statuses, event_users) remain fully public for read and write operations by anyone, as per your previous requirement.
Alternatively, and often preferred for CI/CD or direct production deploys (if you are not using db push):
Commit your supabase/migrations folder to your Git repository. Your CI/CD pipeline (or you manually) would then run supabase migration up against the target environment after pulling the latest changes. This is generally safer as db push can sometimes have issues if the remote schema has diverged significantly in ways not captured by local migrations. supabase migration up only applies pending migrations.
Important Considerations for Supabase Migrations:
Idempotency:
Your CREATE TABLE statements will fail if the tables already exist. This is fine for an initial setup. If you were modifying existing tables, you'd use ALTER TABLE.
CREATE OR REPLACE FUNCTION is idempotent.
CREATE TRIGGER will fail if a trigger with the same name already exists on the table. For an initial setup, this is fine.
ALTER TABLE ... ENABLE ROW LEVEL SECURITY is idempotent.
CREATE POLICY will fail if a policy with the same name already exists on the table. Fine for initial setup.
Order: The order of statements in your SQL script is correct (e.g., tables are created before foreign keys or RLS policies reference them).
Permissions for auth.jwt(): The use of auth.jwt() in RLS policies is standard Supabase practice and works out of the box.
SECURITY DEFINER for Triggers: Using SECURITY DEFINER for the trigger function (public.handle_user_update_timestamp) is a common and often necessary practice in Supabase if the trigger needs to perform actions that the invoking user might not have direct permission for (though in this case, it's just updating a timestamp on the same row, so SECURITY INVOKER might also work, but DEFINER is safer and more common in Supabase examples).
Admin Claim Setup: Remember that the RLS policies for admin access to the users table rely on the JWT claim app_metadata.is_admin = true being correctly set for your admin users. This setup is external to this migration (e.g., done via an Auth Hook, Supabase Management API, or manually in the dashboard).
In summary: Yes, your SQL is migration-ready. Follow the Supabase CLI workflow to incorporate it into your project's migration history.