MySQL Fabricにて”Global” という名前でグループを作成し,その中にサーバを三台登録してあります。
本日は、Shardingの作成とShardingされたTableとグループ全体に対してDDLを実行しました。

【目的】 ShardingされたMySQL Fabric GroupへのCRATE,ALTERなどのDDLの実行と適用範囲の確認

■ Sharding作成前の状況

-bash-4.2$ mysqlfabric group lookup_servers global
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                         server_uuid         address    status       mode weight
------------------------------------ --------------- --------- ---------- ------
fd8f10c5-c3c1-11e4-84b2-080027d65c57 127.0.0.1:63301   PRIMARY READ_WRITE    1.0
fe41edb4-c3c1-11e4-84b2-080027d65c57 127.0.0.1:63302 SECONDARY  READ_ONLY    1.0
fed03648-c3c1-11e4-84b2-080027d65c57 127.0.0.1:63303 SECONDARY  READ_ONLY    1.0

-bash-4.2$ 

■ Sharding Mapping定義作成
-bash-4.2$ mysqlfabric help sharding create_definition
sharding create_definition type_name group_id [–synchronous]

Define a shard mapping.


-bash-4.2$ mysqlfabric sharding create_definition RANGE global
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
1e42e197-7b22-45a5-ba65-7432572e47ee        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425622316.87 Triggered by <mysql.fabric.events.Event object at 0x12fa310>.
    4       2 1425622316.94                     Executing action (_define_shard_mapping).
    5       2 1425622316.95                      Executed action (_define_shard_mapping).


-bash-4.2$ 

-bash-4.2$ mysqlfabric sharding list_definitions
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

mapping_id type_name global_group_id
---------- --------- ---------------
         1     RANGE          global


-bash-4.2$ 

■Sharding用にグループ作成とサーバ追加

-bash-4.2$ mysqlfabric group create shard1
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
fe58c7b1-d881-49f1-be60-c6c456d17926        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425622571.12 Triggered by <mysql.fabric.events.Event object at 0x1b6ecd0>.
    4       2 1425622571.13                             Executing action (_create_group).
    5       2 1425622571.14                              Executed action (_create_group).


-bash-4.2$ mysqlfabric group add shard1 127.0.0.1:63304
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
0b058a45-a48b-4483-b405-0b8a645ba024        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425622571.32 Triggered by <mysql.fabric.events.Event object at 0x1bc30d0>.
    4       2 1425622571.32                               Executing action (_add_server).
    5       2 1425622571.33                                Executed action (_add_server).


-bash-4.2$ mysqlfabric group add shard1 127.0.0.1:63305
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
02446f80-1c38-41fb-a7bc-88f3593ee10a        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425622571.51 Triggered by <mysql.fabric.events.Event object at 0x1bc30d0>.
    4       2 1425622571.51                               Executing action (_add_server).
    5       2 1425622571.52                                Executed action (_add_server).


-bash-4.2$ mysqlfabric group promote shard1
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
34ef4ed7-db5d-4b8d-a4a9-c86784181cd0        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425622571.66 Triggered by <mysql.fabric.events.Event object at 0x12fa410>.
    4       2 1425622571.66                      Executing action (_define_ha_operation).
    5       2 1425622571.66                       Executed action (_define_ha_operation).
    3       2 1425622571.66 Triggered by <mysql.fabric.events.Event object at 0x12fa3d0>.
    4       2 1425622571.66                      Executing action (_find_candidate_fail).
    5       2 1425622571.68                       Executed action (_find_candidate_fail).
    3       2 1425622571.68 Triggered by <mysql.fabric.events.Event object at 0x1b5a2d0>.
    4       2 1425622571.68                     Executing action (_check_candidate_fail).
    5       2 1425622571.69                      Executed action (_check_candidate_fail).
    3       2 1425622571.68 Triggered by <mysql.fabric.events.Event object at 0x1b5a350>.
    4       2 1425622571.69                          Executing action (_wait_slave_fail).
    5       2 1425622571.71                           Executed action (_wait_slave_fail).
    3       2 1425622571.71 Triggered by <mysql.fabric.events.Event object at 0x1b5a490>.
    4       2 1425622571.71                      Executing action (_change_to_candidate).
    5       2 1425622571.79                       Executed action (_change_to_candidate).


-bash-4.2$ mysqlfabric group activate shard1
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
77bc7aa8-8068-4d1d-a2da-4e2a5bd5da87        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425622571.95 Triggered by <mysql.fabric.events.Event object at 0x1bc3290>.
    4       2 1425622571.95                           Executing action (_activate_group).
    5       2 1425622571.96                            Executed action (_activate_group).


