indexTfile.c 33.3 KB
Newer Older
dengyihao's avatar
dengyihao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * 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 已提交
15
#include "indexTfile.h"
16
#include "index.h"
dengyihao's avatar
dengyihao 已提交
17 18 19 20
#include "indexComm.h"
#include "indexFst.h"
#include "indexFstCountingWriter.h"
#include "indexUtil.h"
dengyihao's avatar
dengyihao 已提交
21
#include "taosdef.h"
22
#include "taoserror.h"
dengyihao's avatar
dengyihao 已提交
23
#include "tcoding.h"
dengyihao's avatar
dengyihao 已提交
24
#include "tcompare.h"
dengyihao's avatar
dengyihao 已提交
25

dengyihao's avatar
dengyihao 已提交
26 27
const static uint64_t tfileMagicNumber = 0xdb4775248b80fb57ull;

dengyihao's avatar
dengyihao 已提交
28
typedef struct TFileFstIter {
dengyihao's avatar
dengyihao 已提交
29 30 31 32
  FStmBuilder* fb;
  FStmSt*      st;
  FAutoCtx*    ctx;
  TFileReader* rdr;
dengyihao's avatar
dengyihao 已提交
33 34
} TFileFstIter;

dengyihao's avatar
dengyihao 已提交
35 36
#define TF_TABLE_TATOAL_SIZE(sz) (sizeof(sz) + sz * sizeof(uint64_t))

dengyihao's avatar
dengyihao 已提交
37
static int  tfileStrCompare(const void* a, const void* b);
dengyihao's avatar
dengyihao 已提交
38 39
static int  tfileValueCompare(const void* a, const void* b, const void* param);
static void tfileSerialTableIdsToBuf(char* buf, SArray* tableIds);
dengyihao's avatar
dengyihao 已提交
40

dengyihao's avatar
dengyihao 已提交
41
static int tfileWriteHeader(TFileWriter* writer);
dengyihao's avatar
dengyihao 已提交
42
static int tfileWriteFstOffset(TFileWriter* tw, int32_t offset);
dengyihao's avatar
dengyihao 已提交
43
static int tfileWriteData(TFileWriter* write, TFileValue* tval);
dengyihao's avatar
dengyihao 已提交
44
static int tfileWriteFooter(TFileWriter* write);
dengyihao's avatar
dengyihao 已提交
45

dengyihao's avatar
dengyihao 已提交
46
// handle file corrupt later
dengyihao's avatar
dengyihao 已提交
47 48
static int tfileReaderLoadHeader(TFileReader* reader);
static int tfileReaderLoadFst(TFileReader* reader);
dengyihao's avatar
dengyihao 已提交
49
static int tfileReaderVerify(TFileReader* reader);
dengyihao's avatar
dengyihao 已提交
50
static int tfileReaderLoadTableIds(TFileReader* reader, int32_t offset, SArray* result);
dengyihao's avatar
dengyihao 已提交
51

dengyihao's avatar
dengyihao 已提交
52 53 54 55
static SArray* tfileGetFileList(const char* path);
static int     tfileRmExpireFile(SArray* result);
static void    tfileDestroyFileName(void* elem);
static int     tfileCompare(const void* a, const void* b);
dengyihao's avatar
dengyihao 已提交
56 57 58
static int     tfileParseFileName(const char* filename, uint64_t* suid, char* col, int64_t* version);
static void    tfileGenFileName(char* filename, uint64_t suid, const char* col, int64_t version);
static void    tfileGenFileFullName(char* fullname, const char* path, uint64_t suid, const char* col, int64_t version);
dengyihao's avatar
dengyihao 已提交
59 60 61
/*
 * search from  tfile
 */
