mariadb other features

70
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 1 MariaDB : Other Features Jong Jin Lee SYS4U I&C EC Solution Lab / Software Engineer

Upload: jongjin-lee

Post on 26-Jan-2015

146 views

Category:

Data & Analytics


2 download

DESCRIPTION

*If you see the screen is not good condition, downloading please.* MariaDB Other Features - 성능 향상 - 관리 및 진단 - 개발 생산성 - 파티션 - 백업

TRANSCRIPT

Page 1: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

1

MariaDB : Other Features

Jong Jin Lee

SYS4U I&C EC Solution Lab / Software Engineer

Page 2: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

2

Agenda

• 성능향상

• 관리및진단

• 개발생산성

• 파티션

• 백업

Page 3: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

3

Agenda

• 성능향상

• 관리및진단

• 개발생산성

• 파티션

• 백업

Page 4: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

4

MariaDB : 성능향상

MySQL 서버의스레드풀(Thread Pool) MySQL 5.5나 MySQL 커뮤니티버전에서는스레드풀을사용할수없으며,

스레드풀기능을사용하기위해서는 Oracle MySQL Enterprise 버전을사용해야한다.

동시클라이언트커넥션이많아져도피크수준의처리량이계속유지된다는예시의그래프이지만엔터프라이즈버전에서만그렇다.

Page 5: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

5

MariaDB : 성능향상

MySQL 서버의전통적인연결및처리방식 MySQL 서버는전통적으로하나의클라이언트가접속할때마다그클라이언트만을위한전용스레드를생성한다.

즉서버에연결된클라이언트가 1000개라면 1000개의스레드가생성된다.

스레드가많을수록경합이심해지고자연히성능이떨어진다.

스레드가유휴(Idle) 상태이든작업처리중(Running) 상태에상관없이사용자수만큼스레드가생성되어있어야한다.

Page 6: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

6

MariaDB : 성능향상

MySQL 서버의스레드풀아키텍처

MySQLRunning 쓰레드

Idle 쓰레드

Page 7: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

7

MariaDB : 성능향상

MariaDB의스레드풀 스레드풀의스레드개수는동적으로관리(필요한경우자동으로개수가증가/감소)된다.

스레드풀자체의관리비용이상당히낮다.

운영체제가가진능력을최대한활용한다. 가능하다면운영체제에서지원하는스레드풀기능을사용했으며, 그렇지않은경우에는 I/O 멀티플렉싱방법을사용한다.

• Windows : 네이티브(Native) 스레드풀기능활용

• Uninx/Linux : MariaDB에서직접스레드풀을구현, threadpool_min_threads

시스템변수지원

스레드의최대개수를제한해서시스템의자원사용률을제한한다.

MariaDB 5.1 Over

Page 8: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

8

MariaDB : 성능향상

MariaDB의스레드풀아키텍처

MariaDB

Running 쓰레드

Idle 쓰레드

쓰레드 풀

커넥션 정보

실제처리하고있는커넥션만 스레드를유지하고,

유휴상태인커넥션은 커넥션정보만갖고있다.

특정사용자가쿼리를실행하면 MariaDB 서버는스레드풀에서여유스레드가있는지확인하고할당한다.

또한, 스레드풀의유휴스레드가많을경우일정한규칙에의해서제거한다.

Page 9: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

9

MariaDB : 성능향상

스레드풀은언제사용해야효율적인가? 스레드풀은쿼리하나하나가아주빨리실행되는 CPU 바운드작업인경우효율적이지만, 디스크바운드작업이라면상대적으로느린처리를담당하는디스크에서모든처리의병목현상이발생된다.

언제스레드풀을피해야할까? 주기적(상대적으로긴시간동안의)으로 MariaDB 서버의쿼리요청이폭발적으로늘어났다가다시부하가거의없는상태가반복되는경우에는스레드풀이비효율적으로작동할수있다.

이런경우 thread_pool_idle_timeout(unix 계열),

thread_pool_min_threads(windows 계열) 시스템변수를늘려서유지하면문제를해결할수있다.

Page 10: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

10

MariaDB : 성능향상

MariaDB 스레드풀의사용과튜닝 MariaDB에서스레드풀을사용하기위해서는 thread_handling 시스템변수를 “pool-of-threads”로설정해야한다.(default. One-thread-per-

connection – 이전의 client thread 1:1 방식 )

MariaDB에서는일반적으로스레드풀관련설정및최적화는필요하지않다고소개하지만, 최소스레드개수나새로운스레드를생성해야할시점결정을위해시스템변수를조정해야할경우도존재한다.

Page 11: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

11

MariaDB : 성능향상

MariaDB 스레드풀의사용과튜닝(Windwos 계열) thread_pool_min_threads

• 스레드풀에있어야할스레드의최소개수를지정한다. (default. 1)

• 갑자기한번에몰리는형태의서비스에서는개수를크게해서기본적으로스레드풀에생성되어있어야할스레드개수를늘려둘수있다.

thread_pool_max_threads• 스레드풀이최대로가질수있는스레드의개수를지정한다. (default. 500)

• 만약많은스레드들이동시에필요한경우(시스템의 장애상황이나글로벌잠금이필요한 FLUSH TABLES WITH READ LOCK 쿼리등)에는많은클라이언트들이 대기해야하므로스레드풀의최대스레드개수를넘어설수없다. 이런경우를대비해서 thread_pool_max_threads 시스템변수를크게설정할수도있다.

Page 12: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

12

MariaDB : 성능향상

MariaDB 스레드풀의사용과튜닝(Unix 계열) thread_pool_size

• 스레드풀에서스레드그룹의개수를지정한다. (default. 프로세스(core) 수)

• MariaDB 5.5까지는제공되었지만, MariaDB 10.0에서는없어졌다.

thread_pool_stall_limit• 스레드풀에사용할수있는스레드가하나도남아있지않을때얼마나더기다렸다가새로운스레드를생성할지를결정하는시스템변수이다.

• MariaDB 5.5까지는제공되었지만, MariaDB 10.0에서는없어졌다.

thread_pool_max_threads• 스레드풀이최대로가질수있는스레드의개수를지정한다. (default. 500)

Page 13: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

13

MariaDB : 성능향상

MariaDB 스레드풀의사용과튜닝(Unix 계열) thread_pool_timeout

• 스레드풀에서유휴(Idle) 상태인스레드가최소스레드개수이상인경우에는자동으로스레드의개수가줄어든다. 이때 thread_pool_idle_timeout 시간만큼대기했다가제거된다.

• MariaDB 5.5까지는제공되었지만, MariaDB 10.0에서는없어졌다.

thread_pool_oversubscribe• 스레드풀에사용할수있는스레드가하나도남아있지않을때얼마나더기다렸다가새로운스레드를생성할지를결정하는시스템변수이다.

• MariaDB 5.5까지는제공되었지만, MariaDB 10.0에서는없어졌다.

thread_pool_max_threads• 스레드풀이최대로가질수있는스레드의개수를지정한다. (default. 500)