-bash-4.2$ 

■以下のグループとサーバも上記と同じくShardingの為にGroupとして追加
mysqlfabric group create shard2
mysqlfabric group add shard2 127.0.0.1:63306
mysqlfabric group add shard2 127.0.0.1:63307
mysqlfabric group promote shard2
mysqlfabric group activate shard2

mysqlfabric group create shard3
mysqlfabric group add shard3 127.0.0.1:63308
mysqlfabric group add shard3 127.0.0.1:63309
mysqlfabric group promote shard3
mysqlfabric group activate shard3

■ Add sharding to employee

Mapping IDは以下のコマンドで確認すると1になっているので1でシャーディングを作成する。

-bash-4.2$ mysqlfabric sharding list_definitions
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

mapping_id type_name global_group_id
---------- --------- ---------------
         1     RANGE          global


-bash-4.2$ mysqlfabric sharding add_table 1 test.employees emp_no
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
115ea959-bb38-4a2b-ab04-a59dad52da0e        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425623161.61 Triggered by <mysql.fabric.events.Event object at 0x12fa450>.
    4       2 1425623161.61                        Executing action (_add_shard_mapping).
    5       2 1425623161.69                         Executed action (_add_shard_mapping).


-bash-4.2$ mysqlfabric sharding add_shard 1 shard1/1,shard2/300,shard3/600 --state=enabled
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
794b2bb8-83a5-48c5-9a61-88c30b8d72a8        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425623182.84 Triggered by <mysql.fabric.events.Event object at 0x1bc9410>.
    4       2 1425623182.84                                Executing action (_add_shard).
    5       2 1425623183.45                                 Executed action (_add_shard).


-bash-4.2$ 

-bash-4.2$ mysqlfabric dump sharding_information
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

schema_name table_name column_name lower_bound shard_id type_name group_id global_group
----------- ---------- ----------- ----------- -------- --------- -------- ------------
       test  employees      emp_no           1        1     RANGE   shard1       global
       test  employees      emp_no         300        2     RANGE   shard2       global
       test  employees      emp_no         600        3     RANGE   shard3       global


-bash-4.2$ 

■テーブルが全てのサーバに作成されている。
グループ全体 ”Global” を指定して、CREATE TABLEを実行しています。

-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63301 -e "show tables from test"
Warning: Using a password on the command line interface can be insecure.
-bash-4.2$ python ./alter_shared_create.py 
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63301 -e "show tables from test"
Warning: Using a password on the command line interface can be insecure.
+----------------+
| Tables_in_test |
+----------------+
| employees      |
+----------------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63301 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+----------+------+-----+---------+-------+
| Field      | Type     | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| emp_no     | int(11)  | NO   | PRI | NULL    |       |
| first_name | char(40) | YES  |     | NULL    |       |
| last_name  | char(40) | YES  |     | NULL    |       |
+------------+----------+------+-----+---------+-------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63304 -e "show tables from test"
Warning: Using a password on the command line interface can be insecure.
+----------------+
| Tables_in_test |
+----------------+
| employees      |
+----------------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63304 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+----------+------+-----+---------+-------+
| Field      | Type     | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| emp_no     | int(11)  | NO   | PRI | NULL    |       |
| first_name | char(40) | YES  |     | NULL    |       |
| last_name  | char(40) | YES  |     | NULL    |       |
+------------+----------+------+-----+---------+-------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63306 -e "show tables from test"
Warning: Using a password on the command line interface can be insecure.
+----------------+
| Tables_in_test |
+----------------+
| employees      |
+----------------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63306 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+----------+------+-----+---------+-------+
| Field      | Type     | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| emp_no     | int(11)  | NO   | PRI | NULL    |       |
| first_name | char(40) | YES  |     | NULL    |       |
| last_name  | char(40) | YES  |     | NULL    |       |
+------------+----------+------+-----+---------+-------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63308 -e "show tables from test"
Warning: Using a password on the command line interface can be insecure.
+----------------+
| Tables_in_test |
+----------------+
| employees      |
+----------------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63308 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+----------+------+-----+---------+-------+
| Field      | Type     | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| emp_no     | int(11)  | NO   | PRI | NULL    |       |
| first_name | char(40) | YES  |     | NULL    |       |
| last_name  | char(40) | YES  |     | NULL    |       |
+------------+----------+------+-----+---------+-------+
-bash-4.2$ 

