taosdemo.cs 36.1 KB
Newer Older
sangshuduo's avatar
sangshuduo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * 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/>.
 */

using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Collections;
sangshuduo's avatar
sangshuduo 已提交
21 22
using System.Threading;
using System.Diagnostics;
sangshuduo's avatar
sangshuduo 已提交
23 24 25 26 27 28

namespace TDengineDriver
{
    class TDengineTest
    {
        //connect parameters
29 30 31 32
        private string host = "127.0.0.1";
        private string configDir = "C:/TDengine/cfg";
        private string user = "root";
        private string password = "taosdata";
sangshuduo's avatar
sangshuduo 已提交
33 34 35
        private short port = 0;

        //sql parameters
sangshuduo's avatar
sangshuduo 已提交
36
        private string dbName = "db";
37
        private string stablePrefix = "st";
sangshuduo's avatar
sangshuduo 已提交
38
        private string tablePrefix = "t";
sangshuduo's avatar
sangshuduo 已提交
39 40

        private bool isInsertOnly = false;
41 42
        private string query = "NONE";
        private short queryMode = 1;
sangshuduo's avatar
sangshuduo 已提交
43

44
        private long recordsPerTable = 1;
sangshuduo's avatar
sangshuduo 已提交
45 46
        private int recordsPerRequest = 1;
        private int colsPerRecord = 3;
sangshuduo's avatar
sangshuduo 已提交
47
        private long batchRows = 1000;
48 49
        private long numOfTables = 1;
        private short replica = 1;
sangshuduo's avatar
sangshuduo 已提交
50 51

        private IntPtr conn = IntPtr.Zero;
sangshuduo's avatar
sangshuduo 已提交
52
        //        private long rowsInserted = 0;
sangshuduo's avatar
sangshuduo 已提交
53 54
        private bool useStable = false;
        private short methodOfDelete = 0;
sangshuduo's avatar
sangshuduo 已提交
55
        private long numOfThreads = 1;
56
        private short rateOfOutorder = 10;
sangshuduo's avatar
sangshuduo 已提交
57 58
        private bool order = true;
        private bool skipReadKey = false;
sangshuduo's avatar
sangshuduo 已提交
59
        private bool verbose = false;
60
        private bool debug = false;
sangshuduo's avatar
sangshuduo 已提交
61

sangshuduo's avatar
sangshuduo 已提交
62

63 64 65
        static void HelpPrint(string arg, string desc)
        {
            string indent = "        ";
66
            Console.WriteLine("{0}{1}", indent, arg.PadRight(25) + desc);
67 68
        }

sangshuduo's avatar
sangshuduo 已提交
69 70 71 72 73 74 75 76
        static void PrintHelp(String[] argv)
        {
            for (int i = 0; i < argv.Length; ++i)
            {
                if ("--help" == argv[i])
                {
                    Console.WriteLine("Usage: mono taosdemo.exe [OPTION...]");
                    Console.WriteLine("");
77
                    HelpPrint("--help", "Show usage.");
78
                    Console.WriteLine("");
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

                    HelpPrint("-h <hostname>", "host, The host to connect to TDengine. Default is localhost.");
                    HelpPrint("-p <port>", "port, The TCP/IP port number to use for the connection. Default is 0.");
                    HelpPrint("-u <username>", "user, The user name to use when connecting to the server. Default is 'root'.");
                    HelpPrint("-P <password>", "password, The password to use when connecting to the server. Default is 'taosdata'.");
                    HelpPrint("-d <dbname>", "database, Destination database. Default is 'test'.");
                    HelpPrint("-a <replications>", "replica, Set the replica parameters of the database, Default 1, min: 1, max: 5.");
                    HelpPrint("-m <table prefix>", "table_prefix, Table prefix name. Default is 't'.");
                    HelpPrint("-M", "stable, Use super table.");
                    HelpPrint("-s <stable prefix>", "stable_prefix, STable prefix name. Default is 'st'");
                    HelpPrint("-Q <DEFAULT | command>", "query, Execute query command. set 'DEFAULT' means select * from each table");
                    /* NOT SUPPORT SO FAR
                    HelpPrint("-o", "outputfile, Direct output to the named file. Default is './output.txt'.");
                    HelpPrint("-q", "query_mode, Query mode--0: SYNC, 1: ASYNC. Default is SYNC.");
                    HelpPrint("-b", "type_of_cols, data_type of columns: 'INT', 'TINYINT', 'SMALLINT', 'BIGINT', 'FLOAT', 'DOUBLE', 'BINARY'. Default is 'INT'.");
                    HelpPrint("-w", "length_of_binary, The length of data_type 'BINARY'. Only applicable when type of cols is 'BINARY'. Default is 8");
                    HelpPrint("-l", "num_of_cols_per_record, The number of columns per record. Default is 3.");
96
                    */
97 98 99 100 101 102 103 104 105 106 107 108
                    HelpPrint("-T <number>", "num_of_threads, The number of threads. Default is 10.");
                    HelpPrint("-r <number>", "num_of_records_per_req, The number of records per request. Default is 1000.");
                    HelpPrint("-t <number>", "num_of_tables, The number of tables. Default is 1.");
                    HelpPrint("-n <number>", "num_of_records_per_table, The number of records per table. Default is 1.");
                    HelpPrint("-c <path>", "config_directory, Configuration directory. Default is '/etc/taos/'.");
                    HelpPrint("-x", "flag, Insert only flag.");
                    HelpPrint("-O", "order, Insert mode--0: In order, 1: Out of order. Default is in order.");
                    HelpPrint("-R <number>", "rate, Out of order data's rate--if order=1 Default 10, min: 0, max: 50.");
                    HelpPrint("-D <number>", "Delete data methods 0: don't delete, 1: delete by table, 2: delete by stable, 3: delete by database.");
                    HelpPrint("-v", "Print verbose output");
                    HelpPrint("-g", "Print debug output");
                    HelpPrint("-y", "Skip read key for continous test, default is not skip");
sangshuduo's avatar
sangshuduo 已提交
109 110 111 112 113 114 115 116 117 118 119 120

                    System.Environment.Exit(0);
                }
            }
        }

