Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Fix: Updated to use optimized search columns when getting user counts (#40107)

Ali Waseem7682bac0f35d
diff --git a/apps/studio/components/interfaces/Auth/Users/Users.constants.ts b/apps/studio/components/interfaces/Auth/Users/Users.constants.ts
index 2b7a1dc4d8a..8c0757e66a8 100644
--- a/apps/studio/components/interfaces/Auth/Users/Users.constants.ts
+++ b/apps/studio/components/interfaces/Auth/Users/Users.constants.ts
@@ -1,8 +1,11 @@
import { BASE_PATH } from 'lib/constants'
import { PROVIDER_PHONE, PROVIDERS_SCHEMAS } from '../AuthProvidersFormValidation'
+import { OptimizedSearchColumns } from '@supabase/pg-meta/src/sql/studio/get-users-types'
export type Filter = 'all' | 'verified' | 'unverified' | 'anonymous'
+export type SpecificFilterColumn = OptimizedSearchColumns | 'freeform'
+
export const UUIDV4_LEFT_PREFIX_REGEX =
/^(?:[0-9a-f]{1,8}|[0-9a-f]{8}-|[0-9a-f]{8}-[0-9a-f]{1,4}|[0-9a-f]{8}-[0-9a-f]{4}-|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{0,3}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{0,3}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{0,12})$/i
diff --git a/apps/studio/components/interfaces/Auth/Users/UsersFooter.tsx b/apps/studio/components/interfaces/Auth/Users/UsersFooter.tsx
index eee1b8ed158..99581102ca2 100644
--- a/apps/studio/components/interfaces/Auth/Users/UsersFooter.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UsersFooter.tsx
@@ -2,19 +2,21 @@ import { THRESHOLD_COUNT } from '@supabase/pg-meta/src/sql/studio/get-count-esti
import { HelpCircle, Loader2 } from 'lucide-react'
import { useEffect, useState } from 'react'
+import type { Filter, SpecificFilterColumn } from './Users.constants'
+
+import { OptimizedSearchColumns } from '@supabase/pg-meta/src/sql/studio/get-users-types'
import { useParams } from 'common'
import { formatEstimatedCount } from 'components/grid/components/footer/pagination/Pagination.utils'
import { useUsersCountQuery } from 'data/auth/users-count-query'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import { Filter } from './Users.constants'
interface UsersFooterProps {
filter: Filter
filterKeywords: string
selectedProviders: string[]
- specificFilterColumn: string
+ specificFilterColumn: SpecificFilterColumn
}
export const UsersFooter = ({
@@ -42,6 +44,10 @@ export const UsersFooter = ({
filter: filter === 'all' ? undefined : filter,
providers: selectedProviders,
forceExactCount,
+ // Use optimized search when filtering by specific column
+ ...(specificFilterColumn !== 'freeform'
+ ? { column: specificFilterColumn as OptimizedSearchColumns }
+ : { column: undefined }),
},
{ keepPreviousData: true }
)
diff --git a/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx b/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
index b1b1b9636ee..338f3e14b64 100644
--- a/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
@@ -5,6 +5,8 @@ import { UIEvent, useEffect, useMemo, useRef, useState } from 'react'
import DataGrid, { Column, DataGridHandle, Row } from 'react-data-grid'
import { toast } from 'sonner'
+import type { OptimizedSearchColumns } from '@supabase/pg-meta/src/sql/studio/get-users-types'
+import type { SpecificFilterColumn } from './Users.constants'
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import AlertError from 'components/ui/AlertError'
@@ -91,9 +93,9 @@ export const UsersV2 = () => {
}
}, [showEmailPhoneColumns])
- const [specificFilterColumn, setSpecificFilterColumn] = useQueryState(
+ const [specificFilterColumn, setSpecificFilterColumn] = useQueryState<SpecificFilterColumn>(
'filter',
- parseAsStringEnum(['id', 'email', 'phone', 'freeform']).withDefault('id')
+ parseAsStringEnum<SpecificFilterColumn>(['id', 'email', 'phone', 'freeform']).withDefault('id')
)
const [filterUserType, setFilterUserType] = useQueryState(
'userType',
@@ -138,7 +140,7 @@ export const UsersV2 = () => {
)
const [columns, setColumns] = useState<Column<any>[]>([])
- const [search, setSearch] = useState('')
+ const [search, setSearch] = useState(filterKeywords)
const [selectedUser, setSelectedUser] = useState<string>()
const [selectedUsers, setSelectedUsers] = useState<Set<any>>(new Set([]))
const [selectedUserToDelete, setSelectedUserToDelete] = useState<User>()
@@ -187,7 +189,7 @@ export const UsersV2 = () => {
sort: sortColumn as 'id' | 'created_at' | 'email' | 'phone',
order: sortOrder as 'asc' | 'desc',
...(specificFilterColumn !== 'freeform'
- ? { column: specificFilterColumn }
+ ? { column: specificFilterColumn as OptimizedSearchColumns }
: { column: undefined }),
},
{
diff --git a/apps/studio/data/auth/keys.ts b/apps/studio/data/auth/keys.ts
index 86fa936c13b..02c9fe9084d 100644
--- a/apps/studio/data/auth/keys.ts
+++ b/apps/studio/data/auth/keys.ts
@@ -1,3 +1,5 @@
+import type { OptimizedSearchColumns } from '@supabase/pg-meta/src/sql/studio/get-users-types'
+
export const authKeys = {
users: (
projectRef: string | undefined,
@@ -39,6 +41,7 @@ export const authKeys = {
filter: string | undefined
providers: string[] | undefined
forceExactCount?: boolean
+ column?: OptimizedSearchColumns
}
) =>
['projects', projectRef, 'users-count', ...(params ? [params].filter(Boolean) : [])] as const,
diff --git a/apps/studio/data/auth/users-count-query.ts b/apps/studio/data/auth/users-count-query.ts
index 434d45a13a0..7d78176ad4f 100644
--- a/apps/studio/data/auth/users-count-query.ts
+++ b/apps/studio/data/auth/users-count-query.ts
@@ -1,3 +1,4 @@
+import type { OptimizedSearchColumns } from '@supabase/pg-meta/src/sql/studio/get-users-types'
import { getUsersCountSQL } from '@supabase/pg-meta/src/sql/studio/get-users-count'
import { useQuery } from '@tanstack/react-query'
@@ -13,6 +14,9 @@ type UsersCountVariables = {
filter?: Filter
providers?: string[]
forceExactCount?: boolean
+
+ /** If set, uses optimized prefix search for the specified column */
+ column?: OptimizedSearchColumns
}
export async function getUsersCount(
@@ -23,10 +27,11 @@ export async function getUsersCount(
filter,
providers,
forceExactCount,
+ column,
}: UsersCountVariables,
signal?: AbortSignal
) {
- const sql = getUsersCountSQL({ filter, keywords, providers, forceExactCount })
+ const sql = getUsersCountSQL({ filter, keywords, providers, forceExactCount, column })
const { result } = await executeSql(
{
@@ -63,6 +68,7 @@ export const useUsersCountQuery = <TData = UsersCountData>(
filter,
providers,
forceExactCount,
+ column,
}: UsersCountVariables,
{ enabled = true, ...options }: UseCustomQueryOptions<UsersCountData, UsersCountError, TData> = {}
) =>
@@ -72,6 +78,7 @@ export const useUsersCountQuery = <TData = UsersCountData>(
filter,
providers,
forceExactCount,
+ column,
}),
queryFn: ({ signal }) =>
getUsersCount(
@@ -82,6 +89,7 @@ export const useUsersCountQuery = <TData = UsersCountData>(
filter,
providers,
forceExactCount,
+ column,
},
signal
),
diff --git a/apps/studio/data/auth/users-infinite-query.ts b/apps/studio/data/auth/users-infinite-query.ts
index 0d360f0d9e7..9db0b6bbf67 100644
--- a/apps/studio/data/auth/users-infinite-query.ts
+++ b/apps/studio/data/auth/users-infinite-query.ts
@@ -1,6 +1,7 @@
import { getPaginatedUsersSQL } from '@supabase/pg-meta/src/sql/studio/get-users-paginated'
import { useInfiniteQuery } from '@tanstack/react-query'
+import { OptimizedSearchColumns } from '@supabase/pg-meta/src/sql/studio/get-users-types'
import type { components } from 'data/api'
import { executeSql, ExecuteSqlError } from 'data/sql/execute-sql-query'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
@@ -20,8 +21,8 @@ type UsersVariables = {
providers?: string[]
sort?: 'id' | 'created_at' | 'email' | 'phone' | 'last_sign_in_at'
order?: 'asc' | 'desc'
-
- column?: 'id' | 'email' | 'phone'
+ /** If set, uses optimized prefix search for the specified column */
+ column?: OptimizedSearchColumns
startAt?: string
}
diff --git a/packages/pg-meta/src/sql/studio/get-users-common.ts b/packages/pg-meta/src/sql/studio/get-users-common.ts
new file mode 100644
index 00000000000..c7255a77a67
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/get-users-common.ts
@@ -0,0 +1,51 @@
+export function prefixToUUID(prefix: string, max: boolean) {
+ const mapped = '00000000-0000-0000-0000-000000000000'
+ .split('')
+ .map((c, i) => (c === '-' ? c : prefix[i] ?? c))
+
+ if (prefix.length >= mapped.length) {
+ return mapped.join('')
+ }
+
+ if (prefix.length && prefix.length < 15) {
+ mapped[14] = '4'
+ }
+
+ if (prefix.length && prefix.length < 20) {
+ mapped[19] = max ? 'b' : '8'
+ }
+
+ if (max) {
+ for (let i = prefix.length; i < mapped.length; i += 1) {
+ if (mapped[i] === '0') {
+ mapped[i] = 'f'
+ }
+ }
+ }
+
+ return mapped.join('')
+}
+
+export function stringRange(prefix: string): [string, string | undefined] {
+ if (!prefix) {
+ return [prefix, undefined]
+ }
+
+ const lastCharCode = prefix.charCodeAt(prefix.length - 1)
+ const TILDE_CHAR_CODE = 126 // '~'
+ const Z_CHAR_CODE = 122 // 'z'
+
+ // 'z' (122): append '~' to avoid PostgreSQL collation issues with '{'
+ if (lastCharCode === Z_CHAR_CODE) {
+ return [prefix, prefix + '~']
+ }
+
+ // '~' (126) or beyond: append space since we can't increment further
+ if (lastCharCode >= TILDE_CHAR_CODE) {
+ return [prefix, prefix + ' ']
+ }
+
+ // All other characters: increment the last character
+ const upperBound = prefix.substring(0, prefix.length - 1) + String.fromCharCode(lastCharCode + 1)
+ return [prefix, upperBound]
+}
diff --git a/packages/pg-meta/src/sql/studio/get-users-count.ts b/packages/pg-meta/src/sql/studio/get-users-count.ts
index 1d1f5e6145d..9a012de315a 100644
--- a/packages/pg-meta/src/sql/studio/get-users-count.ts
+++ b/packages/pg-meta/src/sql/studio/get-users-count.ts
@@ -1,4 +1,7 @@
+import type { OptimizedSearchColumns } from './get-users-types'
import { COUNT_ESTIMATE_SQL, THRESHOLD_COUNT } from './get-count-estimate'
+import { stringRange, prefixToUUID } from './get-users-common'
+import { literal } from '../../pg-format'
export const USERS_COUNT_ESTIMATE_SQL = `select reltuples as estimate from pg_class where oid = 'auth.users'::regclass`
@@ -7,11 +10,14 @@ export const getUsersCountSQL = ({
keywords,
providers,
forceExactCount = false,
+ column,
}: {
filter?: 'verified' | 'unverified' | 'anonymous'
keywords?: string
providers?: string[]
forceExactCount?: boolean
+ /** If set, uses optimized prefix search for the specified column */
+ column?: OptimizedSearchColumns
}) => {
const hasValidKeywords = keywords && keywords !== ''
@@ -19,34 +25,59 @@ export const getUsersCountSQL = ({
const baseQueryCount = `select count(*) from auth.users`
const baseQuerySelect = `select * from auth.users`
- if (hasValidKeywords) {
- // [Joshen] Escape single quotes properly
- const formattedKeywords = keywords.replaceAll("'", "''")
- conditions.push(
- `id::text ilike '%${formattedKeywords}%' or email ilike '%${formattedKeywords}%' or phone ilike '%${formattedKeywords}%'`
- )
- }
-
- if (filter === 'verified') {
- conditions.push(`email_confirmed_at IS NOT NULL or phone_confirmed_at IS NOT NULL`)
- } else if (filter === 'anonymous') {
- conditions.push(`is_anonymous is true`)
- } else if (filter === 'unverified') {
- conditions.push(`email_confirmed_at IS NULL AND phone_confirmed_at IS NULL`)
- }
-
- if (providers && providers.length > 0) {
- // [Joshen] This is arguarbly not fully optimized, but at the same time not commonly used
- // JFYI in case we do eventually run into performance issues here when filtering for SAML provider
- if (providers.includes('saml 2.0')) {
+ const optimizedSearchMode = column && hasValidKeywords
+ if (optimizedSearchMode) {
+ if (column === 'email') {
+ const range = stringRange(keywords)
+ const lowerBound = literal(range[0])
+ const upperBound = range[1] ? literal(range[1]) : null
conditions.push(
- `(select jsonb_agg(case when value ~ '^sso' then 'sso' else value end) from jsonb_array_elements_text((raw_app_meta_data ->> 'providers')::jsonb)) ?| array[${providers.map((p) => (p === 'saml 2.0' ? `'sso'` : `'${p}'`)).join(', ')}]`.trim()
+ `lower(email) >= ${lowerBound}${upperBound ? ` and lower(email) < ${upperBound}` : ''} and instance_id = '00000000-0000-0000-0000-000000000000'::uuid`
)
- } else {
+ } else if (column === 'phone') {
+ const range = stringRange(keywords)
+ const lowerBound = literal(range[0])
+ const upperBound = range[1] ? literal(range[1]) : null
+ conditions.push(`phone >= ${lowerBound}${upperBound ? ` and phone < ${upperBound}` : ''}`)
+ } else if (column === 'id') {
+ const lowerUUID = prefixToUUID(keywords, false)
+ const isMatchingUUIDValue = lowerUUID === keywords
+ if (isMatchingUUIDValue) {
+ conditions.push(`id = ${literal(keywords)}`)
+ } else {
+ const upperUUID = prefixToUUID(keywords, true)
+ conditions.push(`id >= ${literal(lowerUUID)} and id < ${literal(upperUUID)}`)
+ }
+ }
+ } else {
+ // Unified search mode - apply all filters
+ if (hasValidKeywords) {
+ const escapedFilterKeywords = literal(`%${keywords}%`)
conditions.push(
- `(raw_app_meta_data->>'providers')::jsonb ?| array[${providers.map((p) => `'${p}'`).join(', ')}]`
+ `id::text ilike ${escapedFilterKeywords} or email ilike ${escapedFilterKeywords} or phone ilike ${escapedFilterKeywords}`
)
}
+
+ if (filter === 'verified') {
+ conditions.push(`email_confirmed_at IS NOT NULL or phone_confirmed_at IS NOT NULL`)
+ } else if (filter === 'anonymous') {
+ conditions.push(`is_anonymous is true`)
+ } else if (filter === 'unverified') {
+ conditions.push(`email_confirmed_at IS NULL AND phone_confirmed_at IS NULL`)
+ }
+
+ if (providers && providers.length > 0) {
+ // [Joshen] This is arguarbly not fully optimized, but at the same time not commonly used
+ // JFYI in case we do eventually run into performance issues here when filtering for SAML provider
+ if (providers.includes('saml 2.0')) {
+ const mappedProviders = providers.map((p) => (p === 'saml 2.0' ? 'sso' : p))
+ conditions.push(
+ `(select jsonb_agg(case when value ~ '^sso' then 'sso' else value end) from jsonb_array_elements_text((raw_app_meta_data ->> 'providers')::jsonb)) ?| array[${literal(mappedProviders)}]`.trim()
+ )
+ } else {
+ conditions.push(`(raw_app_meta_data->>'providers')::jsonb ?| array[${literal(providers)}]`)
+ }
+ }
}
const combinedConditions = conditions.map((x) => `(${x})`).join(' and ')
@@ -58,7 +89,7 @@ export const getUsersCountSQL = ({
const selectBaseSql = `${baseQuerySelect}${whereClause}`
const countBaseSql = `${baseQueryCount}${whereClause}`
- const escapedSelectSql = selectBaseSql.replaceAll("'", "''")
+ const escapedSelectSql = literal(selectBaseSql)
const sql = `
${COUNT_ESTIMATE_SQL}
@@ -66,8 +97,8 @@ ${COUNT_ESTIMATE_SQL}
with approximation as (${USERS_COUNT_ESTIMATE_SQL})
select
case
- when estimate = -1 then (select pg_temp.count_estimate('${escapedSelectSql}'))::int
- when estimate > ${THRESHOLD_COUNT} then ${conditions.length > 0 ? `(select pg_temp.count_estimate('${escapedSelectSql}'))::int` : 'estimate::int'}
+ when estimate = -1 then (select pg_temp.count_estimate(${escapedSelectSql}))::int
+ when estimate > ${THRESHOLD_COUNT} then ${conditions.length > 0 ? `(select pg_temp.count_estimate(${escapedSelectSql}))::int` : 'estimate::int'}
else (${countBaseSql})
end as count,
estimate = -1 or estimate > ${THRESHOLD_COUNT} as is_estimate
diff --git a/packages/pg-meta/src/sql/studio/get-users-paginated.ts b/packages/pg-meta/src/sql/studio/get-users-paginated.ts
index 280aa9b36ac..cb184442607 100644
--- a/packages/pg-meta/src/sql/studio/get-users-paginated.ts
+++ b/packages/pg-meta/src/sql/studio/get-users-paginated.ts
@@ -1,3 +1,6 @@
+import { prefixToUUID, stringRange } from './get-users-common'
+import { OptimizedSearchColumns } from './get-users-types'
+
interface getPaginatedUsersSQLProps {
page?: number
verified?: 'verified' | 'unverified' | 'anonymous'
@@ -8,64 +11,12 @@ interface getPaginatedUsersSQLProps {
limit?: number
/** If set, uses fast queries but these don't allow any sorting so the above parameters are completely ignored. */
- column?: 'id' | 'email' | 'phone'
+ column?: OptimizedSearchColumns
startAt?: string
}
const DEFAULT_LIMIT = 50
-function prefixToUUID(prefix: string, max: boolean) {
- const mapped = '00000000-0000-0000-0000-000000000000'
- .split('')
- .map((c, i) => (c === '-' ? c : prefix[i] ?? c))
-
- if (prefix.length >= mapped.length) {
- return mapped.join('')
- }
-
- if (prefix.length && prefix.length < 15) {
- mapped[14] = '4'
- }
-
- if (prefix.length && prefix.length < 20) {
- mapped[19] = max ? 'b' : '8'
- }
-
- if (max) {
- for (let i = prefix.length; i < mapped.length; i += 1) {
- if (mapped[i] === '0') {
- mapped[i] = 'f'
- }
- }
- }
-
- return mapped.join('')
-}
-
-function stringRange(prefix: string): [string, string | undefined] {
- if (!prefix) {
- return [prefix, undefined]
- }
-
- const lastCharCode = prefix.charCodeAt(prefix.length - 1)
- const TILDE_CHAR_CODE = 126 // '~'
- const Z_CHAR_CODE = 122 // 'z'
-
- // 'z' (122): append '~' to avoid PostgreSQL collation issues with '{'
- if (lastCharCode === Z_CHAR_CODE) {
- return [prefix, prefix + '~']
- }
-
- // '~' (126) or beyond: append space since we can't increment further
- if (lastCharCode >= TILDE_CHAR_CODE) {
- return [prefix, prefix + ' ']
- }
-
- // All other characters: increment the last character
- const upperBound = prefix.substring(0, prefix.length - 1) + String.fromCharCode(lastCharCode + 1)
- return [prefix, upperBound]
-}
-
export const getPaginatedUsersSQL = ({
page = 0,
verified,
diff --git a/packages/pg-meta/src/sql/studio/get-users-types.ts b/packages/pg-meta/src/sql/studio/get-users-types.ts
new file mode 100644
index 00000000000..d0abed10de2
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/get-users-types.ts
@@ -0,0 +1 @@
+export type OptimizedSearchColumns = 'id' | 'email' | 'phone'
diff --git a/packages/pg-meta/test/db/utils.ts b/packages/pg-meta/test/db/utils.ts
index c5e205d2574..abd5b8a739a 100644
--- a/packages/pg-meta/test/db/utils.ts
+++ b/packages/pg-meta/test/db/utils.ts
@@ -76,3 +76,79 @@ export async function createTestDatabase() {
export async function cleanupRoot() {
await rootPool.end()
}
+
+export async function createDatabaseWithAuthSchema(
+ db: Awaited<ReturnType<typeof createTestDatabase>>,
+ options?: { includeIdentities?: boolean }
+) {
+ const { includeIdentities = false } = options || {}
+
+ await db.executeQuery(`
+ CREATE SCHEMA IF NOT EXISTS auth;
+
+ CREATE TABLE IF NOT EXISTS auth.users (
+ instance_id uuid NULL,
+ id uuid NOT NULL UNIQUE,
+ aud varchar(255) NULL,
+ "role" varchar(255) NULL,
+ email varchar(255) NULL,
+ encrypted_password varchar(255) NULL,
+ email_confirmed_at timestamptz NULL,
+ invited_at timestamptz NULL,
+ confirmation_token varchar(255) NULL,
+ confirmation_sent_at timestamptz NULL,
+ recovery_token varchar(255) NULL,
+ recovery_sent_at timestamptz NULL,
+ email_change_token varchar(255) NULL,
+ email_change varchar(255) NULL,
+ email_change_sent_at timestamptz NULL,
+ last_sign_in_at timestamptz NULL,
+ raw_app_meta_data jsonb NULL,
+ raw_user_meta_data jsonb NULL,
+ is_super_admin bool NULL,
+ created_at timestamptz NULL,
+ updated_at timestamptz NULL,
+ phone text NULL,
+ phone_confirmed_at timestamptz NULL,
+ phone_change text NULL,
+ phone_change_token varchar(255) NULL,
+ phone_change_sent_at timestamptz NULL,
+ confirmed_at timestamptz NULL,
+ email_change_token_current varchar(255) NULL,
+ email_change_confirm_status smallint NULL,
+ banned_until timestamptz NULL,
+ reauthentication_token varchar(255) NULL,
+ reauthentication_sent_at timestamptz NULL,
+ is_sso_user bool NOT NULL DEFAULT false,
+ deleted_at timestamptz NULL,
+ is_anonymous bool NOT NULL DEFAULT false,
+ CONSTRAINT users_pkey PRIMARY KEY (id)
+ );
+
+ CREATE INDEX IF NOT EXISTS users_instance_id_idx ON auth.users USING btree (instance_id);
+ CREATE INDEX IF NOT EXISTS users_instance_id_email_idx ON auth.users USING btree (instance_id, lower(email));
+ CREATE INDEX IF NOT EXISTS confirmation_token_idx ON auth.users USING btree (confirmation_token) WHERE confirmation_token IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS recovery_token_idx ON auth.users USING btree (recovery_token) WHERE recovery_token IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS email_change_token_current_idx ON auth.users USING btree (email_change_token_current) WHERE email_change_token_current IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS email_change_token_new_idx ON auth.users USING btree (email_change_token) WHERE email_change_token IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS reauthentication_token_idx ON auth.users USING btree (reauthentication_token) WHERE reauthentication_token IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS users_is_anonymous_idx ON auth.users USING btree (is_anonymous);
+ `)
+
+ if (includeIdentities) {
+ await db.executeQuery(`
+ CREATE TABLE IF NOT EXISTS auth.identities (
+ id text NOT NULL,
+ user_id uuid NOT NULL,
+ identity_data jsonb NOT NULL,
+ provider text NOT NULL,
+ last_sign_in_at timestamptz NULL,
+ created_at timestamptz NULL,
+ updated_at timestamptz NULL,
+ CONSTRAINT identities_pkey PRIMARY KEY (provider, id)
+ );
+
+ CREATE INDEX IF NOT EXISTS identities_user_id_idx ON auth.identities USING btree (user_id);
+ `)
+ }
+}
diff --git a/packages/pg-meta/test/sql/studio/get-users-common.test.ts b/packages/pg-meta/test/sql/studio/get-users-common.test.ts
new file mode 100644
index 00000000000..46020f9b451
--- /dev/null
+++ b/packages/pg-meta/test/sql/studio/get-users-common.test.ts
@@ -0,0 +1,222 @@
+import { expect, test, describe } from 'vitest'
+import { prefixToUUID, stringRange } from '../../../src/sql/studio/get-users-common'
+
+describe('prefixToUUID', () => {
+ test('returns UUID template with no prefix', () => {
+ const result = prefixToUUID('', false)
+ expect(result).toBe('00000000-0000-0000-0000-000000000000')
+ })
+
+ test('returns UUID template with no prefix (max=true)', () => {
+ const result = prefixToUUID('', true)
+ expect(result).toBe('ffffffff-ffff-ffff-ffff-ffffffffffff')
+ })
+
+ test('returns UUID with short prefix', () => {
+ const result = prefixToUUID('abc', false)
+ expect(result).toBe('abc00000-0000-4000-8000-000000000000')
+ })
+
+ test('returns UUID with short prefix (max=true)', () => {
+ const result = prefixToUUID('abc', true)
+ expect(result).toBe('abcfffff-ffff-4fff-bfff-ffffffffffff')
+ })
+
+ test('returns UUID with prefix up to first hyphen', () => {
+ const result = prefixToUUID('12345678', false)
+ expect(result).toBe('12345678-0000-4000-8000-000000000000')
+ })
+
+ test('returns UUID with prefix up to first hyphen (max=true)', () => {
+ const result = prefixToUUID('12345678', true)
+ expect(result).toBe('12345678-ffff-4fff-bfff-ffffffffffff')
+ })
+
+ test('returns UUID with prefix including first hyphen', () => {
+ const result = prefixToUUID('12345678-', false)
+ expect(result).toBe('12345678-0000-4000-8000-000000000000')
+ })
+
+ test('returns UUID with prefix extending into second section', () => {
+ const result = prefixToUUID('12345678-1234', false)
+ expect(result).toBe('12345678-1234-4000-8000-000000000000')
+ })
+
+ test('returns UUID with prefix extending into third section (before position 15)', () => {
+ const result = prefixToUUID('12345678-1234-', false)
+ expect(result).toBe('12345678-1234-4000-8000-000000000000')
+ })
+
+ test('returns UUID with prefix at position 15 (includes version)', () => {
+ const result = prefixToUUID('12345678-1234-5', false)
+ expect(result).toBe('12345678-1234-5000-8000-000000000000')
+ })
+
+ test('returns UUID with prefix extending into fourth section (before position 20)', () => {
+ const result = prefixToUUID('12345678-1234-5678-', false)
+ expect(result).toBe('12345678-1234-5678-8000-000000000000')
+ })
+
+ test('returns UUID with prefix extending into fourth section (before position 20, max=true)', () => {
+ const result = prefixToUUID('12345678-1234-5678-', true)
+ expect(result).toBe('12345678-1234-5678-bfff-ffffffffffff')
+ })
+
+ test('returns UUID with prefix at position 20 (includes variant)', () => {
+ const result = prefixToUUID('12345678-1234-5678-9', false)
+ expect(result).toBe('12345678-1234-5678-9000-000000000000')
+ })
+
+ test('returns UUID with prefix at position 20 (includes variant, max=true)', () => {
+ const result = prefixToUUID('12345678-1234-5678-9', true)
+ expect(result).toBe('12345678-1234-5678-9fff-ffffffffffff')
+ })
+
+ test('returns UUID with long prefix', () => {
+ const result = prefixToUUID('12345678-1234-5678-9abc-def', false)
+ expect(result).toBe('12345678-1234-5678-9abc-def000000000')
+ })
+
+ test('returns UUID with long prefix (max=true)', () => {
+ const result = prefixToUUID('12345678-1234-5678-9abc-def', true)
+ expect(result).toBe('12345678-1234-5678-9abc-deffffffffff')
+ })
+
+ test('returns UUID with full length prefix', () => {
+ const result = prefixToUUID('12345678-1234-5678-9abc-def123456789', false)
+ expect(result).toBe('12345678-1234-5678-9abc-def123456789')
+ })
+
+ test('returns UUID with full length prefix (max=true)', () => {
+ const result = prefixToUUID('12345678-1234-5678-9abc-def123456789', true)
+ expect(result).toBe('12345678-1234-5678-9abc-def123456789')
+ })
+
+ test('returns UUID with prefix longer than template', () => {
+ const result = prefixToUUID('12345678-1234-5678-9abc-def123456789extra', false)
+ expect(result).toBe('12345678-1234-5678-9abc-def123456789')
+ })
+
+ test('maintains hyphen positions in UUID format', () => {
+ const result = prefixToUUID('a', false)
+ expect(result).toBe('a0000000-0000-4000-8000-000000000000')
+ expect(result.match(/-/g)?.length).toBe(4)
+ expect(result[8]).toBe('-')
+ expect(result[13]).toBe('-')
+ expect(result[18]).toBe('-')
+ expect(result[23]).toBe('-')
+ })
+
+ test('sets version nibble to 4 when prefix is shorter than position 15', () => {
+ const result = prefixToUUID('12345678-1234', false)
+ expect(result[14]).toBe('4')
+ })
+
+ test('sets variant to 8 when prefix is shorter than position 20 and max=false', () => {
+ const result = prefixToUUID('12345678-1234-5678', false)
+ expect(result[19]).toBe('8')
+ })
+
+ test('sets variant to b when prefix is shorter than position 20 and max=true', () => {
+ const result = prefixToUUID('12345678-1234-5678', true)
+ expect(result[19]).toBe('b')
+ })
+
+ test('fills remaining positions with f when max=true', () => {
+ const result = prefixToUUID('abc', true)
+ expect(result).toBe('abcfffff-ffff-4fff-bfff-ffffffffffff')
+ // Check that all '0' characters in the template are replaced with 'f'
+ expect(result).not.toContain('0')
+ // Check that hyphens are preserved
+ expect(result[8]).toBe('-')
+ expect(result[13]).toBe('-')
+ expect(result[18]).toBe('-')
+ expect(result[23]).toBe('-')
+ })
+})
+
+describe('stringRange', () => {
+ test('returns empty string and undefined for empty prefix', () => {
+ const result = stringRange('')
+ expect(result).toEqual(['', undefined])
+ })
+
+ test('returns range for single character', () => {
+ const result = stringRange('a')
+ expect(result).toEqual(['a', 'b'])
+ })
+
+ test('returns range for multiple characters', () => {
+ const result = stringRange('abc')
+ expect(result).toEqual(['abc', 'abd'])
+ })
+
+ test('returns range for string with spaces', () => {
+ const result = stringRange('hello world')
+ expect(result).toEqual(['hello world', 'hello worle'])
+ })
+
+ test('returns range for string ending with numbers', () => {
+ const result = stringRange('test123')
+ expect(result).toEqual(['test123', 'test124'])
+ })
+
+ test('returns range for string with uppercase letters', () => {
+ const result = stringRange('ABC')
+ expect(result).toEqual(['ABC', 'ABD'])
+ })
+
+ test('appends space for tilde character to avoid collation issues', () => {
+ const result = stringRange('test~')
+ expect(result).toEqual(['test~', 'test~ '])
+ })
+
+ test('appends space for characters beyond tilde in ASCII', () => {
+ const result = stringRange('test\x7F') // DEL character
+ expect(result).toEqual(['test\x7F', 'test\x7F '])
+ })
+
+ test('increments last character correctly for various ASCII characters', () => {
+ expect(stringRange('a')).toEqual(['a', 'b'])
+ expect(stringRange('z')).toEqual(['z', 'z~']) // Special case: appends '~' to avoid collation issues
+ expect(stringRange('A')).toEqual(['A', 'B'])
+ expect(stringRange('Z')).toEqual(['Z', '['])
+ expect(stringRange('0')).toEqual(['0', '1'])
+ expect(stringRange('9')).toEqual(['9', ':'])
+ })
+
+ test('handles special characters', () => {
+ expect(stringRange('test!')).toEqual(['test!', 'test"'])
+ expect(stringRange('test@')).toEqual(['test@', 'testA'])
+ expect(stringRange('test#')).toEqual(['test#', 'test$'])
+ })
+
+ test('handles underscore', () => {
+ const result = stringRange('test_')
+ expect(result).toEqual(['test_', 'test`'])
+ })
+
+ test('handles hyphen', () => {
+ const result = stringRange('test-')
+ expect(result).toEqual(['test-', 'test.'])
+ })
+
+ test('handles space correctly', () => {
+ const result = stringRange('test ')
+ expect(result).toEqual(['test ', 'test!'])
+ })
+
+ test('appends tilde for strings ending with lowercase z', () => {
+ expect(stringRange('xyz')).toEqual(['xyz', 'xyz~'])
+ expect(stringRange('jazz')).toEqual(['jazz', 'jazz~'])
+ })
+
+ test('handles mixed case strings ending with uppercase Z', () => {
+ expect(stringRange('testZ')).toEqual(['testZ', 'test['])
+ })
+
+ test('handles strings ending with tilde', () => {
+ expect(stringRange('test~')).toEqual(['test~', 'test~ '])
+ expect(stringRange('~~~')).toEqual(['~~~', '~~~ '])
+ })
+})
diff --git a/packages/pg-meta/test/sql/studio/get-users-count.test.ts b/packages/pg-meta/test/sql/studio/get-users-count.test.ts
new file mode 100644
index 00000000000..0c6654faa16
--- /dev/null
+++ b/packages/pg-meta/test/sql/studio/get-users-count.test.ts
@@ -0,0 +1,257 @@
+import { expect, test, afterAll } from 'vitest'
+import { createTestDatabase, cleanupRoot, createDatabaseWithAuthSchema } from '../../db/utils'
+import { getUsersCountSQL } from '../../../src/sql/studio/get-users-count'
+import { randomUUID } from 'crypto'
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+const withTestDatabase = (
+ name: string,
+ fn: (db: Awaited<ReturnType<typeof createTestDatabase>>) => Promise<void>
+) => {
+ test(name, async () => {
+ const db = await createTestDatabase()
+
+ // Initialize minimal auth schema needed for user count tests
+ await createDatabaseWithAuthSchema(db)
+
+ try {
+ await fn(db)
+ } finally {
+ await db.cleanup()
+ }
+ })
+}
+
+withTestDatabase('returns correct count with no filters', async ({ executeQuery }) => {
+ // Insert 5 test users
+ const users = Array.from({ length: 5 }, (_, i) => ({
+ id: randomUUID(),
+ email: `user${i + 1}@supabase.io`,
+ instance_id: '00000000-0000-0000-0000-000000000000',
+ aud: 'authenticated',
+ role: 'authenticated',
+ }))
+
+ const values = users
+ .map(
+ (user) =>
+ `('${user.id}', '${user.email}', '${user.instance_id}', '${user.aud}', '${user.role}', NOW())`
+ )
+ .join(', ')
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, aud, "role", created_at)
+ VALUES ${values}
+ `)
+
+ const userCountSql = getUsersCountSQL({ forceExactCount: true })
+ const result = await executeQuery<Array<{ count: number; is_estimate: boolean }>>(userCountSql)
+
+ expect(result[0].count).toBe(5)
+ expect(result[0].is_estimate).toBe(false)
+})
+
+withTestDatabase('filters verified users correctly', async ({ executeQuery }) => {
+ const now = new Date().toISOString()
+
+ // 2 verified users (email confirmed)
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, email_confirmed_at, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', NOW())
+ `)
+
+ // 1 verified user (phone confirmed)
+ await executeQuery(`
+ INSERT INTO auth.users (id, phone, instance_id, phone_confirmed_at, created_at)
+ VALUES ('${randomUUID()}', '+1234567890', '00000000-0000-0000-0000-000000000000', '${now}', NOW())
+ `)
+
+ // 2 unverified users
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Count verified users
+ const verifiedSql = getUsersCountSQL({ filter: 'verified', forceExactCount: true })
+ const verifiedResult = await executeQuery<Array<{ count: number }>>(verifiedSql)
+ expect(verifiedResult[0].count).toBe(3)
+
+ // Count unverified users
+ const unverifiedSql = getUsersCountSQL({ filter: 'unverified', forceExactCount: true })
+ const unverifiedResult = await executeQuery<Array<{ count: number }>>(unverifiedSql)
+ expect(unverifiedResult[0].count).toBe(2)
+})
+
+withTestDatabase('filters anonymous users correctly', async ({ executeQuery }) => {
+ // 2 anonymous users
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, is_anonymous, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', true, NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', true, NOW())
+ `)
+
+ // 3 regular users
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, is_anonymous, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', false, NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', false, NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', false, NOW())
+ `)
+
+ const anonSql = getUsersCountSQL({ filter: 'anonymous', forceExactCount: true })
+ const result = await executeQuery<Array<{ count: number }>>(anonSql)
+ expect(result[0].count).toBe(2)
+})
+
+withTestDatabase('searches by keywords across multiple fields', async ({ executeQuery }) => {
+ const searchUserId = randomUUID()
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, phone, instance_id, created_at)
+ VALUES
+ ('${searchUserId}', '[email protected]', NULL, '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '+1234567890', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '+9876543210', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Search by email keyword
+ const emailSearchSql = getUsersCountSQL({ keywords: 'john', forceExactCount: true })
+ const emailResult = await executeQuery<Array<{ count: number }>>(emailSearchSql)
+ expect(emailResult[0].count).toBe(1)
+
+ // Search by phone keyword
+ const phoneSearchSql = getUsersCountSQL({ keywords: '1234', forceExactCount: true })
+ const phoneResult = await executeQuery<Array<{ count: number }>>(phoneSearchSql)
+ expect(phoneResult[0].count).toBe(1)
+
+ // Search by ID (partial UUID)
+ const idPrefix = searchUserId.substring(0, 8)
+ const idSearchSql = getUsersCountSQL({ keywords: idPrefix, forceExactCount: true })
+ const idResult = await executeQuery<Array<{ count: number }>>(idSearchSql)
+ expect(idResult[0].count).toBe(1)
+})
+
+withTestDatabase('filters by provider correctly', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, raw_app_meta_data, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["google"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["google"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["github"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["email"]}', NOW())
+ `)
+
+ // Filter by google provider
+ const googleSql = getUsersCountSQL({ providers: ['google'], forceExactCount: true })
+ const googleResult = await executeQuery<Array<{ count: number }>>(googleSql)
+ expect(googleResult[0].count).toBe(2)
+
+ // Filter by multiple providers
+ const multipleSql = getUsersCountSQL({
+ providers: ['google', 'github'],
+ forceExactCount: true,
+ })
+ const multipleResult = await executeQuery<Array<{ count: number }>>(multipleSql)
+ expect(multipleResult[0].count).toBe(3)
+})
+
+withTestDatabase('combines multiple filters correctly', async ({ executeQuery }) => {
+ const now = new Date().toISOString()
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, email_confirmed_at, raw_app_meta_data, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', '{"providers": ["google"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', '{"providers": ["github"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NULL, '{"providers": ["google"]}', NOW())
+ `)
+
+ // Combine verified filter with provider and keyword
+ const combinedSql = getUsersCountSQL({
+ filter: 'verified',
+ providers: ['google'],
+ keywords: 'verified',
+ forceExactCount: true,
+ })
+ const result = await executeQuery<Array<{ count: number }>>(combinedSql)
+ expect(result[0].count).toBe(1)
+})
+
+withTestDatabase('optimized email search works correctly', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Optimized search by email prefix
+ const emailSql = getUsersCountSQL({ column: 'email', keywords: 'ali', forceExactCount: true })
+ const result = await executeQuery<Array<{ count: number }>>(emailSql)
+ expect(result[0].count).toBe(2) // alice and alicia
+})
+
+withTestDatabase('optimized phone search works correctly', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, phone, instance_id, created_at)
+ VALUES
+ ('${randomUUID()}', '+1234567890', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '+1234999999', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '+9876543210', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Optimized search by phone prefix
+ const phoneSql = getUsersCountSQL({ column: 'phone', keywords: '+1234', forceExactCount: true })
+ const result = await executeQuery<Array<{ count: number }>>(phoneSql)
+ expect(result[0].count).toBe(2)
+})
+
+withTestDatabase('optimized id search works correctly', async ({ executeQuery }) => {
+ const userId1 = 'abc12300-0000-4000-8000-000000000001'
+ const userId2 = 'abc12300-0000-4000-8000-000000000002'
+ const userId3 = 'def45600-0000-4000-8000-000000000003'
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES
+ ('${userId1}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${userId2}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${userId3}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Optimized search by id prefix
+ const idSql = getUsersCountSQL({ column: 'id', keywords: 'abc123', forceExactCount: true })
+ const result = await executeQuery<Array<{ count: number }>>(idSql)
+ expect(result[0].count).toBe(2)
+
+ // Exact UUID match
+ const exactSql = getUsersCountSQL({ column: 'id', keywords: userId1, forceExactCount: true })
+ const exactResult = await executeQuery<Array<{ count: number }>>(exactSql)
+ expect(exactResult[0].count).toBe(1)
+})
+
+withTestDatabase('handles SAML provider filtering', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, raw_app_meta_data, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["sso:provider-id-1"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["sso:provider-id-2"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["google"]}', NOW())
+ `)
+
+ // Filter by SAML provider (special handling for sso: prefix)
+ const samlSql = getUsersCountSQL({ providers: ['saml 2.0'], forceExactCount: true })
+ const result = await executeQuery<Array<{ count: number }>>(samlSql)
+ expect(result[0].count).toBe(2)
+})
diff --git a/packages/pg-meta/test/sql/studio/get-users-paginated.test.ts b/packages/pg-meta/test/sql/studio/get-users-paginated.test.ts
new file mode 100644
index 00000000000..5cbf7c927ef
--- /dev/null
+++ b/packages/pg-meta/test/sql/studio/get-users-paginated.test.ts
@@ -0,0 +1,342 @@
+import { expect, test, afterAll } from 'vitest'
+import { createTestDatabase, cleanupRoot, createDatabaseWithAuthSchema } from '../../db/utils'
+import { getPaginatedUsersSQL } from '../../../src/sql/studio/get-users-paginated'
+import { randomUUID } from 'crypto'
+
+afterAll(async () => {
+ await cleanupRoot()
+})
+
+const withTestDatabase = (
+ name: string,
+ fn: (db: Awaited<ReturnType<typeof createTestDatabase>>) => Promise<void>
+) => {
+ test(name, async () => {
+ const db = await createTestDatabase()
+
+ // Initialize minimal auth schema needed for user pagination tests
+ await createDatabaseWithAuthSchema(db, { includeIdentities: true })
+
+ try {
+ await fn(db)
+ } finally {
+ await db.cleanup()
+ }
+ })
+}
+
+withTestDatabase('returns paginated users with default settings', async ({ executeQuery }) => {
+ // Insert 10 users with different created_at times
+ for (let i = 0; i < 10; i++) {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES (
+ '${randomUUID()}',
+ 'user${i}@supabase.io',
+ '00000000-0000-0000-0000-000000000000',
+ NOW() + INTERVAL '${i} minutes'
+ )
+ `)
+ }
+
+ // Get first page (default limit 50, page 0)
+ const sql = getPaginatedUsersSQL({ sort: 'created_at', order: 'desc' })
+ const result = await executeQuery<Array<{ email: string }>>(sql)
+
+ expect(result.length).toBe(10)
+ // Should be ordered by created_at desc, so user9 should be first
+ expect(result[0].email).toBe('[email protected]')
+ expect(result[9].email).toBe('[email protected]')
+})
+
+withTestDatabase('respects custom limit and pagination', async ({ executeQuery }) => {
+ // Insert 30 users
+ for (let i = 0; i < 30; i++) {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES (
+ '${randomUUID()}',
+ 'user${String(i).padStart(2, '0')}@supabase.io',
+ '00000000-0000-0000-0000-000000000000',
+ NOW() + INTERVAL '${i} minutes'
+ )
+ `)
+ }
+
+ // Get page 1 with limit 10 (should skip first 10, get next 10)
+ const sql = getPaginatedUsersSQL({ sort: 'created_at', order: 'desc', limit: 10, page: 1 })
+ const result = await executeQuery<Array<{ email: string }>>(sql)
+
+ expect(result.length).toBe(10)
+ // Page 1 should start at user19 (0-indexed, skipping first 10)
+ expect(result[0].email).toBe('[email protected]')
+ expect(result[9].email).toBe('[email protected]')
+})
+
+withTestDatabase('sorts by email in ascending order', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ const sql = getPaginatedUsersSQL({ sort: 'email', order: 'asc', limit: 10 })
+ const result = await executeQuery<Array<{ email: string }>>(sql)
+
+ expect(result.length).toBe(3)
+ expect(result[0].email).toBe('[email protected]')
+ expect(result[1].email).toBe('[email protected]')
+ expect(result[2].email).toBe('[email protected]')
+})
+
+withTestDatabase('filters by keywords across multiple fields', async ({ executeQuery }) => {
+ const searchUserId = randomUUID()
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, phone, instance_id, raw_user_meta_data, created_at)
+ VALUES
+ ('${searchUserId}', '[email protected]', NULL, '00000000-0000-0000-0000-000000000000', '{"full_name": "John Doe"}', NOW()),
+ ('${randomUUID()}', '[email protected]', '+1234567890', '00000000-0000-0000-0000-000000000000', '{"full_name": "Jane Smith"}', NOW()),
+ ('${randomUUID()}', '[email protected]', '+9876543210', '00000000-0000-0000-0000-000000000000', '{"full_name": "Bob Jones"}', NOW())
+ `)
+
+ // Search by keyword "john" - should find john.doe by email
+ const emailSql = getPaginatedUsersSQL({ sort: 'created_at', order: 'desc', keywords: 'john' })
+ const emailResult = await executeQuery<Array<{ email: string }>>(emailSql)
+ expect(emailResult.length).toBe(1)
+ expect(emailResult[0].email).toBe('[email protected]')
+
+ // Search by phone
+ const phoneSql = getPaginatedUsersSQL({ sort: 'created_at', order: 'desc', keywords: '1234' })
+ const phoneResult = await executeQuery<Array<{ phone: string }>>(phoneSql)
+ expect(phoneResult.length).toBe(1)
+ expect(phoneResult[0].phone).toBe('+1234567890')
+
+ // Search by ID prefix
+ const idPrefix = searchUserId.substring(0, 8)
+ const idSql = getPaginatedUsersSQL({ sort: 'created_at', order: 'desc', keywords: idPrefix })
+ const idResult = await executeQuery<Array<{ email: string }>>(idSql)
+ expect(idResult.length).toBe(1)
+ expect(idResult[0].email).toBe('[email protected]')
+})
+
+withTestDatabase('filters verified and unverified users', async ({ executeQuery }) => {
+ const now = new Date().toISOString()
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, email_confirmed_at, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NULL, NOW())
+ `)
+
+ // Filter verified users
+ const verifiedSql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ verified: 'verified',
+ })
+ const verifiedResult = await executeQuery<Array<{ email: string }>>(verifiedSql)
+ expect(verifiedResult.length).toBe(2)
+
+ // Filter unverified users
+ const unverifiedSql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ verified: 'unverified',
+ })
+ const unverifiedResult = await executeQuery<Array<{ email: string }>>(unverifiedSql)
+ expect(unverifiedResult.length).toBe(1)
+ expect(unverifiedResult[0].email).toBe('[email protected]')
+})
+
+withTestDatabase('filters anonymous users', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, is_anonymous, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', true, NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', true, NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', false, NOW())
+ `)
+
+ const sql = getPaginatedUsersSQL({ sort: 'created_at', order: 'desc', verified: 'anonymous' })
+ const result = await executeQuery<Array<{ email: string }>>(sql)
+ expect(result.length).toBe(2)
+})
+
+withTestDatabase('filters by providers', async ({ executeQuery }) => {
+ const user1 = randomUUID()
+ const user2 = randomUUID()
+ const user3 = randomUUID()
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, raw_app_meta_data, created_at)
+ VALUES
+ ('${user1}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["google"]}', NOW()),
+ ('${user2}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["google"]}', NOW()),
+ ('${user3}', '[email protected]', '00000000-0000-0000-0000-000000000000', '{"providers": ["github"]}', NOW())
+ `)
+
+ // Also insert identities for the users
+ await executeQuery(`
+ INSERT INTO auth.identities (id, user_id, provider, identity_data, created_at)
+ VALUES
+ ('google1', '${user1}', 'google', '{}', NOW()),
+ ('google2', '${user2}', 'google', '{}', NOW()),
+ ('github1', '${user3}', 'github', '{}', NOW())
+ `)
+
+ // Filter by google provider
+ const googleSql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ providers: ['google'],
+ })
+ const googleResult = await executeQuery<Array<{ email: string }>>(googleSql)
+ expect(googleResult.length).toBe(2)
+
+ // Filter by multiple providers
+ const multipleSql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ providers: ['google', 'github'],
+ })
+ const multipleResult = await executeQuery<Array<{ email: string }>>(multipleSql)
+ expect(multipleResult.length).toBe(3)
+})
+
+withTestDatabase('combines multiple filters', async ({ executeQuery }) => {
+ const now = new Date().toISOString()
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, email_confirmed_at, raw_app_meta_data, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', '{"providers": ["google"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', '${now}', '{"providers": ["github"]}', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NULL, '{"providers": ["google"]}', NOW())
+ `)
+
+ // Combine verified filter with provider and keyword
+ const sql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ keywords: 'verified',
+ verified: 'verified',
+ providers: ['google'],
+ })
+ const result = await executeQuery<Array<{ email: string }>>(sql)
+ expect(result.length).toBe(1)
+ expect(result[0].email).toBe('[email protected]')
+})
+
+withTestDatabase('optimized email search works correctly', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Optimized search by email prefix
+ const sql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ column: 'email',
+ keywords: 'ali',
+ limit: 10,
+ })
+ const result = await executeQuery<Array<{ email: string }>>(sql)
+ expect(result.length).toBe(2)
+ expect(result[0].email).toBe('[email protected]')
+ expect(result[1].email).toBe('[email protected]')
+})
+
+withTestDatabase('optimized phone search works correctly', async ({ executeQuery }) => {
+ await executeQuery(`
+ INSERT INTO auth.users (id, phone, instance_id, created_at)
+ VALUES
+ ('${randomUUID()}', '+1234567890', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '+1234999999', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${randomUUID()}', '+9876543210', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Optimized search by phone prefix
+ const sql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ column: 'phone',
+ keywords: '+1234',
+ limit: 10,
+ })
+ const result = await executeQuery<Array<{ phone: string }>>(sql)
+ expect(result.length).toBe(2)
+})
+
+withTestDatabase('optimized id search works correctly', async ({ executeQuery }) => {
+ const userId1 = 'abc12300-0000-4000-8000-000000000001'
+ const userId2 = 'abc12300-0000-4000-8000-000000000002'
+ const userId3 = 'def45600-0000-4000-8000-000000000003'
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES
+ ('${userId1}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${userId2}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW()),
+ ('${userId3}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Optimized search by id prefix
+ const sql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ column: 'id',
+ keywords: 'abc123',
+ limit: 10,
+ })
+ const result = await executeQuery<Array<{ id: string }>>(sql)
+ expect(result.length).toBe(2)
+ expect(result[0].id).toBe(userId1)
+ expect(result[1].id).toBe(userId2)
+
+ // Exact UUID match
+ const exactSql = getPaginatedUsersSQL({
+ sort: 'created_at',
+ order: 'desc',
+ column: 'id',
+ keywords: userId1,
+ limit: 10,
+ })
+ const exactResult = await executeQuery<Array<{ id: string }>>(exactSql)
+ expect(exactResult.length).toBe(1)
+ expect(exactResult[0].id).toBe(userId1)
+})
+
+withTestDatabase('includes provider information from identities', async ({ executeQuery }) => {
+ const userId = randomUUID()
+
+ await executeQuery(`
+ INSERT INTO auth.users (id, email, instance_id, created_at)
+ VALUES ('${userId}', '[email protected]', '00000000-0000-0000-0000-000000000000', NOW())
+ `)
+
+ // Insert multiple identities for the user
+ await executeQuery(`
+ INSERT INTO auth.identities (id, user_id, provider, identity_data, created_at)
+ VALUES
+ ('google1', '${userId}', 'google', '{}', NOW()),
+ ('github1', '${userId}', 'github', '{}', NOW())
+ `)
+
+ const sql = getPaginatedUsersSQL({ sort: 'created_at', order: 'desc', limit: 10 })
+ const result = await executeQuery<Array<{ email: string; providers: string[] }>>(sql)
+
+ expect(result.length).toBe(1)
+ expect(result[0].email).toBe('[email protected]')
+ expect(result[0].providers).toHaveLength(2)
+ expect(result[0].providers).toContain('google')
+ expect(result[0].providers).toContain('github')
+})