数据库表结构对比小工具

数据库表结构对比小工

  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
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/bin/env python3
# coding: utf8
"""数据结构 - 对比工具

QA -

"""
import csv
import logging
import time
from typing import Union

import pymssql
import pymysql

logger = logging.getLogger('sql.contrast')


class SqlWriteError(Exception):
    pass


class BaseSql:
    def __init__(self, host, port, user, password, db, charset='utf8',
                 use_unicode=True, **kwargs):
        super().__init__()
        self.SQL_HOST = host  # 主机
        self.SQL_PORT = port  # 端口
        self.SQL_USER = user  # 用户
        self.SQL_PASSWD = password  # 密码
        self.SQL_DB = db  # 数据库
        self.SQL_CHARSET = charset  # 编码
        self.use_unicode = use_unicode
        # 表前缀
        self.TABLE_PREFIX = kwargs.pop('prefix', '')
        self.kwargs = kwargs
        self.pooled_sql = None

    @property
    def _sql(self):
        raise NotImplementedError

    def set_use_db(self, db_name):
        """设置当前数据库"""
        return self._sql.select_db(db_name)

    def set_charset(self, charset):
        """设置数据库链接字符集"""
        return self._sql.set_charset(charset)

    def close(self):
        """关闭数据库连接"""
        self._sql.close()

    def read_db(self, command, args=None, ):
        """执行数据库读取数据, 返回结果
        :param command
        :param args
        """
        if self.pooled_sql is not None:
            _sql = self.pooled_sql.connection()
        else:
            _sql = self._sql

        cur = _sql.cursor()
        cur.execute(command, args)
        results = cur.fetchall()
        cur.close()
        return results


class MySqlAPI(BaseSql):
    @property
    def _sql(self):
        return pymysql.connect(
            host=self.SQL_HOST,
            port=self.SQL_PORT,
            user=self.SQL_USER,
            password=self.SQL_PASSWD,  # 可以用 passwd为别名
            database=self.SQL_DB,  # 可以用 db    为别名;
            charset=self.SQL_CHARSET,
            use_unicode=self.use_unicode,
            **self.kwargs
        )

    def tables_name(self):
        return [_c[0].decode() if isinstance(_c[0], bytes) else _c[0] for _c in self.read_db("show tables")]

    def columns(self, table, ):
        """返回table中列(字段)的所有信息

         +-------+-------+------+------+-----+---------+-------+
         | index |   0   |  1   |   2  |  3  |    4    |   5   |
         +-------+-------+------+------+-----+---------+-------+
         | dict  | Field | Type | Null | Key | Default | Extra |
         +-------+-------+------+------+-----+---------+-------+
        """
        return self.read_db(f'show columns from `{table}`', )

    def columns_name(self, table) -> list:
        """返回 table 中的 列名在一个列表中"""
        return [_c[0].decode() if isinstance(_c[0], bytes) else _c[0] for _c in self.columns(table)]


class MsSqlAPI(BaseSql):

    @property
    def _sql(self):
        return pymssql.connect(
            host=self.SQL_HOST,
            port=self.SQL_PORT,
            user=self.SQL_USER,
            password=self.SQL_PASSWD,  # 可以用 passwd为别名
            database=self.SQL_DB,  # 可以用 db    为别名;
            charset=self.SQL_CHARSET,
            **self.kwargs
        )

    def tables_name(self):
        """"""
        return [
            _c[0].decode() if isinstance(_c[0], bytes) else _c[0]
            for _c in self.read_db("select name FROM [sysobjects] where [xtype]='u'")
        ]

    def columns(self, table):
        """

        :param table:
        :return:
        """

        return [
            _c
            for _c in self.read_db(f"sp_columns [{table}]")
            if _c[1] == 'dbo'
        ]