上記で実行したスクリプト


import mysql.connector 
from mysql.connector import fabric

import time

def connect():
    try:
       conn=mysql.connector.connect(
          fabric={"host" : "localhost", "port" : 32274, "username": "admin", "password": "admin"},
          user="root", database="test", password="root",
          autocommit=True
       )
    except mysql.connector.Error as e: 
        print "Error trying to get a new database connection"
        print "Error code:", e.errno 
        print "SQLSTATE value:", e.sqlstate
        print "Error message:", e.msg
        quit()
    return conn

conn = connect()
conn.set_property(group='global')
cur = conn.cursor()
cur.execute(
    "CREATE TABLE employees ("
    "   emp_no INT PRIMARY KEY, "
    "   first_name CHAR(40), "
    "   last_name CHAR(40)"
    ")"
    )

conn.commit()
conn.close()
conn = connect()

alter-table0

■テーブル定義の変更
上記で作成したテーブルに対して、Alter Tableで列を追加する。


-bash-4.2$ python ./alter_shared.py 
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63301 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| emp_no     | int(11)     | NO   | PRI | NULL    |       |
| first_name | char(40)    | YES  |     | NULL    |       |
| last_name  | char(40)    | YES  |     | NULL    |       |
| nickname   | varchar(64) | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63304 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| emp_no     | int(11)     | NO   | PRI | NULL    |       |
| first_name | char(40)    | YES  |     | NULL    |       |
| last_name  | char(40)    | YES  |     | NULL    |       |
| nickname   | varchar(64) | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63306 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| emp_no     | int(11)     | NO   | PRI | NULL    |       |
| first_name | char(40)    | YES  |     | NULL    |       |
| last_name  | char(40)    | YES  |     | NULL    |       |
| nickname   | varchar(64) | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+
-bash-4.2$ mysql -uroot -proot -h127.0.0.1 -P63308 -e "desc  test.employees"
Warning: Using a password on the command line interface can be insecure.
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| emp_no     | int(11)     | NO   | PRI | NULL    |       |
| first_name | char(40)    | YES  |     | NULL    |       |
| last_name  | char(40)    | YES  |     | NULL    |       |
| nickname   | varchar(64) | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+
-bash-4.2$ 

上記で実行したスクリプト


import mysql.connector 
from mysql.connector import fabric

import time

def connect():
    try:
       conn=mysql.connector.connect(
          fabric={"host" : "localhost", "port" : 32274, "username": "admin", "password": "admin"},
          user="root", database="test", password="root",
          autocommit=True
       )
    except mysql.connector.Error as e: 
        print "Error trying to get a new database connection"
        print "Error code:", e.errno 
        print "SQLSTATE value:", e.sqlstate
        print "Error message:", e.msg
        quit()
    return conn

conn = connect()
conn.set_property(group='global')
cur = conn.cursor()
cur.execute("ALTER TABLE test.employees ADD nickname VARCHAR(64)")


conn.commit()
conn.close()
conn = connect()

alter-table

こちらは、グローバルグループに複数のSharding定義を追加した場合(例)
グループにテーブル定義を追加してあげると、複数の定義を追加出来ます。

shardbefore

-bash-4.2$ mysqlfabric sharding create_definition RANGE global
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
0d675538-8b4a-4c57-b4a8-a29b529f0c7c        1       1      2

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2  1425626498.5 Triggered by <mysql.fabric.events.Event object at 0x12fa310>.
    4       2  1425626498.5                     Executing action (_define_shard_mapping).
    5       2 1425626498.59                      Executed action (_define_shard_mapping).


-bash-4.2$ mysqlfabric sharding list_definitions
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

mapping_id type_name global_group_id
---------- --------- ---------------
         1     RANGE          global
         2     RANGE          global


-bash-4.2$ mysqlfabric sharding create_definition RANGE global
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
5a3500cf-df2f-4219-a96b-9c9af166f33c        1       1      3

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425626647.47 Triggered by <mysql.fabric.events.Event object at 0x12fa310>.
    4       2 1425626647.47                     Executing action (_define_shard_mapping).
    5       2 1425626647.47                      Executed action (_define_shard_mapping).


-bash-4.2$ mysqlfabric sharding list_definitions
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

mapping_id type_name global_group_id
---------- --------- ---------------
         1     RANGE          global
         2     RANGE          global
         3     RANGE          global


-bash-4.2$ 


