Skip to content

feat: support table count via HEAD #291

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions src/lib/PostgresMetaTables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ident, literal } from 'pg-format'
import { DEFAULT_SYSTEM_SCHEMAS } from './constants.js'
import { coalesceRowsToArray, filterByList } from './helpers.js'
import { columnsSql, primaryKeysSql, relationshipsSql, tablesSql } from './sql/index.js'
import { PostgresMetaResult, PostgresTable } from './types.js'
import { FilterParams, PaginationParams, PostgresMetaResult, PostgresTable } from './types.js'

export default class PostgresMetaTables {
query: (sql: string) => Promise<PostgresMetaResult<any>>
Expand All @@ -11,19 +11,36 @@ export default class PostgresMetaTables {
this.query = query
}

async count({
includeSystemSchemas = false,
includedSchemas,
excludedSchemas,
}: FilterParams = {}): Promise<PostgresMetaResult<{ count: number }>> {
let sql = `WITH tables AS (${tablesSql}) SELECT count(1) FROM tables`
const filter = filterByList(
includedSchemas,
excludedSchemas,
!includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
)
if (filter) {
sql += ` WHERE schema ${filter}`
}

const { data, error } = await this.query(sql)
if (error) {
return { data, error }
} else {
return { data: data[0], error }
}
}

async list({
includeSystemSchemas = false,
includedSchemas,
excludedSchemas,
limit,
offset,
}: {
includeSystemSchemas?: boolean
includedSchemas?: string[]
excludedSchemas?: string[]
limit?: number
offset?: number
} = {}): Promise<PostgresMetaResult<PostgresTable[]>> {
}: FilterParams & PaginationParams = {}): Promise<PostgresMetaResult<PostgresTable[]>> {
let sql = enrichedTablesSql
const filter = filterByList(
includedSchemas,
Expand Down
13 changes: 13 additions & 0 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@ import { Options as PrettierOptions } from 'prettier'

export interface FormatterOptions extends PrettierOptions {}

// Request types
export interface FilterParams {
includeSystemSchemas?: boolean
includedSchemas?: string[]
excludedSchemas?: string[]
}

export interface PaginationParams {
limit?: number
offset?: number
}

// Response types
export interface PostgresMetaOk<T> {
data: T
error: null
Expand Down
1 change: 1 addition & 0 deletions src/server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const app = fastify({
logger,
disableRequestLogging: true,
requestIdHeader: PG_META_REQ_HEADER,
ignoreTrailingSlash: true,
})

app.setErrorHandler((error, request, reply) => {
Expand Down
30 changes: 30 additions & 0 deletions src/server/routes/tables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,36 @@ import { DEFAULT_POOL_CONFIG } from '../constants.js'
import { extractRequestForLogging, translateErrorToResponseCode } from '../utils.js'

export default async (fastify: FastifyInstance) => {
fastify.head<{
Headers: { pg: string }
Querystring: {
include_system_schemas?: string
// Note: this only supports comma separated values (e.g., ".../tables?included_schemas=public,core")
included_schemas?: string
excluded_schemas?: string
}
}>('/', async (request, reply) => {
const connectionString = request.headers.pg
const includeSystemSchemas = request.query.include_system_schemas === 'true'
const includedSchemas = request.query.included_schemas?.split(',')
const excludedSchemas = request.query.excluded_schemas?.split(',')

const pgMeta = new PostgresMeta({ ...DEFAULT_POOL_CONFIG, connectionString })
const { data, error } = await pgMeta.tables.count({
includeSystemSchemas,
includedSchemas,
excludedSchemas,
})
await pgMeta.end()
if (error) {
request.log.error({ error, request: extractRequestForLogging(request) })
reply.code(translateErrorToResponseCode(error, 500))
return { error: error.message }
}

return reply.header('content-range', `*/${data.count}`).send()
})

fastify.get<{
Headers: { pg: string }
Querystring: {
Expand Down
13 changes: 13 additions & 0 deletions test/lib/tables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ const cleanNondet = (x: any) => {
}
}

test('count', async () => {
const res = await pgMeta.tables.count()

expect(res).toMatchInlineSnapshot(`
Object {
"data": Object {
"count": 5,
},
"error": null,
}
`)
})

test('list', async () => {
const res = await pgMeta.tables.list()

Expand Down