index.c 18.4 KB
Newer Older
H
refact  
Hongze Cheng 已提交
1 2 3 4
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
dengyihao's avatar
dengyihao 已提交
5 6
 * it under the terms of the GNU Affero General Public License, version 3 * or later ("AGPL"), as published by the Free
 * Software Foundation.
H
refact  
Hongze Cheng 已提交
7 8 9 10 11 12 13 14 15
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

dengyihao's avatar
dengyihao 已提交
16
#include "index.h"
dengyihao's avatar
dengyihao 已提交
17 18
#include "indexCache.h"
#include "indexComm.h"
dengyihao's avatar
dengyihao 已提交
19
#include "indexInt.h"
dengyihao's avatar
dengyihao 已提交
20 21
#include "indexTfile.h"
#include "indexUtil.h"
dengyihao's avatar
dengyihao 已提交
22 23
#include "tcoding.h"
#include "tdataformat.h"
dengyihao's avatar
dengyihao 已提交
24
#include "tdef.h"
dengyihao's avatar
dengyihao 已提交
25
#include "tref.h"
dengyihao's avatar
dengyihao 已提交
26
#include "tsched.h"
H
refact  
Hongze Cheng 已提交
27

dengyihao's avatar
dengyihao 已提交
28 29
#ifdef USE_LUCENE
#include "lucene++/Lucene_c.h"
H
refact  
Hongze Cheng 已提交
30 31
#endif

32
#define INDEX_NUM_OF_THREADS 1
dengyihao's avatar
dengyihao 已提交
33
#define INDEX_QUEUE_SIZE     200
dengyihao's avatar
dengyihao 已提交
34

dengyihao's avatar
dengyihao 已提交
35 36 37 38 39
#define INDEX_DATA_BOOL_NULL      0x02
#define INDEX_DATA_TINYINT_NULL   0x80
#define INDEX_DATA_SMALLINT_NULL  0x8000
#define INDEX_DATA_INT_NULL       0x80000000L
#define INDEX_DATA_BIGINT_NULL    0x8000000000000000L
dengyihao's avatar
dengyihao 已提交
40 41
#define INDEX_DATA_TIMESTAMP_NULL TSDB_DATA_BIGINT_NULL

dengyihao's avatar
dengyihao 已提交
42 43 44 45 46 47
#define INDEX_DATA_FLOAT_NULL    0x7FF00000           // it is an NAN
#define INDEX_DATA_DOUBLE_NULL   0x7FFFFF0000000000L  // an NAN
#define INDEX_DATA_NCHAR_NULL    0xFFFFFFFF
#define INDEX_DATA_BINARY_NULL   0xFF
#define INDEX_DATA_JSON_NULL     0xFFFFFFFF
#define INDEX_DATA_JSON_null     0xFFFFFFFE
dengyihao's avatar
dengyihao 已提交
48 49
#define INDEX_DATA_JSON_NOT_NULL 0x01

dengyihao's avatar
dengyihao 已提交
50
#define INDEX_DATA_UTINYINT_NULL  0xFF
dengyihao's avatar
dengyihao 已提交
51
#define INDEX_DATA_USMALLINT_NULL 0xFFFF
dengyihao's avatar
dengyihao 已提交
52 53
#define INDEX_DATA_UINT_NULL      0xFFFFFFFF
#define INDEX_DATA_UBIGINT_NULL   0xFFFFFFFFFFFFFFFFL
dengyihao's avatar
dengyihao 已提交
54

dengyihao's avatar
dengyihao 已提交
55
#define INDEX_DATA_NULL_STR   "NULL"
dengyihao's avatar
dengyihao 已提交
56 57
#define INDEX_DATA_NULL_STR_L "null"

dengyihao's avatar
dengyihao 已提交
58 59 60 61 62
void*   indexQhandle = NULL;
int32_t indexRefMgt;

static void indexDestroy(void* sIdx);

dengyihao's avatar
dengyihao 已提交
63 64
void indexInit() {
  // refactor later
dengyihao's avatar
dengyihao 已提交
65
  indexQhandle = taosInitScheduler(INDEX_QUEUE_SIZE, INDEX_NUM_OF_THREADS, "index");
dengyihao's avatar
dengyihao 已提交
66
  indexRefMgt = taosOpenRef(10, indexDestroy);
dengyihao's avatar
dengyihao 已提交
67
}
dengyihao's avatar
dengyihao 已提交
68 69 70 71
void indexCleanUp() {
  // refacto later
  taosCleanUpScheduler(indexQhandle);
}
dengyihao's avatar
dengyihao 已提交
72

dengyihao's avatar
dengyihao 已提交
73
typedef struct SIdxColInfo {
74
  int colId;  // generated by index internal
dengyihao's avatar
dengyihao 已提交
75
  int cVersion;
76
} SIdxColInfo;
dengyihao's avatar
dengyihao 已提交
77

wafwerar's avatar
wafwerar 已提交
78
static TdThreadOnce isInit = PTHREAD_ONCE_INIT;
dengyihao's avatar
dengyihao 已提交
79
// static void           indexInit();
dengyihao's avatar
dengyihao 已提交
80
static int indexTermSearch(SIndex* sIdx, SIndexTermQuery* term, SArray** result);
dengyihao's avatar
dengyihao 已提交
81

