Database Design Before AI Code Generation
Decide who owns each row, which rules the database enforces and how the schema will change before an AI tool writes the first query.
6 min read / Updated / Last checked
- Format
- Guide · Intermediate
- Who it is for
- Founders and the builders they hire
- You leave with
- Write a schema with owner columns, constraints, row policies and a migration rule that AI-generated code cannot bypass.
The problem
On March 20, 2025, security researcher Matt Palmer found that a site built with Lovable let anyone read and write its database tables directly. He then scanned 1,645 projects from Lovable's public showcase. 170 of them, about 10.3%, exposed data through 303 vulnerable endpoints: user emails, phone numbers, payment details and API keys. On one site the researchers inserted a record marked as paid and skipped the payment [1]. The issue became CVE-2025-48757, scored 9.3 out of 10 under CVSS 3.1. Lovable disputes it on the grounds that each customer is responsible for protecting its own app's data [2].
The cause was not exotic. The apps queried Supabase directly from the browser, and the row level security (RLS) policies that decide which rows a caller may touch were missing or did not match the app's logic [1]. Palmer adds that a scanner which only checks whether a policy exists gives false comfort, because it cannot tell whether the policy is right [1].
That is a database design failure, and it starts before any code is written. An AI code generator builds whatever data model makes the current screen work. Who owns a row, which values are valid, what must never happen twice and how the schema will change later are product decisions. When nobody makes them first, the generated code makes them by accident, and differently on every prompt.
How it works
Database design before code generation means writing four decisions down and putting them into the database itself. Every client, script and AI-generated endpoint then has to pass through them, whether or not it remembers to.
- Entities and owners. List the nouns of the product (tenant, user, resource, booking) and, for every table, the column that says who owns a row. In a business app that is usually
tenant_id, the account the row belongs to. A row without an owner column cannot be protected by any policy. - Constraints. A constraint is a rule the database refuses to break. The PostgreSQL documentation gives the reason plainly: a data type is too coarse, because no standard type accepts only positive prices [3].
NOT NULL,CHECK,UNIQUEand foreign keys cover facts that must always hold. An exclusion constraint covers "no two rows may overlap," which is exactly a double booking [3]. - Row policies. RLS attaches a filter to a table so a query only sees and writes the rows its caller owns. Once RLS is enabled on a table with no policy, PostgreSQL denies every row by default [4]. Two exceptions matter. Table owners normally bypass policies unless the table is set to
FORCE ROW LEVEL SECURITY, and superusers and roles withBYPASSRLSalways bypass them [4]. Supabase states the rule for its platform: enable RLS on every table in an exposed schema, and keep theservice_rolekey on the server because it bypasses RLS [5]. - Migrations. A migration is a versioned script that changes the schema. It lives in the repository and goes through review like any other code, never as a change typed into a database console from a chat. For changes to tables that already hold data, use expand and contract: add the new shape next to the old one, move every client to it, then remove the old shape [6].
Only after these four are in a schema file does the AI tool get its prompt: here is the schema, write the queries for this screen against it. The model now fills in code inside rules it cannot change, instead of inventing the rules as it goes.
Design order for an AI-built data layer
Fig. 01- Entitiesnouns and their owners
- Constraintsfacts that always hold
- Row policieswho sees which rows
- Migrationsreviewed, versioned changes
- AI codegenqueries inside the rules
By the numbers
- Lovable showcase projects scanned for exposed tables in 2025 [1]
- 1,645
- of the scanned projects had missing or wrong row policies [1]
- 10.3%
- vulnerable endpoints across the 170 affected apps [1]
- 303
- CVSS 3.1 base score of CVE-2025-48757 [2]
- 9.3
- of Stack Overflow's 2025 survey respondents used PostgreSQL [7]
- 55.6%
| Rule | If enforced only in app code | If enforced in the database |
|---|---|---|
| A booking belongs to one tenant | Every endpoint must remember the filter | An RLS policy filters every query from the app role [4] |
| No double booking | Two requests can both pass the check | An exclusion constraint rejects the second row [3] |
| A price is positive | Each form validates on its own | CHECK (price > 0) on the column [3] |
| A booking points at a real resource | Deletes leave orphan rows | A foreign key with RESTRICT or CASCADE [3] |
| Browser clients query tables directly | One missing filter is a leak | No rows are visible to the public key until policies exist [5] |
The 10.3% is one sample: showcase projects of one tool in spring 2025, with only their homepages analyzed [1]. It is not a rate for all AI-built apps, and it should not be quoted as one. What it does show is the pattern. Each affected app worked in its demo, because a demo never asks for another customer's rows.
PostgreSQL appears throughout this guide because it is what most teams already run: 55.6% of Stack Overflow's 2025 respondents used it [7], and Supabase, a common backend for AI app builders, is built on it [5]. The same four decisions apply to any relational database. Only the syntax changes.
Implementation
Write schema.sql before the first prompt. The example below is for a booking product with several business customers (tenants). It runs on PostgreSQL 13 or later.
-- Every row has an owner. Every rule the business relies on is a constraint.
CREATE EXTENSION IF NOT EXISTS btree_gist; -- lets one GiST index mix = and &&
CREATE TABLE tenants (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
name text NOT NULL
);
CREATE TABLE resources (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES tenants (id) ON DELETE CASCADE,
name text NOT NULL,
UNIQUE (tenant_id, name),
UNIQUE (tenant_id, id) -- target for the composite foreign key below
);
CREATE TABLE bookings (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES tenants (id) ON DELETE CASCADE,
resource_id uuid NOT NULL,
customer_email text NOT NULL CHECK (position('@' IN customer_email) > 1),
during tstzrange NOT NULL CHECK (NOT isempty(during)),
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'confirmed', 'cancelled')),
created_at timestamptz NOT NULL DEFAULT now(),
-- A booking can only point at a resource of the same tenant.
FOREIGN KEY (tenant_id, resource_id) REFERENCES resources (tenant_id, id) ON DELETE RESTRICT,
-- No two live bookings may overlap on one resource.
EXCLUDE USING gist (resource_id WITH =, during WITH &&) WHERE (status <> 'cancelled')
);
-- Tenant isolation enforced by the database, not by the UI.
ALTER TABLE bookings ENABLE ROW LEVEL SECURITY;
ALTER TABLE bookings FORCE ROW LEVEL SECURITY; -- applies to the table owner too
CREATE POLICY tenant_isolation ON bookings
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);Three lines carry most of the protection. The composite foreign key means a booking cannot reference another tenant's resource, even if a bug passes the wrong ID. The exclusion constraint settles double bookings inside the database, where two simultaneous requests cannot both win. The policy's USING clause filters which rows a query can see, and WITH CHECK stops a write that would create a row for another tenant [4].
The API sets app.tenant_id at the start of each transaction (SET LOCAL app.tenant_id = ...) from the verified session, never from a value the browser sends. On Supabase, the equivalent policy compares the owner column to auth.uid(), as in the platform's own examples [5]. In a real product, repeat the policy on resources and every other tenant-owned table.
Then give the AI tool rules it must follow, in its project instructions file:
- Treat
schema.sqland themigrations/folder as read-only. Propose schema changes as a new migration file for review. - Never connect with the
service_rolekey or a superuser from code that a browser can reach. - Every new table gets an owner column, RLS enabled and a policy in the same migration.
- Renames and type changes use expand and contract: add the new column, backfill and write to both, switch reads, then drop the old column in a later release [6].
Test it
Run this script against a scratch database after applying schema.sql. It acts as a non-owner role, the way the API does, and expected results are in the comments. Superusers bypass RLS [4], so the seed rows go in before the role switch.
-- Run as a superuser on a scratch database after schema.sql.
CREATE ROLE app_user NOLOGIN;
GRANT SELECT, INSERT, UPDATE ON tenants, resources, bookings TO app_user;
INSERT INTO tenants (id, name) VALUES
('00000000-0000-0000-0000-00000000000a', 'Tenant A'),
('00000000-0000-0000-0000-00000000000b', 'Tenant B');
INSERT INTO resources (id, tenant_id, name) VALUES
('10000000-0000-0000-0000-00000000000a', '00000000-0000-0000-0000-00000000000a', 'Room 1'),
('10000000-0000-0000-0000-00000000000b', '00000000-0000-0000-0000-00000000000b', 'Room 1');
INSERT INTO bookings (tenant_id, resource_id, customer_email, during) VALUES
('00000000-0000-0000-0000-00000000000b', '10000000-0000-0000-0000-00000000000b',
'b@example.com', '[2026-12-01 10:00+00, 2026-12-01 11:00+00)');
SET ROLE app_user;
SET app.tenant_id = '00000000-0000-0000-0000-00000000000a';
SELECT count(*) AS visible FROM bookings; -- 1. expected 0: tenant B's row is invisible
INSERT INTO bookings (tenant_id, resource_id, customer_email, during) VALUES
('00000000-0000-0000-0000-00000000000b', '10000000-0000-0000-0000-00000000000b',
'a@example.com', '[2026-12-02 10:00+00, 2026-12-02 11:00+00)');
-- 2. expected ERROR: new row violates row-level security policy
INSERT INTO bookings (tenant_id, resource_id, customer_email, during) VALUES
('00000000-0000-0000-0000-00000000000a', '10000000-0000-0000-0000-00000000000b',
'a@example.com', '[2026-12-02 10:00+00, 2026-12-02 11:00+00)');
-- 3. expected ERROR: violates foreign key constraint (resource belongs to tenant B)
INSERT INTO bookings (tenant_id, resource_id, customer_email, during) VALUES
('00000000-0000-0000-0000-00000000000a', '10000000-0000-0000-0000-00000000000a',
'a@example.com', '[2026-12-03 10:00+00, 2026-12-03 11:00+00)'),
('00000000-0000-0000-0000-00000000000a', '10000000-0000-0000-0000-00000000000a',
'c@example.com', '[2026-12-03 10:30+00, 2026-12-03 11:30+00)');
-- 4. expected ERROR: conflicting key value violates exclusion constraint
RESET ROLE;Run it with psql -f test_isolation.sql in CI on every migration and compare the output with the comments. The job fails if check 1 returns a number above zero or if any of checks 2 to 4 succeeds. Add one more query to the same job: SELECT relname FROM pg_class WHERE relkind = 'r' AND relnamespace = 'public'::regnamespace AND NOT relrowsecurity; lists every table in the public schema without RLS. Against the example schema it returns tenants and resources, which is the reminder to give them policies too. Expected result in a finished product: no rows, or only tables on a short, reviewed allowlist.
Decision
Spend the first day of an AI-built product on the schema, not the screens. It is the cheapest point to make these choices, and the most expensive one to skip.
- Write
schema.sqlwith owner columns, constraints and RLS before prompting for features. For an early product this is a small job, and retrofitting it after launch is a large one. - Put the rules in the database. App code can add checks, but it should never be the only check.
- Make migrations the only path to schema change, for people and AI tools alike.
- Run the isolation test in CI from the first deploy. If the product is already live without it, run it this week; see Your Vibe-Coded MVP Works. Is It Safe to Launch? for the wider pre-launch review.
Sources
- [1]Statement on CVE-2025-48757 (opens in a new tab)Matt Palmer, May 2025
- [2]CVE-2025-48757 (opens in a new tab)Tenable, May 2025
- [3]Constraints, PostgreSQL 18 documentation (opens in a new tab)PostgreSQL Global Development Group, November 2026
- [4]Row Security Policies, PostgreSQL 18 documentation (opens in a new tab)PostgreSQL Global Development Group, November 2026
- [5]Row Level Security (opens in a new tab)Supabase Docs, November 2026
- [6]ParallelChange (opens in a new tab)Danilo Sato on martinfowler.com, May 2014
- [7]2025 Stack Overflow Developer Survey: Technology (opens in a new tab)Stack Overflow, July 2025
Technical guidance, not legal or security certification.
Related resources
Need a technical review of an AI-built MVP?
Discuss your build