        public void ReadArgument(String[] argv)
        {
            host = this.GetArgumentAsString(argv, "-h", "127.0.0.1");
            port = (short)this.GetArgumentAsLong(argv, "-p", 0, 65535, 6030);
            user = this.GetArgumentAsString(argv, "-u", "root");
            password = this.GetArgumentAsString(argv, "-P", "taosdata");
121
            dbName = this.GetArgumentAsString(argv, "-d", "taosdemo_cs");
122
            stablePrefix = this.GetArgumentAsString(argv, "-s", "st");
sangshuduo's avatar
sangshuduo 已提交
123
            tablePrefix = this.GetArgumentAsString(argv, "-m", "t");
124 125 126
            isInsertOnly = this.GetArgumentAsFlag(argv, "-x", true);
            query = this.GetArgumentAsString(argv, "-Q", "NONE");
            queryMode = (short)this.GetArgumentAsLong(argv, "-q", 0, 1, 0);
127
            numOfTables = this.GetArgumentAsLong(argv, "-t", 1, 1000000000, 1);
sangshuduo's avatar
sangshuduo 已提交
128
            batchRows = this.GetArgumentAsLong(argv, "-r", 1, 10000, 1000);
129
            recordsPerTable = this.GetArgumentAsLong(argv, "-n", 1, 100000000000, 1);
sangshuduo's avatar
sangshuduo 已提交
130 131 132
            recordsPerRequest = (int)this.GetArgumentAsLong(argv, "-r", 1, 10000, 1);
            colsPerRecord = (int)this.GetArgumentAsLong(argv, "-l", 1, 1024, 3);
            configDir = this.GetArgumentAsString(argv, "-c", "C:/TDengine/cfg");
133
            useStable = this.GetArgumentAsFlag(argv, "-M", true);
sangshuduo's avatar
sangshuduo 已提交
134

135
            replica = (short)this.GetArgumentAsLong(argv, "-a", 1, 5, 1);
sangshuduo's avatar
sangshuduo 已提交
136 137
            methodOfDelete = (short)this.GetArgumentAsLong(argv, "-D", 0, 3, 0);
            numOfThreads = (short)this.GetArgumentAsLong(argv, "-T", 1, 10000, 1);
138
            order = this.GetArgumentAsFlag(argv, "-O", false);
139
            rateOfOutorder = (short)this.GetArgumentAsLong(argv, "-R", 0, 50, 10);
sangshuduo's avatar
sangshuduo 已提交
140

141 142 143
            skipReadKey = this.GetArgumentAsFlag(argv, "-y", true);
            verbose = this.GetArgumentAsFlag(argv, "-v", true);
            debug = this.GetArgumentAsFlag(argv, "-g", true);
sangshuduo's avatar
sangshuduo 已提交
144

145 146 147 148 149 150 151 152 153 154 155 156 157
            VerbosePrint("###################################################################\n");
            VerbosePrintFormat("# Server IP:                         {0}\n", host);
            VerbosePrintFormat("# User:                              {0}\n", user);
            VerbosePrintFormat("# Password:                          {0}\n", password);
            VerbosePrintFormat("# Number of Columns per record:      {0}\n", colsPerRecord);
            VerbosePrintFormat("# Number of Threads:                 {0}\n", numOfThreads);
            VerbosePrintFormat("# Number of Tables:                  {0}\n", numOfTables);
            VerbosePrintFormat("# Number of records per Table:       {0}\n", recordsPerTable);
            VerbosePrintFormat("# Records/Request:                   {0}\n", recordsPerRequest);
            VerbosePrintFormat("# Database name:                     {0}\n", dbName);
            VerbosePrintFormat("# Replica:                           {0}\n", replica);
            VerbosePrintFormat("# Use STable:                        {0}\n", useStable);
            VerbosePrintFormat("# Table prefix:                      {0}\n", tablePrefix);
158 159
            if (useStable == true)
            {
160
                VerbosePrintFormat("# STable prefix:                     {0}\n", stablePrefix);
161
            }
162 163 164 165 166 167 168 169
            VerbosePrintFormat("# Data order:                        {0}\n", order);
            VerbosePrintFormat("# Data out of order rate:            {0}\n", rateOfOutorder);
            VerbosePrintFormat("# Delete method:                     {0}\n", methodOfDelete);
            VerbosePrintFormat("# Query command:                     {0}\n", query);
            VerbosePrintFormat("# Query Mode:                        {0}\n", queryMode);
            VerbosePrintFormat("# Insert Only:                       {0}\n", isInsertOnly);
            VerbosePrintFormat("# Verbose output                     {0}\n", verbose);
            VerbosePrintFormat("# Test time:                         {0}\n", DateTime.Now.ToString("h:mm:ss tt"));
sangshuduo's avatar
sangshuduo 已提交
170

171
            VerbosePrint("###################################################################\n");
sangshuduo's avatar
sangshuduo 已提交
172 173 174 175 176 177 178 179

            if (skipReadKey == false)
            {
                Console.Write("Press any key to continue..\n");
                Console.ReadKey();
            }
        }

180
        public bool GetArgumentAsFlag(String[] argv, String argName, bool defaultValue)
sangshuduo's avatar
sangshuduo 已提交
181 182 183 184 185 186
        {
            int argc = argv.Length;
            for (int i = 0; i < argc; ++i)
            {
                if (argName == argv[i])
                {
187
                    return defaultValue;
sangshuduo's avatar
sangshuduo 已提交
188
                }
sangshuduo's avatar
sangshuduo 已提交
189
            }
190
            return !defaultValue;
sangshuduo's avatar
sangshuduo 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        }