thread_pool_max_threads의 max를 넘어 스레드 풀이 꽉 찬 상태에서도 MariaDB 서버에 접속하여 스레드 풀 관련 설정을 조정할 수 있도록extra_port, extra_max_connections 등의 시스템 변수가 존재한다. (상태 확인 – Threadpool_threads, Threadpool_idle_threads)

Page 14: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

14

MariaDB : 성능향상

주의사항 스레드풀이활성화되면자동적으로 MariaDB의스레드캐시(thread_cache_size에의해결정)가비활성화된다. 그래서스레드풀을사용하는경우에는 MariaDB의스레드캐시상태는모니터링할필요가없어진다.

스레드풀이가득차게되면제역할을못하게되고, 아래와같은에러가발생하므로수시로 thread_pool_max_threads 시스템변수에정의된개수만큼소진되지않았는지모니터링이필요하다.

2013-09-06 03:02:41 27330 [ERROR] Threadpool could not create additional thread to handle queries, because the

number of allowed threads was reached. Increasing 'thread_pool_max_threads' parameter can help in this situation.

If 'extra_port' parameter is set, you can still connect to the database with superuser account (it must be TCP

connection using extra_port as TCP port) and troubleshoot the situation. A likely cause of pool blocks are clients

that lock resources for long time. 'show processlist' or 'show engine innodb status' can give additional hints.

2013-09-06 03:02:41 27330 [Note] Threadpool has been blocked for 30 seconds

Page 15: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

15

Agenda

• 성능향상

• 관리및진단

• 개발생산성

• 파티션

• 백업

Page 16: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

16

MariaDB : 관리및진단

SHOW EXPLAIN FOR <THREAD-ID> MariaDB 10.0부터는특정클라이언트의요청을처리하고있는스레드가실행중인쿼리의실행계획을바로볼수있다.

MariaDB [employees]> show processlist;

+----+-------+--------------------- ----+-------+------------------------+------------------+----------+

| Id | User | Command | Time | State | Info | Progress |

+----+-------+--------------------------+-------+------------------------+------------------+----------+

| 1 | root | select sum(a) from tbl | 2 | | NULL | 0.000 |

MariaDB [employees]> SHOW EXPLAIN FOR 1;

+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+

| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |

+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+

| 1 | SIMPLE | tbl | index | NULL | a | 5 | NULL | 1000107 | Using index |

+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+

1 row in set, 1 warning (0.00 sec)

MariaDB [employees]> SHOW WARNINGS;

+-------+------+------------------------+

| Level | Code | Message |

+-------+------+------------------------+

| Note | 1003 | select sum(a) from tbl |

+-------+------+------------------------+

1 row in set (0.00 sec)

MariaDB 10.0 Over

Page 17: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

17

MariaDB : 관리및진단

슬로우쿼리로그에실행계획출력 MariaDB 프로세스가 CPU / 메모리자원을비정상적으로많이사용하여서버의 load averag가급증하거나, 웹페이지접속시로딩속도가현저히지연될경우가있다.이럴때에는쿼리가처리되는데얼마나시간이소요되는지 my.cnf에 slow-query-log를 남기게끔설정하여원인분석을할수있다.

MariaDB 10.0.5 버전부터는슬로우쿼리로그에쿼리의실행시간과수행된쿼리뿐만아니라그쿼리가사용했던실행계획까지함께출력된다.

MariaDB 5.5 버전부터 log_slow_verbosity 시스템변수가제공된다.

MariaDB 10.0.5 Over

Page 18: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

18

MariaDB : 관리및진단

슬로우쿼리로그에실행계획출력 쿼리타임이 ‘3초를’ 초과하는쿼리에대해 /usr/local/mysql/var/mysql-

slow.log 파일에기록한다는뜻이다.

my.cnf에설정및 mysql을리스타트한뒤운영하다보면 slow-query-

log가남게된다.

MariaDB 10.0.5 Over

# vi /etc/my.cnf

[mysqld]

log-slow-queries = /usr/local/mysql/var/mysql-slow.log

long_query_time = 3

Page 19: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

19

MariaDB : 관리및진단

슬로우쿼리로그에실행계획출력 Query time : 쿼리수행시간 Lock time : 테이블 Lock이걸린시간 Row_sent : 쿼리처리결과 Row 수 Rows_examined : 쿼리처리대상의 Row 수

use iamroot;

select max(wr_comment) as max_comment from g4_write_ja

where wr_parent = '92' and wr_is_comment = 1;

# Time: 120809 16:08:15

# User@Host: iamroot[iamroot] @ []

# Query_time: 253 Lock_time: 0 Rows_sent: 1 Rows_examined: 419562

select max(wr_comment) as max_comment from g4_write_ja

where wr_parent = '92' and wr_is_comment = 1;

# Time: 120809 16:08:17

# User@Host: iamroot[iamroot] @ []

# Query_time: 94 Lock_time: 0 Rows_sent: 0 Rows_examined: 640675

use iamroot;

SELECT count(*) from comment where boardcode=1045552594 and boardidx=274;

# Time: 120809 16:08:23

# User@Host: iamroot[iamroot] @ []

# Query_time: 183 Lock_time: 0 Rows_sent: 1 Rows_examined: 268576

Page 20: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

20

MariaDB : 관리및진단

구조화된실행계획출력 MySQL 5.6부터는쿼리의실행계획을 JSON 포맷으로출력할수있다.

MySQL 5.6 Over

MySQL [dbt3sf1]> explain format=json select * from orders,customer where o_orderdate between '1995-01-01' and

'1995-02-02' and c_acctbal <0 and o_custkey + 1 = c_custkey -1 \G

EXPLAIN: {

"query_block": {

"select_id": 1,

"nested_loop": [

{

"table": {

"table_name": "orders",

"access_type": "range",

"possible_keys": [

"i_o_orderdate"

],

… 생략 …

"rows": 149415,

"filtered": 18.037,

"using_join_buffer": "Block Nested Loop",

"attached_condition": "((`dbt3sf1`.`customer`.`c_acctbal` < 0) and ((`dbt3sf1`.`orders`.`o_custkey` + 1)

= (`dbt3sf1`.`customer`.`c_custkey` - 1)))"

}

}

]

}

}

MariaDB 서버의 각 처리부분이 WHERE 절의 어떤조건들을 가지고 수행되었는지 확인 가능 !!!

Page 21: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

21

MariaDB : 관리및진단

스레드단위의메모리사용량 MySQL 서버가사용하는메모리가 10G인데, 버퍼풀이나쿼리캐시그리고 MyISAMd의키캐시메모리이외에는알려주는정보가없다.

MariaDB 10.0 에서는각클라이언트의요청을처리하는스레드가사용하고있는메모리를살펴볼수있는기능이추가되었다.

MySQL 서버에서는 “SHOW STATUS” 명령어로현재커넥션과관련된여러가지상태값들을조회할수있다.

만약모든스레드의메모리사용량을확인하려면INFORMATION_SCHEMA 데이터베이스의 PROCESSLIST테이블을조회하면된다.

MariaDB 10.0 Over

