UNPKG

@opengis/bi

Version:

BI data visualization module

59 lines (51 loc) 2.3 kB
import { pgClients } from "@opengis/fastify-table/utils.js"; const q = `select nspname||'.'||relname as table, json_agg(json_build_object('name',attname, 'type', a.atttypid::regtype, 'description', coalesce(col_description(attrelid, attnum),attname))) as columns from pg_attribute a left join pg_catalog.pg_attrdef d ON (a.attrelid, a.attnum) = (d.adrelid, d.adnum) JOIN pg_class AS i ON i.oid = a.attrelid JOIN pg_namespace AS NS ON i.relnamespace = NS.OID where a.attnum > 0 and nspname||'.'||relname = $1 and not a.attisdropped group by nspname||'.'||relname limit 1`; export default async function dbTablePreview({ pg = pgClients.client, params = {}, query = {} }) { if (!params?.name) { return { message: 'not enough params: name', status: 400 }; } if (query.sql) return q; try { const { table, columns } = await pg .query(q, [params.name.replace(/"/g, '')]) .then(el => el.rows?.[0] || {}); if (!table) { return { message: 'table not found', status: 404 }; } const { count = 0 } = await pg.query('select reltuples as count from pg_class where oid = to_regclass($1)', [params.name]) .then(el => el.rows?.[0] || {}); const geom = columns.find((el) => el.type === 'geometry')?.name; const { bounds, extentStr } = geom ? await pg.query(`select count(*), st_asgeojson(st_extent(${geom}))::json as bounds, replace(regexp_replace(st_extent(${geom})::box2d::text,'BOX\\(|\\)','','g'),' ',',') as "extentStr" from ${params.name}`).then(el => el.rows?.[0] || {}) : {}; const extent = extentStr ? extentStr.split(',') : undefined; const systemColumns = [ 'uid', 'files', 'editor_date', 'cdate', 'editor_id', geom, ]; const columnList = columns.map((el) => el?.name).filter((el) => !systemColumns.includes(el)); const { rows = [] } = await pg.query(`select ${columnList.map(el => `"${el.replace(/'/g, "''")}"`).join(',')} ${geom ? ', st_asgeojson(geom)::json as geom' : ''} from ${params.name.replace(/'/g, '')} limit 10`); return { count, geom: !!geom, bounds, extent, columns, rows, }; } catch (err) { return { error: err.toString(), status: 500 }; } }