        public long GetArgumentAsLong(String[] argv, String argName, int minVal, long maxVal, int defaultValue)
        {
            int argc = argv.Length;
            for (int i = 0; i < argc; ++i)
            {
                if (argName != argv[i])
                {
                    continue;
                }
                if (i < argc - 1)
                {
                    String tmp = argv[i + 1];
                    if (tmp[0] == '-')
                    {
207
                        Console.WriteLine("option {0:G} requires an argument", argName);
208
                        ExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
209 210 211 212 213
                    }

                    long tmpVal = Convert.ToInt64(tmp);
                    if (tmpVal < minVal || tmpVal > maxVal)
                    {
214
                        Console.WriteLine("option {0:G} value should in range [{1:G}, {2:G}]", argName, minVal, maxVal);
215
                        ExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
                    }

                    return tmpVal;
                }
            }

            return defaultValue;
        }

        public String GetArgumentAsString(String[] argv, String argName, String defaultValue)
        {
            int argc = argv.Length;
            for (int i = 0; i < argc; ++i)
            {
                if (argName != argv[i])
                {
                    continue;
                }
                if (i < argc - 1)
                {
                    String tmp = argv[i + 1];
                    if (tmp[0] == '-')
                    {
239
                        Console.WriteLine("option {0:G} requires an argument", argName);
240
                        ExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
241 242 243 244 245 246 247 248
                    }
                    return tmp;
                }
            }

            return defaultValue;
        }

249
        static void CleanAndExitProgram(int ret)
sangshuduo's avatar
sangshuduo 已提交
250 251
        {
            TDengine.Cleanup();
252
            System.Environment.Exit(ret);
sangshuduo's avatar
sangshuduo 已提交
253 254
        }

255
        static void ExitProgram(int ret)
256
        {
257
            System.Environment.Exit(ret);
258 259
        }

260
        private void VerbosePrintFormat(string format, params object[] parameters)
sangshuduo's avatar
sangshuduo 已提交
261 262 263 264 265 266 267
        {
            if (verbose == true)
            {
                Console.Write(format, parameters);
            }
        }

268
        private void VerbosePrint(string str)
sangshuduo's avatar
sangshuduo 已提交
269 270 271 272 273 274 275
        {
            if (verbose == true)
            {
                Console.Write(str);
            }
        }

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        private void DebugPrintFormat(string format, params object[] parameters)
        {
            if (debug == true)
            {
                Console.Write(format, parameters);
            }
        }

        private void DebugPrint(string str)
        {
            if (debug == true)
            {
                Console.Write(str);
            }
        }

sangshuduo's avatar
sangshuduo 已提交
292 293 294 295 296
        public void InitTDengine()
        {
            TDengine.Options((int)TDengineInitOption.TDDB_OPTION_CONFIGDIR, this.configDir);
            TDengine.Options((int)TDengineInitOption.TDDB_OPTION_SHELL_ACTIVITY_TIMER, "60");
            TDengine.Init();
297
            VerbosePrint("TDengine Initialization finished\n");
sangshuduo's avatar
sangshuduo 已提交
298 299 300 301 302
        }

