From 422ab2d97f67f5d090905ca331b84be7ff46d00a Mon Sep 17 00:00:00 2001 From: Moran Date: Fri, 30 Jan 2026 11:34:46 -0300 Subject: [PATCH] feat/Script atualizar latitude e longitude da cidade --- src/utils/scripts/update_coordinates.ts | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/utils/scripts/update_coordinates.ts diff --git a/src/utils/scripts/update_coordinates.ts b/src/utils/scripts/update_coordinates.ts new file mode 100644 index 0000000..445ee2c --- /dev/null +++ b/src/utils/scripts/update_coordinates.ts @@ -0,0 +1,52 @@ +import dotenv from 'dotenv' +import path from 'path' +import { Client } from 'pg' +import { fileURLToPath } from 'url' + +const currentFilename = fileURLToPath(import.meta.url) +const currentDirname = path.dirname(currentFilename) +const projectRoot = path.resolve(currentDirname, '..', '..', '..') + +dotenv.config({ path: path.join(projectRoot, '.env') }) + +const { + PG_DATABASE, + PG_USERNAME, + PG_PASSWORD, + PG_HOST, + PG_PORT, + DATABASE_URL +} = process.env + +const connectionString + = DATABASE_URL + || `postgresql://${PG_USERNAME}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}/${PG_DATABASE}` + +function isValidConnectionString(cs: string | undefined): boolean { + return typeof cs === 'string' && cs.length > 0 && !/undefined/.test(cs) +} + +if (!isValidConnectionString(connectionString)) { + process.exit(1) +} + +async function main(): Promise { + const client = new Client({ connectionString }) + await client.connect() + + try { + await client.query(` + UPDATE cidades + SET + latitude = ST_Y(ST_PointOnSurface(poligono)), + longitude = ST_X(ST_PointOnSurface(poligono)), + updated_at = NOW() + WHERE poligono IS NOT NULL + AND (latitude IS NULL OR longitude IS NULL); + `) + } finally { + await client.end() + } +} + +main().catch(() => process.exit(1))