dengyihao's avatar
dengyihao 已提交
82 83
static void indexInterResultsDestroy(SArray* results);
static int  indexMergeFinalResults(SArray* interResults, EIndexOperatorType oType, SArray* finalResult);
dengyihao's avatar
dengyihao 已提交
84

dengyihao's avatar
dengyihao 已提交
85 86
static int indexGenTFile(SIndex* index, IndexCache* cache, SArray* batch);

dengyihao's avatar
dengyihao 已提交
87
// merge cache and tfile by opera type
dengyihao's avatar
dengyihao 已提交
88
static void indexMergeCacheAndTFile(SArray* result, IterateValue* icache, IterateValue* iTfv, SIdxTempResult* helper);
dengyihao's avatar
dengyihao 已提交
89

dengyihao's avatar
dengyihao 已提交
90 91
// static int32_t indexSerialTermKey(SIndexTerm* itm, char* buf);
// int32_t        indexSerialKey(ICacheKey* key, char* buf);
dengyihao's avatar
dengyihao 已提交
92

dengyihao's avatar
dengyihao 已提交
93 94 95 96 97 98 99 100 101
static void indexPost(void* idx) {
  SIndex* pIdx = idx;
  tsem_post(&pIdx->sem);
}
static void indexWait(void* idx) {
  SIndex* pIdx = idx;
  tsem_wait(&pIdx->sem);
}