        public void ConnectTDengine()
        {
            string db = "";
303
            VerbosePrintFormat("host:{0} user:{1}, pass:{2}; db:{3}, port:{4}\n",
sangshuduo's avatar
sangshuduo 已提交
304
                    this.host, this.user, this.password, db, this.port);
sangshuduo's avatar
sangshuduo 已提交
305 306 307 308
            this.conn = TDengine.Connect(this.host, this.user, this.password, db, this.port);
            if (this.conn == IntPtr.Zero)
            {
                Console.WriteLine("Connect to TDengine failed");
309
                CleanAndExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
310 311 312
            }
            else
            {
313
                VerbosePrint("Connect to TDengine success\n");
sangshuduo's avatar
sangshuduo 已提交
314 315 316 317 318
            }
        }

        public void CreateTablesByThreads()
        {
sangshuduo's avatar
sangshuduo 已提交
319
            Thread[] threadArr = new Thread[numOfThreads];
sangshuduo's avatar
sangshuduo 已提交
320

sangshuduo's avatar
sangshuduo 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
            long quotition = numOfTables / numOfThreads;
            if (quotition < 1)
            {
                numOfThreads = numOfTables;
                quotition = 1;
            }

            long remainder = 0;
            if (numOfThreads != 0)
            {
                remainder = numOfTables % numOfThreads;
            }

            long last = 0;

            for (int i = 0; i < numOfThreads; i++)
            {
                CreateTableThread createTableThread = new CreateTableThread();
                createTableThread.id = i;
                createTableThread.verbose = verbose;
341
                createTableThread.debug = debug;
sangshuduo's avatar
sangshuduo 已提交
342 343
                createTableThread.dbName = this.dbName;
                createTableThread.tablePrefix = this.tablePrefix;
344
                createTableThread.useStable = useStable;
sangshuduo's avatar
sangshuduo 已提交
345 346
                if (useStable)
                {
347
                    createTableThread.stablePrefix = stablePrefix;
sangshuduo's avatar
sangshuduo 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
                }
                createTableThread.conn = conn;

                createTableThread.start = last;
                if (i < remainder)
                {
                    createTableThread.end = last + quotition;
                }
                else
                {
                    createTableThread.end = last + quotition - 1;
                }
                last = createTableThread.end + 1;

                threadArr[i] = new Thread(createTableThread.ThreadMain);
                threadArr[i].Start();
                threadArr[i].Join();
            }
        }

        public void dropDatabase()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("DROP DATABASE IF EXISTS ").Append(this.dbName);
sangshuduo's avatar
sangshuduo 已提交
372
            IntPtr res = TDengine.Query(this.conn, sql.ToString());
373
            if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
sangshuduo's avatar
sangshuduo 已提交
374
            {
375 376 377 378 379 380
                Console.Write(sql.ToString() + " failure, ");
                if (res != IntPtr.Zero) {
                  Console.Write("reason: " + TDengine.Error(res));
                }
                Console.WriteLine("");
                CleanAndExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
381 382 383
            }
            else
            {
384
                VerbosePrint(sql.ToString() + " success\n");
sangshuduo's avatar
sangshuduo 已提交
385
            }
sangshuduo's avatar
sangshuduo 已提交
386 387 388 389 390
        }