-bash-4.2$ mysqlfabric sharding add_table 2 test.employees2 emp_no
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
aadb02ef-c743-4839-b567-045723f7c3e8        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425626950.87 Triggered by <mysql.fabric.events.Event object at 0x12fa450>.
    4       2 1425626950.87                        Executing action (_add_shard_mapping).
    5       2 1425626950.88                         Executed action (_add_shard_mapping).


-bash-4.2$ mysqlfabric sharding add_shard 2 shard1/1,shard2/300,shard3/600 --state=enabled
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
32dd4f37-725c-4717-b6eb-073a26b814b7        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425626974.93 Triggered by <mysql.fabric.events.Event object at 0x1bc9410>.
    4       2 1425626974.94                                Executing action (_add_shard).
    5       2 1425626975.45                                 Executed action (_add_shard).


-bash-4.2$ mysqlfabric sharding add_table 3 test.employees3 emp_no
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
ae7c4c6c-342c-4d8e-b1c4-8ce534a91ffd        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425627239.67 Triggered by <mysql.fabric.events.Event object at 0x12fa450>.
    4       2 1425627239.72                        Executing action (_add_shard_mapping).
    5       2 1425627239.73                         Executed action (_add_shard_mapping).


-bash-4.2$ mysqlfabric sharding add_shard 3 shard1/1,shard2/300,shard3/600 --state=enabled
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

                                uuid finished success result
------------------------------------ -------- ------- ------
0ccb5df2-216c-4076-9966-708cd189b95a        1       1      1

state success          when                                                   description
----- ------- ------------- -------------------------------------------------------------
    3       2 1425627253.49 Triggered by <mysql.fabric.events.Event object at 0x1bc9410>.
    4       2 1425627253.49                                Executing action (_add_shard).
    5       2 1425627253.94                                 Executed action (_add_shard).


-bash-4.2$ mysqlfabric dump sharding_information
Fabric UUID:  5ca1ab1e-a007-feed-f00d-cab3fe13249e
Time-To-Live: 1

schema_name table_name column_name lower_bound shard_id type_name group_id global_group
----------- ---------- ----------- ----------- -------- --------- -------- ------------
       test  employees      emp_no           1        1     RANGE   shard1       global
       test  employees      emp_no         300        2     RANGE   shard2       global
       test  employees      emp_no         600        3     RANGE   shard3       global
       test employees2      emp_no           1        4     RANGE   shard1       global
       test employees2      emp_no         300        5     RANGE   shard2       global
       test employees2      emp_no         600        6     RANGE   shard3       global
       test employees3      emp_no           1        7     RANGE   shard1       global
       test employees3      emp_no         300        8     RANGE   shard2       global
       test employees3      emp_no         600        9     RANGE   shard3       global


-bash-4.2$ 

shardadd

参照: 8.8.4. MySQL Fabric Configuration for Running Samples


ALTER TABLE で既存テーブルの構造を変更する事ができます。例えば、カラムの追加や削除、
インデックスの作成や破壊、既存カラム タイプの変更、またはカラムやテーブル自体の名前の変更
をする事ができます。テーブルや、テーブル タイプのコメントを変更する事もできます。

以下の例は、テーブルに新規の列を場所を指定して追加している例です。


mysql> desc Add_Columns;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| col1 | char(5) | NO | PRI | NULL | |
| col2 | char(5) | NO | PRI | | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> alter table Add_Columns
-> add col0 int first,
-> add col3 int after col2,
-> add col4 int;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc Add_Columns;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| col0 | int(11) | YES | | NULL | |
| col1 | char(5) | NO | PRI | NULL | |
| col2 | char(5) | NO | PRI | | |
| col3 | int(11) | YES | | NULL | |
| col4 | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql>

alter_table_add_col

———————————————
参考サイト
———————————————

12.1.2. ALTER TABLE 構文

12.1.1. ALTER DATABASE 構文


TIMESTAMP列はDEFAULTでは、NOT NULLに設定されます。
あらかじめNULL値が入る事を想定している場合は明示的にNULLを
指定してテーブルを作成する。

以下テーブル作成後のALTER TABLEにて属性変更している。


mysql> CREATE TABLE timestamp_null (
-> data_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-> i INT
-> );
Query OK, 0 rows affected (0.16 sec)

mysql> desc timestamp_null;

+-----------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-----------+------+-----+-------------------+-----------------------------+
| data_time | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| i | int(11) | YES | | NULL | |
+-----------+-----------+------+-----+-------------------+-----------------------------+
2 rows in set (0.01 sec)

mysql> ALTER TABLE timestamp_null
-> MODIFY data_time TIMESTAMP NULL
-> DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc timestamp_null;

