728x90

join_buffer_size

PropertyValue
Command-Line Format--join-buffer-size=#
System Variablejoin_buffer_size
ScopeGlobal, Session
DynamicYes
Type (Other, 64-bit platforms)integer
Type (Other, 32-bit platforms)integer
Type (Windows)integer
Default Value (Other, 64-bit platforms)262144
Default Value (Other, 32-bit platforms)262144
Default Value (Windows)262144
Minimum Value (Other, 64-bit platforms)128
Minimum Value (Other, 32-bit platforms)128
Minimum Value (Windows)128
Maximum Value (Other, 64-bit platforms)18446744073709547520
Maximum Value (Other, 32-bit platforms)4294967295
Maximum Value (Windows)4294967295
 

The minimum size of the buffer that is used for plain index scans, range index scans, and joins that do not use indexes and thus perform full table scans. Normally, the best way to get fast joins is to add indexes. Increase the value of join_buffer_size to get a faster full join when adding indexes is not possible. One join buffer is allocated for each full join between two tables. For a complex join between several tables for which indexes are not used, multiple join buffers might be necessary.

Unless Batched Key Access (BKA) is used, there is no gain from setting the buffer larger than required to hold each matching row, and all joins allocate at least the minimum size, so use caution in setting this variable to a large value globally. It is better to keep the global setting small and change to a larger setting only in sessions that are doing large joins. Memory allocation time can cause substantial performance drops if the global size is larger than needed by most queries that use it.

When BKA is used, the value of join_buffer_size defines how large the batch of keys is in each request to the storage engine. The larger the buffer, the more sequential access will be to the right hand table of a join operation, which can significantly improve performance.

The default is 256KB. The maximum permissible setting for join_buffer_size is 4GB−1. Larger values are permitted for 64-bit platforms (except 64-bit Windows, for which large values are truncated to 4GB−1 with a warning).

For additional information about join buffering, see Section 8.2.1.6, “Nested-Loop Join Algorithms”. For information about Batched Key Access, see Section 8.2.1.11, “Block Nested-Loop and Batched Key Access Joins”.

'DB TUNE' 카테고리의 다른 글

[MySQLD] Tunner  (0) 2018.04.19
[MySQLD] innodb_file_per_table  (0) 2018.04.19
MySQL 튜닝 값을 탐지해주는 유용한 툴  (0) 2018.04.19
[MySQLD] table_open_cache  (0) 2018.04.19
MySQLD DataBase tune  (0) 2018.04.19
728x90

일단 MySQL에서는 

MyISAM, InnoDB, Archive, BerkeleyDB 등등을
테이블 엔진으로 사용할 수 있습니다.
즉 테이블 코어 API 가 존재하고 거기에 Pluggable 하게 
어답터 엔진을 적용 시킬 수 있는 구조이지요.
가장 많이 사용하는 엔진이 InnoDB, 그 다음이 MyISAM 일 것 같군요.

우선 위 두 테이블 엔진의 차이를 제 나름대로 비교해 보았습니다.

InnoDB : Transaction 존재, Record 단위 Lock
MyISAM : Transaction 불가, Table 단위 Lock

위의 특성을 가지고 다음과 같은 데이터의 시나리오를 유추해 보겠습니다.

Read-Only 데이터 성의 로그 파일 입력인 경우:
보통 로그는 단일 Append-Only인 경우가 대부분이고,
Single-Append, Multipl-Read 인 경우가 많습니다.
이런 형식에서는 InnoDB 보다는 MyISAM이 조금 더 유리했습니다.
또한 myisampack 이라는 유틸리티로 나중에 Read-Only용 압축
테이블을 유지할 수도 있어 디스크 용량 등의 관점에서도 훨씬 유리합니다.

빈번하게 입력및 읽는 식의 Event 정보:
여러 다양한 이벤트가 발생하고 Multiple-Insert 및 Multiple-Read 인 경우에는
InnoDB를 사용하는 것이 훨씬 유리하다고 할 수 있습니다.
그 이유는 이벤트를 입력하기 Write-Lock을 거는 단위가 MyISAM 엔진인 경우
테이블 단위기 때문에 테이블의 끝에 레코드를 입력하더라도,
다른 곳의 모든 레코드를 읽을 수 없는 것을 의미하기 때문입니다.

위의 예는 극히 일 부분의 차이를 기술해 본 것으로서,
엔진의 특성을 잘 파악하고 적용하는 것이 꼭 필요하다는 것을 나타냅니다.


