Skip to content

Fix dbs and apis - #24

Open
dvalenca wants to merge 128 commits into
mainfrom
fix-dbs-and-apis-v2
Open

Fix dbs and apis#24
dvalenca wants to merge 128 commits into
mainfrom
fix-dbs-and-apis-v2

Conversation

@dvalenca

@dvalenca dvalenca commented Aug 1, 2026

Copy link
Copy Markdown

fix-dbs-and-apis-v2
Este PR consolida todas as mudanças da branch fix-dbs-and-apis em um único commit limpo, excluindo arquivos de dados grandes (>50MB) que bloqueavam o push para o GitHub.
O que mudou
ciclodados

  • Adiciona traffic_tickets e emergency_calls ao /v1/nearby com top_violations, vulnerable_violations e dados mensais (first_month_data/last_month_data)
  • Suporte a parâmetro street para queries espaciais alinhadas à via
  • Correção: ST_GeomFromGeoJSON para pdc_relation_ways
  • Raio padrão dinâmico: 10m para rua, 200m para ponto
    cyclist-profile
  • API de tabulação cruzada completa (/cross, /categories, /dictionary, /filters, /points, /OD, /distribution, /downloads)
  • Distribuições de renda, escolaridade e cor/raça nos survey-locations
  • Parâmetro min_interviews (padrão 30) nos endpoints
  • Correções: agrupamento GROUP BY street+year, coordenadas GPS, ordem de rotas, pool lazy drizzle
    cyclist-counts
  • 22 novos eventos de contagem com pipeline de processamento e city lookup via point-in-polygon
    cycling-infra
  • Remoção do ciclomapa, correção de city_id via limites IBGE
  • Correção de duplicatas no seed, divergências de sumário e sobreposição non-PDC
    emergency-calls
  • Normalização de categorias de acidentes em JSON compartilhado
  • Novo endpoint v2/streets/history usando FK pcr_street_id
  • Endpoints enriquecidos com geometria/extensão e accidents_by_category no GeoJSON
  • Correções: gender via ILIKE, start_year=2020 padrão, agrupamento por pcr_address
    traffic-tickets (novo app)
  • App completo com Docker, Drizzle ORM, seed pipeline e normalização de ruas
  • Endpoints: /v1/streets, /v1/street-stats, /v1/law-stats, /v1/dashboard
  • Pipeline de verificação de localização com ferramentas de correção
  • Dashboard com street_info e período dinâmico
  • Migrations e MVs migradas para Drizzle
    traffic-deaths
  • Endpoint causas-secundarias corrigido para usar linhaa, filtro transportMode
  • Decoder DATASUS, matriz de colisão, dados 2024, nomes RMR
    database
  • Esquemas, seeds, migrations e OpenAPI specs atualizados para todos os módulos
  • Scripts de seed refatorados e centralizados
    exports
  • Dados do AmeCiclo atualizados: ciclodados, infrações, perfil ciclista, sinistros fatais, vias inseguras, contagens, bicicletários, bike PE, execução cicloviária
    Nota: Arquivos de seed data grandes foram adicionados ao .gitignore para respeitar o limite de 100MB do GitHub.

- Add .env file with database configuration
- Remove SSL config for local development
- Simplify street search queries to use normalized nlogra_conc column
- All 5 endpoints now working (75/76 total endpoints)
- Add /v1/infrastructure/geojson endpoint
- Returns FeatureCollection format compatible with mapping libraries
- Supports type and limit query parameters
- Update OpenAPI documentation
- Fix TypeScript compilation issues
- Add detailed descriptions and examples to InfrastructureSchema fields
- Improve query parameter documentation with type examples
- Update generate-openapi.ts to auto-copy specs to docs directory
- Reorganize route paths to avoid conflicts (/v1/infrastructure-geojson, /v1/infrastructure-nearby)
- Add comprehensive OpenAPI metadata for all 4 infrastructure endpoints:
  - GET /v1/infrastructure - List with filters
  - GET /v1/infrastructure/{id} - Get by ID
  - GET /v1/infrastructure-geojson - GeoJSON format
  - GET /v1/infrastructure-nearby - Proximity search
…nd improved nomenclature