+-----------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-----------+------+-----+-------------------+-----------------------------+
| data_time | timestamp | YES | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| i | int(11) | YES | | NULL | |
+-----------+-----------+------+-----+-------------------+-----------------------------+
2 rows in set (0.00 sec)

mysql>


mysql> INSERT INTO timestamp_null (data_time, i) VALUES (NULL, 10);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT data_time, i FROM timestamp_null;
+-----------+------+
| data_time | i |
+-----------+------+
| NULL | 10 |
+-----------+------+
1 row in set (0.00 sec)

mysql> INSERT INTO timestamp_null (data_time, i) VALUES (now(), 10);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT data_time, i FROM timestamp_null;
+---------------------+------+
| data_time | i |
+---------------------+------+
| NULL | 10 |
| 2009-07-15 04:31:42 | 10 |
+---------------------+------+
2 rows in set (0.00 sec)

mysql>

null_timestamp

TIMESTAMP関連の検証


mysql> CREATE TABLE timestamp_chk (data_time TIMESTAMP NULL);
Query OK, 0 rows affected (0.00 sec)

mysql> desc timestamp_chk;
+-----------+-----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-----------+------+-----+---------+-------+
| data_time | timestamp | YES | | NULL | |
+-----------+-----------+------+-----+---------+-------+
1 row in set (0.01 sec)

mysql> INSERT INTO timestamp_chk VALUES (NULL);
Query OK, 1 row affected (0.00 sec)

mysql> select * from timestamp_chk;
+-----------+
| data_time |
+-----------+
| NULL |
+-----------+
1 row in set (0.00 sec)

mysql> INSERT INTO timestamp_chk VALUES ('文字列');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show warnings;
+---------+------+------------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------------+
| Warning | 1265 | Data truncated for column 'data_time' at row 1 |
+---------+------+------------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from timestamp_chk;
+---------------------+
| data_time |
+---------------------+
| NULL |
| 0000-00-00 00:00:00 | ← 文字列は対象外なので"0" Valueがinsertされる。
+---------------------+
2 rows in set (0.00 sec)

mysql>

timestamp_check

日付列に12 Digit と14 DigitのNumberをInsertした時の違い


mysql> INSERT INTO timestamp_chk VALUES (200202082139);
Query OK, 1 row affected (0.01 sec)

mysql> select * from timestamp_chk;
+---------------------+
| data_time |
+---------------------+
| NULL |
| 0000-00-00 00:00:00 |
| 2020-02-02 08:21:39 |
+---------------------+
3 rows in set (0.00 sec)

mysql> INSERT INTO timestamp_chk VALUES (20020208213900);
Query OK, 1 row affected (0.00 sec)

mysql> select * from timestamp_chk;
+---------------------+
| data_time |
+---------------------+
| NULL |
| 0000-00-00 00:00:00 |
| 2020-02-02 08:21:39 |
| 2002-02-08 21:39:00 |
+---------------------+
4 rows in set (0.00 sec)

timestamp_digit

無効な日付をINSERTした場合

    ※2月31日は存在しない日付

mysql> INSERT INTO timestamp_chk VALUES ('2002-02-31 23:59:59');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show warnings;
+---------+------+------------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------------+
| Warning | 1265 | Data truncated for column 'data_time' at row 1 |
+---------+------+------------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from timestamp_chk;
+---------------------+
| data_time |
+---------------------+
| NULL |
| 0000-00-00 00:00:00 |
| 2020-02-02 08:21:39 |
| 2002-02-08 21:39:00 |
| 0000-00-00 00:00:00 |
+---------------------+
5 rows in set (0.00 sec)

    ※60秒が指定されている。

mysql> INSERT INTO timestamp_chk VALUES ('2002-02-28 23:59:60');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> show warnings;
+---------+------+------------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------------+
| Warning | 1265 | Data truncated for column 'data_time' at row 1 |
+---------+------+------------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from timestamp_chk;
+---------------------+
| data_time |
+---------------------+
| NULL |
| 0000-00-00 00:00:00 |
| 2020-02-02 08:21:39 |
| 2002-02-08 21:39:00 |
| 0000-00-00 00:00:00 |
| 0000-00-00 00:00:00 |
+---------------------+
6 rows in set (0.00 sec)

mysql>

timestamp_digit_2


テーブルにインデックスを付ける事で、パフォーマンスは向上するが、
NULLが入らないようにする事でよりパフォーマンスが向上する。

①もしインデックスが無ければ、インデックス追加