Page 22: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

22

MariaDB : 관리및진단

SHUTDOWN 명령 MySQL 클라이언트프로그램이나 JDBC로서버에접속한경우셧다운할수있는명령이없었다.

MariaDB 10.0.4 버전부터원격지서버의 MariaDB 서버에SHUTDOWN이라는명령을실행할수있도록지원한다.

기본적으로 SHUTDOWN 명령을실행하기위해서는 SHUTDOWN 권한이필요하다.

MariaDB 10.0.4 Over

MariaDB [INFORMATION_SCHEMA]> SHUTDOWN;

Query OK, 0 rows affected (0.00 sec)

Page 23: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

23

MariaDB : 관리및진단

사용자나쿼리실행강제종료(KILL) MySQL 5.6에서는 KILL 명령어로특정세션이나그커넥션에서실행중인쿼리만을즉시종료하는기능을제공하고있다.

MariaDB에서는 KILL 명령어의기능을조금더확장해서즉시종료또는특정시간동안대기했다가종료할수있으며, 또한특정사용자의모든커넥션을강제로종료하는기능도지원하고있다.

MySQL 5.6 Over

Page 24: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

24

MariaDB : 관리및진단

사용자나쿼리실행강제종료(KILL) 특정커넥션의강제접속종료

MySQL 5.6 Over

MariaDB [INFORMATION_SCHEMA]> show processlist;

+----+-----------------+-----------------------+--------------------+---------+

| Id | User | Host | db | Command |

+----+-----------------+-----------------------+--------------------+---------+

| 1 | event_scheduler | localhost | NULL | Daemon |

| 43 | root | 192.168.66.1:51933 | orademo | Sleep |

| 56 | root | localhost | information_schema | Query |

| 58 | ecsees | 192.168.115.198:64376 | orademo | Sleep |

+----+-----------------+-----------------------+--------------------+---------+

7 rows in set (0.28 sec)

MariaDB [INFORMATION_SCHEMA]> kill connection 43;

Query OK, 0 rows affected (0.00 sec)

MariaDB [INFORMATION_SCHEMA]> show processlist;

+----+-----------------+-----------------------+--------------------+---------+

| Id | User | Host | db | Command |

+----+-----------------+-----------------------+--------------------+---------+

| 1 | event_scheduler | localhost | NULL | Daemon |

| 44 | root | 192.168.66.1:51937 | employees | Sleep |

| 56 | root | localhost | information_schema | Query |

| 58 | ecsees | 192.168.115.198:64376 | orademo | Sleep |

+----+-----------------+-----------------------+--------------------+---------+

6 rows in set (0.00 sec)

Page 25: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

25

MariaDB : 관리및진단

사용자나쿼리실행강제종료(KILL) 특정커넥션의쿼리강제종료

• 해당커넥션은그대로남아있고실행중인쿼리만종료한다.

MySQL 5.6 Over

MariaDB [INFORMATION_SCHEMA]> select * from processlist;

+----+-------+---------------------------+------------------------------------------------------+

| ID | TIME | STATE | INFO |

+----+-------+---------------------------+------------------------------------------------------+

| 58 | 41 | | NULL |

| 56 | 0 | executing | select * from processlist |

| 43 | 1 | Queried about 340000 rows | select * from LOG_PV GROUP BY VISIT_DT LIMIT 0, 1000 |

+----+-------+---------------------------+------------------------------------------------------+

7 rows in set (0.00 sec)

MariaDB [INFORMATION_SCHEMA]> kill query 43;

Query OK, 0 rows affected (0.02 sec)

Page 26: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

26

MariaDB : 관리및진단

사용자나쿼리실행강제종료(KILL) 특정유저의커넥션이나쿼리강제종료

MySQL 5.6 Over

MariaDB [INFORMATION_SCHEMA]> kill connection user ‘matt’;

MariaDB [INFORMATION_SCHEMA]> kill connection user ‘matt@’%’’;

MariaDB [INFORMATION_SCHEMA]> kill query user ‘matt’;

MariaDB [INFORMATION_SCHEMA]> kill query user ‘matt@’%’’;

Page 27: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

27

MariaDB : 관리및진단

사용자나쿼리실행강제종료(KILL) 강제종료수준조절

• 대표적으로 MEMORY나 MyISAM, ARIA 스토리지엔진경우특정커넥션을강제종료할경우데이터가알수없는상태(Inconsistent state)로빠질수있다.

• 쿼리강제종료방지옵션으로 HARD(즉시강제종료), SOFT(일관성에 영향을미치는 REPAIR, ALTER INDEX 종료방지)로나눠진다.

MySQL 5.6 Over

MariaDB [INFORMATION_SCHEMA]> kill hard query 11;

MariaDB [INFORMATION_SCHEMA]> kill soft query 11;

Page 28: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

28

MariaDB : 관리및진단

GET DIAGNOSTICS MySQL 5.5 버전부터스토어드프로시저나함수에서예외나에러를캐치(Catch)할수는있었으나, 에러의에러번호나 SQLSTATE 값을조회할수있는방법이없었다.

MySQL 5.6과 MariaDB 10.0.x 버전부터는 GET DIAGNOSTICS를통해에러번호나 SQLSTATE 값그리고에러메시지를스토어드프로그램에서참조할수있게되었다.

MySQL 5.6, MariaDB 10.0.x Over

Page 29: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

29

MariaDB : 관리및진단

GET DIAGNOSTICS MySQL 5.6, MariaDB 10.0.x Over

MariaDB [employees]> CREATE TABLE `test`.`t` (`c` INT) ENGINE = x;

Query OK, 0 rows affected, 2 warnings (0.19 sec)

MariaDB [employees]> GET DIAGNOSTICS @num_conditions = NUMBER;

MariaDB [employees]> SELECT @num_conditions;

+-----------------+

| @num_conditions |

+-----------------+

| 2 |

+-----------------+

MariaDB [employees]> GET DIAGNOSTICS CONDITION 1 @sqlstate = RETURNED_SQLSTATE, @errno = MYSQL_ERRNO, @text =

MESSAGE_TEXT;

MariaDB [employees]> SELECT @sqlstate, @errno, @text;

+-----------+--------+----------------------------+

| @sqlstate | @errno | @text |

+-----------+--------+----------------------------+

| 42000 | 1286 | Unknown storage engine 'x' |

+-----------+--------+----------------------------+

MariaDB [employees]> GET DIAGNOSTICS CONDITION 2 @sqlstate = RETURNED_SQLSTATE, @errno = MYSQL_ERRNO, @text =

MESSAGE_TEXT;

MariaDB [employees]> SELECT @sqlstate, @errno, @text;

+-----------+--------+-------------------------------------------+

| @sqlstate | @errno | @text |

+-----------+--------+-------------------------------------------+

| HY000 | 1266 | Using storage engine InnoDB for table 't' |

+-----------+--------+-------------------------------------------+

Page 30: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

30

Agenda

• 성능향상

• 관리및진단

• 개발생산성

• 파티션

• 백업

Page 31: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

