File: plugin_mysql.py

package info (click to toggle)
rows 0.5.0~dev0~1~1d5a326-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,340 kB
  • sloc: python: 12,672; sh: 117; makefile: 67
file content (187 lines) | stat: -rw-r--r-- 5,918 bytes parent folder | download | duplicates (2)
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
# coding: utf-8

# Copyright 2014-2025 Álvaro Justen <https://github.com/turicas/rows/>
#    This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
#    Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)
#    any later version.
#    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
#    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
#    more details.
#    You should have received a copy of the GNU Lesser General Public License along with this program.  If not, see
#    <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

import datetime

import MySQLdb

from .rows import Table
from .utils import ipartition, slug

__all__ = ["import_from_mysql", "export_to_mysql"]

# TODO: replace 'None' with '' on export_to_*
# TODO: need converters in and out
# TODO: lazy=True|False
# TODO: datetime.time on MYSQL_TYPE
# TODO: import from mysql
# TODO: logging?
# TODO: _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone #
# away')

MYSQL_TYPE = {
    str: "TEXT",
    int: "INT",
    float: "FLOAT",
    datetime.date: "DATE",
    datetime.datetime: "DATETIME",
    bool: "BOOL",
}
# 'BOOL' on MySQL is a shortcut to TINYINT(1)
MYSQLDB_TYPE = {
    getattr(MySQLdb.FIELD_TYPE, x): x
    for x in dir(MySQLdb.FIELD_TYPE)
    if not x.startswith("_")
}
MYSQLDB_TO_PYTHON = {
    "ENUM": str,
    "STRING": str,
    "VAR_STRING": str,
    "BLOB": bytes,
    "LONG_BLOB": bytes,
    "MEDIUM_BLOB": bytes,
    "TINY_BLOB": bytes,
    "DECIMAL": float,
    "DOUBLE": float,
    "FLOAT": float,
    "INT24": int,
    "LONG": int,
    "LONGLONG": int,
    "TINY": int,
    "YEAR": int,
    "DATE": datetime.date,
    "NEWDATE": datetime.date,
    "TIME": int,
    "TIMESTAMP": int,
    "DATETIME": datetime.datetime,
}


def _get_mysql_config(connection_str):
    colon_index = connection_str.index(":")
    at_index = connection_str.index("@")
    slash_index = connection_str.index("/")
    config = {}
    config["user"] = connection_str[:colon_index]
    config["passwd"] = connection_str[colon_index + 1 : at_index]
    config["host"] = connection_str[at_index + 1 : slash_index]
    config["port"] = 3306
    if ":" in config["host"]:
        data = config["host"].split(":")
        config["host"] = data[0]
        config["port"] = int(data[1])
    if connection_str.count("/") == 1:
        table_name = None
        config["db"] = connection_str[slash_index + 1 :]
    else:
        second_slash_index = connection_str.index("/", slash_index + 1)
        config["db"] = connection_str[slash_index + 1 : second_slash_index]
        table_name = connection_str[second_slash_index + 1 :]
    return config, table_name


def _connect_to_mysql(config):
    return MySQLdb.connect(**config)


def import_from_mysql(connection_string, limit=None, order_by=None, query=""):
    # TODO: add 'lazy' option
    config, table_name = _get_mysql_config(connection_string)
    connection = _connect_to_mysql(config)
    cursor = connection.cursor()
    if query:
        sql = query
    else:
        sql = "SELECT * FROM " + table_name
        if limit is not None:
            sql += " LIMIT {0[0]}, {0[1]}".format(limit)
        if order_by is not None:
            sql += " ORDER BY " + order_by
    cursor.execute(sql)
    column_info = [(x[0], x[1]) for x in cursor.description]
    table = Table(fields=[x[0] for x in cursor.description])
    table.types = {
        name: MYSQLDB_TO_PYTHON[MYSQLDB_TYPE[type_]] for name, type_ in column_info
    }
    table_rows = [list(row) for row in cursor.fetchall()]

    encoding = connection.character_set_name()
    for row in table_rows:
        for column_index, value in enumerate(row):
            if type(value) is str:
                row[column_index] = value.decode(encoding)
    table._rows = table_rows
    cursor.close()
    connection.close()
    return table


def export_to_mysql(
    table,
    connection_string,
    encoding=None,
    batch_size=1000,
    commit_every=10000,
    callback=None,
    callback_every=10000,
):
    config, table_name = _get_mysql_config(connection_string)
    connection = _connect_to_mysql(config)
    cursor = connection.cursor()

    # Create table
    fields, types = table.fields, table.types
    field_slugs = [slug(field) for field in fields]
    field_types = [MYSQL_TYPE[types[field]] for field in fields]
    columns_definition = [
        "{} {}".format(field, type_) for field, type_ in zip(field_slugs, field_types)
    ]
    sql = "CREATE TABLE IF NOT EXISTS {} ({})".format(
        table_name, ", ".join(columns_definition)
    )
    cursor.execute(sql)

    # Insert items
    columns = ", ".join(field_slugs)
    # placeholders = ['%s' if types[field] in (int, float, bool) else '"%s"'
    #                for field in fields]
    # TODO: fix this string/formatting problem
    placeholders = ["%s" for field in fields]
    sql = "INSERT INTO {} ({}) VALUES ({})".format(
        table_name, columns, ", ".join(placeholders)
    )

    total = last_commit = last_callback = 0
    for rows in ipartition(iter(table), batch_size):
        values = [[row[field] for field in fields] for row in rows]

        added = len(values)
        total += added
        last_commit += added
        last_callback += added

        cursor.executemany(sql, values)

        if last_commit >= commit_every:
            connection.commit()
            last_commit = 0
        if callback is not None and last_callback >= callback_every:
            callback(total)
            last_callback = 0

    if callback is not None and last_callback > 0:
        callback(total)
    if last_commit > 0:
        connection.commit()
    connection.close()