다음은 MySQL의 설정에 따른 튜닝을 살펴보겠습니다.

최근에 MyISAM 테이블이 있었는데

SELECT COUNT(*) FROM T WHERE F1 >= 'A' AND F1 < 'Z';

라는 레코드 개수를 세는 SQL문을 돌렸습니다.
테이블 결과가 100만 이하인 경우에는 그런데로 속도가 괜찮았는데,

위의 결과가 800만 정도 나올 경우, 수분이 지나도 결과가 나오지 않는 
경우가 발생했습니다.

물론 F1 필드는 색인이 걸려 있었고,

EXPLAIN SELECT COUNT(*) FROM T WHERE F1 >= 'A' AND F1 < 'Z';

으로 살펴보아도 F1 색인을 탄다고 나왔습니다.

그런데 의아한 생각이 들었습니다.
800만이라는 수 만큼의 색인(B-TREE) Traverse 하는 속도는 수초 혹은 십초 안으로 
결과가 나와야 하는 안 나오니 말입니다.

여러가지 원인이 있을 수 있으나,
my.ini 파일에 mysqld 카테고리에 다음과 같은 속성을 
조종하면...

# max_connections (> 100) : Connection pool 등이 연결할 연결 개수 입니다
max_connections=128

# wait_timeout (< 28800) : 연결을 맺은 상태에서 아무 동작을 않을 시 끊길 Timeout 입니다
wait_timeout=28800

# interactive_timeout (< 28800) : 연결을 맺은 상태에서 마지막 SQL 동작 후 Timeout 입니다 (확인요..T.T)
interactive_timeout=28800

# key_buffer_size (> 7.8G) : MyISAM 테이블이 모든 쓰레드에서 공유할 색인 블락 크기
# 결국 위의 Count() 결과는 이 변수와 관계가 깊군요 (실제 메모리의 25% 정도가 적당하다고도 합니다)
key_buffer_size=7.8G

#join_buffer_size (> 128.0K, or always > use indexes with joins)
# 색인을 사용하지 않아 전체 테이블 검색을 요하는 경우에서의 join, 색인 검색, 범위 검색 등의 경우에
# 사용할 버퍼 크기 (이것도 Full Table 검색 시 속도와 관계가 있겠네요)
join_buffer_size=256K

# tmp_table_size (> 16M) : 검색 결과 등을 담기 위한 메모리 임시 테이블 크기
# 만약 이 임시 결과를 넘게 되면 일반 MyISAM 엔진에 임시 결과를 담게 됩니다.
# Count()와 같은 집계 함수가 아니고 일반 SELECT 인 경우에는,
# SELECT * FROM T LIMIT 10, 30 등으로 결과를 제한하시기 바랍니다.
tmp_table_size=64M

# max_heap_table_size (> 16M)
# 사용자가 생성한 메모리 테이블의 최대 크기 (보통 tmp_table_size와 관계 있으며 유사 크기로 지정)
max_heap_table_size=64M

# table_cache (> 1024) : 모든 쓰레드에서 읽힐 open 시켜 놓을 테이블의 개수
table_cache=1024

위와 같은 정도로 튜닝의 시작점을 잡으면 될 것 같습니다.

헌데 문제는 어떻게 최적 값을 잡을 수 있는가 입니다.
이렇게 하기 위해서 다음과 같은 튜너 프로그램이 존재합니다.


위에서와 같은 mysqltuner.pl 스크립트를 저장한 후,
실행시켜 봅니다.
(우분투에서 윈도우에 설치된 MySQL 서버에 돌려보아도 되었습니다.
 윈도우에서는 돌려보지 않았습니다)
이 스크립트는 필요한 정보만 읽어보고 쓰는 정보는 없으므로 
오류 발생에 대한 걱정을 안하셔도 됩니다. (라고 되어 있네요)

그런데 다음과 같은 조건에 하라고 되어 있네요.

  1. 적어도 MySQL 서버를 만 하루 이상 작동하고 있는 상태에서 실행시키십시오. 그렇지 않으면 너무 적은 시각에 따라 부정확한 프로파일링 결과가 나올 수 있습니다.
  2. 만약 tmp_table_size 혹은 max_heap_table_size 변수를 변경하려고 한다면 두 변수 모두 동일한 값으로 설정하십시오. 서버에 충분한 메모리가 있다면 충분한 크기로 늘려도 상관없습니다.
  3. 만약 join_buffer_size 변수를 수정하라고 결과가 나오면 max_connections 변수 값의 몇 배수로 설정값을 조종하시기 바랍니다.
  4. 만약 innodb_buffer_pool_size 값을 늘리라고 나오면 충분히 큰 값을 지정하십시오. 왜냐하면 DBMS 안에서 모든 InnoDB와 관계되어 있기 때문입니다. (만약 RAM이 적다면 구입하셔요~ 헐...)