31

MariaDB : 개발생산성

LIMIT ROWS EXAMINED SELECT 쿼리의실행에서조건절에일치하는지비교해본레코드의건수가특정레코드건수를넘어서게되면쿼리를중지할수있다.

LIMIT ROWS EXAMINED의판정건수는최종결과건수를의미하는것이아니라, MariaDB 내부적으로핸들링한레코드건수를의미한다.

LIMIT ROWS EXAMINED n 절은쿼리문장이적절히인덱스를사용하지못하는경우 N건의레코드를반환하기전에종료될수있다.

WHERE절의인덱스를사용한다하더라도적절하지못할경우, 쿼리의결과건수보다비교를위해서참조된레코드의건수(EXAMINED

ROWS)가더많을수있다.

Page 32: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

32

MariaDB : 개발생산성

LIMIT ROWS EXAMINED

MariaDB [employees]> select * from employees where last_name='Sudbeck' limit rows examined 10;

Empty set, 1 warning (0.01 sec)

MariaDB [employees]> SHOW WARNINGS\G

*************************** 1. row ***************************

Level: Warning

Code: 1931

Message: Query execution was interrupted. The query examined at least 11 rows, which exceeds LIMIT ROWS EXAMINED

(10). The query result may be incomplete.

1 row in set (0.00 sec)

MariaDB [employees]> select count(*) from dept_emp where dept_no='d001' limit rows examined 20000;

Empty set, 1 warning (0.02 sec)

MariaDB [employees]> select count(*) from dept_emp where dept_no='d002' limit rows examined 20000;

+----------+

| count(*) |

+----------+

| 17346 |

+----------+

1 row in set (0.43 sec)

100 조건으로 101번째 비교 순간 종료

20000명 이상 카운트 종료

Page 33: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

33

MariaDB : 개발생산성

DELETE … RETURNING … MySQL 서버에서는 DELETE 문장이실행될때삭제된레코드를확인할수있는방법이없었는데, MariaDB 10.0.5에서새롭게추가되었다.

삭제된레코드의칼럼들을가져오기위해서는 DELETE 문장의마지막에RETURNING 절을추가해준다.

MariaDB 10.0.5 Over

MariaDB [employees]> select * from t1;

id |

----+

1 |

2 |

3 |

4 |

(4 rows)

MariaDB [employees]> DELETE FROM t1 RETURNING id;

id |

----+

1 |

2 |

3 |

4 |

Page 34: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

34

MariaDB : 개발생산성

마이크로초단위의시간저장 기존에는 DATETIME이나 TIMESTAMP 타입에는정밀도(Precision)를지정할수없었으나, MariaDB 5.3 버전부터는정밀도로저장될시간정보를밀리초또는마이크로초단위까지선택할수있다.

정밀도가 3이나 6으로설정되면밀리초나마이크로초단위로시간정보를저장하고조회할수있다.

MariaDB 5.3 Over

MariaDB [employees]> create table tb_microsecond(

-> fd1 datetime(0), fd2 datetime(3), fd3 datetime(6));

Query OK, 0 rows affected (0.18 sec)

MariaDB [employees]> insert into tb_microsecond values (now(6), now(6), now(6));

Query OK, 1 row affected (0.01 sec)

MariaDB [employees]> select * from tb_microsecond;

+---------------------+-------------------------+----------------------------+

| fd1 | fd2 | fd3 |

+---------------------+-------------------------+----------------------------+

| 2014-07-22 13:27:03 | 2014-07-22 13:27:03.795 | 2014-07-22 13:27:03.795856 |

+---------------------+-------------------------+----------------------------+

1 row in set (0.00 sec)

Page 35: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

35

MariaDB : 개발생산성

마이크로초단위의시간저장 정밀도를사용하지않은 NOW() 함수는항상초단위로만현재시간을가져오기때문에 f2, f3처럼 DATETIME 타입의칼럼이정밀도가높아도항상 0으로저장된다.

추가적으로, DATE_SUB나 DATE_ADD 함수에서도시간을더하거나뺄때마이크로초단위로지정할수있다.

MariaDB 5.3 Over

MariaDB [employees]> insert into tb_microsecond values (now(), now(), now());

Query OK, 1 row affected (0.01 sec)

MariaDB [employees]> select * from tb_microsecond;

+---------------------+-------------------------+----------------------------+

| fd1 | fd2 | fd3 |

+---------------------+-------------------------+----------------------------+

| 2014-07-22 13:34:38 | 2014-07-22 13:34:38.000 | 2014-07-22 13:34:38.000000 |

+---------------------+-------------------------+----------------------------+

Query OK, 1 row affected (0.01 sec)

MariaDB [employees]> select now(6), date_sub(now(6), interval 100000 microsecond);

+----------------------------+-----------------------------------------------+

| now(6) | date_sub(now(6), interval 100000 microsecond) |

+----------------------------+-----------------------------------------------+

| 2014-07-22 13:37:51.542347 | 2014-07-22 13:37:51.442347 |

+----------------------------+-----------------------------------------------+

1 row in set (0.00 sec)

Page 36: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

36

MariaDB : 개발생산성

DATETIME 타입의기본값설정 MySQL 5.5 버전이나 MariaDB 5.5 버전까지는 TIMESTAMP 타입은현재시간을기본값으로가지도록할수있었지만, DATETIME 타입의칼럼은설정할수없었다.

MariaDB 10.0 부터는 DATETIME 타입의칼럼도현재시간을기본값으로설정할수있다.

CURRENT_TIMESTAMP를기본값으로가지는 TIMESTAMP 타입의칼럼은 FRM 파일의특성상테이블당하나만지정가능했지만, DATETIME

타입에는이런제약사항이없어, 여러칼럼을지정가능하다.

또한 MariaDB 5.3 버전부터는마이크로초단위까지 DATETIME이나TIMESTAMP 타입에저장할수있다.

MariaDB 10.0 Over

FRM = format(schema) file

(테이블 구조 저장 파일)

Page 37: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

37

MariaDB : 개발생산성

DATETIME 타입의기본값설정 MariaDB 10.0 Over

MariaDB [employees]> create table test (str varchar(32), ts DATETIME DEFAULT CURRENT_TIMESTAMP);

Query OK, 0 rows affected (0.00 sec)

MariaDB [employees]> desc test;

+-------+-------------+------+-----+-------------------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------+-------------+------+-----+-------------------+-------+

| str | varchar(32) | YES | | NULL | |

| ts | datetime | NO | | CURRENT_TIMESTAMP | |

+-------+-------------+------+-----+-------------------+-------+

2 rows in set (0.00 sec)

MariaDB [employees]> insert into test (str) values ("demo");

Query OK, 1 row affected (0.00 sec)

MariaDB [employees]> select * from test;

+------+---------------------+

| str | ts |

+------+---------------------+

| demo | 2014-07-22 13:50:31 |

+------+---------------------+

1 row in set (0.00 sec)

Page 38: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

38

MariaDB : 개발생산성

정규표현식기능확장 기존 POSIX 호환의정규표현식방법에서 MariaDB 10.0.5로버전업되면서 PCRE(Perl Compatible Regular Expression)정규표현식라이브러리를사용하도록변경되었다.

MySQL에서는정규표현식을이용해서전체일치또는부분일치여부만확인할수있지만, MariaDB 10.0.5부터는기존의일치여부기능에추가해서정규표현식을이용한위치파악및문자열대치기능들이보안되었다.

MariaDB 10.0.5 Over

Page 39: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

39

MariaDB : 개발생산성

정규표현식기능확장 REGEXP_REPLACE(subject, pattern, replace)

• 첫번째인자로주어진문자열에서정규표현식에일치하는부분을검색해서일치된부분을 “대체문자열”로 대체한결과를리턴한다.

• 대소문자비교규칙을적용하려면 “(?i)”, “(?-i)”를 사용하고, “(?-i)”는 대소문자구별을강제로하며, “(?i)”는 대소문자구분없이비교한다.

MariaDB 10.0.5 Over

// 정규 표현식을 이용한 REPLACE

SELECT REGEXP_REPLACE('ab12cd','[0-9]','') AS remove_digits;

-> abcd

// 정규 표현식을 REPLACE에서 대소문자 구분SELECT REGEXP_REPLACE('ABC','(?-i)b','-') AS force_case_sensitive;

-> ABC

// 정규 표현식을 REPLACE에서 대소문자 구분 없음SELECT REGEXP_REPLACE(BINARY 'ABC','(?i)b','-') AS force_case_insensitive;

-> A-C

Page 40: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

40

MariaDB : 개발생산성

정규표현식기능확장 REGEXP_INSTR(subject, pattern)

• 주어진문자열에서정규표현식에일치하는문자열의위치를찾아서리턴한다.

• 문자열의위치는바이트단위가아니라문자단위로리턴한다.

• 만약멀티바이트문자(한국어를 포함한아시아권언어)에서 정규표현식으로문자열의위치를바이트단위로찾을때에는 BINARY로타입캐스팅후실행하면된다.

MariaDB 10.0.5 Over

// 정규 표현식을 이용한 문자열 위치 찾기SELECT REGEXP_INSTR('abc','b');

-> 2

SELECT REGEXP_INSTR('abc','x');

-> 0

SELECT REGEXP_INSTR('BJORN','N');

-> 5

// 정규 표현식을 이용한 문자열 위치 찾기(바이트 위치)

SELECT REGEXP_INSTR(BINARY 'BJORN','N') AS cast_utf8_to_binary;

-> 6

Page 41: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

41

MariaDB : 개발생산성

정규표현식기능확장 REGEXP_SUBSTR(subject, pattern)

• 함수의첫번째인자로주어진문자열에서정규표현식에일치하는부분만리턴한다.

• 대소문자구분은 REGEXP_REPLACE와같이기존의칼럼규칙을따라가지만“(?i)”, “(?-i)”로 재정의가능하다.

MariaDB 10.0.5 Over

SELECT REGEXP_SUBSTR('ab12cd','[0-9]+');

-> 12

SELECT REGEXP_SUBSTR('ABC','(?i)b');

-> B

SELECT REGEXP_SUBSTR('ABC' COLLATE utf8_bin,'(?+i)b');

-> B

Page 42: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

42

MariaDB : 개발생산성

가상(Virtual) 칼럼 가상컬럼은흔히다른칼럼에의해서자동으로설정되는기능을의미한다.

가상칼럼은 INSERT된이후값을변경하는것은불가하다.• 경고메시지 (1906. The value specified for computed column '%s' in table '%s' ignored)

먼저가상칼럼은아래와같은제약사항을가진다.• 가상칼럼의표현식은 255 문자이내로정의해야한다.

• 서브쿼리와같이외부테이블의데이터를참조하는표현식은사용불가하다.

• UDF(User Defined Function)와스토어드함수를이용하는표현식은사용불가하다.

• 상수표현식은가상칼럼의표현식으로사용될수없다.

• 가상칼럼의표현식에다른가상칼럼은사용될수없다.

MariaDB 5.2 Over

Page 43: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

43

MariaDB : 개발생산성

가상(Virtual) 칼럼 가상칼럼은 2가지종류로나눠진다.

• VIRTUAL

VIRTUAL 가상칼럼은현재 MariaDB에서 VIRTUAL 가상칼럼을지원하는 InnoDB,

Aria, MyISAM, CONNECT 스토리지엔진에서만생성가능하다.

실제스토리지에값을저장하는것이아니라접근할때마다그때그때값이계산되기때문에인덱스생성이불가하다.

ALTER TABLE MODIFY나 CHANGE와같이칼럼의정의를변경하는 DDL은사용될수없다.

• PERSISTENT

PERSISTENT 가상칼럼은 MariaDB에서지원하는스토리지엔진에서는모두사용가능하다.

또한 PERSISTENT 가상칼럼은실제스토리지엔진에서하나의칼럼으로관리되기때문에, 프라이머리키나인덱스생성이가능하며 DDL 문장으로칼럼의정의변경도가능하다.

MariaDB 5.2 Over

Page 44: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

44

MariaDB : 개발생산성

가상(Virtual) 칼럼 MariaDB 5.2 Over

MariaDB [employees]> CREATE TABLE table1 (

a INT NOT NULL,

b VARCHAR(32),

c INT AS (a mod 10) VIRTUAL,

d VARCHAR(5) AS (left(b,5)) PERSISTENT);

MariaDB [employees]> INSERT INTO table1 VALUES (1, 'some text',default,default);

Query OK, 1 row affected (0.00 sec)

MariaDB [employees]> INSERT INTO table1 VALUES (2, 'more text',5,default);

Query OK, 1 row affected, 1 warning (0.00 sec)

Warning (Code 1645): The value specified for computed column 'c' in table 'table1' ignored.

MariaDB [employees]> INSERT INTO table1 VALUES (123, 'even more text',default,'something');

Query OK, 1 row affected, 2 warnings (0.00 sec)

Warning (Code 1645): The value specified for computed column 'd' in table 'table1' ignored.

Warning (Code 1265): Data truncated for column 'd' at row 1

MariaDB [employees]> SELECT * FROM table1;

+-----+----------------+------+-------+

| a | b | c | d |

+-----+----------------+------+-------+

| 1 | some text | 1 | some |

| 2 | more text | 2 | more |

| 123 | even more text | 3 | even |

+-----+----------------+------+-------+

3 rows in set (0.00 sec)

Page 45: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

45

MariaDB : 개발생산성

동적(Virtual) 칼럼 MariaDB 서버 5.3 버전부터는 NoSQL 형태의데이터저장및접근을위해서동적칼럼기능을제공한다.

동적칼럼은하나의대용량칼럼을정의하고, 그칼럼에여러개의임의칼럼을정의해서사용할수있는기능이다. 즉물리적인하나의칼럼으로여러개의논리적칼럼을동시에사용할수있는것이다.

논리적칼럼생성시사용되는 COLUMN_CREATE() 함수는이진데이터를만들어서데이터를저장하기때문에, 반드시이진타입인 VARBINARY나BLOB 타입만사용가능하다. 만약, VARCHAR나 TEXT 이진타입이아닌형식으로정의할경우에러메시지가발생한다.

• 경고메시지 (1366. Incorrect %s value: '%s' for column '%s' at row %ld)

MariaDB 5.3 Over

Page 46: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

46

MariaDB : 개발생산성

동적(Virtual) 칼럼 동적칼럼은두가지제약사항을가진다.

• 하나의물리동적칼럼에저장될수있는논리칼럼은최대 65535개이다.

• 물리동적칼럼은 max_allowed_packet 시스템변수에설정된바이트수만큼의값만저장가능하다.

MariaDB 5.3 Over

Page 47: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

47

MariaDB : 개발생산성

동적(Virtual) 칼럼 MariaDB 5.3 Over

MariaDB [employees]> create table assets (

-> item_name varchar(32) primary key, -- A common attribute for all items

-> dynamic_cols blob -- Dynamic columns will be stored here

-> );

MariaDB [employees]> INSERT INTO assets VALUES

-> ('MariaDB T-shirt', COLUMN_CREATE('color', 'blue', 'size', 'XL'));

MariaDB [employees]> INSERT INTO assets VALUES

-> ('Thinkpad Laptop', COLUMN_CREATE('color', 'black', 'price', 500));

MariaDB [employees]> SELECT item_name, COLUMN_GET(dynamic_cols, 'color' as char) AS color FROM assets;

+-----------------+-------+

| item_name | color |

+-----------------+-------+

| MariaDB T-shirt | blue |

| Thinkpad Laptop | black |

+-----------------+-------+

-- Remove a column:

MariaDB [employees]> UPDATE assets SET dynamic_cols=COLUMN_DELETE(dynamic_cols, "price")

-> WHERE COLUMN_GET(dynamic_cols, 'color' as char)='black';

-- Add a column:

MariaDB [employees]> UPDATE assets SET dynamic_cols=COLUMN_ADD(dynamic_cols, 'warranty', '3 years')

-> WHERE item_name='Thinkpad Laptop';

Page 48: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

48

Agenda

• 성능향상

• 관리및진단

• 개발생산성

• 파티션

• 백업

Page 49: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

49

MariaDB : 파티션

파티션 MySQL 5.6과 MariaDB 10.0에서파티션기능은큰변화는존재하지않는다.

다만, MySQL 5.6과 MariaDB 10.0에서파티션테이블사용에있어서개선된것은파티션의최대개수가 1024개에서 8192개로확장되었다는것이다.

그리고명시적파티션지정과파티션테이블의임포트익스포트기능이추가된정도이다.

MariaDB 5.6 Over

Page 50: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

50

MariaDB : 파티션

명시적파티션지정 MySQL 5.5나 MariaDB 5.5 버전에서는옵티마이저가자동으로필요한파티션만골라내는파티션프루닝기능을 SELECT 쿼리에서만작동하지만명시적파티션지정기능은대부분 DML 문장과 SELECT 쿼리문장에서모두사용할수있게되었다.

명시적파티션지정기능을사용하기위해서는 PARTITION(partition_name1,

partition_name2, …) 절을 FROM 절의테이블뒤에사용해야한다. 이때PARTITION 절은항상그파티션이속한테이블의이름뒤에명시해야한다.

만약명시된이름의파티션이존재하지않는다면경우에러메시지가발생한다.

• 경고메시지 (“partition ‘partition_name1’ doesn’t exist”)

MariaDB 5.6 Over

Page 51: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

51

MariaDB : 파티션

명시적파티션지정사용법 MariaDB 5.6 Over

MariaDB [employees]> create table tb_partition_employees(

-> emp_no int not null,

-> birth_date date not null,

-> first_name varchar(14) not null,

-> last_name varchar(16) not null,

-> gender enum('M','F') not null,

-> hire_date date not null

-> ) engine=tokudb

-> partition by range columns(hire_date) (

-> partition p0 values less than ('1990-01-01'),

-> partition p1 values less than ('2000-01-01'),

-> partition p2 values less than ('2010-01-01')

->);

Query OK, 0 rows affected (0.25 sec)

MariaDB [employees]> insert into tb_partition_employees select * from employees;

Query OK, 300024 rows affected (1.79 sec)

MariaDB [employees]> select count(*) from tb_partition_employees;

+----------+

| count(*) |

+----------+

| 300024 |

+----------+

MariaDB [employees]> select count(*) from tb_partition_employees partition(p0);

+----------+

| count(*) |

+----------+

| 164797 |

+----------+

Page 52: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

52

MariaDB : 파티션

명시적파티션지정사용법 MariaDB 5.6 Over

MariaDB [employees]> insert into tb_partition_employees partition(p0)

-> values (1, '1984-01-12', 'Matt', 'Lee', 'M', '2009-01-01');

ERROR 1748 (HY000): Found a row not matching the given partition set

MariaDB [employees]> select * from tb_partition_employees where emp_no=10001;

+--------+------------+------------+-----------+--------+------------+

| emp_no | birth_date | first_name | last_name | gender | hire_date |

+--------+------------+------------+-----------+--------+------------+

| 10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 |

+--------+------------+------------+-----------+--------+------------+

1 row in set (0.11 sec)

MariaDB [employees]> select * from tb_partition_employees partition(p2) where emp_no=10001;

Empty set (0.00 sec)

Page 53: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

53

MariaDB : 파티션

명시적파티션지정기능의용도(Partition pruning) MariaDB 5.6 Over

MariaDB [employees]> CREATE TABLE t1 ( recdate DATETIME NOT NULL, ... )

-> PARTITION BY RANGE( TO_DAYS(recdate) ) (

-> PARTITION p0 VALUES LESS THAN ( TO_DAYS('2007-01-01') ),

-> PARTITION p1 VALUES LESS THAN ( TO_DAYS('2007-02-01') ),

-> ...

-> );

MariaDB [employees]> EXPLAIN PARTITIONS SELECT * FROM t1 WHERE recdate='2007-01-15';

+----+-------------+-------+------------+------+-...

| id | select_type | table | partitions | type |

+----+-------------+-------+------------+------+-...

| 1 | SIMPLE | t1 | p1 | ALL |

+----+-------------+-------+------------+------+-...

MariaDB [employees]> EXPLAIN PARTITIONS SELECT * FROM t1 WHERE TO_DAYS(recdate)=TO_DAYS(’2007-01-15′);

+----+-------------+-------+------------+------+-...

| id | select_type | table | partitions | type |

+----+-------------+-------+------------+------+-...

| 1 | simple | t1 | p0,p1,p2,p3,p4 | all |

+----+-------------+-------+------------+------+-...

MariaDB [employees]> EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION(p1)WHERE TO_DAYS(recdate)=TO_DAYS(’2007-01-15′);

+----+-------------+-------+------------+------+-...

| id | select_type | table | partitions | type |

+----+-------------+-------+------------+------+-...