class ContrastSQL:
    """数据结构对比"""

    def __init__(self, sql_obj1, sql_obj2, attention_cols: Union[dict, list] = None):
        self.sql_1: MySqlAPI = sql_obj1
        self.sql_2: MySqlAPI = sql_obj2
        if type(sql_obj1) != type(sql_obj2):
            raise TypeError

        if type(sql_obj1) == MsSqlAPI:
            self.check_type = 'sqlserver'
            self.column_name = 'COLUMN_NAME'
            self.type_name_2_index = self.mssql_type_name_2_index
        elif type(sql_obj1) == MySqlAPI:
            self.check_type = 'mysql'
            self.column_name = 'Field'
            self.type_name_2_index = self.mysql_type_name_2_index
        else:
            raise

        self.attention_cols = set(
            attention_cols[self.check_type] if isinstance(attention_cols, (dict,)) else attention_cols or []
        )

        if len(self.attention_cols) == 0:
            if self.check_type == 'sqlserver':
                self.attention_cols = self.mssql_all
            else:
                self.attention_cols = self.mysql_all

        logger.info(
            '=' * 20 + f'[{self.check_type.upper()}] QA({self.sql_1.SQL_DB}) <--> PROD({self.sql_2.SQL_DB})' + '=' * 20
        )
        self.com_tables = self.tables_diff()
        for t in self.com_tables:
            self.columns_diff(t)

    def tables_diff(self):
        """数据表对比"""
        tables1 = set(self.sql_1.tables_name())
        tables2 = set(self.sql_2.tables_name())

        table_common = tables2 & tables1
        logger.debug('COMMON TABLE: %s', table_common)

        if tables1 - table_common:
            logger.info(f'[{self.check_type.upper()}]QA_CLOUD. {self.sql_1.SQL_DB} 独有的表: {tables1 - table_common}')
        if tables2 - table_common:
            logger.info(f'[{self.check_type.upper()}]PROD_CLOUD {self.sql_2.SQL_DB} 独有的表: {tables2 - table_common}')
        return table_common

    mssql_all = [
        'TABLE_QUALIFIER', 'TABLE_OWNER', 'TABLE_NAME', 'COLUMN_NAME', 'DATA_TYPE', 'TYPE_NAME', 'PRECISION',
        'LENGTH', 'SCALE', 'RADIX', 'NULLABLE', 'REMARKS', 'COLUMN_DEF', 'SQL_DATA_TYPE', 'SQL_DATETIME_SUB',
        'CHAR_OCTET_LENGTH', 'ORDINAL_POSITION', 'IS_NULLABLE', 'SS_DATA_TYPE'
    ]
    mysql_all = [
        'Field', 'Type', 'Null', 'Key', 'Default', 'Extra'
    ]

    def mssql_type_name_2_index(self, name):
        """MSSQL COL_NAME 转索引"""
        return self.mssql_all.index(name)

    def mysql_type_name_2_index(self, name):
        """MYSQL COL_NAME 转索引"""
        return self.mysql_all.index(name)

    def columns_diff(self, table):
        """列差异对比"""

        logger.info('-' * 20 + f'{self.sql_2.SQL_DB}.{table}' + '-' * 20)

        def get_names(xs):
            return {_[self.type_name_2_index(self.column_name)] for _ in xs}

        def find_item(name, cols) -> dict:
            """在列信息中查找一个元素"""
            for _c in cols:
                if _c[self.type_name_2_index(self.column_name)] == name:
                    return {_: _c[self.type_name_2_index(_)] for _ in self.attention_cols}
            raise Exception(f'{name}, {cols}, {self.column_name}, {self.type_name_2_index(self.column_name)}')

        def zip_dict(dic1: dict, dic2: dict):
            if dic1.keys() != dic2.keys():
                raise
            for key in dic1.keys():
                yield key, dic1[key], dic2[key]

        columns1: list = self.sql_1.columns(table, )
        columns2: list = self.sql_2.columns(table, )
        col_name1 = set(get_names(columns1))
        col_name2 = set(get_names(columns2))

        col_common = col_name1 & col_name2

        logger.debug('COMMON COLUMNS : %s', col_common)

        if len(col_name1 - col_common) != 0:
            logger.info(f'[{self.check_type.upper()}.QA]{self.sql_1.SQL_DB}.{table}独有的列: {col_name1 - col_common}')
        if len(col_name2 - col_common) != 0:
            logger.info(
                f'[{self.check_type.upper()}.PROD].{self.sql_2.SQL_DB}.{table}独有的列: {col_name2 - col_common}')

        for _col_name in col_common:
            c1 = find_item(_col_name, columns1)
            c2 = find_item(_col_name, columns2)

            logger.debug(f'{c1} -- {c2}')

            if c1 == c2:
                continue

            logger.debug('差异的列属性')
            # db.table [Field] 字段差异:  (差异字段) <差异属性值QA> - <差异属性值PROD>, <差异属性值QA> - <差异属性值PROD> ...
            diff_fields = (
                f'({key})<{str(field1)}>-<{str(field2)}>'
                for key, field1, field2 in zip_dict(c1, c2) if field1 != field2
                # TODO 如有需要 后期此处判断可以使用方法做复杂校验
            )
            logger.info(f'[{self.check_type.upper()}]{self.sql_2.SQL_DB}.{table} [{_col_name}] 字段差异: %s',
                        ', '.join(diff_fields))