위와 같은 결과를 간과하지 마십시오. 퍼포먼스에 심각한 영향을 끼칠 수 있습니다.

또한 다음과 같은 Perfomance Metrics 결과 리포트에 주목하십시오.

[--] Total buffers: 2.6G global + 130.6M per thread (100 max threads)
[OK] Maximum possible memory usage: 15.3G (48% of installed RAM)
[OK] Highest usage of available connections: 81% (81/100)

위와 같은 결과에서Maximum possible memory usage 의 결과가 50% 이하로 나오도록 해야 합니다.
그 아래의 결과는 max_connections 에 비하여 얼마나 연결을 사용하는가 하는 것입니다.
만약 값이 충분히 작다면 (예, 70% 이하)  max_connections 값을 더 낮추십시오.
위의 join_buffer_size 하고도 관계있습니다.
단 주의할 점은 MySQL 서버를 적어도 24시간 이상 정상 동작 시켜야만
보다 정확한 결과를 얻을 수 있습니다.

다음은 실제 돌려본 결과의 예, 입니다.


$ ./mysqltuner.pl --host 1.2.3.4 --user root --pass password --forcemem 8192 

 >>  MySQLTuner 1.2.0 - Major Hayden <major@mhtx.net>
 >>  Bug reports, feature requests, and downloads at http://mysqltuner.com/
 >>  Run with '--help' for additional options and output filtering
[--] Performing tests on 1.2.3.4:3306
[OK] Logged in using credentials passed on the command line
[--] Assuming 1024 MB of physical memory
[!!] Assuming 0 MB of swap space (use --forceswap to specify)

-------- General Statistics --------------------------------------------------
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.5.16

-------- Storage Engine Statistics -------------------------------------------
[--] Status: +Archive -BDB -Federated +InnoDB -ISAM -NDBCluster 
[--] Data in MyISAM tables: 26G (Tables: 12)
[--] Data in InnoDB tables: 976K (Tables: 18)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 17)
[!!] Total fragmented tables: 18

-------- Security Recommendations  -------------------------------------------
[OK] All database users have passwords assigned

-------- Performance Metrics -------------------------------------------------
[--] Up for: 14h 45m 43s (3K q [0.059 qps], 61 conn, TX: 3M, RX: 634K)
[--] Reads / Writes: 98% / 2%
[--] Total buffers: 41.0M global + 896.0K per thread (100 max threads)
[OK] Maximum possible memory usage: 128.5M (12% of installed RAM)
[OK] Slow queries: 0% (2/3K)
[OK] Highest usage of available connections: 10% (10/100)
[!!] Key buffer size / total MyISAM indexes: 11.0M/8.8G
[!!] Key buffer hit rate: 0.0% (10M cached / 10M reads)
[!!] Query cache is disabled
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 20 sorts)
[OK] Temporary tables created on disk: 0% (1 on disk / 181 total)
[OK] Thread cache hit rate: 83% (10 created / 61 connections)
[OK] Table cache hit rate: 34% (71 open / 206 opened)
[OK] Open file limit used: 2% (72/2K)
[OK] Table locks acquired immediately: 100% (1K immediate / 1K locks)
[OK] InnoDB data size / buffer pool: 976.0K/18.0M

-------- Recommendations -----------------------------------------------------
General recommendations:
    Run OPTIMIZE TABLE to defragment tables for better performance
    MySQL started within last 24 hours - recommendations may be inaccurate
    Enable the slow query log to troubleshoot bad queries
Variables to adjust:
    key_buffer_size (> 8.8G)
    query_cache_size (>= 8M)

차분하게 마지막 결과만 잘 반영해도
많은 차이가 날 것입니다.


결국 검색 결과가 너무 많을 경우에는,

SELECT COUNT(1) FROM T WHERE F1 >= 'A' AND F1 < 'Z';
에서 제한을 걸기 위하여