        public void CreateDb()
        {
            StringBuilder sql = new StringBuilder();
391
            sql.Append("CREATE DATABASE IF NOT EXISTS ").Append(this.dbName).Append(" replica ").Append(this.replica).Append(" keep 36500");
sangshuduo's avatar
sangshuduo 已提交
392
            IntPtr res = TDengine.Query(this.conn, sql.ToString());
393
            if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
sangshuduo's avatar
sangshuduo 已提交
394
            {
395 396 397 398 399 400
                Console.Write(sql.ToString() + " failure, ");
                if (res != IntPtr.Zero) {
                  Console.Write("reason: " + TDengine.Error(res));
                }
                Console.WriteLine("");
                CleanAndExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
401 402 403
            }
            else
            {
404
                VerbosePrint(sql.ToString() + " success\n");
sangshuduo's avatar
sangshuduo 已提交
405 406 407 408
            }
            TDengine.FreeResult(res);
        }

sangshuduo's avatar
sangshuduo 已提交
409
        public void CreateStable()
sangshuduo's avatar
sangshuduo 已提交
410 411
        {
            StringBuilder sql = new StringBuilder();
sangshuduo's avatar
sangshuduo 已提交
412 413 414

            sql.Clear();
            sql.Append("CREATE TABLE IF NOT EXISTS ").
415
                Append(this.dbName).Append(".").Append(this.stablePrefix).
416
                Append("(ts timestamp, v1 bool, v2 tinyint, v3 smallint, v4 int, v5 bigint, v6 float, v7 double, v8 binary(10), v9 nchar(10), v10 tinyint unsigned, v11 smallint unsigned, v12 int unsigned, v13 bigint unsigned) tags(t1 int)");
sangshuduo's avatar
sangshuduo 已提交
417
            IntPtr res = TDengine.Query(this.conn, sql.ToString());
418
            if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
sangshuduo's avatar
sangshuduo 已提交
419
            {
420 421 422 423 424 425
                Console.Write(sql.ToString() + " failure, ");
                if (res != IntPtr.Zero) {
                  Console.Write("reason: " + TDengine.Error(res));
                }
                Console.WriteLine("");
                CleanAndExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
426 427 428
            }
            else
            {
429
                VerbosePrint(sql.ToString() + " success\n");
sangshuduo's avatar
sangshuduo 已提交
430 431 432 433
            }
            TDengine.FreeResult(res);
        }

sangshuduo's avatar
sangshuduo 已提交
434
        public void InsertByThreads()
sangshuduo's avatar
sangshuduo 已提交
435
        {
sangshuduo's avatar
sangshuduo 已提交
436
            Thread[] threadArr = new Thread[numOfThreads];
sangshuduo's avatar
sangshuduo 已提交
437

sangshuduo's avatar
sangshuduo 已提交
438 439
            long quotition = numOfTables / numOfThreads;
            if (quotition < 1)
sangshuduo's avatar
sangshuduo 已提交
440
            {
sangshuduo's avatar
sangshuduo 已提交
441 442 443
                numOfThreads = numOfTables;
                quotition = 1;
            }
sangshuduo's avatar
sangshuduo 已提交
444

sangshuduo's avatar
sangshuduo 已提交
445 446 447 448 449
            long remainder = 0;
            if (numOfThreads != 0)
            {
                remainder = numOfTables % numOfThreads;
            }
sangshuduo's avatar
sangshuduo 已提交
450

sangshuduo's avatar
sangshuduo 已提交
451 452 453 454 455 456 457 458 459 460
            long last = 0;

            for (int i = 0; i < numOfThreads; i++)
            {
                InsertDataThread insertThread = new InsertDataThread();
                insertThread.id = i;
                insertThread.recordsPerTable = recordsPerTable;
                insertThread.batchRows = batchRows;
                insertThread.numOfTables = numOfTables;
                insertThread.verbose = verbose;
461
                insertThread.debug = debug;
sangshuduo's avatar
sangshuduo 已提交
462 463
                insertThread.dbName = this.dbName;
                insertThread.tablePrefix = this.tablePrefix;
464 465
                insertThread.order = this.order;
                insertThread.rateOfOutorder = this.rateOfOutorder;
sangshuduo's avatar
sangshuduo 已提交
466 467
                if (useStable)
                {
468
                    insertThread.stablePrefix = stablePrefix;
sangshuduo's avatar
sangshuduo 已提交
469
                }
sangshuduo's avatar
sangshuduo 已提交
470
                insertThread.conn = conn;
sangshuduo's avatar
sangshuduo 已提交
471

sangshuduo's avatar
sangshuduo 已提交
472 473 474 475 476 477 478 479 480 481
                insertThread.start = last;
                if (i < remainder)
                {
                    insertThread.end = last + quotition;
                }
                else
                {
                    insertThread.end = last + quotition - 1;
                }
                last = insertThread.end + 1;
sangshuduo's avatar
sangshuduo 已提交
482

sangshuduo's avatar
sangshuduo 已提交
483 484 485 486
                threadArr[i] = new Thread(insertThread.ThreadMain);
                threadArr[i].Start();
                threadArr[i].Join();
            }
sangshuduo's avatar
sangshuduo 已提交
487 488 489 490 491 492
        }

