AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 333628
Accepted
Kokizzu
Kokizzu
Asked: 2023-12-01 14:56:28 +0800 CST2023-12-01 14:56:28 +0800 CST 2023-12-01 14:56:28 +0800 CST

Restaure, mas apenas os dados ausentes na tabela

  • 772

Tenho 2 bancos de dados já restaurados em 2 bancos de dados diferentes na mesma instância, chamo-o geoe restore1 o esquema é idêntico, a única diferença é que geoo banco de dados contém apenas registros antes de <= 2023-11-23e depois de >= 2023-12-01, enquanto restore1contém <= 2023-11-30, como posso copiá-los valores ausentes ( 2023-11-23até 2023-11-30o banco restore1de geodados) para cada tabela facilmente?

uma maneira que eu poderia pensar é criar um programa, para cada tabela, selecionando o último id antes 2023-11-24de geo(chamá-lo X), em seguida, selecionar todos os registros com id maior que Xe, em seguida, inseri-lo manualmente no geobanco de dados.

Existe alguma maneira mais simples?

existem centenas de tabelas, mas a maioria delas é algo assim:

restore1=# \d station_logs_599
                                              Table "public.station_logs_599"
         Column         |              Type              | Collation | Nullable |                 Default
------------------------+--------------------------------+-----------+----------+------------------------------------------
 id                     | integer                        |           | not null | nextval('station_logs_id_seq'::regclass)
 created_at             | timestamp(6) without time zone |           |          |
 updated_at             | timestamp(6) without time zone |           |          |
 deleted_at             | timestamp(6) without time zone |           |          |
 submitted_at           | timestamp(6) without time zone |           | not null |
 sequence               | integer                        |           |          |
 level_sensor           | double precision               |           |          |
 accel_x                | double precision               |           |          |
 accel_y                | double precision               |           |          |
 accel_z                | double precision               |           |          |
 power_current          | double precision               |           |          |
 ip_address             | character varying(50)          |           |          |
 log_type               | integer                        |           |          |
 station_id             | integer                        |           | not null |
 power_voltage          | double precision               |           |          |
 data                   | jsonb                          |           |          |
 is_deleted             | boolean                        |           | not null | false
 temperature            | double precision               |           |          |
 wind_speed             | double precision               |           |          |
 soil_moisture          | double precision               |           |          |
 wind_direction         | double precision               |           |          |
 raindrop               | double precision               |           |          |
 humidity               | integer                        |           |          |
 barometric_pressure    | double precision               |           |          |
 wind_speed_average     | double precision               |           |          |
 wind_gust              | double precision               |           |          |
 wind_direction_average | double precision               |           |          |
 rain_rate              | double precision               |           |          |
Indexes:
    "station_logs_599_epoch" btree (date_part('epoch'::text, submitted_at))
    "station_logs_599_submitted_at" btree (submitted_at)
    "uniq_sid_sat_599" UNIQUE CONSTRAINT, btree (submitted_at)
Foreign-key constraints:
    "station_logs_599_station_fk" FOREIGN KEY (station_id) REFERENCES stations(id)
postgresql
  • 1 1 respostas
  • 46 Views