SELECT COUNT(1) FROM T WHERE F1 >= 'A' AND F1 < 'Z' LIMIT 100000;
이라고 10만으로 제한을 걸어도 결국 COUNT() 집계 함수는 모든 Traverse를 다 하게 됨으로
결과가 느렸습니다. (실제 결과가 천만, 억 등이 넘는 경우)

이런 경우, 다음과 같이 질의를 하면 빠른 결과를 찾을 수 있습니다...

SELECT 1 FROM T WHERE F1 >= 'A' AND F1 < 'Z' LIMIT 100000,1;

위의 결과가 '1' 이라고 나오면 100000만번째 결과가 있는 것이고,
이 결과가 없으면 100000개 이하의 결과가 있는 것입니다.

아주 큰 데이터인 경우, COUNT() 대신 이런 식으로 제한을 걸어,
첫 페이지를

SELECT * FROM T WHERE F1 >= 'A' AND F1 < 'Z' LIMIT 0, 100;
와 같이 구하면 비교적 빠른 검색 결과를 얻을 수 있을 것입니다.


어느분께는 도움이 되셨기를...


'DB TUNE' 카테고리의 다른 글

[MySQLD] Tunner  (0) 2018.04.19
[MySQLD] innodb_file_per_table  (0) 2018.04.19
MySQL 튜닝 값을 탐지해주는 유용한 툴  (0) 2018.04.19
[MySQLD] table_open_cache  (0) 2018.04.19
[MySQLD] join_buffer_size  (0) 2018.04.19
728x90

Query.getScript()

원문 링크  http://api.jquery.com/jQuery.getScript/

jQuery.getScript( url [, success(script, textStatus, jqXHR)] )Returns : jqXHR

개요 : HTTP GET 방식 요청을 통해 서버로부터 받은 JavaScript 파일을 로드하고 실행합니다.

  • jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
  • url 정보를 요청할 URL
  • success(data, textStatus, jqXHR) 요청이 성공하면 실행될 콜백 함수

이 함수의 가장 간단한 사용법은 아래와 같습니다.

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

스크립트가 실행되면 다른 변수에서 접근이 가능하고 jQuery 함수에서도 사용할 수 있습니다. 포함된 스크립트는 현재 페이지에 영향을 줄 수 있습니다.

Success Callback

이 콜백함수는 JavaScript 파일을 반환 받습니다. 스크립트가 이미 이 시점에서 실행되므로 이것은 일반적으로 유용하지 않습니다.

$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");

스크립트는 파일이름을 참고한 후 로드하고 실행됩니다.

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
   console.log(data); //data returned
   console.log(textStatus); //success
   console.log(jqxhr.status); //200
   console.log('Load was performed.');
});

Handling Errors

jQuery 1.5 부터 .fail() 함수를 사용할 수 있게 되었습니다.

$.getScript("ajax/test.js")
.done(function(script, textStatus) {
  console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
  $( "div.log" ).text( "Triggered ajaxError handler." );
});  

jQuery 1.5 이전 버젼에서는, .ajaxError() 콜백 이벤트에 $.getScript() 에러 처리 구문을 포함해서 사용해야 합니다.

$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
  if (settings.dataType=='script') {
    $(this).text( "Triggered ajaxError handler." );
  }
});

Caching Responses

기본적으로 $.getScript() 의 cache 속성값은 false 입니다. 스크립트를 요청시에 URL에 timestamped 를 포함하여 브라우져가 항상 새로운 스크립트를 요청하도록 하십시오. cache 속성의 전역값을 새로 세팅하려면 $.ajaxSetup()에서 하셔야 합니다.

$.ajaxSetup({
  cache: true
});

예 제  
캐싱된 스크립트를 가져올 수 있도록 $.cachedScript() 함수에서 정의합니다.

jQuery.cachedScript = function(url, options) {

  // allow user to set any option except for dataType, cache, and url
  options = $.extend(options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax(options);
};

// Usage
$.cachedScript("ajax/test.js").done(function(script, textStatus) {
  console.log( textStatus );
});

음, 솔직히 말씀드려서 위 예제가 실행되면 어떻게 된다는 건지 정확하게 모르겠습니다. :-(

 

예 제  
공식 jQuery 컬러 애니메이션 플러그인 파일을 로드하고 특정 컬러를 반영합니다.

<!DOCTYPE html>
<html>
<head>
  <style>
.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<button id="go">&raquo; Run</button>

<div class="block"></div>

<script>
$.getScript("/scripts/jquery.color.js", function() {
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: "pink" }, 1000)
      .delay(500)
      .animate( { backgroundColor: "blue" }, 1000);
  });
});
</script>

