To move a Firestore data model to Postgres, turn each top-level collection into a table and each subcollection into a child table with a foreign key to its parent. Keep document IDs as text primary keys. Arrays become array columns or join tables, maps become columns or jsonb, references become foreign keys, and Security Rules become Row Level Security policies. On WoWSQL, every table you create gets a REST API (PostgREST at /rest/v1) and works with WoWSQL Auth, so the SQL below is the whole backend change. Your client code is the part that needs rewriting.
Everything SQL in this guide ran on PostgreSQL 17.12 on 28 November 2026. The REST calls and the import script ran against a local PostgREST 16.6 server with a stand-in auth.uid() function, to check the requests. The Firestore export part (firebase-admin 14.5.1) was type-checked but not run against a real Firebase project, and nothing was run on a live WoWSQL project.
Key facts
- Firestore limits that shape your old model: a document can be at most 1 MiB (Firestore quotas), which is why many apps split data into subcollections and copy fields around. Postgres rows don't push you that way, so you can normalise.
- WoWSQL REST API: PostgREST at
https://<project>.wowsqlconnect.com/rest/v1. Send the anon key (wowsql_anon_...) inapikeyand the signed-in user's token inAuthorization: Bearerso RLS applies. The service key bypasses RLS and belongs on servers only. There is no GraphQL API.- WoWSQL Auth: email and password, magic links, email or phone OTP, OAuth with 19 working providers, TOTP two-factor, optional Cloudflare Turnstile CAPTCHA, and anonymous sign-in when you enable it (auth docs).
- Supabase's tool, for comparison: its Firestore migration scripts copy one collection into one table with
text,numeric,booleanorjsonbcolumns, and leave splitting nested data to you (Supabase guide, updated 24 September 2026).
The mapping cheat sheet
| Firestore | Postgres | Notes |
|---|---|---|
Collection posts |
Table posts |
One row per document |
| Document ID | id text primary key |
Keep the original ID so links, URLs and references still work |
Subcollection posts/{id}/comments |
Table comments with post_id references posts(id) |
on delete cascade replaces recursive deletes |
Collection group query on comments |
A normal query on comments |
Every comment is already in one table |
| Reference field | Foreign key column | The database enforces that the target exists |
Array of strings (tags) |
text[] with a GIN index |
@> replaces array-contains |
Map used as a set (likes: {uid: true}) |
Join table post_likes (post_id, user_uid) |
No more document-size worries for popular posts |
| Map you filter or sort on | Real columns | Typed, indexed, validated |
| Map you only read back | jsonb |
Query with -> and ->> when you need to |
Timestamp |
timestamptz |
Store UTC; format in the client |
Denormalised copy (authorName) |
Keep it, or join | Joins are cheap; copies are fine for display names |
FieldValue.increment() counters |
A view with count(*), or a trigger |
Start with a view; add a counter column only when you measure a need |
| Security Rules | RLS policies | One policy per operation |
onSnapshot listeners |
WoWSQL realtime (INSERT/UPDATE/DELETE events) | Enable each table for realtime first |
The example: a small social app
The Firestore side looks like this:
users/{uid}:displayName,photoURL,email, a nestedsettingsmapposts/{postId}:author(reference),authorName,title,body,tags(array),likes(map of uid totrue),createdAtposts/{postId}/comments/{commentId}:author,body,createdAt
Step 1: Decide how user IDs carry over
This is the decision most guides skip. Firebase UIDs are 28-character strings, and your Firestore documents point at them everywhere. A WoWSQL user gets a new ID when they sign up, and RLS policies compare against auth.uid().
The pattern that keeps everything intact: give every person a stable app-level uid (the old Firebase UID, or the new auth ID for people who sign up after the move), plus a nullable user_id that you fill in when they first sign in to WoWSQL. All foreign keys point at uid, so imported rows never need rewriting.
Step 2: Create the tables
create table app_users (
uid text primary key, -- Firebase UID (or the auth id for new sign-ups)
user_id uuid unique, -- WoWSQL auth user id, linked on first sign-in
email text unique,
display_name text not null,
photo_url text,
settings jsonb not null default '{}', -- nested map you never filter on
created_at timestamptz not null default now()
);
-- The signed-in user's app uid, used by every policy
create or replace function current_uid() returns text
language sql stable security definer set search_path = public
as $$ select uid from app_users where user_id = auth.uid() $$;
create table posts ( -- was posts/{postId}
id text primary key, -- Firestore auto-ID kept as-is
author_uid text not null references app_users(uid) on delete cascade,
author_name text not null, -- denormalised copy, same as in Firestore
title text not null,
body text not null,
tags text[] not null default '{}',
extra jsonb not null default '{}', -- leftover fields to type later
created_at timestamptz not null default now()
);
create index posts_author_created on posts (author_uid, created_at desc);
create index posts_tags on posts using gin (tags);
create table comments ( -- was posts/{postId}/comments/{commentId}
id text primary key,
post_id text not null references posts(id) on delete cascade,
author_uid text not null references app_users(uid) on delete cascade,
body text not null,
created_at timestamptz not null default now()
);
create index comments_post_created on comments (post_id, created_at);
create index comments_author on comments (author_uid);
create table post_likes ( -- was likes: { uid: true }
post_id text not null references posts(id) on delete cascade,
user_uid text not null references app_users(uid) on delete cascade,
created_at timestamptz not null default now(),
primary key (post_id, user_uid)
);
create view post_stats with (security_invoker = true) as
select p.id,
(select count(*) from post_likes l where l.post_id = p.id) as like_count,
(select count(*) from comments c where c.post_id = p.id) as comment_count
from posts p;
The extra jsonb column is a safety net. Firestore documents in the same collection often drift apart over the years, so anything you haven't mapped lands there instead of being dropped. Query it, see what's really in use, then promote fields to proper columns.
Step 3: Turn Security Rules into RLS
A typical rule set for posts and comments:
match /posts/{postId} {
allow read: if true;
allow create: if request.auth != null && request.resource.data.author == request.auth.uid;
allow update, delete: if request.auth.uid == resource.data.author;
match /comments/{commentId} {
allow read: if true;
allow create: if request.auth != null && request.resource.data.author == request.auth.uid;
allow delete: if request.auth.uid == resource.data.author
|| request.auth.uid == get(/databases/$(database)/documents/posts/$(postId)).data.author;
}
}
The same rules in Postgres:
alter table app_users enable row level security;
alter table posts enable row level security;
alter table comments enable row level security;
alter table post_likes enable row level security;
create policy "profiles are public" on app_users for select using (true);
create policy "edit own profile" on app_users for update using (uid = current_uid()) with check (uid = current_uid());
create policy "posts are public" on posts for select using (true);
create policy "create own posts" on posts for insert with check (author_uid = current_uid());
create policy "edit own posts" on posts for update using (author_uid = current_uid()) with check (author_uid = current_uid());
create policy "delete own posts" on posts for delete using (author_uid = current_uid());
create policy "comments are public" on comments for select using (true);
create policy "create own comments" on comments for insert with check (author_uid = current_uid());
create policy "delete own or on own post" on comments for delete using (
author_uid = current_uid()
or exists (select 1 from posts p where p.id = post_id and p.author_uid = current_uid())
);
create policy "likes are public" on post_likes for select using (true);
create policy "like as yourself" on post_likes for insert with check (user_uid = current_uid());
create policy "unlike as yourself" on post_likes for delete using (user_uid = current_uid());
In our test, a user could delete someone else's comment on her own post, got zero rows affected when deleting a comment on another user's post or editing another user's post, and got a policy error when inserting a post under someone else's uid. Note the difference from Firestore: a blocked update or delete in Postgres silently matches zero rows instead of failing, so check row counts in your client.
One big gain: the get(...) lookup in the comment rule costs a document read in Firestore. In Postgres it's an indexed exists subquery.
Step 4: Copy the data
Run this once from your machine with a Firebase service account and the WoWSQL service key. It upserts in batches of 500, so you can re-run it after fixing a mapping without creating duplicates.
// firestore-to-wowsql.ts (Node 18+)
import { initializeApp, applicationDefault } from 'firebase-admin/app'
import { getFirestore, type DocumentData } from 'firebase-admin/firestore'
const REST = `${process.env.WOWSQL_URL}/rest/v1` // https://myproject.wowsqlconnect.com
const KEY = process.env.WOWSQL_SERVICE_KEY! // bypasses RLS: keep it off clients
type Row = Record<string, unknown>
const iso = (v: any): string | null => (typeof v?.toDate === 'function' ? v.toDate().toISOString() : null)
const refId = (v: any): string => (typeof v === 'string' ? v : v.id) // DocumentReference -> id
export function userRow(id: string, u: DocumentData): Row {
return {
uid: id, user_id: null, email: u.email ?? null, display_name: u.displayName ?? 'Unknown',
photo_url: u.photoURL ?? null, settings: u.settings ?? {}, created_at: iso(u.createdAt) ?? new Date().toISOString(),
}
}
export function postRows(id: string, p: DocumentData): { post: Row; likes: Row[] } {
const { author, authorName, title, body, tags, likes, createdAt, ...rest } = p
return {
post: {
id, author_uid: refId(author), author_name: authorName ?? '', title: title ?? '', body: body ?? '',
tags: Array.isArray(tags) ? tags : [], extra: rest, created_at: iso(createdAt) ?? new Date().toISOString(),
},
likes: Object.entries(likes ?? {}).filter(([, v]) => v === true)
.map(([uid]) => ({ post_id: id, user_uid: uid })),
}
}
export function commentRow(id: string, postId: string, c: DocumentData): Row {
return { id, post_id: postId, author_uid: refId(c.author), body: c.body ?? '', created_at: iso(c.createdAt) ?? new Date().toISOString() }
}
export async function upsert(table: string, rows: Row[]) {
for (let i = 0; i < rows.length; i += 500) {
const res = await fetch(`${REST}/${table}`, {
method: 'POST',
headers: { apikey: KEY, Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json',
Prefer: 'resolution=merge-duplicates' },
body: JSON.stringify(rows.slice(i, i + 500)),
})
if (!res.ok) throw new Error(`${table}: ${res.status} ${await res.text()}`)
}
}
export async function main() {
initializeApp({ credential: applicationDefault() }) // GOOGLE_APPLICATION_CREDENTIALS=service-account.json
const db = getFirestore()
const users = await db.collection('users').get()
await upsert('app_users', users.docs.map(d => userRow(d.id, d.data())))
const posts = await db.collection('posts').get()
const converted = posts.docs.map(d => postRows(d.id, d.data()))
await upsert('posts', converted.map(c => c.post))
await upsert('post_likes', converted.flatMap(c => c.likes))
// collectionGroup reads every "comments" subcollection; the parent doc id is the post id
const comments = await db.collectionGroup('comments').get()
await upsert('comments', comments.docs.map(d => commentRow(d.id, d.ref.parent.parent!.id, d.data())))
console.log(`users ${users.size}, posts ${posts.size}, comments ${comments.size}`)
}
Order matters because of the foreign keys: users, then posts, then likes and comments. Every object in one batch must have the same keys (PostgREST rejects mixed shapes with PGRST102), which is why the row builders always set every field, even to null. For large collections, page through Firestore with limit() and startAfter() instead of one big get().
Step 5: Link people when they first sign in
After the move, people sign in to WoWSQL (by password reset, magic link, OTP or the same Google account). Right after their first sign-in, call this from your server so their imported profile gets their new auth ID:
// link-user.ts, server side
import { ProjectAuthClient } from '@wowsql/sdk'
const URL_ = process.env.WOWSQL_URL!
const SERVICE_KEY = process.env.WOWSQL_SERVICE_KEY!
const auth = new ProjectAuthClient({ projectUrl: URL_, apiKey: process.env.WOWSQL_ANON_KEY! })
const svc = { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}`, 'Content-Type': 'application/json' }
export async function linkFirebaseProfile(accessToken: string): Promise<string> {
const user = await auth.getUser(accessToken)
if (!user.emailVerified) throw new Error('Verify your email before we link your old account')
// 1. Claim the imported profile with the same email, if it is still unclaimed
const email = encodeURIComponent(user.email.toLowerCase())
const claim = await fetch(`${URL_}/rest/v1/app_users?email=eq.${email}&user_id=is.null`, {
method: 'PATCH', headers: { ...svc, Prefer: 'return=representation' },
body: JSON.stringify({ user_id: user.id }),
})
const claimed: { uid: string }[] = await claim.json()
if (claimed.length) return claimed[0].uid
// 2. Already linked, or a brand-new user: make sure a profile exists
const res = await fetch(`${URL_}/rest/v1/app_users?on_conflict=user_id`, {
method: 'POST', headers: { ...svc, Prefer: 'resolution=ignore-duplicates,return=representation' },
body: JSON.stringify({ uid: user.id, user_id: user.id, email: user.email.toLowerCase(), display_name: user.fullName ?? user.email }),
})
const created: { uid: string }[] = await res.json()
if (created.length) return created[0].uid
const me = await fetch(`${URL_}/rest/v1/app_users?user_id=eq.${user.id}&select=uid`, { headers: svc })
return (await me.json())[0].uid
}
Only link on a verified email; otherwise anyone could sign up with someone else's address and claim their history. Moving the accounts themselves is covered in Firebase Authentication alternatives.
Step 6: Rewrite the queries
| Firestore client call | WoWSQL REST (/rest/v1/...) |
|---|---|
where('tags', 'array-contains', 'postgres') |
posts?select=id,title&tags=cs.{postgres} |
orderBy('createdAt', 'desc').limit(10) |
posts?order=created_at.desc&limit=10 |
where('settings.theme', '==', 'dark') |
app_users?settings->>theme=eq.dark |
| A post plus its comments subcollection | posts?select=id,title,comments(id,body) |
collectionGroup('comments').where('author', '==', uid) |
comments?author_uid=eq.<uid> |
| Counter fields | post_stats?select=* |
These are standard PostgREST filters, and all six returned the expected rows on our local PostgREST 16.6 test. WoWSQL runs PostgREST, but test the embedded comments(...) select on your own project before you rely on it. Use the @wowsql/sdk query builder for simple filters with the anon key; for rows protected by RLS, send the user's token yourself, because WowSQLClient in 3.10.0 sends the anon key as the bearer token.
Firestore vs Postgres options
| Firestore | WoWSQL (Postgres) | Firebase SQL Connect | Supabase | |
|---|---|---|---|---|
| Data model | Documents and subcollections | Tables, joins, jsonb |
Postgres on Cloud SQL, accessed through GraphQL | Tables, joins, jsonb |
| API | Firebase SDKs | REST (PostgREST), official SDKs in 11 languages | Generated SDKs from your GraphQL schema | REST, GraphQL (docs), SDKs |
| Offline cache | Built in; on by default on Android and Apple, opt-in on web (docs) | Not built in | Not stated on the overview page we read | Not built in |
| Starting price | Spark free tier; Blaze pay as you go | Free $0; Pro $25/month | 3-month no-cost Cloud SQL trial, then from $9.37/month (pricing) | Free $0; Pro from $25/month |
Facts checked on 28 November 2026. Firestore is still better at offline-first mobile apps and at scaling without any thought about indexes or connections. Firebase SQL Connect is the lowest-friction way to get Postgres if you want to stay inside Firebase and are happy with GraphQL. Supabase has the most mature Firestore migration tooling. WoWSQL is a good fit if you want plain SQL tables with a REST API, auth and realtime in one project, priced in clear plans, with regions in Mumbai, US East and Frankfurt.
Related guides
- How to migrate Firebase to Postgres
- WoWSQL vs Firebase
- What is Row Level Security?
- What is PostgREST?
- Upload images from React to cloud storage
- Build a RAG app backend on Postgres
FAQ
How do I model Firestore documents in Postgres tables?
Make one table per collection, keep the document ID as a text primary key, and give each subcollection its own table with a foreign key to the parent. Use typed columns for fields you filter on, jsonb for nested maps you only read back, and array columns or join tables for arrays.
Should I just store each Firestore document as JSONB?
Only as a temporary step. A single jsonb column gets you running quickly, but you lose type checks, foreign keys and simple indexes. Move the fields you query into real columns and keep a jsonb column for the leftovers.
How do Firestore subcollections map to SQL?
A subcollection becomes a child table with a column pointing at the parent row, such as comments.post_id references posts(id) on delete cascade. Collection group queries then become ordinary queries on that one table.
How do I convert Firebase Security Rules to Row Level Security?
Enable RLS on each table and write one policy per operation. request.auth.uid == resource.data.author becomes using (author_uid = current_uid()), and request.resource.data checks become with check (...). Blocked updates affect zero rows instead of throwing, so check row counts.
What happens to Firebase user IDs when I migrate to Postgres?
Keep them. Store the Firebase UID as a stable uid text key that all your tables reference, and add a nullable column for the new auth user ID. Fill it in when each person first signs in with a verified email.
Do I lose real-time listeners when I leave Firestore?
You swap them for a different mechanism. WoWSQL realtime streams INSERT, UPDATE and DELETE events over a WebSocket once you enable a table. It authenticates with the API key in the socket URL, not the user's token, so test what each client receives before you stream private rows. Firestore's offline cache has no direct equivalent.