        public void ExecuteQuery()
        {
            long queryRows = 0;

493
            for (int i = 0; i < this.numOfTables; ++i)
sangshuduo's avatar
sangshuduo 已提交
494
            {
495 496 497 498 499 500 501 502 503 504 505
                string sql;

                if (query == "DEFAULT")
                {
                    sql = "select * from " + this.dbName + "." + tablePrefix + i;
                }
                else
                {
                    sql = query;
                }
                DebugPrintFormat("query: {0}, sql:{1}\n", query, sql);
sangshuduo's avatar
sangshuduo 已提交
506 507

                IntPtr res = TDengine.Query(conn, sql);
508
                DebugPrintFormat("res: {0}\n", res);
509
                if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
sangshuduo's avatar
sangshuduo 已提交
510
                {
511 512 513 514 515
                    Console.Write(sql.ToString() + " failure, ");
                    if (res != IntPtr.Zero) {
                      Console.Write("reason: " + TDengine.Error(res));
                    }
                    Console.WriteLine("");
516
                    CleanAndExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
517 518 519
                }

                int fieldCount = TDengine.FieldCount(res);
520
                DebugPrint("field count: " + fieldCount + "\n");
sangshuduo's avatar
sangshuduo 已提交
521 522 523 524 525

                List<TDengineMeta> metas = TDengine.FetchFields(res);
                for (int j = 0; j < metas.Count; j++)
                {
                    TDengineMeta meta = (TDengineMeta)metas[j];
526
                    DebugPrint("index:" + j + ", type:" + meta.type + ", typename:" + meta.TypeName() + ", name:" + meta.name + ", size:" + meta.size + "\n");
sangshuduo's avatar
sangshuduo 已提交
527 528 529 530
                }

                IntPtr rowdata;
                StringBuilder builder = new StringBuilder();
531

sangshuduo's avatar
sangshuduo 已提交
532 533 534 535 536 537 538 539 540
                while ((rowdata = TDengine.FetchRows(res)) != IntPtr.Zero)
                {
                    queryRows++;
                    for (int fields = 0; fields < fieldCount; ++fields)
                    {
                        TDengineMeta meta = metas[fields];
                        int offset = IntPtr.Size * fields;
                        IntPtr data = Marshal.ReadIntPtr(rowdata, offset);

541
                        builder.Append(" | ");
sangshuduo's avatar
sangshuduo 已提交
542 543 544 545 546 547 548 549 550 551 552 553 554 555

                        if (data == IntPtr.Zero)
                        {
                            builder.Append("NULL");
                            continue;
                        }

                        switch ((TDengineDataType)meta.type)
                        {
                            case TDengineDataType.TSDB_DATA_TYPE_BOOL:
                                bool v1 = Marshal.ReadByte(data) == 0 ? false : true;
                                builder.Append(v1);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_TINYINT:
556
                                sbyte v2 = (sbyte)Marshal.ReadByte(data);
sangshuduo's avatar
sangshuduo 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
                                builder.Append(v2);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_SMALLINT:
                                short v3 = Marshal.ReadInt16(data);
                                builder.Append(v3);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_INT:
                                int v4 = Marshal.ReadInt32(data);
                                builder.Append(v4);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_BIGINT:
                                long v5 = Marshal.ReadInt64(data);
                                builder.Append(v5);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_FLOAT:
                                float v6 = (float)Marshal.PtrToStructure(data, typeof(float));
                                builder.Append(v6);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_DOUBLE:
                                double v7 = (double)Marshal.PtrToStructure(data, typeof(double));
                                builder.Append(v7);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_BINARY:
                                string v8 = Marshal.PtrToStringAnsi(data);
                                builder.Append(v8);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP:
                                long v9 = Marshal.ReadInt64(data);
                                builder.Append(v9);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_NCHAR:
                                string v10 = Marshal.PtrToStringAnsi(data);
                                builder.Append(v10);
                                break;
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
                            case TDengineDataType.TSDB_DATA_TYPE_UTINYINT:
                                byte v11 = Marshal.ReadByte(data);
                                builder.Append(v11);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_USMALLINT:
                                ushort v12 = (ushort)Marshal.ReadInt16(data);
                                builder.Append(v12);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_UINT:
                                uint v13 = (uint)Marshal.ReadInt32(data);
                                builder.Append(v13);
                                break;
                            case TDengineDataType.TSDB_DATA_TYPE_UBIGINT:
                                ulong v14 = (ulong)Marshal.ReadInt64(data);
                                builder.Append(v14);
                                break;
sangshuduo's avatar
sangshuduo 已提交
607 608
                        }
                    }
609
                    builder.Append(" | ");
sangshuduo's avatar
sangshuduo 已提交
610

611
                    VerbosePrint(builder.ToString() + "\n");
sangshuduo's avatar
sangshuduo 已提交
612 613 614 615 616
                    builder.Clear();
                }

                if (TDengine.ErrorNo(res) != 0)
                {
sangshuduo's avatar
sangshuduo 已提交
617 618
                    Console.Write("Query is not complete, Error {0:G}",
                            TDengine.ErrorNo(res), TDengine.Error(res));
sangshuduo's avatar
sangshuduo 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
                }

                TDengine.FreeResult(res);
            }
        }

        public void CloseConnection()
        {
            if (this.conn != IntPtr.Zero)
            {
                TDengine.Close(this.conn);
            }
        }