</body>
</html>

미리보기

jquery.color.js 파일을 열어보세요. 무지 복잡하게 뭐라무라 되어 있네요. 그중에 colors = jQuery.Color.names 변수에 위 예제에 있는 blue와 pink 에 대한 16진수 값이 들어 있습니다. 그 js 파일을 열어서 관련 로직을 반영시키는 것입니다.

 

음;;; 이 방식이 딱히 필요한지 모르겠습니다만.... 어디선가 쓸일이 있을지도 모르겠네요. 사용해 보신 분들 사례 좀 말씀해 주세용!!

※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.



출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

'WEB > jQuery' 카테고리의 다른 글

특정 div 프린트 하기  (0) 2018.05.11
Returning JSON data using jQuery POST function from server  (0) 2018.05.10
Refresh Part of Page (div)  (0) 2018.04.13
jQuery Select Box Control  (0) 2018.04.13
turn.js  (0) 2018.03.08
728x90

dbDelta( string|array $queries = ''bool $execute = true )

Modifies the database based on specified SQL statements.


Description Description

Useful for creating new tables and updating existing tables to a new structure.


Parameters Parameters

$queries

(string|array) (Optional) The query to run. Can be multiple queries in an array, or a string of queries separated by semicolons.

Default value: ''

$execute

(bool) (Optional) Whether or not to execute the query right away.

Default value: true


Top ↑

Return Return

(array) Strings containing the results of the various update queries.


Top ↑

Source Source

File: wp-admin/includes/upgrade.php