1 respostas

  • Voted
  1. Best Answer
    Kokizzu
    2023-12-05T00:44:53+08:002023-12-05T00:44:53+08:00

    Eu uso golang para resolver isso:

    tl;dw:

    1. leia a tabela de todas as estações
    2. se ambos existirem, selecione recapitulação por data para origem e destino ( DATE(submitted_at), COUNT(1))
    3. se o destino tiver um número diferente da origem, insira no destino
        var src, dest *Pg.RDBMS
        {
            opt := `host=127.0.0.1 user=x password=x dbname=x sslmode=disable` 
            conn := sqlx.MustConnect(`postgres`, opt)
            conn.DB.SetMaxOpenConns(61) 
            dest = &Pg.RDBMS{
                Name:    `destination`,
                Adapter: conn,
            }
        }
    
        {
            opt := `host=127.0.0.1 user=y password=y dbname=y sslmode=disable` 
            conn := sqlx.MustConnect(`postgres`, opt)
            src = &Pg.RDBMS{
                Name:    `source`,
                Adapter: conn,
            }
        }
    
    
        srcStations := src.QStrMapMap(`imei`, `SELECT * FROM stations`)
        destStations := dest.QStrMapMap(`imei`, `SELECT * FROM stations`)
    
        // compare stations
        removeUnecessary := func(m M.SX) {
            delete(m, `last_level_sensor`)
            delete(m, `last_submitted_at`)
            delete(m, `updated_at`)
            delete(m, `updated_by`)
            delete(m, `name`)
            delete(m, `lat`)
            delete(m, `long`)
        }
    
        for imei := range srcStations {
            ss := srcStations.GetMSX(imei)
            removeUnecessary(ss)
            ds := destStations.GetMSX(imei)
            removeUnecessary(ds)
    
            // check the diff of stations table
            if len(ds) == 0 {
                fmt.Println(`missing from destination: `+imei, ss)
                // TODO: insert on destination
                continue
            } else if !reflect.DeepEqual(ss, ds) {
                fmt.Println(`different: ` + imei)
                diffs := pretty.Diff(ss, ds)
                for _, diff := range diffs {
                    fmt.Println(diff)
                }
            }
    
            // if source different from destination, there might be one more than station created not with same order after moving server
            srcStationId := fmt.Sprint(ss[`id`])
            dstStationId := fmt.Sprint(ds[`id`])
            if srcStationId != dstStationId {
                fmt.Println(`source station id not the same as destination`, srcStationId, dstStationId)
            }
    
            // check whether tables exists
            if !src.TableExists(`station_logs_` + srcStationId) {
                fmt.Println(`missing source table station_logs_` + srcStationId)
                continue
            }
            if !dest.TableExists(`station_logs_` + dstStationId) {
                fmt.Println(`missing destination table station_logs_` + dstStationId)
                continue
            }
    
            srcSelect1 := fmt.Sprintf(`SELECT DATE(submitted_at)::TEXT, COUNT(1) FROM station_logs_%s GROUP BY 1`, srcStationId)
            srcDtCount := src.QStrIntMap(srcSelect1)
    
            dstSelect1 := fmt.Sprintf(`SELECT DATE(submitted_at)::TEXT, COUNT(1) FROM station_logs_%s GROUP BY 1`, dstStationId)
            dstDtCount := dest.QStrIntMap(dstSelect1)
    
            fmt.Println(`comparing station_logs_`, srcStationId, dstStationId)
    
            for submittedAt, srcCount := range srcDtCount {
                dstCount := dstDtCount[submittedAt]
                if srcCount != dstCount {
                    fmt.Println(`different count: `, srcStationId, submittedAt, srcCount, dstCount)
    
                    query2 := fmt.Sprintf(`SELECT * FROM station_logs_%s WHERE DATE(submitted_at) = '%s'`, srcStationId, submittedAt)
    
                    srcLogs := src.QStrMapMap(`id`, query2)
    
                    dstInsertLogs := fmt.Sprintf(`
    INSERT INTO station_logs_%s (
        created_at, updated_at, submitted_at, sequence, level_sensor, accel_x, accel_y, accel_z, power_current, ip_address, log_type, station_id, power_voltage, data, is_deleted, temperature, wind_speed, soil_moisture, wind_direction, raindrop, humidity, barometric_pressure, wind_speed_average, wind_gust, wind_direction_average, rain_rate
    ) VALUES (
                $1,         $2,        $3,           $4,           $5,         $6,      $7,      $8,      $9,            $10,       $11,      $12,        $13,           $14,   $15,        $16,         $17,        $18,           $19,         $20,      $21,                 $22,                 $23,       $24,                  $25,        $26 
    )`, dstStationId)
                    query3 := fmt.Sprintf(`
    SELECT COUNT(1) FROM station_logs_%s WHERE submitted_at = $1`, dstStationId)
    
                    skipped := 0
                    dest.DoTransaction(func(tx *Pg.Tx) string {
                        for id := range srcLogs {
                            log := srcLogs.GetMSX(id)
                            if tx.QInt(query3, log[`submitted_at`]) > 0 {
                                skipped++
                                continue
                            }
    
                            tx.DoExec(dstInsertLogs,
                                log[`created_at`],
                                log[`updated_at`],
                                log[`submitted_at`],
                                log[`sequence`],
                                log[`level_sensor`],
                                log[`accel_x`],
                                log[`accel_y`],
                                log[`accel_z`],
                                log[`power_current`],
                                log[`ip_address`],
                                log[`log_type`],
                                log[`station_id`],
                                log[`power_voltage`],
                                log[`data`],
                                log[`is_deleted`],
                                log[`temperature`],
                                log[`wind_speed`],
                                log[`soil_moisture`],
                                log[`wind_direction`],
                                log[`raindrop`],
                                log[`humidity`],
                                log[`barometric_pressure`],
                                log[`wind_speed_average`],
                                log[`wind_gust`],
                                log[`wind_direction_average`],
                                log[`rain_rate`],
                            )
                        }
                        return ``
                    })
    
                    fmt.Println(`inserted: `, srcStationId, submittedAt, len(srcLogs), `skipped`, skipped)
    
                }
    
            }
       }
    
    • 0

relate perguntas

  • Posso ativar o PITR depois que o banco de dados foi usado

  • Práticas recomendadas para executar a replicação atrasada do deslocamento de tempo

  • Os procedimentos armazenados impedem a injeção de SQL?

  • Sequências Biológicas do UniProt no PostgreSQL

  • Qual é a diferença entre a replicação do PostgreSQL 9.0 e o Slony-I?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve