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
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
2
Agenda
• 성능 향상
• 관리 및 진단
• 개발 생산성
• 파티션
• 백업
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
3
Agenda
• 성능 향상
• 관리 및 진단
• 개발 생산성
• 파티션
• 백업
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 버전을
사용해야 한다.
 동시 클라이언트 커넥션이 많아져도 피크 수준의 처리량이 계속
유지된다는 예시의 그래프이지만 엔터프라이즈 버전에서만 그렇다.
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) 상태에 상관없이
사용자 수만큼 스레드가 생성되어 있어야 한다.
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 쓰레드
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
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 서버는
스레드 풀에서 여유 스레드가 있는지 확인하고 할당한다.
또한, 스레드 풀의 유휴 스레드가 많을 경우
일정한 규칙에 의해서 제거한다.
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 계열) 시스템 변수를 늘려서 유지하면
문제를 해결 할 수 있다.
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에서는 일반적으로 스레드 풀 관련 설정 및 최적화는 필요하지
않다고 소개하지만, 최소 스레드 개수나 새로운 스레드를 생성해야 할
시점 결정을 위해 시스템 변수를 조정해야 할 경우도 존재한다.
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 시스템 변수를 크게
설정할 수도 있다.
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)
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)
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
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
15
Agenda
• 성능 향상
• 관리 및 진단
• 개발 생산성
• 파티션
• 백업
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
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
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
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
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 절의 어떤
조건들을 가지고 수행되었
는지 확인 가능 !!!
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
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)
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
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)
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)
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@’%’’;
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;
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
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' |
+-----------+--------+-------------------------------------------+
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
30
Agenda
• 성능 향상
• 관리 및 진단
• 개발 생산성
• 파티션
• 백업
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)가 더 많을 수 있다.
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 WARNINGSG
*************************** 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명 이상 카운트 종료
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 |
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)
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)
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
(테이블 구조 저장 파일)
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)
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
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
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
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
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
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
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)
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
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
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';
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
48
Agenda
• 성능 향상
• 관리 및 진단
• 개발 생산성
• 파티션
• 백업
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
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
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 |
+----------+
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)
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 |
+----+-------------+-------+------------+------+-...
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
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
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
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 작업은 블로킹된다.
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
58
Agenda
• 성능 향상
• 관리 및 진단
• 개발 생산성
• 파티션
• 백업
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
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
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
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
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 스토리지 엔진의 실시간 백업 및, 리두
로그를 수집해서 아카이빙하거나 데이터 파일의 복사를 처리한다.
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
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
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!
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
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”
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
69
Q & A
Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee
Blog : http://ora-sysdba.tistory.com/
70

More Related Content

PDF
MySQL 상태 메시지 분석 및 활용
PDF
MariaDB Administrator 교육
PDF
MySQL 5.5 Guide to InnoDB Status
PPTX
MariaDB High Availability
PDF
1.mysql disk io 모니터링 및 분석사례
PPTX
Maxscale 소개 1.1.1
PDF
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
PDF
Conhecendo Apache Cassandra @Movile
MySQL 상태 메시지 분석 및 활용
MariaDB Administrator 교육
MySQL 5.5 Guide to InnoDB Status
MariaDB High Availability
1.mysql disk io 모니터링 및 분석사례
Maxscale 소개 1.1.1
[오픈소스컨설팅] EFK Stack 소개와 설치 방법
Conhecendo Apache Cassandra @Movile

What's hot (20)

PDF
Maxscale_메뉴얼
PPTX
Union FileSystem - A Building Blocks Of a Container
PDF
MySQL Advanced Administrator 2021 - 네오클로바
DOCX
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
PDF
AWS 환경에서 MySQL BMT
PDF
Ansible 101
PDF
InnoDB Performance Optimisation
PDF
MariaDB 10.5 binary install (바이너리 설치)
PDF
Parallel Replication in MySQL and MariaDB
PDF
MariaDB MaxScale monitor 매뉴얼
PDF
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
PDF
Automated master failover
PPTX
Maria db 이중화구성_고민하기
PDF
MariaDB 마이그레이션 - 네오클로바
PPTX
Running MariaDB in multiple data centers
PDF
Change Data Streaming Patterns For Microservices With Debezium (Gunnar Morlin...
PPTX
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
PPTX
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
PPTX
MaxScale이해와활용-2023.11
PDF
How to Manage Scale-Out Environments with MariaDB MaxScale
Maxscale_메뉴얼
Union FileSystem - A Building Blocks Of a Container
MySQL Advanced Administrator 2021 - 네오클로바
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
AWS 환경에서 MySQL BMT
Ansible 101
InnoDB Performance Optimisation
MariaDB 10.5 binary install (바이너리 설치)
Parallel Replication in MySQL and MariaDB
MariaDB MaxScale monitor 매뉴얼
What’s the Best PostgreSQL High Availability Framework? PAF vs. repmgr vs. Pa...
Automated master failover
Maria db 이중화구성_고민하기
MariaDB 마이그레이션 - 네오클로바
Running MariaDB in multiple data centers
Change Data Streaming Patterns For Microservices With Debezium (Gunnar Morlin...
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
MaxScale이해와활용-2023.11
How to Manage Scale-Out Environments with MariaDB MaxScale
Ad

Viewers also liked (20)

PPTX
MariaDB
PPTX
개발자도 알아야 하는 DBMS튜닝
PDF
A beginners guide to MariaDB
PDF
MySQL Cluster performance best practices
PDF
[2015-05-22] Oracle Ways of Concurrency Control
PDF
[2015-06-05] Oracle TX Lock
DOC
Oracle History #9
PDF
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
PDF
MariaDB Optimization
PDF
『프로젝트 성패를 결정짓는 데이터 모델링 이야기』 - 미리보기
PDF
개발자가 도전하는 MariaDB 서버구축
PDF
제 5회 엑셈 수요 세미나 자료 연구컨텐츠팀
PDF
7급 공무원도 쉽게 따라하는 쉘 스크립트
PDF
간단한 쉘 스크립트 작성하기
PDF
『프로젝트 성패를 결정짓는 데이터 모델링 이야기』 - 구성 지도
PDF
H3 2011 대형사이트 구축을 위한 MySQL 튜닝전략
 
PDF
[2015-06-12] Oracle 성능 최적화 및 품질 고도화 1
PDF
조대협의 서버 사이드 - 대용량 아키텍처와 성능튜닝
PPTX
MySQL 기초
PDF
성능 좋은 SQL 작성법
MariaDB
개발자도 알아야 하는 DBMS튜닝
A beginners guide to MariaDB
MySQL Cluster performance best practices
[2015-05-22] Oracle Ways of Concurrency Control
[2015-06-05] Oracle TX Lock
Oracle History #9
[2015-07-10-윤석준] Oracle 성능 관리 & v$sysstat
MariaDB Optimization
『프로젝트 성패를 결정짓는 데이터 모델링 이야기』 - 미리보기
개발자가 도전하는 MariaDB 서버구축
제 5회 엑셈 수요 세미나 자료 연구컨텐츠팀
7급 공무원도 쉽게 따라하는 쉘 스크립트
간단한 쉘 스크립트 작성하기
『프로젝트 성패를 결정짓는 데이터 모델링 이야기』 - 구성 지도
H3 2011 대형사이트 구축을 위한 MySQL 튜닝전략
 
[2015-06-12] Oracle 성능 최적화 및 품질 고도화 1
조대협의 서버 사이드 - 대용량 아키텍처와 성능튜닝
MySQL 기초
성능 좋은 SQL 작성법
Ad

Similar to MariaDB Other Features (20)

PPTX
MySQL_MariaDB-성능개선-202201.pptx
PDF
Migration to Azure Database for MySQL
PDF
MariaDB 제품 소개
PDF
MySQL InnoDB Cluster 소개
PDF
[2010 네이트 앱스토어 개발자 세미나] 앱스 제작 사례 (2) 소셜게임 서버 구성 전략
PPT
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
PPTX
Azure Database for MySQL
PDF
DB Migration to Azure Database for MySQL
PDF
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
PDF
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
PDF
Amazon Aurora 신규 서비스 알아보기::최유정::AWS Summit Seoul 2018
PPTX
Vectorized processing in_a_nutshell_DeView2014
PPTX
Hadoop security DeView 2014
PPT
Rhea_MMO_SNG_Convergence_Server_Architecture
PPTX
1711 azure-live
PDF
[Games on AWS 2019] AWS 사용자를 위한 만랩 달성 트랙 | Aurora로 게임 데이터베이스 레벨 업! - 김병수 AWS ...
PDF
MySQL/MariaDB Proxy Software Test
PDF
오픈소스컨설팅 클러스터제안 V1.0
PDF
Fluentd with MySQL
PDF
MySQL Administrator 2021 - 네오클로바
MySQL_MariaDB-성능개선-202201.pptx
Migration to Azure Database for MySQL
MariaDB 제품 소개
MySQL InnoDB Cluster 소개
[2010 네이트 앱스토어 개발자 세미나] 앱스 제작 사례 (2) 소셜게임 서버 구성 전략
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
Azure Database for MySQL
DB Migration to Azure Database for MySQL
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
Amazon Aurora 신규 서비스 알아보기::최유정::AWS Summit Seoul 2018
Vectorized processing in_a_nutshell_DeView2014
Hadoop security DeView 2014
Rhea_MMO_SNG_Convergence_Server_Architecture
1711 azure-live
[Games on AWS 2019] AWS 사용자를 위한 만랩 달성 트랙 | Aurora로 게임 데이터베이스 레벨 업! - 김병수 AWS ...
MySQL/MariaDB Proxy Software Test
오픈소스컨설팅 클러스터제안 V1.0
Fluentd with MySQL
MySQL Administrator 2021 - 네오클로바

MariaDB Other Features

  • 1. 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
  • 2. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 2 Agenda • 성능 향상 • 관리 및 진단 • 개발 생산성 • 파티션 • 백업
  • 3. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 3 Agenda • 성능 향상 • 관리 및 진단 • 개발 생산성 • 파티션 • 백업
  • 4. 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 버전을 사용해야 한다.  동시 클라이언트 커넥션이 많아져도 피크 수준의 처리량이 계속 유지된다는 예시의 그래프이지만 엔터프라이즈 버전에서만 그렇다.
  • 5. 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) 상태에 상관없이 사용자 수만큼 스레드가 생성되어 있어야 한다.
  • 6. 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 쓰레드
  • 7. 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
  • 8. 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 서버는 스레드 풀에서 여유 스레드가 있는지 확인하고 할당한다. 또한, 스레드 풀의 유휴 스레드가 많을 경우 일정한 규칙에 의해서 제거한다.
  • 9. 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 계열) 시스템 변수를 늘려서 유지하면 문제를 해결 할 수 있다.
  • 10. 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에서는 일반적으로 스레드 풀 관련 설정 및 최적화는 필요하지 않다고 소개하지만, 최소 스레드 개수나 새로운 스레드를 생성해야 할 시점 결정을 위해 시스템 변수를 조정해야 할 경우도 존재한다.
  • 11. 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 시스템 변수를 크게 설정할 수도 있다.
  • 12. 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)
  • 13. 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)
  • 14. 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
  • 15. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 15 Agenda • 성능 향상 • 관리 및 진단 • 개발 생산성 • 파티션 • 백업
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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 절의 어떤 조건들을 가지고 수행되었 는지 확인 가능 !!!
  • 21. 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
  • 22. 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)
  • 23. 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
  • 24. 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)
  • 25. 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)
  • 26. 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@’%’’;
  • 27. 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;
  • 28. 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
  • 29. 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' | +-----------+--------+-------------------------------------------+
  • 30. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 30 Agenda • 성능 향상 • 관리 및 진단 • 개발 생산성 • 파티션 • 백업
  • 31. 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)가 더 많을 수 있다.
  • 32. 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 WARNINGSG *************************** 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명 이상 카운트 종료
  • 33. 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 |
  • 34. 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)
  • 35. 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)
  • 36. 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 (테이블 구조 저장 파일)
  • 37. 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)
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. 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
  • 42. 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
  • 43. 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
  • 44. 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)
  • 45. 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
  • 46. 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
  • 47. 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';
  • 48. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 48 Agenda • 성능 향상 • 관리 및 진단 • 개발 생산성 • 파티션 • 백업
  • 49. 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
  • 50. 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
  • 51. 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 | +----------+
  • 52. 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)
  • 53. 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 | +----+-------------+-------+------------+------+-...
  • 54. 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
  • 55. 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
  • 56. 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
  • 57. 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 작업은 블로킹된다.
  • 58. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 58 Agenda • 성능 향상 • 관리 및 진단 • 개발 생산성 • 파티션 • 백업
  • 59. 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
  • 60. 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
  • 61. 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
  • 62. 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
  • 63. 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 스토리지 엔진의 실시간 백업 및, 리두 로그를 수집해서 아카이빙하거나 데이터 파일의 복사를 처리한다.
  • 64. 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
  • 65. 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
  • 66. 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!
  • 67. 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
  • 68. 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”
  • 69. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 69 Q & A
  • 70. Copyright(c)2014 by ora-sysdba. All Page content is property of dbjongjin.lee Blog : http://ora-sysdba.tistory.com/ 70