2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
function dbDelta( $queries = '', $execute = true ) {
    global $wpdb;
 
    if ( in_array( $queries, array( '', 'all', 'blog', 'global', 'ms_global' ), true ) )
        $queries = wp_get_db_schema( $queries );
 
    // Separate individual queries into an array
    if ( !is_array($queries) ) {
        $queries = explode( ';', $queries );
        $queries = array_filter( $queries );
    }
 
    /**
     * Filters the dbDelta SQL queries.
     *
     * @since 3.3.0
     *
     * @param array $queries An array of dbDelta SQL queries.
     */
    $queries = apply_filters( 'dbdelta_queries', $queries );
 
    $cqueries = array(); // Creation Queries
    $iqueries = array(); // Insertion Queries
    $for_update = array();
 
    // Create a tablename index for an array ($cqueries) of queries
    foreach ($queries as $qry) {
        if ( preg_match( "|CREATE TABLE ([^ ]*)|", $qry, $matches ) ) {
            $cqueries[ trim( $matches[1], '`' ) ] = $qry;
            $for_update[$matches[1]] = 'Created table '.$matches[1];
        } elseif ( preg_match( "|CREATE DATABASE ([^ ]*)|", $qry, $matches ) ) {
            array_unshift( $cqueries, $qry );
        } elseif ( preg_match( "|INSERT INTO ([^ ]*)|", $qry, $matches ) ) {
            $iqueries[] = $qry;
        } elseif ( preg_match( "|UPDATE ([^ ]*)|", $qry, $matches ) ) {
            $iqueries[] = $qry;
        } else {
            // Unrecognized query type
        }
    }
 
    /**
     * Filters the dbDelta SQL queries for creating tables and/or databases.
     *
     * Queries filterable via this hook contain "CREATE TABLE" or "CREATE DATABASE".
     *
     * @since 3.3.0
     *
     * @param array $cqueries An array of dbDelta create SQL queries.
     */
    $cqueries = apply_filters( 'dbdelta_create_queries', $cqueries );
 
    /**
     * Filters the dbDelta SQL queries for inserting or updating.
     *
     * Queries filterable via this hook contain "INSERT INTO" or "UPDATE".
     *
     * @since 3.3.0
     *
     * @param array $iqueries An array of dbDelta insert or update SQL queries.
     */
    $iqueries = apply_filters( 'dbdelta_insert_queries', $iqueries );
 
    $text_fields = array( 'tinytext', 'text', 'mediumtext', 'longtext' );
    $blob_fields = array( 'tinyblob', 'blob', 'mediumblob', 'longblob' );
 
    $global_tables = $wpdb->tables( 'global' );
    foreach ( $cqueries as $table => $qry ) {
        // Upgrade global tables only for the main site. Don't upgrade at all if conditions are not optimal.
        if ( in_array( $table, $global_tables ) && ! wp_should_upgrade_global_tables() ) {
            unset( $cqueries[ $table ], $for_update[ $table ] );
            continue;
        }
 
        // Fetch the table column structure from the database
        $suppress = $wpdb->suppress_errors();
        $tablefields = $wpdb->get_results("DESCRIBE {$table};");
        $wpdb->suppress_errors( $suppress );
 
        if ( ! $tablefields )
            continue;
 
        // Clear the field and index arrays.
        $cfields = $indices = $indices_without_subparts = array();
 
        // Get all of the field names in the query from between the parentheses.
        preg_match("|\((.*)\)|ms", $qry, $match2);
        $qryline = trim($match2[1]);
 
        // Separate field lines into an array.
        $flds = explode("\n", $qryline);
 
        // For every field line specified in the query.
        foreach ( $flds as $fld ) {
            $fld = trim( $fld, " \t\n\r\0\x0B," ); // Default trim characters, plus ','.
 
            // Extract the field name.
            preg_match( '|^([^ ]*)|', $fld, $fvals );
            $fieldname = trim( $fvals[1], '`' );
            $fieldname_lowercased = strtolower( $fieldname );
 
            // Verify the found field name.
            $validfield = true;
            switch ( $fieldname_lowercased ) {
                case '':
                case 'primary':
                case 'index':
                case 'fulltext':
                case 'unique':
                case 'key':
                case 'spatial':
                    $validfield = false;
 
                    /*
                     * Normalize the index definition.
                     *
                     * This is done so the definition can be compared against the result of a
                     * `SHOW INDEX FROM $table_name` query which returns the current table
                     * index information.
                     */
 
                    // Extract type, name and columns from the definition.
                    preg_match(
                          '/^'
                        .   '(?P<index_type>'             // 1) Type of the index.
                        .       'PRIMARY\s+KEY|(?:UNIQUE|FULLTEXT|SPATIAL)\s+(?:KEY|INDEX)|KEY|INDEX'
                        .   ')'
                        .   '\s+'                         // Followed by at least one white space character.
                        .   '(?:'                         // Name of the index. Optional if type is PRIMARY KEY.
                        .       '`?'                      // Name can be escaped with a backtick.
                        .           '(?P<index_name>'     // 2) Name of the index.
                        .               '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
                        .           ')'
                        .       '`?'                      // Name can be escaped with a backtick.
                        .       '\s+'                     // Followed by at least one white space character.
                        .   ')*'
                        .   '\('                          // Opening bracket for the columns.
                        .       '(?P<index_columns>'
                        .           '.+?'                 // 3) Column names, index prefixes, and orders.
                        .       ')'
                        .   '\)'                          // Closing bracket for the columns.
                        . '$/im',
                        $fld,
                        $index_matches
                    );
 
                    // Uppercase the index type and normalize space characters.
                    $index_type = strtoupper( preg_replace( '/\s+/', ' ', trim( $index_matches['index_type'] ) ) );
 
                    // 'INDEX' is a synonym for 'KEY', standardize on 'KEY'.
                    $index_type = str_replace( 'INDEX', 'KEY', $index_type );
 
                    // Escape the index name with backticks. An index for a primary key has no name.
                    $index_name = ( 'PRIMARY KEY' === $index_type ) ? '' : '`' . strtolower( $index_matches['index_name'] ) . '`';
 
                    // Parse the columns. Multiple columns are separated by a comma.
                    $index_columns = $index_columns_without_subparts = array_map( 'trim', explode( ',', $index_matches['index_columns'] ) );
 
                    // Normalize columns.
                    foreach ( $index_columns as $id => &$index_column ) {
                        // Extract column name and number of indexed characters (sub_part).
                        preg_match(
                              '/'
                            .   '`?'                      // Name can be escaped with a backtick.
                            .       '(?P<column_name>'    // 1) Name of the column.
                            .           '(?:[0-9a-zA-Z$_-]|[\xC2-\xDF][\x80-\xBF])+'
                            .       ')'
                            .   '`?'                      // Name can be escaped with a backtick.
                            .   '(?:'                     // Optional sub part.
                            .       '\s*'                 // Optional white space character between name and opening bracket.
                            .       '\('                  // Opening bracket for the sub part.
                            .           '\s*'             // Optional white space character after opening bracket.
                            .           '(?P<sub_part>'
                            .               '\d+'         // 2) Number of indexed characters.
                            .           ')'
                            .           '\s*'             // Optional white space character before closing bracket.
                            .        '\)'                 // Closing bracket for the sub part.
                            .   ')?'
                            . '/',
                            $index_column,
                            $index_column_matches
                        );
 
                        // Escape the column name with backticks.
                        $index_column = '`' . $index_column_matches['column_name'] . '`';
 
                        // We don't need to add the subpart to $index_columns_without_subparts
                        $index_columns_without_subparts[ $id ] = $index_column;
 
                        // Append the optional sup part with the number of indexed characters.
                        if ( isset( $index_column_matches['sub_part'] ) ) {
                            $index_column .= '(' . $index_column_matches['sub_part'] . ')';
                        }
                    }
 
                    // Build the normalized index definition and add it to the list of indices.
                    $indices[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns ) . ")";
                    $indices_without_subparts[] = "{$index_type} {$index_name} (" . implode( ',', $index_columns_without_subparts ) . ")";
 
                    // Destroy no longer needed variables.
                    unset( $index_column, $index_column_matches, $index_matches, $index_type, $index_name, $index_columns, $index_columns_without_subparts );
 
                    break;
            }
 
            // If it's a valid field, add it to the field array.
            if ( $validfield ) {
                $cfields[ $fieldname_lowercased ] = $fld;
            }
        }
 
        // For every field in the table.
        foreach ( $tablefields as $tablefield ) {
            $tablefield_field_lowercased = strtolower( $tablefield->Field );
            $tablefield_type_lowercased = strtolower( $tablefield->Type );
 
            // If the table field exists in the field array ...
            if ( array_key_exists( $tablefield_field_lowercased, $cfields ) ) {
 
                // Get the field type from the query.
                preg_match( '|`?' . $tablefield->Field . '`? ([^ ]*( unsigned)?)|i', $cfields[ $tablefield_field_lowercased ], $matches );
                $fieldtype = $matches[1];
                $fieldtype_lowercased = strtolower( $fieldtype );
 
                // Is actual field type different from the field type in query?
                if ($tablefield->Type != $fieldtype) {
                    $do_change = true;
                    if ( in_array( $fieldtype_lowercased, $text_fields ) && in_array( $tablefield_type_lowercased, $text_fields ) ) {
                        if ( array_search( $fieldtype_lowercased, $text_fields ) < array_search( $tablefield_type_lowercased, $text_fields ) ) {
                            $do_change = false;
                        }
                    }
 
                    if ( in_array( $fieldtype_lowercased, $blob_fields ) && in_array( $tablefield_type_lowercased, $blob_fields ) ) {
                        if ( array_search( $fieldtype_lowercased, $blob_fields ) < array_search( $tablefield_type_lowercased, $blob_fields ) ) {
                            $do_change = false;
                        }
                    }
 
                    if ( $do_change ) {
                        // Add a query to change the column type.
                        $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN `{$tablefield->Field}` " . $cfields[ $tablefield_field_lowercased ];
                        $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}";
                    }
                }
 
                // Get the default value from the array.
                if ( preg_match( "| DEFAULT '(.*?)'|i", $cfields[ $tablefield_field_lowercased ], $matches ) ) {
                    $default_value = $matches[1];
                    if ($tablefield->Default != $default_value) {
                        // Add a query to change the column's default value
                        $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN `{$tablefield->Field}` SET DEFAULT '{$default_value}'";
                        $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}";
                    }
                }
 
                // Remove the field from the array (so it's not added).
                unset( $cfields[ $tablefield_field_lowercased ] );
            } else {
                // This field exists in the table, but not in the creation queries?
            }
        }
 
        // For every remaining field specified for the table.
        foreach ($cfields as $fieldname => $fielddef) {
            // Push a query line into $cqueries that adds the field to that table.
            $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef";
            $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname;
        }
 
        // Index stuff goes here. Fetch the table index structure from the database.
        $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};");
 
        if ($tableindices) {
            // Clear the index array.
            $index_ary = array();
 
            // For every index in the table.
            foreach ($tableindices as $tableindex) {
 
                // Add the index to the index data array.
                $keyname = strtolower( $tableindex->Key_name );
                $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part);
                $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false;
                $index_ary[$keyname]['index_type'] = $tableindex->Index_type;
            }
 
            // For each actual index in the index array.
            foreach ($index_ary as $index_name => $index_data) {
 
                // Build a create string to compare to the query.
                $index_string = '';
                if ($index_name == 'primary') {
                    $index_string .= 'PRIMARY ';
                } elseif ( $index_data['unique'] ) {
                    $index_string .= 'UNIQUE ';
                }
                if ( 'FULLTEXT' === strtoupper( $index_data['index_type'] ) ) {
                    $index_string .= 'FULLTEXT ';
                }
                if ( 'SPATIAL' === strtoupper( $index_data['index_type'] ) ) {
                    $index_string .= 'SPATIAL ';
                }
                $index_string .= 'KEY ';
                if ( 'primary' !== $index_name  ) {
                    $index_string .= '`' . $index_name . '`';
                }
                $index_columns = '';
 
                // For each column in the index.
                foreach ($index_data['columns'] as $column_data) {
                    if ( $index_columns != '' ) {
                        $index_columns .= ',';
                    }
 
                    // Add the field to the column list string.
                    $index_columns .= '`' . $column_data['fieldname'] . '`';
                }
 
                // Add the column list to the index create string.
                $index_string .= " ($index_columns)";
 
                // Check if the index definition exists, ignoring subparts.
                if ( ! ( ( $aindex = array_search( $index_string, $indices_without_subparts ) ) === false ) ) {
                    // If the index already exists (even with different subparts), we don't need to create it.
                    unset( $indices_without_subparts[ $aindex ] );
                    unset( $indices[ $aindex ] );
                }
            }
        }
 
        // For every remaining index specified for the table.
        foreach ( (array) $indices as $index ) {
            // Push a query line into $cqueries that adds the index to that table.
            $cqueries[] = "ALTER TABLE {$table} ADD $index";
            $for_update[] = 'Added index ' . $table . ' ' . $index;
        }
 
        // Remove the original table creation query from processing.
        unset( $cqueries[ $table ], $for_update[ $table ] );
    }
 
    $allqueries = array_merge($cqueries, $iqueries);
    if ($execute) {
        foreach ($allqueries as $query) {
            $wpdb->query($query);
        }
    }
 
    return $for_update;
}

Top ↑

Changelog Changelog

Changelog
VersionDescription
1.5.0Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Store Locator Plus — 

    You must be very careful in your SQL command structure when creating tables with indexes.

    Here is a simple example of the proper create table syntax for a table with a primary key on a field named “id” and a secondary key on a field named “first”.

    PRIMARY KEY must be followed by TWO SPACES then the open parenthesis then the field name and a closing parenthesis.

    KEY must be followed by a SINGLE SPACE then the key name then a space then open parenthesis with the field name then a closed parenthesis.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    private function index_test_001() {
         global $wpdb;
         $table_name = $wpdb->prefix . 'dbdelta_test_001';
         $wpdb_collate = $wpdb->collate;
         $sql =
             "CREATE TABLE {$table_name} (
             id mediumint(8) unsigned NOT NULL auto_increment ,
             first varchar(255) NULL,
             PRIMARY KEY  (id),
             KEY first (first)
             )
             COLLATE {$wpdb_collate}";
     
         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
         dbDelta( $sql );
     }
  2. Skip to note content
    Contributed by Earnest Boyd — 

    Be careful not to put a COMMENT on field or key; the preg_match code doesn’t handle it. The following code is wrong (thanks to Store Locator Plus’ code).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    private function index_test_001() {
         global $wpdb;
         $table_name = $wpdb->prefix . 'dbdelta_test_001';
         $wpdb_collate = $wpdb->collate;
         $sql =
             "CREATE TABLE {$table_name} (
             id mediumint(8) unsigned NOT NULL auto_increment ,
             first varchar(255) NULL,
             PRIMARY KEY  (id),
             KEY first (first) COMMENT 'First name'
             )
             COLLATE {$wpdb_collate}";
      
         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
         dbDelta( $sql );
     }
  3. Skip to note content
    Contributed by octag — 

    (I post here a corrected version of my previous note. Several typographical mistakes have slipped into the original version.)
    As a side-note, the dbDelta function cannot be used to drop a table from the wp_ database . A function such as the one below can be used instead (don’t forget to replace my_theme with your own theme name):

    1
    2
    3
    4
    5
    6
    7
    8
    function my_theme_drop_table ( $table_name = 'the_name_without_any_prefix' ){
        global $wpdb;
     
        $table_name_prepared = $wpdb->prefix . $table_name;
        $the_removal_query = "DROP TABLE IF EXISTS {$table_name_prepared}";
     
        $wpdb->query( $the_removal_query );
    }

    See also https://developer.wordpress.org/plugins/the-basics/uninstall-methods/.


+ Recent posts