        // Main entry
        static void Main(string[] args)
        {
            PrintHelp(args);

            TDengineTest tester = new TDengineTest();
            tester.ReadArgument(args);

            tester.InitTDengine();
            tester.ConnectTDengine();

644
            if (tester.isInsertOnly == false)
sangshuduo's avatar
sangshuduo 已提交
645
            {
646 647 648
                tester.dropDatabase();
                tester.CreateDb();

sangshuduo's avatar
sangshuduo 已提交
649

650 651 652 653 654 655 656
                if (tester.useStable == true)
                {
                    tester.CreateStable();
                }

                tester.CreateTablesByThreads();
            }
sangshuduo's avatar
sangshuduo 已提交
657 658 659 660 661 662

            Stopwatch watch = Stopwatch.StartNew();
            tester.InsertByThreads();
            watch.Stop();
            double elapsedMs = watch.Elapsed.TotalMilliseconds;

663
            Console.WriteLine("C# taosdemo: Spent {0} seconds to insert {1} records with {2} record(s) per request: {3} records/second",
sangshuduo's avatar
sangshuduo 已提交
664 665 666 667
                    elapsedMs / 1000,
                tester.recordsPerTable * tester.numOfTables,
                tester.batchRows,
                (tester.recordsPerTable * tester.numOfTables * 1000) / elapsedMs);
sangshuduo's avatar
sangshuduo 已提交
668

669 670 671 672 673 674 675
            tester.DebugPrintFormat("query command:{0}\n", tester.query);
            if (tester.query != "NONE")
            {
                watch = Stopwatch.StartNew();
                tester.ExecuteQuery();
                watch.Stop();
                elapsedMs = watch.Elapsed.TotalMilliseconds;
676 677
                Console.WriteLine("C# taosdemo: Spent {0} seconds to query {1} records.\n",
                        elapsedMs / 1000,
678 679 680
                        tester.recordsPerTable * tester.numOfTables
                        );
            }
sangshuduo's avatar
sangshuduo 已提交
681 682 683
            tester.CloseConnection();

            Console.WriteLine("End.");
684
            CleanAndExitProgram(0);
sangshuduo's avatar
sangshuduo 已提交
685
        }
sangshuduo's avatar
sangshuduo 已提交
686 687 688 689 690 691 692 693 694

        public class InsertDataThread
        {
            public long id { set; get; }
            public long start { set; get; }
            public long end { set; get; }
            public string dbName { set; get; }
            public IntPtr conn { set; get; }
            public string tablePrefix { set; get; }
695
            public string stablePrefix { set; get; }
sangshuduo's avatar
sangshuduo 已提交
696 697 698 699
            public long recordsPerTable { set; get; }
            public long batchRows { set; get; }
            public long numOfTables { set; get; }
            public bool verbose { set; get; }
700
            public bool debug { set; get; }
701 702
            public bool order { set; get; }
            public short rateOfOutorder { set; get; }
sangshuduo's avatar
sangshuduo 已提交
703

704
            private void VerbosePrintFormat(string format, params object[] parameters)
sangshuduo's avatar
sangshuduo 已提交
705 706 707 708 709 710 711
            {
                if (verbose == true)
                {
                    Console.Write(format, parameters);
                }
            }

712
            private void VerbosePrint(string str)
sangshuduo's avatar
sangshuduo 已提交
713 714 715 716 717 718 719
            {
                if (verbose == true)
                {
                    Console.Write(str);
                }
            }

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
            private void DebugPrintFormat(string format, params object[] parameters)
            {
                if (debug == true)
                {
                    Console.Write(format, parameters);
                }
            }

            private void DebugPrint(string str)
            {
                if (debug == true)
                {
                    Console.Write(str);
                }
            }

sangshuduo's avatar
sangshuduo 已提交
736 737
            public void ThreadMain()
            {
738
                VerbosePrintFormat("InsertDataThread {0} from {1} to {2}\n", id, start, end);
sangshuduo's avatar
sangshuduo 已提交
739
                StringBuilder sql = new StringBuilder();
740 741 742 743 744 745

                DateTime now = DateTime.Now;
                int h = now.Hour;
                int m = now.Minute;
                int s = now.Second;

746
                long baseTimestamp = -16094340000;   // 1969-06-29 01:21:00
747
                VerbosePrintFormat("beginTime is {0} + {1}h:{2}m:{3}s\n", baseTimestamp, h, m, s);
748
                long beginTimestamp = baseTimestamp + ((h * 60 + m) * 60 + s) * 1000;
749
                Random random = new Random();
750

sangshuduo's avatar
sangshuduo 已提交
751 752 753 754 755 756 757 758 759 760 761 762 763
                long rowsInserted = 0;

                long i = 0;
                while (i < recordsPerTable)
                {
                    for (long table = start; table <= end; ++table)
                    {
                        long inserted = i;

                        sql.Clear();
                        sql.Append("INSERT INTO ").
                            Append(this.dbName).Append(".").Append(this.tablePrefix).Append(table).
                            Append(" VALUES");
764 765 766 767 768
                        if (recordsPerTable < batchRows)
                        {
                            batchRows = recordsPerTable;
                        }
                        for (int batch = 0; batch < batchRows; ++batch)
sangshuduo's avatar
sangshuduo 已提交
769
                        {
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
                            long writeTimeStamp = beginTimestamp + i + batch;
                            int rnd = 100;
                            if (this.order == false)
                            {
                                rnd = random.Next(1, 100);
                                if (rnd <= this.rateOfOutorder)
                                {
                                    writeTimeStamp = writeTimeStamp + rnd * 10000;
                                    DebugPrint("### ");
                                }
                                DebugPrintFormat("order:{0} rnd:{1} timestamp:{2}\n", this.order, rnd, writeTimeStamp);
                            }
                            else
                            {
                                DebugPrintFormat("order:{0} timestamp:{1}\n", this.order, writeTimeStamp);
                            }

sangshuduo's avatar
sangshuduo 已提交
787
                            sql.Append("(")
788
                                .Append(writeTimeStamp)
789 790 791 792 793 794 795
                                .Append(", 1, -2, -3,")
                                .Append(i + batch - 127)
                                .Append(", -5, -6, -7, 'abc', 'def', 254, 65534,")
                                .Append(4294967294 - (uint)i - (uint)batch)
                                .Append(",")
                                .Append(18446744073709551614 - (ulong)i - (ulong)batch)
                                .Append(")");
sangshuduo's avatar
sangshuduo 已提交
796 797

                        }
798
                        VerbosePrint(sql.ToString() + "\n");
sangshuduo's avatar
sangshuduo 已提交
799
                        IntPtr res = TDengine.Query(this.conn, sql.ToString());
800
                        if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
sangshuduo's avatar
sangshuduo 已提交
801
                        {
802 803 804 805 806
                            Console.Write(sql.ToString() + " failure, ");
                            if (res != IntPtr.Zero) {
                              Console.Write("reason: " + TDengine.Error(res));
                            }
                            Console.WriteLine("");
sangshuduo's avatar
sangshuduo 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
                        }

                        inserted += this.batchRows;

                        int affectRows = TDengine.AffectRows(res);
                        rowsInserted += affectRows;

                        TDengine.FreeResult(res);
                        if (table == end)
                        {
                            i = inserted;
                        }
                    }
                }

            }
        }