dengyihao's avatar
dengyihao 已提交
102
int indexOpen(SIndexOpts* opts, const char* path, SIndex** index) {
wafwerar's avatar
wafwerar 已提交
103
  taosThreadOnce(&isInit, indexInit);
wafwerar's avatar
wafwerar 已提交
104
  SIndex* sIdx = taosMemoryCalloc(1, sizeof(SIndex));
dengyihao's avatar
dengyihao 已提交
105 106 107
  if (sIdx == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
108

dengyihao's avatar
dengyihao 已提交
109 110
  // sIdx->cache = (void*)indexCacheCreate(sIdx);
  sIdx->tindex = indexTFileCreate(path);
dengyihao's avatar
dengyihao 已提交
111 112 113
  if (sIdx->tindex == NULL) {
    goto END;
  }
dengyihao's avatar
dengyihao 已提交
114

115 116
  sIdx->colObj = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
  sIdx->cVersion = 1;
dengyihao's avatar
dengyihao 已提交
117
  sIdx->path = tstrdup(path);
wafwerar's avatar
wafwerar 已提交
118
  taosThreadMutexInit(&sIdx->mtx, NULL);
dengyihao's avatar
dengyihao 已提交
119
  tsem_init(&sIdx->sem, 0, 0);
dengyihao's avatar
dengyihao 已提交
120 121

  sIdx->refId = indexAddRef(sIdx);
dengyihao's avatar
dengyihao 已提交
122
  indexAcquireRef(sIdx->refId);
dengyihao's avatar
dengyihao 已提交
123

124 125
  *index = sIdx;
  return 0;
dengyihao's avatar
dengyihao 已提交
126

dengyihao's avatar
dengyihao 已提交
127
END:
dengyihao's avatar
dengyihao 已提交
128 129 130
  if (sIdx != NULL) {
    indexClose(sIdx);
  }
dengyihao's avatar
dengyihao 已提交
131 132
  *index = NULL;
  return -1;
H
refact  
Hongze Cheng 已提交
133
}
dengyihao's avatar
dengyihao 已提交
134

dengyihao's avatar
dengyihao 已提交
135 136
void indexDestroy(void* handle) {
  SIndex* sIdx = handle;
dengyihao's avatar
dengyihao 已提交
137
  taosThreadMutexDestroy(&sIdx->mtx);
dengyihao's avatar
dengyihao 已提交
138
  tsem_destroy(&sIdx->sem);
dengyihao's avatar
dengyihao 已提交
139 140 141 142 143 144 145
  indexTFileDestroy(sIdx->tindex);
  taosMemoryFree(sIdx->path);
  taosMemoryFree(sIdx);
  return;
}
void indexClose(SIndex* sIdx) {
  bool ref = 0;
dengyihao's avatar
dengyihao 已提交
146 147 148 149 150
  if (sIdx->colObj != NULL) {
    void* iter = taosHashIterate(sIdx->colObj, NULL);
    while (iter) {
      IndexCache** pCache = iter;
      indexCacheForceToMerge((void*)(*pCache));
151
      indexInfo("%s wait to merge", (*pCache)->colName);
dengyihao's avatar
dengyihao 已提交
152
      indexWait((void*)(sIdx));
dengyihao's avatar
dengyihao 已提交
153
      iter = taosHashIterate(sIdx->colObj, iter);
dengyihao's avatar
dengyihao 已提交
154 155
      indexCacheUnRef(*pCache);
    }
dengyihao's avatar
dengyihao 已提交
156 157
    taosHashCleanup(sIdx->colObj);
    sIdx->colObj = NULL;
dengyihao's avatar
dengyihao 已提交
158
  }
159
  indexReleaseRef(sIdx->refId);
dengyihao's avatar
dengyihao 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  indexRemoveRef(sIdx->refId);
}
int64_t indexAddRef(void* p) {
  // impl
  return taosAddRef(indexRefMgt, p);
}
int32_t indexRemoveRef(int64_t ref) {
  // impl later
  return taosRemoveRef(indexRefMgt, ref);
}

void indexAcquireRef(int64_t ref) {
  // impl
  taosAcquireRef(indexRefMgt, ref);
}
void indexReleaseRef(int64_t ref) {
  // impl
  taosReleaseRef(indexRefMgt, ref);
}
dengyihao's avatar
dengyihao 已提交
179

dengyihao's avatar
dengyihao 已提交
180
int indexPut(SIndex* index, SIndexMultiTerm* fVals, uint64_t uid) {
181
  // TODO(yihao): reduce the lock range
wafwerar's avatar
wafwerar 已提交
182
  taosThreadMutexLock(&index->mtx);
dengyihao's avatar
dengyihao 已提交
183
  for (int i = 0; i < taosArrayGetSize(fVals); i++) {
dengyihao's avatar
dengyihao 已提交
184 185
    SIndexTerm* p = taosArrayGetP(fVals, i);

dengyihao's avatar
dengyihao 已提交
186 187 188
    char      buf[128] = {0};
    ICacheKey key = {.suid = p->suid, .colName = p->colName, .nColName = strlen(p->colName), .colType = p->colType};
    int32_t   sz = indexSerialCacheKey(&key, buf);
dengyihao's avatar
dengyihao 已提交
189 190

    IndexCache** cache = taosHashGet(index->colObj, buf, sz);
dengyihao's avatar
dengyihao 已提交
191
    if (cache == NULL) {
dengyihao's avatar
dengyihao 已提交
192 193
      IndexCache* pCache = indexCacheCreate(index, p->suid, p->colName, p->colType);
      taosHashPut(index->colObj, buf, sz, &pCache, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
194
    }
195
  }
dengyihao's avatar
dengyihao 已提交
196
  taosThreadMutexUnlock(&index->mtx);
dengyihao's avatar
dengyihao 已提交
197 198

  for (int i = 0; i < taosArrayGetSize(fVals); i++) {
dengyihao's avatar
dengyihao 已提交
199 200
    SIndexTerm* p = taosArrayGetP(fVals, i);

dengyihao's avatar
dengyihao 已提交
201 202 203
    char      buf[128] = {0};
    ICacheKey key = {.suid = p->suid, .colName = p->colName, .nColName = strlen(p->colName), .colType = p->colType};
    int32_t   sz = indexSerialCacheKey(&key, buf);
dengyihao's avatar
dengyihao 已提交
204 205

    IndexCache** cache = taosHashGet(index->colObj, buf, sz);
dengyihao's avatar
dengyihao 已提交
206 207
    assert(*cache != NULL);
    int ret = indexCachePut(*cache, p, uid);
dengyihao's avatar
dengyihao 已提交
208 209 210
    if (ret != 0) {
      return ret;
    }
dengyihao's avatar
dengyihao 已提交
211
  }
dengyihao's avatar
dengyihao 已提交
212
  return 0;
dengyihao's avatar
dengyihao 已提交
213
}
dengyihao's avatar
dengyihao 已提交
214
int indexSearch(SIndex* index, SIndexMultiTermQuery* multiQuerys, SArray* result) {
215 216
  EIndexOperatorType opera = multiQuerys->opera;  // relation of querys

dengyihao's avatar
dengyihao 已提交
217
  SArray* iRslts = taosArrayInit(4, POINTER_BYTES);
218
  int     nQuery = taosArrayGetSize(multiQuerys->query);
dengyihao's avatar
dengyihao 已提交
219
  for (size_t i = 0; i < nQuery; i++) {
dengyihao's avatar
dengyihao 已提交
220 221 222 223
    SIndexTermQuery* qterm = taosArrayGet(multiQuerys->query, i);
    SArray*          trslt = NULL;
    indexTermSearch(index, qterm, &trslt);
    taosArrayPush(iRslts, (void*)&trslt);
224
  }
dengyihao's avatar
dengyihao 已提交
225 226
  indexMergeFinalResults(iRslts, opera, result);
  indexInterResultsDestroy(iRslts);
dengyihao's avatar
dengyihao 已提交
227
  return 0;
dengyihao's avatar
dengyihao 已提交
228 229
}

230 231
int indexDelete(SIndex* index, SIndexMultiTermQuery* query) { return 1; }
int indexRebuild(SIndex* index, SIndexOpts* opts) { return 0; }
dengyihao's avatar
dengyihao 已提交
232

233 234
SIndexOpts* indexOptsCreate() { return NULL; }
void        indexOptsDestroy(SIndexOpts* opts) { return; }
dengyihao's avatar
dengyihao 已提交
235 236 237 238
/*
 * @param: oper
 *
 */
dengyihao's avatar
dengyihao 已提交
239
SIndexMultiTermQuery* indexMultiTermQueryCreate(EIndexOperatorType opera) {
dengyihao's avatar
dengyihao 已提交
240 241
  SIndexMultiTermQuery* mtq = (SIndexMultiTermQuery*)taosMemoryMalloc(sizeof(SIndexMultiTermQuery));
  if (mtq == NULL) {
dengyihao's avatar
dengyihao 已提交
242 243
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
244 245 246
  mtq->opera = opera;
  mtq->query = taosArrayInit(4, sizeof(SIndexTermQuery));
  return mtq;
dengyihao's avatar
dengyihao 已提交
247
}
dengyihao's avatar
dengyihao 已提交
248
void indexMultiTermQueryDestroy(SIndexMultiTermQuery* pQuery) {
dengyihao's avatar
dengyihao 已提交
249
  for (int i = 0; i < taosArrayGetSize(pQuery->query); i++) {
dengyihao's avatar
dengyihao 已提交
250
    SIndexTermQuery* p = (SIndexTermQuery*)taosArrayGet(pQuery->query, i);
dengyihao's avatar
dengyihao 已提交
251
    indexTermDestroy(p->term);
dengyihao's avatar
dengyihao 已提交
252
  }
253
  taosArrayDestroy(pQuery->query);
wafwerar's avatar
wafwerar 已提交
254
  taosMemoryFree(pQuery);
dengyihao's avatar
dengyihao 已提交
255
};
dengyihao's avatar
dengyihao 已提交
256
int indexMultiTermQueryAdd(SIndexMultiTermQuery* pQuery, SIndexTerm* term, EIndexQueryType qType) {
257
  SIndexTermQuery q = {.qType = qType, .term = term};
dengyihao's avatar
dengyihao 已提交
258 259
  taosArrayPush(pQuery->query, &q);
  return 0;
dengyihao's avatar
dengyihao 已提交
260 261
}

dengyihao's avatar
dengyihao 已提交
262 263
SIndexTerm* indexTermCreate(int64_t suid, SIndexOperOnColumn oper, uint8_t colType, const char* colName,
                            int32_t nColName, const char* colVal, int32_t nColVal) {
dengyihao's avatar
dengyihao 已提交
264 265
  SIndexTerm* tm = (SIndexTerm*)taosMemoryCalloc(1, (sizeof(SIndexTerm)));
  if (tm == NULL) {
dengyihao's avatar
dengyihao 已提交
266 267
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
268

dengyihao's avatar
dengyihao 已提交
269 270 271
  tm->suid = suid;
  tm->operType = oper;
  tm->colType = colType;
dengyihao's avatar
dengyihao 已提交
272

dengyihao's avatar
dengyihao 已提交
273
#if 0
dengyihao's avatar
dengyihao 已提交
274 275 276
  tm->colName = (char*)taosMemoryCalloc(1, nColName + 1);
  memcpy(tm->colName, colName, nColName);
  tm->nColName = nColName;
dengyihao's avatar
dengyihao 已提交
277

dengyihao's avatar
dengyihao 已提交
278 279 280
  tm->colVal = (char*)taosMemoryCalloc(1, nColVal + 1);
  memcpy(tm->colVal, colVal, nColVal);
  tm->nColVal = nColVal;
dengyihao's avatar
dengyihao 已提交
281 282 283 284 285 286 287 288 289
#endif

#if 1

  tm->colName = (char*)taosMemoryCalloc(1, nColName + 1);
  memcpy(tm->colName, colName, nColName);
  tm->nColName = nColName;

  char*   buf = NULL;
290
  int32_t len = indexConvertDataToStr((void*)colVal, INDEX_TYPE_GET_TYPE(colType), (void**)&buf);
dengyihao's avatar
dengyihao 已提交
291 292 293 294 295 296
  assert(len != -1);

  tm->colVal = buf;
  tm->nColVal = len;

#endif
dengyihao's avatar
dengyihao 已提交
297 298

  return tm;
dengyihao's avatar
dengyihao 已提交
299
}
dengyihao's avatar
dengyihao 已提交
300
void indexTermDestroy(SIndexTerm* p) {
wafwerar's avatar
wafwerar 已提交
301 302 303
  taosMemoryFree(p->colName);
  taosMemoryFree(p->colVal);
  taosMemoryFree(p);
dengyihao's avatar
dengyihao 已提交
304 305
}

dengyihao's avatar
dengyihao 已提交
306
SIndexMultiTerm* indexMultiTermCreate() { return taosArrayInit(4, sizeof(SIndexTerm*)); }
307

dengyihao's avatar
dengyihao 已提交
308
int indexMultiTermAdd(SIndexMultiTerm* terms, SIndexTerm* term) {
309 310
  taosArrayPush(terms, &term);
  return 0;
dengyihao's avatar
dengyihao 已提交
311
}
dengyihao's avatar
dengyihao 已提交
312
void indexMultiTermDestroy(SIndexMultiTerm* terms) {
dengyihao's avatar
dengyihao 已提交
313
  for (int32_t i = 0; i < taosArrayGetSize(terms); i++) {
dengyihao's avatar
dengyihao 已提交
314
    SIndexTerm* p = taosArrayGetP(terms, i);
dengyihao's avatar
dengyihao 已提交
315 316
    indexTermDestroy(p);
  }
dengyihao's avatar
dengyihao 已提交
317
  taosArrayDestroy(terms);
dengyihao's avatar
dengyihao 已提交
318
}
dengyihao's avatar
dengyihao 已提交
319

dengyihao's avatar
dengyihao 已提交
320 321 322
static int indexTermSearch(SIndex* sIdx, SIndexTermQuery* query, SArray** result) {
  SIndexTerm* term = query->term;
  const char* colName = term->colName;
323
  int32_t     nColName = term->nColName;
dengyihao's avatar
dengyihao 已提交
324

dengyihao's avatar
dengyihao 已提交
325 326
  // Get col info
  IndexCache* cache = NULL;
dengyihao's avatar
dengyihao 已提交
327 328

  char      buf[128] = {0};
dengyihao's avatar
dengyihao 已提交
329 330 331
  ICacheKey key = {
      .suid = term->suid, .colName = term->colName, .nColName = strlen(term->colName), .colType = term->colType};
  int32_t sz = indexSerialCacheKey(&key, buf);
dengyihao's avatar
dengyihao 已提交
332

wafwerar's avatar
wafwerar 已提交
333
  taosThreadMutexLock(&sIdx->mtx);
dengyihao's avatar
dengyihao 已提交
334
  IndexCache** pCache = taosHashGet(sIdx->colObj, buf, sz);
dengyihao's avatar
dengyihao 已提交
335
  cache = (pCache == NULL) ? NULL : *pCache;
wafwerar's avatar
wafwerar 已提交
336
  taosThreadMutexUnlock(&sIdx->mtx);
337

dengyihao's avatar
dengyihao 已提交
338
  *result = taosArrayInit(4, sizeof(uint64_t));
339
  // TODO: iterator mem and tidex
dengyihao's avatar
dengyihao 已提交
340
  STermValueType s = kTypeValue;
dengyihao's avatar
dengyihao 已提交
341

dengyihao's avatar
add UT  
dengyihao 已提交
342 343
  int64_t st = taosGetTimestampUs();

dengyihao's avatar
dengyihao 已提交
344 345
  SIdxTempResult* tr = sIdxTempResultCreate();
  if (0 == indexCacheSearch(cache, query, tr, &s)) {
dengyihao's avatar
dengyihao 已提交
346
    if (s == kTypeDeletion) {
dengyihao's avatar
dengyihao 已提交
347
      indexInfo("col: %s already drop by", term->colName);
348
      // coloum already drop by other oper, no need to query tindex
dengyihao's avatar
dengyihao 已提交
349 350
      return 0;
    } else {
dengyihao's avatar
add UT  
dengyihao 已提交
351
      st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
352
      if (0 != indexTFileSearch(sIdx->tindex, query, tr)) {
353
        indexError("corrupt at index(TFile) col:%s val: %s", term->colName, term->colVal);
dengyihao's avatar
dengyihao 已提交
354
        goto END;
355
      }
dengyihao's avatar
add UT  
dengyihao 已提交
356 357
      int64_t tfCost = taosGetTimestampUs() - st;
      indexInfo("tfile search cost: %" PRIu64 "us", tfCost);
dengyihao's avatar
dengyihao 已提交
358 359 360
    }
  } else {
    indexError("corrupt at index(cache) col:%s val: %s", term->colName, term->colVal);
dengyihao's avatar
dengyihao 已提交
361
    goto END;
dengyihao's avatar
dengyihao 已提交
362
  }
dengyihao's avatar
add UT  
dengyihao 已提交
363 364
  int64_t cost = taosGetTimestampUs() - st;
  indexInfo("search cost: %" PRIu64 "us", cost);
dengyihao's avatar
dengyihao 已提交
365 366

  sIdxTempResultMergeTo(*result, tr);
dengyihao's avatar
add UT  
dengyihao 已提交
367

dengyihao's avatar
dengyihao 已提交
368
  sIdxTempResultDestroy(tr);
dengyihao's avatar
dengyihao 已提交
369
  return 0;
dengyihao's avatar
dengyihao 已提交
370 371 372
END:
  sIdxTempResultDestroy(tr);
  return -1;
dengyihao's avatar
dengyihao 已提交
373
}
dengyihao's avatar
dengyihao 已提交
374
static void indexInterResultsDestroy(SArray* results) {
dengyihao's avatar
dengyihao 已提交
375 376 377
  if (results == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
378 379 380

  size_t sz = taosArrayGetSize(results);
  for (size_t i = 0; i < sz; i++) {
dengyihao's avatar
dengyihao 已提交
381
    SArray* p = taosArrayGetP(results, i);
382 383
    taosArrayDestroy(p);
  }
dengyihao's avatar
dengyihao 已提交
384 385
  taosArrayDestroy(results);
}
dengyihao's avatar
dengyihao 已提交
386

dengyihao's avatar
dengyihao 已提交
387
static int indexMergeFinalResults(SArray* interResults, EIndexOperatorType oType, SArray* fResults) {
388
  // refactor, merge interResults into fResults by oType
dengyihao's avatar
dengyihao 已提交
389 390 391 392 393
  for (int i = 0; i < taosArrayGetSize(interResults); i--) {
    SArray* t = taosArrayGetP(interResults, i);
    taosArraySort(t, uidCompare);
    taosArrayRemoveDuplicate(t, uidCompare, NULL);
  }
dengyihao's avatar
dengyihao 已提交
394

dengyihao's avatar
dengyihao 已提交
395
  if (oType == MUST) {
dengyihao's avatar
dengyihao 已提交
396
    iIntersection(interResults, fResults);
dengyihao's avatar
dengyihao 已提交
397
  } else if (oType == SHOULD) {
dengyihao's avatar
dengyihao 已提交
398
    iUnion(interResults, fResults);
dengyihao's avatar
dengyihao 已提交
399
  } else if (oType == NOT) {
400
    // just one column index, enhance later
dengyihao's avatar
dengyihao 已提交
401
    taosArrayAddAll(fResults, interResults);
402
    // not use currently
dengyihao's avatar
dengyihao 已提交
403 404 405
  }
  return 0;
}
dengyihao's avatar
dengyihao 已提交
406

dengyihao's avatar
dengyihao 已提交
407
static void indexMayMergeTempToFinalResult(SArray* result, TFileValue* tfv, SIdxTempResult* tr) {
408 409 410 411
  int32_t sz = taosArrayGetSize(result);
  if (sz > 0) {
    TFileValue* lv = taosArrayGetP(result, sz - 1);
    if (tfv != NULL && strcmp(lv->colVal, tfv->colVal) != 0) {
dengyihao's avatar
dengyihao 已提交
412 413
      sIdxTempResultMergeTo(lv->tableId, tr);
      sIdxTempResultClear(tr);
414 415 416

      taosArrayPush(result, &tfv);
    } else if (tfv == NULL) {
dengyihao's avatar
dengyihao 已提交
417 418
      // handle last iterator
      sIdxTempResultMergeTo(lv->tableId, tr);
419
    } else {
dengyihao's avatar
dengyihao 已提交
420
      // temp result saved in help
421 422 423 424 425 426
      tfileValueDestroy(tfv);
    }
  } else {
    taosArrayPush(result, &tfv);
  }
}
dengyihao's avatar
dengyihao 已提交
427
static void indexMergeCacheAndTFile(SArray* result, IterateValue* cv, IterateValue* tv, SIdxTempResult* tr) {
428
  char*       colVal = (cv != NULL) ? cv->colVal : tv->colVal;
dengyihao's avatar
dengyihao 已提交
429
  TFileValue* tfv = tfileValueCreate(colVal);
430

dengyihao's avatar
dengyihao 已提交
431
  indexMayMergeTempToFinalResult(result, tfv, tr);
432

dengyihao's avatar
dengyihao 已提交
433
  if (cv != NULL) {
434
    uint64_t id = *(uint64_t*)taosArrayGet(cv->val, 0);
dengyihao's avatar
dengyihao 已提交
435
    uint32_t ver = cv->ver;
dengyihao's avatar
dengyihao 已提交
436
    if (cv->type == ADD_VALUE) {
dengyihao's avatar
dengyihao 已提交
437
      INDEX_MERGE_ADD_DEL(tr->deled, tr->added, id)
dengyihao's avatar
dengyihao 已提交
438
    } else if (cv->type == DEL_VALUE) {
dengyihao's avatar
dengyihao 已提交
439
      INDEX_MERGE_ADD_DEL(tr->added, tr->deled, id)
dengyihao's avatar
dengyihao 已提交
440 441 442
    }
  }
  if (tv != NULL) {
dengyihao's avatar
dengyihao 已提交
443
    taosArrayAddAll(tr->total, tv->val);
dengyihao's avatar
dengyihao 已提交
444 445
  }
}
dengyihao's avatar
dengyihao 已提交
446
static void indexDestroyFinalResult(SArray* result) {
dengyihao's avatar
dengyihao 已提交
447 448 449 450 451 452 453
  int32_t sz = result ? taosArrayGetSize(result) : 0;
  for (size_t i = 0; i < sz; i++) {
    TFileValue* tv = taosArrayGetP(result, i);
    tfileValueDestroy(tv);
  }
  taosArrayDestroy(result);
}
454

dengyihao's avatar
dengyihao 已提交
455
int indexFlushCacheToTFile(SIndex* sIdx, void* cache) {
dengyihao's avatar
dengyihao 已提交
456 457 458
  if (sIdx == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
459
  indexInfo("suid %" PRIu64 " merge cache into tindex", sIdx->suid);
dengyihao's avatar
dengyihao 已提交
460

dengyihao's avatar
dengyihao 已提交
461 462
  int64_t st = taosGetTimestampUs();

dengyihao's avatar
dengyihao 已提交
463
  IndexCache*  pCache = (IndexCache*)cache;
dengyihao's avatar
dengyihao 已提交
464
  TFileReader* pReader = tfileGetReaderByCol(sIdx->tindex, pCache->suid, pCache->colName);
dengyihao's avatar
dengyihao 已提交
465 466 467
  if (pReader == NULL) {
    indexWarn("empty tfile reader found");
  }
dengyihao's avatar
dengyihao 已提交
468 469
  // handle flush
  Iterate* cacheIter = indexCacheIteratorCreate(pCache);
dengyihao's avatar
dengyihao 已提交
470 471 472 473
  if (cacheIter == NULL) {
    indexError("%p immtable is empty, ignore merge opera", pCache);
    indexCacheDestroyImm(pCache);
    tfileReaderUnRef(pReader);
dengyihao's avatar
dengyihao 已提交
474
    if (sIdx->quit) {
dengyihao's avatar
dengyihao 已提交
475 476
      indexPost(sIdx);
      // indexCacheBroadcast(pCache);
dengyihao's avatar
dengyihao 已提交
477
    }
dengyihao's avatar
dengyihao 已提交
478 479 480 481
    indexReleaseRef(sIdx->refId);
    return 0;
  }

dengyihao's avatar
dengyihao 已提交
482
  Iterate* tfileIter = tfileIteratorCreate(pReader);
dengyihao's avatar
dengyihao 已提交
483 484 485
  if (tfileIter == NULL) {
    indexWarn("empty tfile reader iterator");
  }
dengyihao's avatar
dengyihao 已提交
486 487 488

  SArray* result = taosArrayInit(1024, sizeof(void*));

dengyihao's avatar
dengyihao 已提交
489 490
  bool cn = cacheIter ? cacheIter->next(cacheIter) : false;
  bool tn = tfileIter ? tfileIter->next(tfileIter) : false;
491

dengyihao's avatar
dengyihao 已提交
492
  SIdxTempResult* tr = sIdxTempResultCreate();
dengyihao's avatar
dengyihao 已提交
493 494 495 496 497 498 499 500 501 502 503 504
  while (cn == true || tn == true) {
    IterateValue* cv = (cn == true) ? cacheIter->getValue(cacheIter) : NULL;
    IterateValue* tv = (tn == true) ? tfileIter->getValue(tfileIter) : NULL;

    int comp = 0;
    if (cn == true && tn == true) {
      comp = strcmp(cv->colVal, tv->colVal);
    } else if (cn == true) {
      comp = -1;
    } else {
      comp = 1;
    }
dengyihao's avatar
dengyihao 已提交
505
    if (comp == 0) {
dengyihao's avatar
dengyihao 已提交
506
      indexMergeCacheAndTFile(result, cv, tv, tr);
dengyihao's avatar
dengyihao 已提交
507 508 509
      cn = cacheIter->next(cacheIter);
      tn = tfileIter->next(tfileIter);
    } else if (comp < 0) {
dengyihao's avatar
dengyihao 已提交
510
      indexMergeCacheAndTFile(result, cv, NULL, tr);
dengyihao's avatar
dengyihao 已提交
511 512
      cn = cacheIter->next(cacheIter);
    } else {
dengyihao's avatar
dengyihao 已提交
513
      indexMergeCacheAndTFile(result, NULL, tv, tr);
dengyihao's avatar
dengyihao 已提交
514 515 516
      tn = tfileIter->next(tfileIter);
    }
  }
dengyihao's avatar
dengyihao 已提交
517 518
  indexMayMergeTempToFinalResult(result, NULL, tr);
  sIdxTempResultDestroy(tr);
519

dengyihao's avatar
dengyihao 已提交
520
  int ret = indexGenTFile(sIdx, pCache, result);
dengyihao's avatar
dengyihao 已提交
521
  indexDestroyFinalResult(result);
dengyihao's avatar
dengyihao 已提交
522

dengyihao's avatar
dengyihao 已提交
523
  indexCacheDestroyImm(pCache);
dengyihao's avatar
dengyihao 已提交
524 525 526 527

  indexCacheIteratorDestroy(cacheIter);
  tfileIteratorDestroy(tfileIter);

dengyihao's avatar
dengyihao 已提交
528 529
  tfileReaderUnRef(pReader);
  indexCacheUnRef(pCache);
dengyihao's avatar
dengyihao 已提交
530 531 532 533 534 535 536

  int64_t cost = taosGetTimestampUs() - st;
  if (ret != 0) {
    indexError("failed to merge, time cost: %" PRId64 "ms", cost / 1000);
  } else {
    indexInfo("success to merge , time cost: %" PRId64 "ms", cost / 1000);
  }
dengyihao's avatar
dengyihao 已提交
537 538 539
  if (sIdx->quit) {
    indexPost(sIdx);
  }
dengyihao's avatar
dengyihao 已提交
540
  indexReleaseRef(sIdx->refId);
dengyihao's avatar
dengyihao 已提交
541

dengyihao's avatar
dengyihao 已提交
542
  return ret;
dengyihao's avatar
dengyihao 已提交
543
}
dengyihao's avatar
dengyihao 已提交
544 545 546
void iterateValueDestroy(IterateValue* value, bool destroy) {
  if (destroy) {
    taosArrayDestroy(value->val);
dengyihao's avatar
dengyihao 已提交
547
    value->val = NULL;
dengyihao's avatar
dengyihao 已提交
548
  } else {
dengyihao's avatar
dengyihao 已提交
549 550 551
    if (value->val != NULL) {
      taosArrayClear(value->val);
    }
dengyihao's avatar
dengyihao 已提交
552
  }
wafwerar's avatar
wafwerar 已提交
553
  taosMemoryFree(value->colVal);
dengyihao's avatar
dengyihao 已提交
554 555
  value->colVal = NULL;
}
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575

static int64_t indexGetAvaialbleVer(SIndex* sIdx, IndexCache* cache) {
  ICacheKey key = {.suid = cache->suid, .colName = cache->colName, .nColName = strlen(cache->colName)};
  int64_t   ver = CACHE_VERSION(cache);
  taosThreadMutexLock(&sIdx->mtx);
  TFileReader* trd = tfileCacheGet(((IndexTFile*)sIdx->tindex)->cache, &key);
  if (trd != NULL) {
    if (ver < trd->header.version) {
      ver = trd->header.version + 1;
    } else {
      ver += 1;
    }
    indexInfo("header: %d, ver: %" PRId64 "", trd->header.version, ver);
    tfileReaderUnRef(trd);
  } else {
    indexInfo("not found reader base %p", trd);
  }
  taosThreadMutexUnlock(&sIdx->mtx);
  return ver;
}
dengyihao's avatar
dengyihao 已提交
576
static int indexGenTFile(SIndex* sIdx, IndexCache* cache, SArray* batch) {
577 578
  int64_t version = indexGetAvaialbleVer(sIdx, cache);
  indexInfo("file name version: %" PRId64 "", version);
dengyihao's avatar
dengyihao 已提交
579 580
  uint8_t colType = cache->type;

dengyihao's avatar
dengyihao 已提交
581
  TFileWriter* tw = tfileWriterOpen(sIdx->path, cache->suid, version, cache->colName, colType);
dengyihao's avatar
dengyihao 已提交
582 583 584 585 586 587 588 589 590 591 592 593
  if (tw == NULL) {
    indexError("failed to open file to write");
    return -1;
  }

  int ret = tfileWriterPut(tw, batch, true);
  if (ret != 0) {
    indexError("failed to write into tindex ");
    goto END;
  }
  tfileWriterClose(tw);

dengyihao's avatar
dengyihao 已提交
594
  TFileReader* reader = tfileReaderOpen(sIdx->path, cache->suid, version, cache->colName);
dengyihao's avatar
dengyihao 已提交
595 596 597
  if (reader == NULL) {
    return -1;
  }
598
  indexInfo("success to create tfile, reopen it, %s", reader->ctx->file.buf);
dengyihao's avatar
dengyihao 已提交
599 600

  TFileHeader* header = &reader->header;
dengyihao's avatar
dengyihao 已提交
601
  ICacheKey    key = {.suid = cache->suid, .colName = header->colName, .nColName = strlen(header->colName)};
dengyihao's avatar
dengyihao 已提交
602

wafwerar's avatar
wafwerar 已提交
603
  taosThreadMutexLock(&sIdx->mtx);
dengyihao's avatar
dengyihao 已提交
604 605
  IndexTFile* ifile = (IndexTFile*)sIdx->tindex;
  tfileCachePut(ifile->cache, &key, reader);
wafwerar's avatar
wafwerar 已提交
606
  taosThreadMutexUnlock(&sIdx->mtx);
dengyihao's avatar
dengyihao 已提交
607 608
  return ret;
END:
dengyihao's avatar
dengyihao 已提交
609 610
  if (tw != NULL) {
    writerCtxDestroy(tw->ctx, true);
wafwerar's avatar
wafwerar 已提交
611
    taosMemoryFree(tw);
dengyihao's avatar
dengyihao 已提交
612
  }
dengyihao's avatar
dengyihao 已提交
613
  return -1;
dengyihao's avatar
dengyihao 已提交
614
}
dengyihao's avatar
dengyihao 已提交
615

dengyihao's avatar
dengyihao 已提交
616 617
int32_t indexSerialCacheKey(ICacheKey* key, char* buf) {
  bool hasJson = INDEX_TYPE_CONTAIN_EXTERN_TYPE(key->colType, TSDB_DATA_TYPE_JSON);
dengyihao's avatar
dengyihao 已提交
618

dengyihao's avatar
dengyihao 已提交
619
  char* p = buf;
dengyihao's avatar
dengyihao 已提交
620 621 622 623
  char  tbuf[65] = {0};
  indexInt2str((int64_t)key->suid, tbuf, 0);

  SERIALIZE_STR_VAR_TO_BUF(buf, tbuf, strlen(tbuf));
dengyihao's avatar
dengyihao 已提交
624
  SERIALIZE_VAR_TO_BUF(buf, '_', char);
dengyihao's avatar
dengyihao 已提交
625 626 627 628 629
  if (hasJson) {
    SERIALIZE_STR_VAR_TO_BUF(buf, JSON_COLUMN, strlen(JSON_COLUMN));
  } else {
    SERIALIZE_STR_MEM_TO_BUF(buf, key, colName, key->nColName);
  }
dengyihao's avatar
dengyihao 已提交
630 631
  return buf - p;
}