| 1 | SIMPLE | t1 | p1 | ALL |

+----+-------------+-------+------------+------+-...

Page 54: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

54

MariaDB : 파티션

파티션테이블스페이스교체(Exchange) MySQL 5.6과 MariaDB 10.0에서는파티션의테이블스페이스를교체(Exchange)하는기능도추가되었다. 여기서두개의테이블스페이스를스와핑(Swapping)하는 것을의미한다.

테이블스페이스교체는파티션의테이블스페이스와파티션되지않은단일테이블의테이블스페이스와스와핑하는형태로진행된다.

스와핑이실행될때기존테이블들의트리거는호출되지않으며,

Auto_increment 칼럼이있다면스와핑완료후 Auto_increment 값은다시초기화된다. (1로초기화가아닌최댓값에서부터재시작설정)

스와핑기능을이용하면파티션의테이블스페이스를단일테이블로변환한다음그단일테이블의테이블스페이스를복사할수있는것이다.

MariaDB 5.6 Over

Page 55: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

55

MariaDB : 파티션

파티션테이블스페이스교체(Exchange) 테이블스페이스교체가실행되기위한몇가지조건이필요하다.

• 파티션테이블과스와핑할테이블의구조는동일해야한다.

• 스와핑될테이블은임시테이블이아니여야한다.

• 스와핑될테이블은해당파티션의기준칼럼조건(파티션 범위)을만족해야한다.

• 스와핑되는두테이블은다른테이블과의참조관계(Foreign Key)가 없어야한다.

• 해당테이블에대해서 ALTER와 INSERT 그리고 CREATE, DROP 권한이있어야한다.

MySQL 5.6, MariaDB 10.0 Over

Page 56: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

56

MariaDB : 파티션

파티션테이블스페이스교체(Exchange) MySQL 5.6, MariaDB 10.0 Over

MariaDB [employees]> CREATE TABLE e (

-> id INT NOT NULL,

-> fname VARCHAR(30),

-> lname VARCHAR(30)

-> )

-> PARTITION BY RANGE (id) (

-> PARTITION p0 VALUES LESS THAN (50),

-> PARTITION p1 VALUES LESS THAN (100),

-> PARTITION p2 VALUES LESS THAN (150),

-> PARTITION p3 VALUES LESS THAN (MAXVALUE)

->);

MariaDB [e]> INSERT INTO e VALUES

-> (1669, "Jim", "Smith"),

-> (337, "Mary", "Jones"),

-> (16, "Frank", "White"),

-> (2005, "Linda", "Black");

mployees

MariaDB [employees]> CREATE TABLE e2 LIKE e;

Query OK, 0 rows affected (1.34 sec)

MariaDB [employees]> ALTER TABLE e2 REMOVE PARTITIONING;

Query OK, 0 rows affected (0.90 sec)

Records: 0 Duplicates: 0 Warnings: 0

Page 57: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

57

MariaDB : 파티션

파티션테이블스페이스교체(Exchange) MySQL 5.6, MariaDB 10.0 Over

MariaDB [employees]> SELECT PARTITION_NAME, TABLE_ROWS

-> FROM INFORMATION_SCHEMA.PARTITIONS

-> WHERE TABLE_NAME = 'e';

+----------------+------------+

| PARTITION_NAME | TABLE_ROWS |

+----------------+------------+

| p0 | 1 |

| p1 | 0 |

| p2 | 0 |

| p3 | 3 |

+----------------+------------+

4 rows in set (0.00 sec)

MariaDB [employees]> ALTER TABLE e EXCHANGE PARTITION p0 WITH TABLE e2;

Query OK, 0 rows affected (0.28 sec)

MariaDB [employees]> SELECT PARTITION_NAME, TABLE_ROWS

-> FROM INFORMATION_SCHEMA.PARTITIONS

-> WHERE TABLE_NAME = 'e';

+----------------+------------+

| PARTITION_NAME | TABLE_ROWS |

+----------------+------------+

| p0 | 0 |

| p1 | 0 |

| p2 | 0 |

| p3 | 3 |

+----------------+------------+

4 rows in set (0.00 sec)

메타 데이터 잠금이 걸리기 때문에 DML 작업은 블로킹된다.

Page 58: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

58

Agenda

• 성능향상

• 관리및진단

• 개발생산성

• 파티션

• 백업

Page 59: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

59

MariaDB : 백업

백업 MySQL 5.0과 5.1 버전이많이사용되던 2012년까지는 mysqldump라는논리적데이터덤프도구가유일한무료백업도구였지만, 백업자체가논리적백업이라서 MySQL 서버의성능에도많은영향을미쳤으며,

시간도적지않게걸린다.

이모든문제점을해결해준것이 Percona에서만든 XtraBackup이라는백업도구이다. XtraBackup은 MariaDB나 Percona의 PerconaServer,

그리고 MySQL 커뮤니티, 엔터프라이즈버전모두백업가능하다.

또, MySQL 5.6과 MariaDB 10.0 버전부터는원격서버에서바이너리로그를백업할수있는기능이추가되었다.

바이너리로그는복제를위해사용되기도하지만, PIT(Point In Time)

복구를위해서도사용된다.

MySQL 5.6, MariaDB 10.0 Over

Page 60: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

60

MariaDB : 백업

바이너리로그원격백업 바이너리로그는안전을위해서원격서버에백업본이보존되어야한다.

이전에는로컬서버에서복사해서원격서버로보내는과정을반복했다.

MySQL 5.6이나 MariaDB 10.0 버전부터는 mysqlbinlog 유틸리티프로그램에원격서버의바이너리로그를로컬컴퓨터로실시간복사해올수잇는기능이추가되었다.

실제 mysqlbinlog의 바이너리로그백업기능이하나의 MySQL

슬레이브로실행되는것처럼작동한다. (래플리케이션 API 사용)

MySQL의슬레이브와마찬가지로커넥션이끊겨지면 mysqlbinlog는 더이상바이너리로그파일을복사하지않는다.

MySQL 5.6, MariaDB 10.0 Over

Page 61: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

61

MariaDB : 백업

바이너리로그원격백업 Local에서바이너리로그백업

MySQL 5.6, MariaDB 10.0 Over

// mariadb-bin.000152 파일을 txt format으로 변환하고자 할 때shell> mysqlbinlog mariadb-bin.000152

// 백업shell> mysqlbinlog mariadb-bin.000001 > /tmp/mariadb-bin.sql

shell> mysqlbinlog mariadb-bin.000002 >> /tmp/mariadb-bin.sql

// 여러 개의 바이너리 로그 백업shell> mysqlbinlog mariadb-bin.000001 mariadb-bin.000002 | mysql -u root -p

shell> mysqlbinlog mariadb-bin.[0-9]* | mysql -u root -p

Page 62: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

62

MariaDB : 백업

바이너리로그원격백업 원격백업

MySQL 5.6, MariaDB 10.0 Over

//바이너리 로그 파일 확인MariaDB [information_schema]> SHOW BINARY LOGS;

+---------------+-----------+

