You need to enable JavaScript to run this app. 已完成SQL Server到Postgres全量迁移后,如何同步增量更新数据
优惠活动
大模型
产品
解决方案
定价
更多

已完成SQL Server到Postgres全量迁移后,如何同步增量更新数据

增量同步实现场景说明

基础背景

  • 已完成SQL Server到Postgres的全量数据迁移,可实现跨库对应表的行数差异比对
  • 核心需求:SQL Server侧目标表新增单行数据时,仅同步该新增行到Postgres对应表,无需重新执行全表迁移

当前已编写的实现代码

import pandas as pd
from sqlalchemy import create_engine

def ask_mssql():
    engine = create_engine('mssql+pyodbc://@' + 'RONY' + '/' + 'testdb' + '?driver=SQL+Server')
    return engine


def ask_postgre():
    db_string = "postgres+psycopg2://{}:{}@{}/{}".format('postgres', 'rony1234',
                                                     '127.0.0.1',
                                                     'mockdb')
    engine = create_engine(db_string)
    return engine


def mssql_syntax(diff, tablename, order):
    query = 'select top {} * from {} order by {} desc'.format(diff, tablename, order)
    return query

def postgre_syntax(diff, tablename, order):
    query = 'select * from {} order by {} desc limit {}'.format(tablename, order, diff)
    return query

if __name__ == '__main__':
    db_type = input("Please enter client's db: mssql, postgresql, oracle\n")
    db_type = db_type.lower()
    if db_type == 'mssql':
        engine_client = ask_mssql()

    db_type_our = input("Please enter your db: mssql, postgresql, oracle\n")
    db_type_our = db_type_our.lower()
    if db_type_our == 'postgresql':
        engine_our = ask_postgre()

    table_name = input('\nInput the client table:\n')
    query = 'select count(*) from {}'.format(table_name)
    df_client = pd.read_sql(query,engine_client)

    our_table = input('\nInput the table name in your db\n')
    pquery = 'select count(*) from {}'.format(our_table)
    df_our = pd.read_sql(pquery,engine_our)

    if df_client.values[0][0] != df_our.values[0][0]:
        diff = df_client.values[0][0] - df_our.values[0][0]
        print('\nDifference of {} rows found'.format(diff))
        order_column = input('\nPlease enter a column to order the data on\n')

        if db_type == 'mssql':
            query = mssql_syntax(diff, table_name, order_column)

        if db_type == 'postgresql':
            query = postgre_syntax(diff, table_name, order_column)

            df = pd.read_sql(query, engine_client)

            df.to_sql(our_table, engine_our, if_exists='append')

        else:
            print('\nTable already Updated.')

代码存在的实际问题

  • 分支判断错位:生成增量查询语句后,代码仅在源端库为PostgreSQL的分支下执行数据读取、写入流程;当源端为SQL Server时,生成对应查询语句后会直接进入else分支,输出“表已更新”,完全不执行同步动作
  • 异常场景覆盖不足:仅计算源端行数减目标端行数的差值,未处理目标端行数多于源端的情况;若差值为负,拼接SQL时会出现TOP/LIMIT后接负数的语法错误
  • 增量识别存在强前提:按差值行数排序取数的逻辑,要求用户输入的排序列必须是单调递增的唯一列(如自增主键、毫秒精度的创建时间戳);若列值重复、乱序,取出的行不一定是真实的新增数据,存在同步错误数据的风险
  • 语法封装未落地:提前编写了适配SQL Server、PostgreSQL的查询生成函数,但实际执行时按源端类型匹配逻辑,没有真正适配不同库的语法差异

内容的提问来源于stack exchange,提问作者Rony Varghese

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.03 19:45:04