mysql> desc TABLE911;
+---------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-----------------+------+-----+---------+----------------+
| id | int(4) unsigned | NO | PRI | NULL | auto_increment |
| comment | varchar(45) | YES | | NULL | |
+---------+-----------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> ALTER TABLE TABLE911 ADD INDEX (comment(10));
Query OK, 12 rows affected (0.04 sec)
Records: 12 Duplicates: 0 Warnings: 0

mysql> desc TABLE911;
+---------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-----------------+------+-----+---------+----------------+
| id | int(4) unsigned | NO | PRI | NULL | auto_increment |
| comment | varchar(45) | YES | MUL | NULL | |
+---------+-----------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql>

add_index

②パフォーマンス向上を図る為に、where句で指定されているcomment列にNULLが
入らないようにする。


mysql> desc TABLE911;
+---------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-----------------+------+-----+---------+----------------+
| id | int(4) unsigned | NO | PRI | NULL | auto_increment |
| comment | varchar(45) | YES | MUL | NULL | |
+---------+-----------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> alter table TABLE911
-> modify comment varchar(45) NOT NULL;
Query OK, 12 rows affected (0.03 sec)
Records: 12 Duplicates: 0 Warnings: 0

mysql> desc TABLE911;
+---------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-----------------+------+-----+---------+----------------+
| id | int(4) unsigned | NO | PRI | NULL | auto_increment |
| comment | varchar(45) | NO | MUL | NULL | |
+---------+-----------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql>

modify

===========================================
TABLE OPTIMIZATION
===========================================
■適切なINDEXを付ける (付けすぎは良くないです)
■COLUMNSは出来るだけ必要最低限の長さで
■短めのINDEXを作成することで、WHERE句などの比較が可能であれば短めのINDEXを作成する
■COLUMNは出来るだけNOT NULLを指定して作成する。(DEFAULT値でカバーもあり)
===========================================


INNODBテーブルのデフラグメント化

■調査
mysql> show table status like ‘T1’\G
*************************** 1. row ***************************
Name: T1
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 12
Avg_row_length: 1365
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 4194304
Auto_increment: 13
Create_time: 2009-02-06 11:54:08
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)

mysql>

■メンテナンス
mysql> ALTER TABLE T1 ENGINE=INNODB;
Query OK, 12 rows affected (0.06 sec)
Records: 12 Duplicates: 0 Warnings: 0

————————————————————————————–
ALTER TABLE 操作を定期的に実行すればインデックス スキャンの速度を上げる
事ができます:
それによって MySQL はテーブルを再構成します。デフラグ操作を行う別の方法は、
テーブルをテキスト ファイルにダンプし、テーブルをドロップし、
そしてそれをダンプ ファイルから再ロードする為に mysqldump を利用する事です。


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

MyISAM          MySQLの基本となるタイプ。テーブル単位のロック
BDB(BerkeleyDB) トランザクション,ページ単位のロックが可能
InnoDB        トランザクション,行単位のロック,外部キーが可能

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

CREATE TABLE `DB01`.`TABLE007` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`comment` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE = MyISAM;

mysql> show create table DB01.TABLE007 \G
*************************** 1. row ***************************
Table: TABLE007
Create Table: CREATE TABLE `TABLE007` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`comment` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
mysql>

mysql> show table status like ‘TABLE007’\G
*************************** 1. row ***************************
Name: TABLE007
Engine: MyISAM
Version: 10
Row_format: Dynamic
Rows: 3
Avg_row_length: 24
Data_length: 72
Max_data_length: 281474976710655
Index_length: 2048
Data_free: 0
Auto_increment: 4
Create_time: 2009-02-03 10:23:48
Update_time: 2009-02-03 10:28:37
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.13 sec)

mysql>

mysql> ALTER TABLE TABLE007 ENGINE = InnoDB;
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0
TABLEがINNODBに変換されていることを確認出来ます。
mysql> show table status like ‘TABLE007’\G
*************************** 1. row *******************
Name: TABLE007
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 3
Avg_row_length: 5461
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 4194304
Auto_increment: 4
Create_time: 2009-02-03 10:34:22
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.12 sec)

mysql>

mysql> select table_name,engine from INFORMATION_SCHEMA.TABLES where TABLE_NAME
=’TABLE007’;
+————+——–+
| table_name | engine |
+————+——–+
| TABLE007 | InnoDB |
+————+——–+
1 row in set (0.26 sec)

mysql>

MYISAM

MYISAM



INNODB

INNODB