dengyihao's avatar
dengyihao 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74
static int32_t tfSearchTerm(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchPrefix(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchSuffix(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchRegex(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchLessThan(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchLessEqual(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchGreaterThan(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchGreaterEqual(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchRange(void* reader, SIndexTerm* tem, SIdxTRslt* tr);

static int32_t tfSearchCompareFunc(void* reader, SIndexTerm* tem, SIdxTRslt* tr, RangeType ctype);

static int32_t tfSearchTerm_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
dengyihao's avatar
dengyihao 已提交
75
static int32_t tfSearchEqual_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
dengyihao's avatar
dengyihao 已提交
76 77 78 79 80 81 82 83 84 85 86 87
static int32_t tfSearchPrefix_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchSuffix_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchRegex_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchLessThan_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchLessEqual_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchGreaterThan_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchGreaterEqual_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);
static int32_t tfSearchRange_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr);

static int32_t tfSearchCompareFunc_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr, RangeType ctype);

static int32_t (*tfSearch[][QUERY_MAX])(void* reader, SIndexTerm* tem, SIdxTRslt* tr) = {
88 89
    {tfSearchTerm, tfSearchPrefix, tfSearchSuffix, tfSearchRegex, tfSearchLessThan, tfSearchLessEqual,
     tfSearchGreaterThan, tfSearchGreaterEqual, tfSearchRange},
dengyihao's avatar
dengyihao 已提交
90
    {tfSearchEqual_JSON, tfSearchPrefix_JSON, tfSearchSuffix_JSON, tfSearchRegex_JSON, tfSearchLessThan_JSON,
91
     tfSearchLessEqual_JSON, tfSearchGreaterThan_JSON, tfSearchGreaterEqual_JSON, tfSearchRange_JSON}};
dengyihao's avatar
dengyihao 已提交
92

dengyihao's avatar
dengyihao 已提交
93
TFileCache* tfileCacheCreate(const char* path) {
wafwerar's avatar
wafwerar 已提交
94
  TFileCache* tcache = taosMemoryCalloc(1, sizeof(TFileCache));
dengyihao's avatar
dengyihao 已提交
95 96 97
  if (tcache == NULL) {
    return NULL;
  }
98 99 100 101

  tcache->tableCache = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_ENTRY_LOCK);
  tcache->capacity = 64;

dengyihao's avatar
dengyihao 已提交
102
  SArray* files = tfileGetFileList(path);
dengyihao's avatar
dengyihao 已提交
103
  for (size_t i = 0; i < taosArrayGetSize(files); i++) {
dengyihao's avatar
dengyihao 已提交
104
    char* file = taosArrayGetP(files, i);
dengyihao's avatar
dengyihao 已提交
105

dengyihao's avatar
dengyihao 已提交
106
    WriterCtx* wc = writerCtxCreate(TFile, file, true, 1024 * 1024 * 64);
107
    if (wc == NULL) {
dengyihao's avatar
dengyihao 已提交
108
      indexError("failed to open index:%s", file);
109
      goto End;
dengyihao's avatar
dengyihao 已提交
110
    }
dengyihao's avatar
dengyihao 已提交
111

dengyihao's avatar
dengyihao 已提交
112
    TFileReader* reader = tfileReaderCreate(wc);
dengyihao's avatar
dengyihao 已提交
113 114 115 116
    if (reader == NULL) {
      indexInfo("skip invalid file: %s", file);
      continue;
    }
dengyihao's avatar
dengyihao 已提交
117
    TFileHeader* header = &reader->header;
dengyihao's avatar
dengyihao 已提交
118
    ICacheKey    key = {.suid = header->suid, .colName = header->colName, .nColName = (int32_t)strlen(header->colName)};
dengyihao's avatar
dengyihao 已提交
119

dengyihao's avatar
dengyihao 已提交
120
    char    buf[128] = {0};
dengyihao's avatar
dengyihao 已提交
121
    int32_t sz = idxSerialCacheKey(&key, buf);
dengyihao's avatar
dengyihao 已提交
122 123
    assert(sz < sizeof(buf));
    taosHashPut(tcache->tableCache, buf, sz, &reader, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
124
    tfileReaderRef(reader);
dengyihao's avatar
dengyihao 已提交
125
  }
dengyihao's avatar
dengyihao 已提交
126
  taosArrayDestroyEx(files, tfileDestroyFileName);
dengyihao's avatar
dengyihao 已提交
127
  return tcache;
dengyihao's avatar
dengyihao 已提交
128
End:
129
  tfileCacheDestroy(tcache);
dengyihao's avatar
dengyihao 已提交
130
  taosArrayDestroyEx(files, tfileDestroyFileName);
131
  return NULL;
dengyihao's avatar
dengyihao 已提交
132
}
dengyihao's avatar
dengyihao 已提交
133
void tfileCacheDestroy(TFileCache* tcache) {
dengyihao's avatar
dengyihao 已提交
134 135 136
  if (tcache == NULL) {
    return;
  }
137
  // free table cache
dengyihao's avatar
dengyihao 已提交
138
  TFileReader** reader = taosHashIterate(tcache->tableCache, NULL);
139
  while (reader) {
dengyihao's avatar
dengyihao 已提交
140
    TFileReader* p = *reader;
141 142
    indexInfo("drop table cache suid: %" PRIu64 ", colName: %s, colType: %d", p->header.suid, p->header.colName,
              p->header.colType);
dengyihao's avatar
dengyihao 已提交
143
    tfileReaderUnRef(p);
144 145 146
    reader = taosHashIterate(tcache->tableCache, reader);
  }
  taosHashCleanup(tcache->tableCache);
wafwerar's avatar
wafwerar 已提交
147
  taosMemoryFree(tcache);
dengyihao's avatar
dengyihao 已提交
148 149
}

dengyihao's avatar
dengyihao 已提交
150 151
TFileReader* tfileCacheGet(TFileCache* tcache, ICacheKey* key) {
  char    buf[128] = {0};
dengyihao's avatar
dengyihao 已提交
152
  int32_t sz = idxSerialCacheKey(key, buf);
dengyihao's avatar
dengyihao 已提交
153 154
  assert(sz < sizeof(buf));
  TFileReader** reader = taosHashGet(tcache->tableCache, buf, sz);
155
  if (reader == NULL || *reader == NULL) {
dengyihao's avatar
dengyihao 已提交
156 157
    return NULL;
  }
158
  tfileReaderRef(*reader);
dengyihao's avatar
dengyihao 已提交
159

160
  return *reader;
dengyihao's avatar
dengyihao 已提交
161
}
dengyihao's avatar
dengyihao 已提交
162 163
void tfileCachePut(TFileCache* tcache, ICacheKey* key, TFileReader* reader) {
  char    buf[128] = {0};
dengyihao's avatar
dengyihao 已提交
164
  int32_t sz = idxSerialCacheKey(key, buf);
dengyihao's avatar
dengyihao 已提交
165
  // remove last version index reader
dengyihao's avatar
dengyihao 已提交
166
  TFileReader** p = taosHashGet(tcache->tableCache, buf, sz);
167
  if (p != NULL && *p != NULL) {
dengyihao's avatar
dengyihao 已提交
168
    TFileReader* oldRdr = *p;
dengyihao's avatar
dengyihao 已提交
169
    taosHashRemove(tcache->tableCache, buf, sz);
dengyihao's avatar
dengyihao 已提交
170 171 172
    indexInfo("found %s, should remove file %s", buf, oldRdr->ctx->file.buf);
    oldRdr->remove = true;
    tfileReaderUnRef(oldRdr);
dengyihao's avatar
dengyihao 已提交
173
  }
dengyihao's avatar
dengyihao 已提交
174
  taosHashPut(tcache->tableCache, buf, sz, &reader, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
175
  tfileReaderRef(reader);
dengyihao's avatar
dengyihao 已提交
176
  return;
177
}
dengyihao's avatar
dengyihao 已提交
178
TFileReader* tfileReaderCreate(WriterCtx* ctx) {
wafwerar's avatar
wafwerar 已提交
179
  TFileReader* reader = taosMemoryCalloc(1, sizeof(TFileReader));
dengyihao's avatar
dengyihao 已提交
180 181 182
  if (reader == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
183
  reader->ctx = ctx;
dengyihao's avatar
dengyihao 已提交
184 185

  if (0 != tfileReaderVerify(reader)) {
dengyihao's avatar
dengyihao 已提交
186
    indexError("invalid tfile, suid: %" PRIu64 ", colName: %s", reader->header.suid, reader->header.colName);
dengyihao's avatar
dengyihao 已提交
187
    tfileReaderDestroy(reader);
dengyihao's avatar
dengyihao 已提交
188 189 190
    return NULL;
  }
  // T_REF_INC(reader);
dengyihao's avatar
dengyihao 已提交
191
  if (0 != tfileReaderLoadHeader(reader)) {
192 193
    indexError("failed to load index header, suid: %" PRIu64 ", colName: %s", reader->header.suid,
               reader->header.colName);
dengyihao's avatar
dengyihao 已提交
194
    tfileReaderDestroy(reader);
dengyihao's avatar
dengyihao 已提交
195 196 197 198
    return NULL;
  }

  if (0 != tfileReaderLoadFst(reader)) {
dengyihao's avatar
dengyihao 已提交
199 200
    indexError("failed to load index fst, suid: %" PRIu64 ", colName: %s, errno: %d", reader->header.suid,
               reader->header.colName, errno);
dengyihao's avatar
dengyihao 已提交
201 202 203
    tfileReaderDestroy(reader);
    return NULL;
  }
204
  reader->remove = false;
dengyihao's avatar
dengyihao 已提交
205

206
  return reader;
dengyihao's avatar
dengyihao 已提交
207
}
dengyihao's avatar
dengyihao 已提交
208
void tfileReaderDestroy(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
209 210 211
  if (reader == NULL) {
    return;
  }
212
  // T_REF_INC(reader);
dengyihao's avatar
dengyihao 已提交
213
  fstDestroy(reader->fst);
dengyihao's avatar
dengyihao 已提交
214 215 216 217 218
  if (reader->remove) {
    indexInfo("%s is removed", reader->ctx->file.buf);
  } else {
    indexInfo("%s is not removed", reader->ctx->file.buf);
  }
dengyihao's avatar
dengyihao 已提交
219
  writerCtxDestroy(reader->ctx, reader->remove);
dengyihao's avatar
dengyihao 已提交
220

wafwerar's avatar
wafwerar 已提交
221
  taosMemoryFree(reader);
dengyihao's avatar
dengyihao 已提交
222
}
dengyihao's avatar
dengyihao 已提交
223
static int32_t tfSearchTerm(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
224 225 226
  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
227

dengyihao's avatar
dengyihao 已提交
228 229 230 231 232 233 234 235
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  uint64_t offset;
  if (fstGet(((TFileReader*)reader)->fst, &key, &offset)) {
    int64_t et = taosGetTimestampUs();
    int64_t cost = et - st;
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, found table info in tindex, time cost: %" PRIu64 "us",
              tem->suid, tem->colName, tem->colVal, cost);
dengyihao's avatar
dengyihao 已提交
236

dengyihao's avatar
dengyihao 已提交
237
    ret = tfileReaderLoadTableIds((TFileReader*)reader, (int32_t)offset, tr->total);
dengyihao's avatar
dengyihao 已提交
238 239 240 241 242 243 244
    cost = taosGetTimestampUs() - et;
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, load all table info, time cost: %" PRIu64 "us", tem->suid,
              tem->colName, tem->colVal, cost);
  }
  fstSliceDestroy(&key);
  return 0;
}
dengyihao's avatar
dengyihao 已提交
245

dengyihao's avatar
dengyihao 已提交
246
static int32_t tfSearchPrefix(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
247 248 249 250 251
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;

  SArray* offsets = taosArrayInit(16, sizeof(uint64_t));

dengyihao's avatar
dengyihao 已提交
252 253 254 255 256
  FAutoCtx*    ctx = automCtxCreate((void*)p, AUTOMATION_PREFIX);
  FStmBuilder* sb = fstSearch(((TFileReader*)reader)->fst, ctx);
  FStmSt*      st = stmBuilderIntoStm(sb);
  FStmStRslt*  rt = NULL;
  while ((rt = stmStNextWith(st, NULL)) != NULL) {
dengyihao's avatar
dengyihao 已提交
257 258 259
    taosArrayPush(offsets, &(rt->out.out));
    swsResultDestroy(rt);
  }
dengyihao's avatar
dengyihao 已提交
260 261
  stmStDestroy(st);
  stmBuilderDestroy(sb);
dengyihao's avatar
dengyihao 已提交
262 263 264 265 266 267 268 269

  int32_t ret = 0;
  for (int i = 0; i < taosArrayGetSize(offsets); i++) {
    uint64_t offset = *(uint64_t*)taosArrayGet(offsets, i);
    ret = tfileReaderLoadTableIds((TFileReader*)reader, offset, tr->total);
    if (ret != 0) {
      indexError("failed to find target tablelist");
      return TSDB_CODE_TDB_FILE_CORRUPTED;
dengyihao's avatar
add UT  
dengyihao 已提交
270
    }
dengyihao's avatar
dengyihao 已提交
271
  }
dengyihao's avatar
dengyihao 已提交
272 273
  return 0;
}
dengyihao's avatar
dengyihao 已提交
274
static int32_t tfSearchSuffix(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
275 276 277 278 279 280 281 282
  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  fstSliceDestroy(&key);
  return 0;
}
dengyihao's avatar
dengyihao 已提交
283
static int32_t tfSearchRegex(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
284 285 286 287 288 289
  bool hasJson = INDEX_TYPE_CONTAIN_EXTERN_TYPE(tem->colType, TSDB_DATA_TYPE_JSON);

  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
  if (hasJson) {
dengyihao's avatar
dengyihao 已提交
290
    p = idxPackJsonData(tem);
dengyihao's avatar
dengyihao 已提交
291 292 293 294 295 296 297 298 299 300 301 302
    sz = strlen(p);
  }
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  /*impl later*/

  if (hasJson) {
    taosMemoryFree(p);
  }
  fstSliceDestroy(&key);
  return 0;
}
dengyihao's avatar
dengyihao 已提交
303

dengyihao's avatar
dengyihao 已提交
304
static int32_t tfSearchCompareFunc(void* reader, SIndexTerm* tem, SIdxTRslt* tr, RangeType type) {
305 306 307 308
  int                  ret = 0;
  char*                p = tem->colVal;
  int                  skip = 0;
  _cache_range_compare cmpFn = indexGetCompare(type);
dengyihao's avatar
dengyihao 已提交
309

dengyihao's avatar
dengyihao 已提交
310 311
  SArray* offsets = taosArrayInit(16, sizeof(uint64_t));

dengyihao's avatar
dengyihao 已提交
312 313
  FAutoCtx*    ctx = automCtxCreate((void*)p, AUTOMATION_ALWAYS);
  FStmBuilder* sb = fstSearch(((TFileReader*)reader)->fst, ctx);
dengyihao's avatar
dengyihao 已提交
314

dengyihao's avatar
dengyihao 已提交
315
  FstSlice h = fstSliceCreate((uint8_t*)p, skip);
dengyihao's avatar
dengyihao 已提交
316
  stmBuilderSetRange(sb, &h, type);
dengyihao's avatar
dengyihao 已提交
317 318
  fstSliceDestroy(&h);

dengyihao's avatar
dengyihao 已提交
319 320 321
  FStmSt*     st = stmBuilderIntoStm(sb);
  FStmStRslt* rt = NULL;
  while ((rt = stmStNextWith(st, NULL)) != NULL) {
322 323
    FstSlice* s = &rt->data;
    char*     ch = (char*)fstSliceData(s, NULL);
324 325 326 327 328 329
    // if (0 != strncmp(ch, tem->colName, tem->nColName)) {
    //  swsResultDestroy(rt);
    //  break;
    //}

    TExeCond cond = cmpFn(ch, p, tem->colType);
330 331 332 333 334 335 336
    if (MATCH == cond) {
      tfileReaderLoadTableIds((TFileReader*)reader, rt->out.out, tr->total);
    } else if (CONTINUE == cond) {
    } else if (BREAK == cond) {
      swsResultDestroy(rt);
      break;
    }
dengyihao's avatar
dengyihao 已提交
337 338
    swsResultDestroy(rt);
  }
dengyihao's avatar
dengyihao 已提交
339 340
  stmStDestroy(st);
  stmBuilderDestroy(sb);
dengyihao's avatar
dengyihao 已提交
341 342
  return TSDB_CODE_SUCCESS;
}
dengyihao's avatar
dengyihao 已提交
343
static int32_t tfSearchLessThan(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
344
  return tfSearchCompareFunc(reader, tem, tr, LT);
dengyihao's avatar
dengyihao 已提交
345
}
dengyihao's avatar
dengyihao 已提交
346
static int32_t tfSearchLessEqual(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
347
  return tfSearchCompareFunc(reader, tem, tr, LE);
dengyihao's avatar
dengyihao 已提交
348
}
dengyihao's avatar
dengyihao 已提交
349
static int32_t tfSearchGreaterThan(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
350
  return tfSearchCompareFunc(reader, tem, tr, GT);
dengyihao's avatar
dengyihao 已提交
351
}
dengyihao's avatar
dengyihao 已提交
352
static int32_t tfSearchGreaterEqual(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
353
  return tfSearchCompareFunc(reader, tem, tr, GE);
dengyihao's avatar
dengyihao 已提交
354
}
dengyihao's avatar
dengyihao 已提交
355
static int32_t tfSearchRange(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
356 357 358 359 360 361 362 363
  int      ret = 0;
  char*    p = tem->colVal;
  uint64_t sz = tem->nColVal;
  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  fstSliceDestroy(&key);
  return 0;
}
dengyihao's avatar
dengyihao 已提交
364
static int32_t tfSearchTerm_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
365
  int   ret = 0;
dengyihao's avatar
dengyihao 已提交
366
  char* p = idxPackJsonData(tem);
367 368 369 370 371 372 373 374 375 376 377 378 379
  int   sz = strlen(p);

  int64_t  st = taosGetTimestampUs();
  FstSlice key = fstSliceCreate(p, sz);
  uint64_t offset;
  if (fstGet(((TFileReader*)reader)->fst, &key, &offset)) {
    int64_t et = taosGetTimestampUs();
    int64_t cost = et - st;
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, found table info in tindex, time cost: %" PRIu64 "us",
              tem->suid, tem->colName, tem->colVal, cost);

    ret = tfileReaderLoadTableIds((TFileReader*)reader, offset, tr->total);
    cost = taosGetTimestampUs() - et;
dengyihao's avatar
dengyihao 已提交
380 381 382
    indexInfo("index: %" PRIu64 ", col: %s, colVal: %s, load all table info, offset: %" PRIu64
              ", size: %d, time cost: %" PRIu64 "us",
              tem->suid, tem->colName, tem->colVal, offset, (int)taosArrayGetSize(tr->total), cost);
383 384 385 386
  }
  fstSliceDestroy(&key);
  return 0;
}
dengyihao's avatar
dengyihao 已提交
387 388
static int32_t tfSearchEqual_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
  return tfSearchCompareFunc_JSON(reader, tem, tr, EQ);
389
}
dengyihao's avatar
dengyihao 已提交
390
static int32_t tfSearchPrefix_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
391
  return tfSearchCompareFunc_JSON(reader, tem, tr, CONTAINS);
392
}
dengyihao's avatar
dengyihao 已提交
393
static int32_t tfSearchSuffix_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
394 395 396
  // impl later
  return TSDB_CODE_SUCCESS;
}
dengyihao's avatar
dengyihao 已提交
397
static int32_t tfSearchRegex_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
398 399 400
  // impl later
  return TSDB_CODE_SUCCESS;
}
dengyihao's avatar
dengyihao 已提交
401
static int32_t tfSearchLessThan_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
402 403
  return tfSearchCompareFunc_JSON(reader, tem, tr, LT);
}
dengyihao's avatar
dengyihao 已提交
404
static int32_t tfSearchLessEqual_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
405 406
  return tfSearchCompareFunc_JSON(reader, tem, tr, LE);
}
dengyihao's avatar
dengyihao 已提交
407
static int32_t tfSearchGreaterThan_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
408 409
  return tfSearchCompareFunc_JSON(reader, tem, tr, GT);
}
dengyihao's avatar
dengyihao 已提交
410
static int32_t tfSearchGreaterEqual_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
411 412
  return tfSearchCompareFunc_JSON(reader, tem, tr, GE);
}
dengyihao's avatar
dengyihao 已提交
413
static int32_t tfSearchRange_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr) {
414 415 416 417
  // impl later
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
418
static int32_t tfSearchCompareFunc_JSON(void* reader, SIndexTerm* tem, SIdxTRslt* tr, RangeType ctype) {
419 420 421
  int ret = 0;
  int skip = 0;

dengyihao's avatar
dengyihao 已提交
422 423 424 425 426 427 428
  char* p = NULL;
  if (ctype == CONTAINS) {
    SIndexTerm tm = {.suid = tem->suid,
                     .operType = tem->operType,
                     .colType = tem->colType,
                     .colName = tem->colVal,
                     .nColName = tem->nColVal};
dengyihao's avatar
dengyihao 已提交
429
    p = idxPackJsonDataPrefixNoType(&tm, &skip);
dengyihao's avatar
dengyihao 已提交
430
  } else {
dengyihao's avatar
dengyihao 已提交
431
    p = idxPackJsonDataPrefix(tem, &skip);
dengyihao's avatar
dengyihao 已提交
432
  }
433 434 435 436

  _cache_range_compare cmpFn = indexGetCompare(ctype);

  SArray* offsets = taosArrayInit(16, sizeof(uint64_t));
dengyihao's avatar
dengyihao 已提交
437

dengyihao's avatar
dengyihao 已提交
438 439
  FAutoCtx*    ctx = automCtxCreate((void*)p, AUTOMATION_PREFIX);
  FStmBuilder* sb = fstSearch(((TFileReader*)reader)->fst, ctx);
440

dengyihao's avatar
dengyihao 已提交
441 442 443
  FStmSt*     st = stmBuilderIntoStm(sb);
  FStmStRslt* rt = NULL;
  while ((rt = stmStNextWith(st, NULL)) != NULL) {
444
    FstSlice* s = &rt->data;
445

dengyihao's avatar
dengyihao 已提交
446 447 448 449
    int32_t  sz = 0;
    char*    ch = (char*)fstSliceData(s, &sz);
    TExeCond cond = CONTINUE;
    if (ctype == CONTAINS) {
dengyihao's avatar
dengyihao 已提交
450
      if (0 == strncmp(ch, p, skip)) {
dengyihao's avatar
dengyihao 已提交
451 452 453
        cond = MATCH;
      }
    } else {
dengyihao's avatar
dengyihao 已提交
454
      if (0 != strncmp(ch, p, skip - 1)) {
dengyihao's avatar
dengyihao 已提交
455 456
        swsResultDestroy(rt);
        break;
dengyihao's avatar
dengyihao 已提交
457 458
      } else if (0 != strncmp(ch, p, skip)) {
        continue;
dengyihao's avatar
dengyihao 已提交
459 460
      }
      cond = cmpFn(ch + skip, tem->colVal, INDEX_TYPE_GET_TYPE(tem->colType));
461
    }
462 463 464 465 466 467 468 469 470
    if (MATCH == cond) {
      tfileReaderLoadTableIds((TFileReader*)reader, rt->out.out, tr->total);
    } else if (CONTINUE == cond) {
    } else if (BREAK == cond) {
      swsResultDestroy(rt);
      break;
    }
    swsResultDestroy(rt);
  }
dengyihao's avatar
dengyihao 已提交
471 472
  stmStDestroy(st);
  stmBuilderDestroy(sb);
473 474
  return TSDB_CODE_SUCCESS;
}
dengyihao's avatar
dengyihao 已提交
475
int tfileReaderSearch(TFileReader* reader, SIndexTermQuery* query, SIdxTRslt* tr) {
dengyihao's avatar
dengyihao 已提交
476 477
  SIndexTerm*     term = query->term;
  EIndexQueryType qtype = query->qType;
dengyihao's avatar
dengyihao 已提交
478
  int             ret = 0;
479
  if (INDEX_TYPE_CONTAIN_EXTERN_TYPE(term->colType, TSDB_DATA_TYPE_JSON)) {
dengyihao's avatar
dengyihao 已提交
480
    ret = tfSearch[1][qtype](reader, term, tr);
dengyihao's avatar
dengyihao 已提交
481
  } else {
dengyihao's avatar
dengyihao 已提交
482
    ret = tfSearch[0][qtype](reader, term, tr);
dengyihao's avatar
dengyihao 已提交
483
  }
484

dengyihao's avatar
dengyihao 已提交
485
  tfileReaderUnRef(reader);
dengyihao's avatar
dengyihao 已提交
486
  return ret;
dengyihao's avatar
dengyihao 已提交
487 488
}

dengyihao's avatar
dengyihao 已提交
489
TFileWriter* tfileWriterOpen(char* path, uint64_t suid, int64_t version, const char* colName, uint8_t colType) {
dengyihao's avatar
dengyihao 已提交
490
  char fullname[256] = {0};
dengyihao's avatar
dengyihao 已提交
491
  tfileGenFileFullName(fullname, path, suid, colName, version);
dengyihao's avatar
dengyihao 已提交
492
  // indexInfo("open write file name %s", fullname);
dengyihao's avatar
dengyihao 已提交
493
  WriterCtx* wcx = writerCtxCreate(TFile, fullname, false, 1024 * 1024 * 64);
dengyihao's avatar
dengyihao 已提交
494 495 496
  if (wcx == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
497 498 499 500 501 502 503 504 505

  TFileHeader tfh = {0};
  tfh.suid = suid;
  tfh.version = version;
  memcpy(tfh.colName, colName, strlen(colName));
  tfh.colType = colType;

  return tfileWriterCreate(wcx, &tfh);
}
dengyihao's avatar
dengyihao 已提交
506
TFileReader* tfileReaderOpen(char* path, uint64_t suid, int64_t version, const char* colName) {
dengyihao's avatar
dengyihao 已提交
507
  char fullname[256] = {0};
dengyihao's avatar
dengyihao 已提交
508 509
  tfileGenFileFullName(fullname, path, suid, colName, version);

dengyihao's avatar
dengyihao 已提交
510
  WriterCtx* wc = writerCtxCreate(TFile, fullname, true, 1024 * 1024 * 1024);
dengyihao's avatar
dengyihao 已提交
511
  if (wc == NULL) {
512 513
    terrno = TAOS_SYSTEM_ERROR(errno);
    indexError("failed to open readonly file: %s, reason: %s", fullname, terrstr());
dengyihao's avatar
dengyihao 已提交
514 515
    return NULL;
  }
516
  indexTrace("open read file name:%s, file size: %d", wc->file.buf, wc->file.size);
dengyihao's avatar
dengyihao 已提交
517

dengyihao's avatar
dengyihao 已提交
518
  TFileReader* reader = tfileReaderCreate(wc);
dengyihao's avatar
dengyihao 已提交
519 520
  return reader;
}
dengyihao's avatar
dengyihao 已提交
521
TFileWriter* tfileWriterCreate(WriterCtx* ctx, TFileHeader* header) {
wafwerar's avatar
wafwerar 已提交
522
  TFileWriter* tw = taosMemoryCalloc(1, sizeof(TFileWriter));
dengyihao's avatar
dengyihao 已提交
523
  if (tw == NULL) {
dengyihao's avatar
dengyihao 已提交
524
    indexError("index: %" PRIu64 " failed to alloc TFilerWriter", header->suid);
dengyihao's avatar
dengyihao 已提交
525 526
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
527 528
  tw->ctx = ctx;
  tw->header = *header;
dengyihao's avatar
dengyihao 已提交
529
  tfileWriteHeader(tw);
dengyihao's avatar
dengyihao 已提交
530 531
  return tw;
}
dengyihao's avatar
dengyihao 已提交
532

dengyihao's avatar
dengyihao 已提交
533
int tfileWriterPut(TFileWriter* tw, void* data, bool order) {
dengyihao's avatar
dengyihao 已提交
534
  // sort by coltype and write to tindex
dengyihao's avatar
dengyihao 已提交
535 536
  if (order == false) {
    __compar_fn_t fn;
dengyihao's avatar
dengyihao 已提交
537 538

    int8_t colType = tw->header.colType;
dengyihao's avatar
add UT  
dengyihao 已提交
539
    colType = INDEX_TYPE_GET_TYPE(colType);
dengyihao's avatar
dengyihao 已提交
540 541 542 543 544 545
    if (colType == TSDB_DATA_TYPE_BINARY || colType == TSDB_DATA_TYPE_NCHAR) {
      fn = tfileStrCompare;
    } else {
      fn = getComparFunc(colType, 0);
    }
    taosArraySortPWithExt((SArray*)(data), tfileValueCompare, &fn);
dengyihao's avatar
dengyihao 已提交
546
  }
dengyihao's avatar
dengyihao 已提交
547

dengyihao's avatar
dengyihao 已提交
548
  int32_t bufLimit = 64 * 4096, offset = 0;
wafwerar's avatar
wafwerar 已提交
549
  // char*   buf = taosMemoryCalloc(1, sizeof(char) * bufLimit);
dengyihao's avatar
dengyihao 已提交
550
  // char*   p = buf;
dengyihao's avatar
dengyihao 已提交
551
  int32_t sz = taosArrayGetSize((SArray*)data);
dengyihao's avatar
dengyihao 已提交
552 553 554 555 556
  int32_t fstOffset = tw->offset;

  // ugly code, refactor later
  for (size_t i = 0; i < sz; i++) {
    TFileValue* v = taosArrayGetP((SArray*)data, i);
dengyihao's avatar
dengyihao 已提交
557 558
    taosArraySort(v->tableId, idxUidCompare);
    taosArrayRemoveDuplicate(v->tableId, idxUidCompare, NULL);
dengyihao's avatar
dengyihao 已提交
559
    int32_t tbsz = taosArrayGetSize(v->tableId);
dengyihao's avatar
dengyihao 已提交
560
    fstOffset += TF_TABLE_TATOAL_SIZE(tbsz);
dengyihao's avatar
dengyihao 已提交
561 562 563
  }
  tfileWriteFstOffset(tw, fstOffset);

dengyihao's avatar
dengyihao 已提交
564 565 566 567 568 569 570
  for (size_t i = 0; i < sz; i++) {
    TFileValue* v = taosArrayGetP((SArray*)data, i);

    int32_t tbsz = taosArrayGetSize(v->tableId);
    // check buf has enough space or not
    int32_t ttsz = TF_TABLE_TATOAL_SIZE(tbsz);

wafwerar's avatar
wafwerar 已提交
571
    char* buf = taosMemoryCalloc(1, ttsz * sizeof(char));
dengyihao's avatar
dengyihao 已提交
572
    char* p = buf;
dengyihao's avatar
dengyihao 已提交
573
    tfileSerialTableIdsToBuf(p, v->tableId);
dengyihao's avatar
dengyihao 已提交
574
    tw->ctx->write(tw->ctx, buf, ttsz);
dengyihao's avatar
dengyihao 已提交
575 576
    v->offset = tw->offset;
    tw->offset += ttsz;
wafwerar's avatar
wafwerar 已提交
577
    taosMemoryFree(buf);
dengyihao's avatar
dengyihao 已提交
578
  }
dengyihao's avatar
dengyihao 已提交
579

dengyihao's avatar
dengyihao 已提交
580 581
  tw->fb = fstBuilderCreate(tw->ctx, 0);
  if (tw->fb == NULL) {
dengyihao's avatar
dengyihao 已提交
582
    tfileWriterClose(tw);
dengyihao's avatar
dengyihao 已提交
583 584
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
585 586

  // write data
dengyihao's avatar
dengyihao 已提交
587 588 589
  for (size_t i = 0; i < sz; i++) {
    // TODO, fst batch write later
    TFileValue* v = taosArrayGetP((SArray*)data, i);
dengyihao's avatar
dengyihao 已提交
590 591 592 593
    if (tfileWriteData(tw, v) != 0) {
      indexError("failed to write data: %s, offset: %d len: %d", v->colVal, v->offset,
                 (int)taosArrayGetSize(v->tableId));
    } else {
dengyihao's avatar
dengyihao 已提交
594 595
      // indexInfo("success to write data: %s, offset: %d len: %d", v->colVal, v->offset,
      //          (int)taosArrayGetSize(v->tableId));
dengyihao's avatar
dengyihao 已提交
596 597

      // indexInfo("tfile write data size: %d", tw->ctx->size(tw->ctx));
dengyihao's avatar
dengyihao 已提交
598 599
    }
  }
600

dengyihao's avatar
dengyihao 已提交
601 602 603
  fstBuilderFinish(tw->fb);
  fstBuilderDestroy(tw->fb);
  tw->fb = NULL;
dengyihao's avatar
dengyihao 已提交
604 605

  tfileWriteFooter(tw);
dengyihao's avatar
dengyihao 已提交
606 607
  return 0;
}
dengyihao's avatar
dengyihao 已提交
608
void tfileWriterClose(TFileWriter* tw) {
dengyihao's avatar
dengyihao 已提交
609 610 611
  if (tw == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
612
  writerCtxDestroy(tw->ctx, false);
wafwerar's avatar
wafwerar 已提交
613
  taosMemoryFree(tw);
dengyihao's avatar
dengyihao 已提交
614
}
dengyihao's avatar
dengyihao 已提交
615
void tfileWriterDestroy(TFileWriter* tw) {
dengyihao's avatar
dengyihao 已提交
616 617 618
  if (tw == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
619
  writerCtxDestroy(tw->ctx, false);
wafwerar's avatar
wafwerar 已提交
620
  taosMemoryFree(tw);
dengyihao's avatar
dengyihao 已提交
621
}
dengyihao's avatar
dengyihao 已提交
622

dengyihao's avatar
dengyihao 已提交
623
IndexTFile* idxTFileCreate(const char* path) {
dengyihao's avatar
dengyihao 已提交
624
  TFileCache* cache = tfileCacheCreate(path);
dengyihao's avatar
dengyihao 已提交
625 626 627
  if (cache == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
628

wafwerar's avatar
wafwerar 已提交
629
  IndexTFile* tfile = taosMemoryCalloc(1, sizeof(IndexTFile));
dengyihao's avatar
dengyihao 已提交
630 631 632 633
  if (tfile == NULL) {
    tfileCacheDestroy(cache);
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
634
  taosThreadMutexInit(&tfile->mtx, NULL);
dengyihao's avatar
dengyihao 已提交
635
  tfile->cache = cache;
dengyihao's avatar
dengyihao 已提交
636 637
  return tfile;
}
dengyihao's avatar
dengyihao 已提交
638
void idxTFileDestroy(IndexTFile* tfile) {
dengyihao's avatar
dengyihao 已提交
639 640 641
  if (tfile == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
642
  taosThreadMutexDestroy(&tfile->mtx);
dengyihao's avatar
dengyihao 已提交
643
  tfileCacheDestroy(tfile->cache);
wafwerar's avatar
wafwerar 已提交
644
  taosMemoryFree(tfile);
dengyihao's avatar
dengyihao 已提交
645
}
dengyihao's avatar
dengyihao 已提交
646

dengyihao's avatar
dengyihao 已提交
647
int idxTFileSearch(void* tfile, SIndexTermQuery* query, SIdxTRslt* result) {
dengyihao's avatar
dengyihao 已提交
648
  int ret = -1;
dengyihao's avatar
dengyihao 已提交
649 650 651
  if (tfile == NULL) {
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
652

dengyihao's avatar
add UT  
dengyihao 已提交
653
  int64_t     st = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
654
  IndexTFile* pTfile = tfile;
655

dengyihao's avatar
dengyihao 已提交
656 657
  SIndexTerm* term = query->term;
  ICacheKey key = {.suid = term->suid, .colType = term->colType, .colName = term->colName, .nColName = term->nColName};
dengyihao's avatar
dengyihao 已提交
658 659

  taosThreadMutexLock(&pTfile->mtx);
660
  TFileReader* reader = tfileCacheGet(pTfile->cache, &key);
dengyihao's avatar
dengyihao 已提交
661
  taosThreadMutexUnlock(&pTfile->mtx);
dengyihao's avatar
dengyihao 已提交
662 663 664
  if (reader == NULL) {
    return 0;
  }
dengyihao's avatar
add UT  
dengyihao 已提交
665 666
  int64_t cost = taosGetTimestampUs() - st;
  indexInfo("index tfile stage 1 cost: %" PRId64 "", cost);
dengyihao's avatar
dengyihao 已提交
667

dengyihao's avatar
dengyihao 已提交
668
  return tfileReaderSearch(reader, query, result);
dengyihao's avatar
dengyihao 已提交
669
}
dengyihao's avatar
dengyihao 已提交
670
int idxTFilePut(void* tfile, SIndexTerm* term, uint64_t uid) {
671 672
  // TFileWriterOpt wOpt = {.suid = term->suid, .colType = term->colType, .colName = term->colName, .nColName =
  // term->nColName, .version = 1};
dengyihao's avatar
dengyihao 已提交
673

674 675
  return 0;
}
dengyihao's avatar
dengyihao 已提交
676 677 678 679 680 681 682
static bool tfileIteratorNext(Iterate* iiter) {
  IterateValue* iv = &iiter->val;
  iterateValueDestroy(iv, false);

  char*    colVal = NULL;
  uint64_t offset = 0;

dengyihao's avatar
dengyihao 已提交
683 684
  TFileFstIter* tIter = iiter->iter;
  FStmStRslt*   rt = stmStNextWith(tIter->st, NULL);
dengyihao's avatar
dengyihao 已提交
685 686 687
  if (rt == NULL) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
688 689 690

  int32_t sz = 0;
  char*   ch = (char*)fstSliceData(&rt->data, &sz);
wafwerar's avatar
wafwerar 已提交
691
  colVal = taosMemoryCalloc(1, sz + 1);
dengyihao's avatar
dengyihao 已提交
692 693 694 695 696
  memcpy(colVal, ch, sz);

  offset = (uint64_t)(rt->out.out);
  swsResultDestroy(rt);
  // set up iterate value
dengyihao's avatar
dengyihao 已提交
697 698 699
  if (tfileReaderLoadTableIds(tIter->rdr, offset, iv->val) != 0) {
    return false;
  }
dengyihao's avatar
dengyihao 已提交
700

dengyihao's avatar
dengyihao 已提交
701
  iv->ver = 0;
702
  iv->type = ADD_VALUE;  // value in tfile always ADD_VALUE
dengyihao's avatar
dengyihao 已提交
703
  iv->colVal = colVal;
dengyihao's avatar
dengyihao 已提交
704
  return true;
dengyihao's avatar
dengyihao 已提交
705 706 707
  // std::string key(ch, sz);
}

708
static IterateValue* tifileIterateGetValue(Iterate* iter) { return &iter->val; }
dengyihao's avatar
dengyihao 已提交
709 710

static TFileFstIter* tfileFstIteratorCreate(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
711 712
  TFileFstIter* iter = taosMemoryCalloc(1, sizeof(TFileFstIter));
  if (iter == NULL) {
dengyihao's avatar
dengyihao 已提交
713 714
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
715

dengyihao's avatar
dengyihao 已提交
716 717
  iter->ctx = automCtxCreate(NULL, AUTOMATION_ALWAYS);
  iter->fb = fstSearch(reader->fst, iter->ctx);
dengyihao's avatar
dengyihao 已提交
718
  iter->st = stmBuilderIntoStm(iter->fb);
dengyihao's avatar
dengyihao 已提交
719 720
  iter->rdr = reader;
  return iter;
dengyihao's avatar
dengyihao 已提交
721 722 723
}

Iterate* tfileIteratorCreate(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
724 725 726
  if (reader == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
727

wafwerar's avatar
wafwerar 已提交
728
  Iterate* iter = taosMemoryCalloc(1, sizeof(Iterate));
dengyihao's avatar
dengyihao 已提交
729
  iter->iter = tfileFstIteratorCreate(reader);
730
  if (iter->iter == NULL) {
wafwerar's avatar
wafwerar 已提交
731
    taosMemoryFree(iter);
732 733
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
734 735
  iter->next = tfileIteratorNext;
  iter->getValue = tifileIterateGetValue;
dengyihao's avatar
dengyihao 已提交
736
  iter->val.val = taosArrayInit(1, sizeof(uint64_t));
737
  iter->val.colVal = NULL;
dengyihao's avatar
dengyihao 已提交
738 739 740
  return iter;
}
void tfileIteratorDestroy(Iterate* iter) {
dengyihao's avatar
dengyihao 已提交
741 742 743
  if (iter == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
744

dengyihao's avatar
dengyihao 已提交
745 746 747 748
  IterateValue* iv = &iter->val;
  iterateValueDestroy(iv, true);

  TFileFstIter* tIter = iter->iter;
dengyihao's avatar
dengyihao 已提交
749 750
  stmStDestroy(tIter->st);
  stmBuilderDestroy(tIter->fb);
dengyihao's avatar
dengyihao 已提交
751
  automCtxDestroy(tIter->ctx);
wafwerar's avatar
wafwerar 已提交
752
  taosMemoryFree(tIter);
dengyihao's avatar
dengyihao 已提交
753

wafwerar's avatar
wafwerar 已提交
754
  taosMemoryFree(iter);
dengyihao's avatar
dengyihao 已提交
755 756
}

dengyihao's avatar
dengyihao 已提交
757
TFileReader* tfileGetReaderByCol(IndexTFile* tf, uint64_t suid, char* colName) {
dengyihao's avatar
dengyihao 已提交
758 759 760
  if (tf == NULL) {
    return NULL;
  }
dengyihao's avatar
dengyihao 已提交
761 762 763 764 765 766 767
  TFileReader* rd = NULL;
  ICacheKey    key = {.suid = suid, .colType = TSDB_DATA_TYPE_BINARY, .colName = colName, .nColName = strlen(colName)};

  taosThreadMutexLock(&tf->mtx);
  rd = tfileCacheGet(tf->cache, &key);
  taosThreadMutexUnlock(&tf->mtx);
  return rd;
dengyihao's avatar
dengyihao 已提交
768
}
dengyihao's avatar
dengyihao 已提交
769

dengyihao's avatar
dengyihao 已提交
770 771
static int tfileStrCompare(const void* a, const void* b) {
  int ret = strcmp((char*)a, (char*)b);
dengyihao's avatar
dengyihao 已提交
772 773 774
  if (ret == 0) {
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
775 776 777
  return ret < 0 ? -1 : 1;
}

dengyihao's avatar
dengyihao 已提交
778 779 780 781 782 783 784 785
static int tfileValueCompare(const void* a, const void* b, const void* param) {
  __compar_fn_t fn = *(__compar_fn_t*)param;

  TFileValue* av = (TFileValue*)a;
  TFileValue* bv = (TFileValue*)b;

  return fn(av->colVal, bv->colVal);
}
dengyihao's avatar
dengyihao 已提交
786 787

TFileValue* tfileValueCreate(char* val) {
wafwerar's avatar
wafwerar 已提交
788
  TFileValue* tf = taosMemoryCalloc(1, sizeof(TFileValue));
dengyihao's avatar
dengyihao 已提交
789 790 791
  if (tf == NULL) {
    return NULL;
  }
792
  tf->colVal = tstrdup(val);
dengyihao's avatar
dengyihao 已提交
793 794 795 796
  tf->tableId = taosArrayInit(32, sizeof(uint64_t));
  return tf;
}
int tfileValuePush(TFileValue* tf, uint64_t val) {
dengyihao's avatar
dengyihao 已提交
797 798 799
  if (tf == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
800 801 802 803 804
  taosArrayPush(tf->tableId, &val);
  return 0;
}
void tfileValueDestroy(TFileValue* tf) {
  taosArrayDestroy(tf->tableId);
wafwerar's avatar
wafwerar 已提交
805 806
  taosMemoryFree(tf->colVal);
  taosMemoryFree(tf);
dengyihao's avatar
dengyihao 已提交
807
}
dengyihao's avatar
dengyihao 已提交
808 809 810 811 812
static void tfileSerialTableIdsToBuf(char* buf, SArray* ids) {
  int sz = taosArrayGetSize(ids);
  SERIALIZE_VAR_TO_BUF(buf, sz, int32_t);
  for (size_t i = 0; i < sz; i++) {
    uint64_t* v = taosArrayGet(ids, i);
dengyihao's avatar
dengyihao 已提交
813 814 815 816 817 818 819
    SERIALIZE_VAR_TO_BUF(buf, *v, uint64_t);
  }
}

static int tfileWriteFstOffset(TFileWriter* tw, int32_t offset) {
  int32_t fstOffset = offset + sizeof(tw->header.fstOffset);
  tw->header.fstOffset = fstOffset;
dengyihao's avatar
dengyihao 已提交
820

dengyihao's avatar
dengyihao 已提交
821 822 823
  if (sizeof(fstOffset) != tw->ctx->write(tw->ctx, (char*)&fstOffset, sizeof(fstOffset))) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
824
  indexInfo("tfile write fst offset: %d", tw->ctx->size(tw->ctx));
dengyihao's avatar
dengyihao 已提交
825
  tw->offset += sizeof(fstOffset);
dengyihao's avatar
dengyihao 已提交
826 827 828
  return 0;
}
static int tfileWriteHeader(TFileWriter* writer) {
dengyihao's avatar
dengyihao 已提交
829
  char buf[TFILE_HEADER_NO_FST] = {0};
dengyihao's avatar
dengyihao 已提交
830 831 832 833

  TFileHeader* header = &writer->header;
  memcpy(buf, (char*)header, sizeof(buf));

dengyihao's avatar
dengyihao 已提交
834
  indexInfo("tfile pre write header size: %d", writer->ctx->size(writer->ctx));
dengyihao's avatar
dengyihao 已提交
835
  int nwrite = writer->ctx->write(writer->ctx, buf, sizeof(buf));
dengyihao's avatar
dengyihao 已提交
836 837 838
  if (sizeof(buf) != nwrite) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
839 840

  indexInfo("tfile after write header size: %d", writer->ctx->size(writer->ctx));
dengyihao's avatar
dengyihao 已提交
841 842 843 844 845 846
  writer->offset = nwrite;
  return 0;
}
static int tfileWriteData(TFileWriter* write, TFileValue* tval) {
  TFileHeader* header = &write->header;
  uint8_t      colType = header->colType;
dengyihao's avatar
add UT  
dengyihao 已提交
847 848

  colType = INDEX_TYPE_GET_TYPE(colType);
849 850
  FstSlice key = fstSliceCreate((uint8_t*)(tval->colVal), (size_t)strlen(tval->colVal));
  if (fstBuilderInsert(write->fb, key, tval->offset)) {
dengyihao's avatar
dengyihao 已提交
851
    fstSliceDestroy(&key);
852
    return 0;
dengyihao's avatar
dengyihao 已提交
853
  }
854 855 856 857 858 859 860 861 862 863 864 865 866
  return -1;

  // if (colType == TSDB_DATA_TYPE_BINARY || colType == TSDB_DATA_TYPE_NCHAR) {
  //  FstSlice key = fstSliceCreate((uint8_t*)(tval->colVal), (size_t)strlen(tval->colVal));
  //  if (fstBuilderInsert(write->fb, key, tval->offset)) {
  //    fstSliceDestroy(&key);
  //    return 0;
  //  }
  //  fstSliceDestroy(&key);
  //  return -1;
  //} else {
  //  // handle other type later
  //}
dengyihao's avatar
dengyihao 已提交
867
}
dengyihao's avatar
dengyihao 已提交
868 869 870 871
static int tfileWriteFooter(TFileWriter* write) {
  char  buf[sizeof(tfileMagicNumber) + 1] = {0};
  void* pBuf = (void*)buf;
  taosEncodeFixedU64((void**)(void*)&pBuf, tfileMagicNumber);
dengyihao's avatar
dengyihao 已提交
872
  int nwrite = write->ctx->write(write->ctx, buf, (int32_t)strlen(buf));
dengyihao's avatar
dengyihao 已提交
873 874

  indexInfo("tfile write footer size: %d", write->ctx->size(write->ctx));
dengyihao's avatar
dengyihao 已提交
875 876 877
  assert(nwrite == sizeof(tfileMagicNumber));
  return nwrite;
}
dengyihao's avatar
dengyihao 已提交
878
static int tfileReaderLoadHeader(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
879
  // TODO simple tfile header later
dengyihao's avatar
dengyihao 已提交
880
  char buf[TFILE_HEADER_SIZE] = {0};
dengyihao's avatar
dengyihao 已提交
881

dengyihao's avatar
dengyihao 已提交
882
  int64_t nread = reader->ctx->readFrom(reader->ctx, buf, sizeof(buf), 0);
dengyihao's avatar
dengyihao 已提交
883
  if (nread == -1) {
dengyihao's avatar
dengyihao 已提交
884 885
    indexError("actual Read: %d, to read: %d, errno: %d, filename: %s", (int)(nread), (int)sizeof(buf), errno,
               reader->ctx->file.buf);
dengyihao's avatar
dengyihao 已提交
886
  } else {
dengyihao's avatar
dengyihao 已提交
887
    indexInfo("actual Read: %d, to read: %d, filename: %s", (int)(nread), (int)sizeof(buf), reader->ctx->file.buf);
dengyihao's avatar
dengyihao 已提交
888 889
  }
  // assert(nread == sizeof(buf));
dengyihao's avatar
dengyihao 已提交
890
  memcpy(&reader->header, buf, sizeof(buf));
dengyihao's avatar
dengyihao 已提交
891

dengyihao's avatar
dengyihao 已提交
892 893
  return 0;
}
dengyihao's avatar
dengyihao 已提交
894
static int tfileReaderLoadFst(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
895 896
  WriterCtx* ctx = reader->ctx;
  int        size = ctx->size(ctx);
dengyihao's avatar
dengyihao 已提交
897

dengyihao's avatar
dengyihao 已提交
898 899
  // current load fst into memory, refactor it later
  int   fstSize = size - reader->header.fstOffset - sizeof(tfileMagicNumber);
wafwerar's avatar
wafwerar 已提交
900
  char* buf = taosMemoryCalloc(1, fstSize);
dengyihao's avatar
dengyihao 已提交
901 902 903
  if (buf == NULL) {
    return -1;
  }
dengyihao's avatar
dengyihao 已提交
904

dengyihao's avatar
dengyihao 已提交
905
  int64_t ts = taosGetTimestampUs();
dengyihao's avatar
dengyihao 已提交
906
  int32_t nread = ctx->readFrom(ctx, buf, fstSize, reader->header.fstOffset);
dengyihao's avatar
dengyihao 已提交
907
  int64_t cost = taosGetTimestampUs() - ts;
dengyihao's avatar
dengyihao 已提交
908
  indexInfo("nread = %d, and fst offset=%d, fst size: %d, filename: %s, file size: %d, time cost: %" PRId64 "us", nread,
dengyihao's avatar
dengyihao 已提交
909
            reader->header.fstOffset, fstSize, ctx->file.buf, ctx->file.size, cost);
dengyihao's avatar
dengyihao 已提交
910
  // we assuse fst size less than FST_MAX_SIZE
dengyihao's avatar
dengyihao 已提交
911
  assert(nread > 0 && nread <= fstSize);
dengyihao's avatar
dengyihao 已提交
912 913 914

  FstSlice st = fstSliceCreate((uint8_t*)buf, nread);
  reader->fst = fstCreate(&st);
wafwerar's avatar
wafwerar 已提交
915
  taosMemoryFree(buf);
dengyihao's avatar
dengyihao 已提交
916 917
  fstSliceDestroy(&st);

dengyihao's avatar
dengyihao 已提交
918
  return reader->fst != NULL ? 0 : -1;
dengyihao's avatar
dengyihao 已提交
919
}
dengyihao's avatar
dengyihao 已提交
920
static int tfileReaderLoadTableIds(TFileReader* reader, int32_t offset, SArray* result) {
dengyihao's avatar
dengyihao 已提交
921
  // TODO(yihao): opt later
dengyihao's avatar
dengyihao 已提交
922
  WriterCtx* ctx = reader->ctx;
923
  // add block cache
dengyihao's avatar
dengyihao 已提交
924
  char    block[4096] = {0};
925
  int32_t nread = ctx->readFrom(ctx, block, sizeof(block), offset);
dengyihao's avatar
dengyihao 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939
  assert(nread >= sizeof(uint32_t));

  char*   p = block;
  int32_t nid = *(int32_t*)p;
  p += sizeof(nid);

  while (nid > 0) {
    int32_t left = block + sizeof(block) - p;
    if (left >= sizeof(uint64_t)) {
      taosArrayPush(result, (uint64_t*)p);
      p += sizeof(uint64_t);
    } else {
      char buf[sizeof(uint64_t)] = {0};
      memcpy(buf, p, left);
dengyihao's avatar
dengyihao 已提交
940

dengyihao's avatar
dengyihao 已提交
941 942 943 944
      memset(block, 0, sizeof(block));
      offset += sizeof(block);
      nread = ctx->readFrom(ctx, block, sizeof(block), offset);
      memcpy(buf + left, block, sizeof(uint64_t) - left);
dengyihao's avatar
dengyihao 已提交
945

dengyihao's avatar
dengyihao 已提交
946 947 948 949
      taosArrayPush(result, (uint64_t*)buf);
      p = block + sizeof(uint64_t) - left;
    }
    nid -= 1;
dengyihao's avatar
dengyihao 已提交
950
  }
dengyihao's avatar
dengyihao 已提交
951 952
  return 0;
}
dengyihao's avatar
dengyihao 已提交
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
static int tfileReaderVerify(TFileReader* reader) {
  // just validate header and Footer, file corrupted also shuild be verified later
  WriterCtx* ctx = reader->ctx;

  uint64_t tMagicNumber = 0;

  char buf[sizeof(tMagicNumber) + 1] = {0};
  int  size = ctx->size(ctx);

  if (size < sizeof(tMagicNumber) || size <= sizeof(reader->header)) {
    return -1;
  } else if (ctx->readFrom(ctx, buf, sizeof(tMagicNumber), size - sizeof(tMagicNumber)) != sizeof(tMagicNumber)) {
    return -1;
  }

  taosDecodeFixedU64(buf, &tMagicNumber);
  return tMagicNumber == tfileMagicNumber ? 0 : -1;
}

dengyihao's avatar
dengyihao 已提交
972
void tfileReaderRef(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
973 974 975
  if (reader == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
976 977 978 979
  int ref = T_REF_INC(reader);
  UNUSED(ref);
}

dengyihao's avatar
dengyihao 已提交
980
void tfileReaderUnRef(TFileReader* reader) {
dengyihao's avatar
dengyihao 已提交
981 982 983
  if (reader == NULL) {
    return;
  }
dengyihao's avatar
dengyihao 已提交
984
  int ref = T_REF_DEC(reader);
985
  if (ref == 0) {
dengyihao's avatar
dengyihao 已提交
986
    // do nothing
987 988
    tfileReaderDestroy(reader);
  }
dengyihao's avatar
dengyihao 已提交
989
}
dengyihao's avatar
dengyihao 已提交
990

dengyihao's avatar
dengyihao 已提交
991
static SArray* tfileGetFileList(const char* path) {
dengyihao's avatar
dengyihao 已提交
992 993
  char     buf[128] = {0};
  uint64_t suid;
dengyihao's avatar
dengyihao 已提交
994
  int64_t  version;
dengyihao's avatar
dengyihao 已提交
995
  SArray*  files = taosArrayInit(4, sizeof(void*));
dengyihao's avatar
dengyihao 已提交
996

wafwerar's avatar
wafwerar 已提交
997 998
  TdDirPtr pDir = taosOpenDir(path);
  if (NULL == pDir) {
dengyihao's avatar
dengyihao 已提交
999 1000
    return NULL;
  }
wafwerar's avatar
wafwerar 已提交
1001 1002 1003
  TdDirEntryPtr pDirEntry;
  while ((pDirEntry = taosReadDir(pDir)) != NULL) {
    char* file = taosGetDirEntryName(pDirEntry);
dengyihao's avatar
dengyihao 已提交
1004 1005 1006
    if (0 != tfileParseFileName(file, &suid, buf, &version)) {
      continue;
    }
dengyihao's avatar
dengyihao 已提交
1007 1008

    size_t len = strlen(path) + 1 + strlen(file) + 1;
wafwerar's avatar
wafwerar 已提交
1009
    char*  buf = taosMemoryCalloc(1, len);
dengyihao's avatar
dengyihao 已提交
1010
    sprintf(buf, "%s/%s", path, file);
dengyihao's avatar
dengyihao 已提交
1011
    taosArrayPush(files, &buf);
dengyihao's avatar
dengyihao 已提交
1012
  }
wafwerar's avatar
wafwerar 已提交
1013
  taosCloseDir(&pDir);
dengyihao's avatar
dengyihao 已提交
1014 1015 1016 1017 1018

  taosArraySort(files, tfileCompare);
  tfileRmExpireFile(files);

  return files;
dengyihao's avatar
dengyihao 已提交
1019
}
dengyihao's avatar
dengyihao 已提交
1020 1021 1022 1023
static int tfileRmExpireFile(SArray* result) {
  // TODO(yihao): remove expire tindex after restart
  return 0;
}
dengyihao's avatar
dengyihao 已提交
1024 1025
static void tfileDestroyFileName(void* elem) {
  char* p = *(char**)elem;
wafwerar's avatar
wafwerar 已提交
1026
  taosMemoryFree(p);
dengyihao's avatar
dengyihao 已提交
1027 1028
}
static int tfileCompare(const void* a, const void* b) {
dengyihao's avatar
dengyihao 已提交
1029 1030 1031
  const char* as = *(char**)a;
  const char* bs = *(char**)b;
  return strcmp(as, bs);
dengyihao's avatar
dengyihao 已提交
1032
}
dengyihao's avatar
dengyihao 已提交
1033

dengyihao's avatar
dengyihao 已提交
1034 1035
static int tfileParseFileName(const char* filename, uint64_t* suid, char* col, int64_t* version) {
  if (3 == sscanf(filename, "%" PRIu64 "-%[^-]-%" PRId64 ".tindex", suid, col, version)) {
dengyihao's avatar
dengyihao 已提交
1036 1037 1038 1039 1040
    // read suid & colid & version  success
    return 0;
  }
  return -1;
}
dengyihao's avatar
dengyihao 已提交
1041
// tfile name suid-colId-version.tindex
dengyihao's avatar
dengyihao 已提交
1042 1043
static void tfileGenFileName(char* filename, uint64_t suid, const char* col, int64_t version) {
  sprintf(filename, "%" PRIu64 "-%s-%" PRId64 ".tindex", suid, col, version);
dengyihao's avatar
dengyihao 已提交
1044 1045
  return;
}
dengyihao's avatar
dengyihao 已提交
1046
static void tfileGenFileFullName(char* fullname, const char* path, uint64_t suid, const char* col, int64_t version) {
dengyihao's avatar
dengyihao 已提交
1047 1048 1049 1050
  char filename[128] = {0};
  tfileGenFileName(filename, suid, col, version);
  sprintf(fullname, "%s/%s", path, filename);
}