def create_sql(info, test=False):
    def _add_host(name: str):
        if name[0] in map(str, {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}):
            return name
        if name.endswith('.com'):
            return name
        # return name
        return name + '.cloud.wal-mart.com'

    db_qa = info[1]
    db_prod = info[8] if info[8] else info[1]

    if info[0].lower() == 'mysql':
        qa = MySqlAPI(host=_add_host(info[2]), port=3306, user=info[3], password=info[4], db=db_qa, )
        prod = MySqlAPI(host=_add_host(info[5]), port=3306, user=info[6], password=info[7], db=db_prod, )
    elif info[0].lower() == 'sqlserver':
        qa = MsSqlAPI(host=_add_host(info[2]), port=14481, user=info[3], password=info[4], db=db_qa, )
        prod = MsSqlAPI(host=_add_host(info[5]), port=14481, user=info[6], password=info[7], db=db_prod, )
    else:
        raise ValueError(f'值错误: %s', info)
    qa.zone, prod.zone = 'qa', 'prod'
    if test:
        qa.tables_name(), prod.tables_name()
    return qa, prod


def main(config_file: str):
    """"""
    map_ = {
        'mysql': ['Field', 'Type', 'Key', 'Default', 'Extra'],
        'sqlserver': [
            'TABLE_OWNER', 'TABLE_NAME', 'COLUMN_NAME', 'TYPE_NAME', 'PRECISION',
            'LENGTH', 'SCALE', 'RADIX', 'NULLABLE', 'COLUMN_DEF', 'SQL_DATA_TYPE', 'SS_DATA_TYPE'
        ]
    }

    for line in csv.reader(open(config_file, encoding='gbk')):
        if line[0] == '':
            break
        if line[0].lower() in {'数据库类型', } or line[0][-1] == '-':
            logger.info(f'skip -- [{line[0].upper()}]{line[1]}')
            continue
        if line[1] not in ['d_sam_logistics']:
            # logger.info('skip %s', line[1])
            continue
        if line[2] == '':
            logger.info(f'=== Waring: (DB HOST Not Find [{line[0].upper()}]{line[1]})')
            continue
        try:
            ContrastSQL(*create_sql(line), map_)
            # create_sql(line, test=True)
            print(f'{line[1]} Success ')
        except Exception as _e:
            logger.warning('!=' * 20 + f"[{line[0].upper()}]{line[1]} Error" + '!=' * 10, )
            logger.warning(f'!#!# {_e} !#!#')
            logger.warning('!=' * 20 + f"[{line[0].upper()}]{line[1]} Error" + '!=' * 10, )


if __name__ == '__main__':
    logging.basicConfig(level='DEBUG')
    logger.setLevel('INFO')
    file = logging.FileHandler('sql-2.log', 'w', encoding='utf8')
    file.setLevel('INFO')
    logging.getLogger().addHandler(file)
    logger.info(time.strftime('=== Start Time %x %X'))

    pa = r'C:\Users\vn54lnb\Desktop\WMT\bcdr_prod_qa_sql.csv'
    main(pa)

    logger.info(time.strftime('=== End Time %x %X'))
使用 Hugo 构建
主题 StackJimmy 设计