UNPKG

@opengis/bi

Version:

BI data visualization module

60 lines (51 loc) 2.09 kB
import { randomBytes, createHash } from 'node:crypto'; const schema = 'data_user'; const columnType = { text: 'text', select: 'text', date: 'date', 'yes/no': 'boolean', badge: 'text', number: 'numeric', tags: 'text[]', geom: 'geom', }; export default function createTable(columns, name) { const tableName = randomBytes(64).toString('hex').substring(0, 24).replace(/^\d+/, ''); const table = `${schema}.${tableName}`; const pkey = tableName.concat('_id'); columns?.forEach?.((el, i) => Object.assign(el, { name: `col_${i}`, // el.name type: columnType[el.format || 'text'] || 'text', })); const clsQuery = columns ?.filter?.(col => col?.format === 'select' && col.data?.length) ?.map(col => { const data = JSON.stringify(col.data).replace(/'/g, "''"); Object.assign(col, { data: createHash('md5').update([tableName, col.name].join()).digest('hex') }); return `insert into admin.cls(clsid,name,type,module) values('${col.data}','${col.data}','json', '${table}'); insert into admin.cls(code,name,parent,icon,data,module) select value->>'id',value->>'text','${col.data}',value->>'icon',value->>'data', '${table}' from json_array_elements('${data}'::json)`; }) ?.join(';'); const createQuery = `create table if not exists ${table} ( ${pkey} text not null default encode(public.gen_random_bytes(6), 'hex'), geom public.geometry, ${columns ? ` ${columns?.map?.((el) => `${el.name} ${el.type}`).join(', ')},` : ''} cdate timestamp without time zone not null default now(), editor_date timestamp without time zone, uid text, editor_id text, files json, constraint ${table.replace(/\./g, '_')}_constraint_pkey PRIMARY KEY (${pkey}) )`; const commentQuery = columns ?.filter?.((el) => el.title) ?.map((el) => `comment on column ${table}.${el.name} is '${el.title}'`) ?.join(';'); return { table, pkey, sql: [createQuery, commentQuery, (name ? `comment on table ${table} is '${name}'` : undefined), clsQuery].filter((el) => el).join(';'), }; }