| Log_name | File_size |

+---------------+-----------+

| binlog.000130 | 27459 |

| binlog.000131 | 13719 |

| binlog.000132 | 43268 |

+---------------+-----------+

//--read-from-remote-server : 이 옵션이 명시되지 않으면, 로컬 디스크에 있는 바이너리 로그를 찾아서 텍스트 파일로 변환한다.

//--raw : mysqlbinlog 유틸리티는 가져온 이진 형태의 바이너리 로그를 그대로 디스크에 저장한다.

//--stop-nevaer : 마지막 로그 파일의 끝에 도달 한 후 서버에 연결 상태를 유지하고 새로운 이벤트를 계속 읽는다.

(--to-last-log 옵션 활성화)

//--to-last-log : mysqlbinlog와 함께 사용하면, 지정된 바이너리 로그 파일뿐만 아니라 그 이후에 발생한 모든 바이너리 로그 파일 포함

shell> mysqlbinlog --read-from-remote-server --host=host_name --raw binlog.000130 binlog.000131 binlog.000132

shell> mysqlbinlog --read-from-remote-server --host=host_name --raw --to-last-log binlog.000130

shell> mysqlbinlog --read-from-remote-server --host=host_name --raw --stop-never binlog.000999

Page 63: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

63

MariaDB : 백업

XtraBackup XtraBackup은 Percona에서개발해서오픈소스로배포하는물리수준의백업도구이다.

XtraBackup은 MySQL 엔터프라이즈라이선스에포함된엔터프라이즈백업도구에서제공하는모든기능들을제공하고있으며, 추가적으로관리상더유용한기능들을제공하고있다.

XtraBackup의기본원리는 InnoDB 스토리지엔진의자동장애복구(Crash-Recovery)기능을 활용하고 InnoDB, XtraDB, MyISAM 엔진등을백업할수있다.

XtraBackup은백업중에데이터베이스를잠그지않는다.

XtraBackup은 xtrabackup C program, innobackupex Perl script 조합이다.

Xtrabackup은 InnoDB, XtraDB 스토리지엔진의실시간백업및, 리두로그를수집해서아카이빙하거나데이터파일의복사를처리한다.

Page 64: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

64

MariaDB : 백업

XtraBackup 원리

Maria DB Backup1단계(00:00)

Maria DB Backup2단계(00:10)

데이터 파일

리두 로그 파일

백업된 데이터 파일

백업된 리두 로그 파일

데이터 파일

리두 로그 파일

백업된 데이터 파일

백업된 리두 로그 파일

Copy

Copy

Page 65: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

65

MariaDB : 백업

XtraBackup 원리

Maria DB Backup4단계BACKUP 완료

(00:10)

데이터 파일

리두 로그 파일

백업된 데이터 파일

백업된 리두 로그 파일

Maria DB Backup데이터 파일

리두 로그 파일

백업된 데이터 파일

백업된 리두 로그 파일

3단계UPDATE 발생

(00:15)

변경사항이 유입되는 상황에서 스냅샷(Snapshot)

기능이 없이 데이터 파일을 백업으로 복사하여 변경 사항은 백업되지 못함.

백업 시점 전의 변경사항은 백업 파일로 정상 변경되었고 백업 파일과 현재데이터 파일은 비 일관성(Inconsistent)상태이다.

이 떄 !!! 백업된 리두 로그를 이용해서롤 포워드(Roll forward) 작업을 수행

Copy

Copy

Page 66: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

66

MariaDB : 백업

XtraBackup 사용법 이장에서는기본적인사용법만설명한다. (Ref. http://www.percona.com/software/percona-xtrabackup)

// 백업 디렉토리 생성# mkdir -p /mysqlbackup/xtrabackup/

// 데이터 백업 (복구시 my.cnf 설정이 동일해야 함으로 백업 권장)

# /usr/bin/innobackupex --user UUUUUUU --password PPPPPPP /mysqlbackup/xtrabackup

.............

.............

>> log scanned up to (542812997)

xtrabackup: Stopping log copying thread.

xtrabackup: Transaction log of lsn (542812997) to (542812997) was copied.

110719 18:25:44 innobackupex: All tables unlocked

110719 18:25:44 innobackupex: Connection to database server closed

innobackupex: Backup created in directory '/mysqlbackup/xtrabackup/2011-07-19_18-25-17'

innobackupex: MySQL binlog position: filename 'mysql-bin.000012', position 599281561

innobackupex: MySQL slave binlog position: master host '', filename '', position

110719 18:25:44 innobackupex: completed OK!

// 로그 백업# /usr/bin/innobackupex --user UUUUUUU --password PPPPPPP --apply-log /mysqlbackup/xtrabackup/2011-07-19_18-25-17

.............

.............

xtrabackup: starting shutdown with innodb_fast_shutdown = 1

110719 18:32:40 InnoDB: Starting shutdown...

110719 18:32:40 InnoDB: Shutdown completed; log sequence number 542814220

110719 18:32:40 innobackupex: completed OK!

Page 67: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

67

MariaDB : 백업

XtraBackup 사용법 이장에서는기본적인사용법만설명한다. (Ref. http://www.percona.com/software/percona-xtrabackup)

// 복구 (데이터베이스를 중지 시키고, data 디렉토리를 비운후에(기왕이면 기존 파일 따로 보관, 새로만들어서)

# /usr/bin/innobackupex --copy-back /mysqlbackup/xtrabackup/2011-07-19_18-25-17

// 혹시 ib_logfile에서 사이즈 오류가 날 경우를 대비하여 my.cnf 수정InnoDB: Error: log file ./ib_logfile0 is of different size 0 134217728 bytes

InnoDB: than specified in the .cnf file 0 126877696 bytes!

110720 13:48:47 [ERROR] Plugin 'InnoDB' init function returned error.

110720 13:48:47 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.

110720 13:48:47 [ERROR] Unknown/unsupported storage engine: InnoDB

110720 13:48:47 [ERROR] Aborting

.............

.............

# emacs /etc/my.cnf

innodb_log_file_size = XXX M

Page 68: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

68

Reference

Site : MariaDB Knowledge Base(SHOW EXPLAIN)

MariaDB Knowledge Base(EXPLAIN FORMAT=JSON in MySQL)

MariaDB Knowledge Base(GET DIAGNOSTICS)

MariaDB Knowledge Base(PCRE Regular Expressions)

MariaDB Knowledge Base(REGEXP_REPLACE, REGEXP_INSTR, REGEXP_SUBSTR)

MariaDB Knowledge Base(Virtual Columns)

MySQL Documentation(Exchanging Partitions and Subpartitions with Tables)

MySQL Documentation(Using mysqlbinlog to Back Up Binary Log Files)

http://wyseburn.tistory.com/203 (XtraBackup)

http://faq.hostway.co.kr/Linux_DB/1325

(슬로우쿼리로그에실행계획출력)

Book : “Real MariaDB”

Page 69: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

69

Q & A

Page 70: MariaDB Other Features

Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee

Blog : http://ora-sysdba.tistory.com/

70