        public class CreateTableThread
        {
            public long id { set; get; }
            public long start { set; get; }
            public long end { set; get; }
            public string dbName { set; get; }
            public IntPtr conn { set; get; }
            public string tablePrefix { set; get; }
833
            public string stablePrefix { set; get; }
sangshuduo's avatar
sangshuduo 已提交
834
            public bool verbose { set; get; }
835
            public bool debug { set; get; }
836
            public bool useStable { set; get; }
sangshuduo's avatar
sangshuduo 已提交
837

838
            private void VerbosePrintFormat(string format, params object[] parameters)
sangshuduo's avatar
sangshuduo 已提交
839 840 841 842 843 844 845
            {
                if (verbose == true)
                {
                    Console.Write(format, parameters);
                }
            }

846
            private void VerbosePrint(string str)
sangshuduo's avatar
sangshuduo 已提交
847 848 849 850 851 852 853
            {
                if (verbose == true)
                {
                    Console.Write(str);
                }
            }

854 855 856 857 858 859 860 861
            private void DebugPrintFormat(string format, params object[] parameters)
            {
                if (debug == true)
                {
                    Console.Write(format, parameters);
                }
            }

sangshuduo's avatar
sangshuduo 已提交
862 863
            public void ThreadMain()
            {
864
                VerbosePrintFormat("CreateTable {0} from {1} to {2}\n", id, start, end);
sangshuduo's avatar
sangshuduo 已提交
865 866 867 868 869 870 871

                StringBuilder sql = new StringBuilder();

                for (long tableId = start; tableId <= end; tableId++)
                {
                    sql.Clear();
                    sql = sql.Append("CREATE TABLE IF NOT EXISTS ").
872 873 874
                        Append(this.dbName).Append(".").Append(this.tablePrefix).Append(tableId);
                    if (useStable == true)
                    {
875
                        sql = sql.Append(" USING ").Append(this.dbName).Append(".").Append(this.stablePrefix).
876 877 878 879
                            Append(" TAGS(").Append(tableId).Append(")");
                    }
                    else
                    {
880
                        sql = sql.Append("(ts timestamp, v1 bool, v2 tinyint, v3 smallint, v4 int, v5 bigint, v6 float, v7 double, v8 binary(10), v9 nchar(10), v10 tinyint unsigned, v11 smallint unsigned, v12 int unsigned, v13 bigint unsigned)");
881
                    }
sangshuduo's avatar
sangshuduo 已提交
882
                    IntPtr res = TDengine.Query(this.conn, sql.ToString());
883
                    if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
sangshuduo's avatar
sangshuduo 已提交
884
                    {
885 886 887 888 889 890
                        Console.Write(sql.ToString() + " failure, ");
                        if (res != IntPtr.Zero) {
                          Console.Write("reason: " + TDengine.Error(res));
                        }
                        Console.WriteLine("");
                        CleanAndExitProgram(1);
sangshuduo's avatar
sangshuduo 已提交
891 892 893
                    }
                    else
                    {
894
                        VerbosePrint(sql.ToString() + " success\n");
sangshuduo's avatar
sangshuduo 已提交
895 896 897 898 899 900
                    }
                    TDengine.FreeResult(res);
                }

            }
        }
sangshuduo's avatar
sangshuduo 已提交
901 902
    }
}