From c0f008e43682c4aba9d15f8d73d6ce06655f6bc4 Mon Sep 17 00:00:00 2001 From: Moran Date: Wed, 18 Feb 2026 17:10:02 -0300 Subject: [PATCH 1/2] feat/migration sanitizacao tombos com locais de coleta vazios --- ...218133831_sanitiza_locais_coleta_vazios.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts diff --git a/src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts b/src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts new file mode 100644 index 0000000..94ee57f --- /dev/null +++ b/src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts @@ -0,0 +1,20 @@ +import { Knex } from 'knex' + +export async function run(knex: Knex): Promise { + await knex.transaction(async trx => { + await trx.raw(` + UPDATE tombos t + JOIN locais_coleta lc ON lc.id = t.local_coleta_id + SET t.local_coleta_id = NULL + WHERE lc.descricao IS NULL OR TRIM(lc.descricao) = '' + `) + + await trx.raw(` + DELETE lc + FROM locais_coleta lc + LEFT JOIN tombos t ON t.local_coleta_id = lc.id + WHERE (lc.descricao IS NULL OR TRIM(lc.descricao) = '') + AND t.hcf IS NULL + `) + }) +} From 07b484daa0ee718eff43bc2b11aeb5aef582f1ea Mon Sep 17 00:00:00 2001 From: Moran Date: Wed, 18 Feb 2026 20:20:24 -0300 Subject: [PATCH 2/2] Melhorias sql --- ...60218133831_sanitiza_locais_coleta_vazios.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts b/src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts index 94ee57f..0027f22 100644 --- a/src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts +++ b/src/database/migration/20260218133831_sanitiza_locais_coleta_vazios.ts @@ -3,18 +3,19 @@ import { Knex } from 'knex' export async function run(knex: Knex): Promise { await knex.transaction(async trx => { await trx.raw(` - UPDATE tombos t - JOIN locais_coleta lc ON lc.id = t.local_coleta_id - SET t.local_coleta_id = NULL - WHERE lc.descricao IS NULL OR TRIM(lc.descricao) = '' + UPDATE tombos + SET local_coleta_id = NULL + FROM locais_coleta lc + WHERE tombos.local_coleta_id = lc.id + AND (lc.descricao IS NULL OR TRIM(lc.descricao) = '') `) await trx.raw(` - DELETE lc - FROM locais_coleta lc - LEFT JOIN tombos t ON t.local_coleta_id = lc.id + DELETE FROM locais_coleta lc WHERE (lc.descricao IS NULL OR TRIM(lc.descricao) = '') - AND t.hcf IS NULL + AND NOT EXISTS ( + SELECT 1 FROM tombos t WHERE t.local_coleta_id = lc.id + ) `) }) }