- Add gzip compression middleware for 90%+ size reduction
- Implement geometry simplification with ST_Simplify (optional)
- Add decimal precision control for coordinates (4-6 decimal places)
- Add minimal mode with only essential status properties
- Improve nomenclature for PDC status categories:
  - pdc_realizado_designado: Built within PDC with designated infrastructure
  - pdc_realizado_nao_designado: Built within PDC with non-designated infrastructure
  - realizado_fora_pdc: Built outside PDC
  - pdc_nao_realizado: PDC not built
- Add pagination support (limit/offset) without forced defaults
- Update OpenAPI documentation with new parameters
- Optimize response size from 5.6MB to 283KB with all optimizations combined
- Add only_all query parameter to return direct FeatureCollection
- Update handler to return simplified format when only_all=true
- Update route schema to support both response formats
- Maintains backward compatibility with existing all/byCity structure
- Add by_length parameter to prioritize streets by extension
- Add by_elements parameter (structure ready for future implementation)
- Implement hybrid fuzzy search with pg_trgm fallback to ILIKE
- Add length field in search response when requested
- Support both similarity-based and length-based ordering
- Maintain backward compatibility with existing search API

Examples:
- /v1/streets/search?q=boa&by_length=true (orders by street length)
- /v1/streets/search?q=boa (orders by similarity score)
…port

- Fix empty coordinates by using ST_AsGeoJSON for PostGIS geometry
- Change street details to return all segments with same name
- Convert response to proper GeoJSON FeatureCollection format
- Add totalSegments and totalLength in properties
- Support MultiLineString geometry from PostGIS
- Maintain backward compatibility with single ID lookup

Tested with AV BOA VIAGEM:
- Returns complete geometry with 16 line segments
- Total length: 8.498 km correctly calculated
- Proper GeoJSON FeatureCollection structure
- Resolves 'too many clients already' error
- Allows multiple services to connect simultaneously
- Adds shared_buffers configuration for better performance
- Atualiza schemas com estruturas de dados baseadas nos schemas reais do banco
- Adiciona schemas para cycling counts, traffic violations, cycling infra, shared bikes e bike racks
- Copia OpenAPI atualizado para documentação (porta 3001)
- Cria estrutura para rotas de tráfego (preparação para implementação futura)
…atic research locations

- Add static list of 17 research locations with correct coordinates
- Implement efficient in-memory search for cycling profile availability
- Return 1/0 for cycling_profile field in data summary endpoint
- Support bidirectional street matching (works for both streets in intersections)
- Maintain real database queries for cycling_counts data
- Workaround for incorrect coordinates in cyclist_profiles table
… sources

- Remove simulated dangerous_streets and traffic_violations fields
- Implement real cycling infrastructure PDC analysis queries
- Add emergency_calls count from emergency_calls table
- Maintain cycling_counts with 30m precision radius
- Keep cycling_profile static lookup for accurate results
- All endpoints now return only real data from database
- Tested with Agamenon (no profile/counts) and Domingos Ferreira (has both)
- Remove slow PDC spatial queries from data-summary (6s -> 0.059s)
- Keep only fast essential data: cycling_counts, cycling_profile, emergency_calls
- PDC analysis can be implemented as separate endpoint when needed
- Maintain data accuracy while dramatically improving response time
- All queries now use efficient indexes and simple lookups
body: JSON.stringify({ location_id: l.location_id, verified: 'false',
corrected_street: name, corrected_street_code: code }),
});
wrapper.parentNode.innerHTML = '<span>'+esc(name)+' <span style="color:#888;font-size:10px;">['+code+']</span></span>';
Mover arquivos de dados que estavam em apps/*/src/db/ para
packages/database/seed-data/ (bicycle-racks, shared-bike,
traffic-calls, cycling-infra, emergency-calls).

Atualizar paths nos seed scripts correspondentes.
- pipelines/convert-dbc.py: add PRELIM fallback for recent DATASUS data
- pipelines/convert-dbc.py: support year ranges in --download (2016-2026)
- scripts/split-data.sh: split traffic-tickets TSVs into <100 MB parts
- scripts/recompose-data.sh: recompose parts before seeding
- .gitignore: unify seed-data patterns, ignore recompiled artifacts
- package.json: db:seed now runs recompose before seed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants