未验证 提交 02b43db2 编写于 作者: X xiaolei li 提交者: GitHub

fix:remove c# connector from TDengine (#11837)

* fix:remove c# connector from TDengine

* docs:replace c# reference doc with sperate repo's hyperlink
上级 b80282ba
...@@ -144,8 +144,8 @@ namespace TDengineExample ...@@ -144,8 +144,8 @@ namespace TDengineExample
| [stmt](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/stmt) | 使用 TDengine.Connector 实现的参数绑定的示例 | | [stmt](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/stmt) | 使用 TDengine.Connector 实现的参数绑定的示例 |
| [schemaless](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/schemaless) | 使用 TDengine.Connector 实现的使用 schemaless 写入的示例 | | [schemaless](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/schemaless) | 使用 TDengine.Connector 实现的使用 schemaless 写入的示例 |
| [benchmark](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/taosdemo) | 使用 TDengine.Connector 实现的简易 Benchmark | | [benchmark](https://github.com/taosdata/TDengine/tree/develop/examples/C%23/taosdemo) | 使用 TDengine.Connector 实现的简易 Benchmark |
| [async query](https://github.com/taosdata/TDengine/blob/develop/src/connector/C%23/examples/QueryAsyncSample.cs) | 使用 TDengine.Connector 实现的异步查询的示例 | | [async query](https://github.com/taosdata/taos-connector-dotnet/blob/develop/examples/QueryAsyncSample.cs) | 使用 TDengine.Connector 实现的异步查询的示例 |
| [subscribe](https://github.com/taosdata/TDengine/blob/develop/src/connector/C%23/examples/SubscribeSample.cs) | 使用 TDengine.Connector 实现的订阅数据的示例 | | [subscribe](https://github.com/taosdata/taos-connector-dotnet/blob/develop/examples/SubscribeSample.cs) | 使用 TDengine.Connector 实现的订阅数据的示例 |
## 重要更新记录 ## 重要更新记录
......

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A1FB5B66-E32F-4789-9BE9-042E5BD21087}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TDengineDriver", "src\TDengineDriver\TDengineDriver.csproj", "{5BED7402-0A65-4ED9-A491-C56BFB518045}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{CB8E6458-31E1-4351-B704-1B918E998654}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XUnitTest", "src\test\XUnitTest\XUnitTest.csproj", "{64C0A478-2591-4459-9F8F-A70F37976A41}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunctionTest", "src\test\FunctionTest\FunctionTest.csproj", "{E66B034B-4677-4BFB-8B87-84715D281E21}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Debug|x64.ActiveCfg = Debug|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Debug|x64.Build.0 = Debug|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Debug|x86.ActiveCfg = Debug|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Debug|x86.Build.0 = Debug|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Release|Any CPU.Build.0 = Release|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Release|x64.ActiveCfg = Release|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Release|x64.Build.0 = Release|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Release|x86.ActiveCfg = Release|Any CPU
{5BED7402-0A65-4ED9-A491-C56BFB518045}.Release|x86.Build.0 = Release|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Debug|x64.ActiveCfg = Debug|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Debug|x64.Build.0 = Debug|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Debug|x86.ActiveCfg = Debug|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Debug|x86.Build.0 = Debug|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Release|Any CPU.Build.0 = Release|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Release|x64.ActiveCfg = Release|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Release|x64.Build.0 = Release|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Release|x86.ActiveCfg = Release|Any CPU
{64C0A478-2591-4459-9F8F-A70F37976A41}.Release|x86.Build.0 = Release|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Debug|x64.ActiveCfg = Debug|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Debug|x64.Build.0 = Debug|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Debug|x86.ActiveCfg = Debug|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Debug|x86.Build.0 = Debug|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Release|Any CPU.Build.0 = Release|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Release|x64.ActiveCfg = Release|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Release|x64.Build.0 = Release|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Release|x86.ActiveCfg = Release|Any CPU
{E66B034B-4677-4BFB-8B87-84715D281E21}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{5BED7402-0A65-4ED9-A491-C56BFB518045} = {A1FB5B66-E32F-4789-9BE9-042E5BD21087}
{CB8E6458-31E1-4351-B704-1B918E998654} = {A1FB5B66-E32F-4789-9BE9-042E5BD21087}
{64C0A478-2591-4459-9F8F-A70F37976A41} = {CB8E6458-31E1-4351-B704-1B918E998654}
{E66B034B-4677-4BFB-8B87-84715D281E21} = {CB8E6458-31E1-4351-B704-1B918E998654}
EndGlobalSection
EndGlobal
using System;
using Sample.UtilsTools;
using System.Runtime.InteropServices;
using TDengineDriver;
using Example;
using System.Collections.Generic;
namespace AsyncQueryExample
{
public class EntryPoint
{
static void Main(string[] args)
{
IntPtr conn = UtilsTools.TDConnection();
AsyncQuerySample asyncQuery = new AsyncQuerySample();
asyncQuery.RunQueryAsync(conn, "query_async");
SubscribeSample subscribeSample = new SubscribeSample();
subscribeSample.RunSubscribeWithCallback(conn, "subscribe_with_callback");
subscribeSample.RunSubscribeWithoutCallback(conn, "subscribe_without_callback");
UtilsTools.CloseConnection(conn);
SchemalessSample schemalessSample = new SchemalessSample();
schemalessSample.RunSchemaless();
}
}
}
using System;
using TDengineDriver;
using Sample.UtilsTools;
using System.Runtime.InteropServices;
using System.Threading;
namespace Example
{
public class AsyncQuerySample
{
public void RunQueryAsync(IntPtr conn, string table)
{
QueryAsyncCallback queryAsyncCallback = new QueryAsyncCallback(QueryCallback);
PrepareData(conn, table);
Console.WriteLine($"Start calling QueryAsync(),query {table}'s data asynchronously.");
TDengine.QueryAsync(conn, $"select * from {table}", queryAsyncCallback, IntPtr.Zero);
Thread.Sleep(2000);
Console.WriteLine("QueryAsync done.");
}
//prepare the data(table and insert data)
public void PrepareData(IntPtr conn, string tableName)
{
string createTable = $"create table if not exists {tableName} (ts timestamp,i8 tinyint,i16 smallint,i32 int,i64 bigint)tags(t_bnry binary(50), t_nchr nchar(50));";
string insert1 = $"insert into {tableName}_s01 using {tableName} tags('tag1','标签1') values(now,1,2,3,4)(now+1m,5,6,7,8)(now+2m,9,0,-1,-2)(now+3m,-3,-4,-5,-6)(now+4m,-7,-8,-9,0)";
string insert2 = $"insert into {tableName}_s02 using {tableName} tags('tag2','标签2') values(now,1,2,3,4)(now+1m,5,6,7,8)(now+2m,9,0,-1,-2)(now+3m,-3,-4,-5,-6)(now+4m,-7,-8,-9,0)";
string insert3 = $"insert into {tableName}_s03 using {tableName} tags('tag3','标签3') values(now,1,2,3,4)(now+1m,5,6,7,8)(now+2m,9,0,-1,-2)(now+3m,-3,-4,-5,-6)(now+4m,-7,-8,-9,0)";
string insert4 = $"insert into {tableName}_s04 using {tableName} tags('tag4','标签4') values(now,1,2,3,4)(now+1m,5,6,7,8)(now+2m,9,0,-1,-2)(now+3m,-3,-4,-5,-6)(now+4m,-7,-8,-9,0)";
string insert5 = $"insert into {tableName}_s05 using {tableName} tags('tag5','标签5') values(now,1,2,3,4)(now+1m,5,6,7,8)(now+2m,9,0,-1,-2)(now+3m,-3,-4,-5,-6)(now+4m,-7,-8,-9,0)";
UtilsTools.ExecuteUpdate(conn, createTable);
UtilsTools.ExecuteUpdate(conn, insert1);
Thread.Sleep(100);
UtilsTools.ExecuteUpdate(conn, insert2);
Thread.Sleep(100);
UtilsTools.ExecuteUpdate(conn, insert3);
Thread.Sleep(100);
UtilsTools.ExecuteUpdate(conn, insert4);
Thread.Sleep(100);
UtilsTools.ExecuteUpdate(conn, insert5);
}
public void QueryCallback(IntPtr param, IntPtr taosRes, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchCallback);
TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param);
}
else
{
Console.WriteLine($"async query data failed, failed code {code}");
}
}
// Iteratively call this interface until "numOfRows" is no greater than 0.
public void FetchCallback(IntPtr param, IntPtr taosRes, int numOfRows)
{
if (numOfRows > 0)
{
Console.WriteLine($"{numOfRows} rows async retrieved");
UtilsTools.DisplayRes(taosRes);
TDengine.FetchRowAsync(taosRes, FetchCallback, param);
}
else
{
if (numOfRows == 0)
{
Console.WriteLine("async retrieve complete.");
}
else
{
Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}");
}
TDengine.FreeResult(taosRes);
}
}
}
}
\ No newline at end of file
/*
* 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;
using Sample.UtilsTools;
using TDengineDriver;
namespace Example
{
class SchemalessSample
{
private IntPtr conn = IntPtr.Zero;
private string dbName = "csharp_schemaless_example";
public void RunSchemaless()
{
string[] lines = {
"stg,t1=3i64,t2=4f64,t3=\"t3\" c1=3i64,c3=L\"passit\",c2=false,c4=4f64 1626006833639000000",
"stg,t1=4i64,t3=\"t4\",t2=5f64,t4=5f64 c1=3i64,c3=L\"passitagin\",c2=true,c4=5f64,c5=5f64 1626006833641000000"
};
string[] jsonStr = {
"{"
+"\"metric\": \"stb0_0\","
+"\"timestamp\": 1626006833,"
+"\"value\": 10,"
+"\"tags\": {"
+" \"t1\": true,"
+"\"t2\": false,"
+"\"t3\": 10,"
+"\"t4\": \"123_abc_.!@#$%^&*:;,./?|+-=()[]{}<>\""
+"}"
+"}"
};
StringBuilder querySql = new StringBuilder();
Console.WriteLine(querySql.ToString());
this.conn = UtilsTools.TDConnection(this.dbName);
schemalessInsert(lines, 2, (int)TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NANO_SECONDS);
querySql.Append("select * from ").Append(this.dbName).Append(".").Append("stg");
UtilsTools.DisplayRes(UtilsTools.ExecuteQuery(this.conn, querySql.ToString()));
schemalessInsert(jsonStr, 1, (int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_SECONDS);
querySql.Clear();
querySql.Append("select * from ").Append(this.dbName).Append(".").Append("stb0_0");
UtilsTools.DisplayRes(UtilsTools.ExecuteQuery(this.conn, querySql.ToString()));
querySql.Clear();
querySql.Append("drop database if exists ").Append(this.dbName);
UtilsTools.ExecuteUpdate(this.conn, querySql.ToString());
UtilsTools.CloseConnection(this.conn);
}
public void schemalessInsert(string[] sqlstr, int lineCnt, int protocol, int precision)
{
IntPtr res = TDengine.SchemalessInsert(this.conn, sqlstr, lineCnt, protocol, precision);
if (TDengine.ErrorNo(res) != 0)
{
Console.WriteLine("schemaless_insert failed:{0}", TDengine.Error(res));
Console.WriteLine("line string:{0}", sqlstr);
Console.WriteLine("");
System.Environment.Exit(0);
}
else
{
Console.WriteLine("else");
Console.WriteLine("schemaless insert success:{0}", TDengine.ErrorNo(res));
}
}
}
}
using System;
using TDengineDriver;
using Sample.UtilsTools;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Threading;
namespace Example
{
public class SubscribeSample
{
long ts = 1646150410000;
public void RunSubscribeWithCallback(IntPtr conn, string table)
{
PrepareData(conn, table);
string topic = $"{table}_topic";
string sql = $"select * from {table}";
SubscribeCallback subscribeCallback = new SubscribeCallback(SubCallback);
// Subscribe from earliest timestamp in the table.
IntPtr subscribe = TDengine.Subscribe(conn, true, topic, sql, subscribeCallback, IntPtr.Zero, 1000);
// Add new data.
for (int i = 0; i < 4; i++)
{
InsertData(conn, table);
}
Console.WriteLine("Unsubscribe and keep the subscribe progress ");
TDengine.Unsubscribe(subscribe, true);
Console.WriteLine("Subscribe from last subscribe progress");
subscribe = TDengine.Subscribe(conn, false, topic, sql, subscribeCallback, IntPtr.Zero, 1000);
for (int i = 0; i < 4; i++)
{
InsertData(conn, table);
}
Console.WriteLine("Unsubscribe and remove the subscribe progress ");
TDengine.Unsubscribe(subscribe, false);
}
public void RunSubscribeWithoutCallback(IntPtr conn, string table)
{
PrepareData(conn, table);
string topic = $"{table}_topic";
string sql = $"select * from {table}";
IntPtr subscribe = TDengine.Subscribe(conn, true, topic, sql, null, IntPtr.Zero, 1000);
Console.WriteLine("consume from begin");
//Don't release this TAO_RES and end of the subscribe application,other wise will lead crash.
IntPtr taosRes = TDengine.Consume(subscribe);
UtilsTools.DisplayRes(taosRes);
for (int i = 0; i < 3; i++)
{
InsertData(conn, table);
}
Console.WriteLine("consume new data");
taosRes = TDengine.Consume(subscribe);
UtilsTools.DisplayRes(taosRes);
Console.WriteLine("Unsubscribe and keep progress");
TDengine.Unsubscribe(subscribe, true);
// Subscribe from last subscribe progress.
subscribe = TDengine.Subscribe(conn, false, topic, sql, null, IntPtr.Zero, 1000);
for (int i = 0; i < 3; i++)
{
InsertData(conn, table);
Console.WriteLine($"Consume {i+1} time");
taosRes = TDengine.Consume(subscribe);
// The interval between two consume should greater than "interval" pass in Subscribe().
// Otherwise consume will be blocked.
Thread.Sleep(1000);
UtilsTools.DisplayRes(taosRes);
}
TDengine.Unsubscribe(subscribe, false);
TDengine.FreeResult(taosRes);
}
public void SubCallback(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
// cannot free taosRes using taosRes, otherwise will cause crash.
Console.WriteLine($"Display taosRes in subscribe callback");
UtilsTools.DisplayRes(taosRes);
}
else
{
Console.WriteLine($"async query data failed, failed code {code}");
}
}
public void PrepareData(IntPtr conn, string tableName)
{
string createTable = $"create table if not exists {tableName} (ts timestamp,i8 tinyint,i16 smallint,i32 int,i64 bigint);";
string insert1 = $"insert into {tableName} values({ts},1,2,3,4)";
UtilsTools.ExecuteUpdate(conn, createTable);
UtilsTools.ExecuteUpdate(conn, insert1);
}
public void InsertData(IntPtr conn, string tableName)
{
ts = ts + 100;
string insert1 = $"insert into {tableName} values({ts},1,2,3,4)";
ts = ts + 100;
string insert2 = $"insert into {tableName} values({ts},-1,-2,-3,-4)";
UtilsTools.ExecuteUpdate(conn, insert1);
UtilsTools.ExecuteUpdate(conn, insert2);
Thread.Sleep(500);
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\src\TDengineDriver\TDengineDriver.csproj" />
</ItemGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
using System;
using TDengineDriver;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
namespace Sample.UtilsTools
{
public class UtilsTools
{
static string ip = "127.0.0.1";
static string user = "root";
static string password = "taosdata";
static string db = "";
static short port = 0;
static string globalDbName = "csharp_example_db";
//get a TDengine connection
public static IntPtr TDConnection(string dbName = "csharp_example_db")
{
TDengine.Options((int)TDengineInitOption.TSDB_OPTION_CONFIGDIR, GetConfigPath());
TDengine.Options((int)TDengineInitOption.TSDB_OPTION_SHELL_ACTIVITY_TIMER, "60");
TDengine.Init();
IntPtr conn = TDengine.Connect(ip, user, password, db, port);
UtilsTools.ExecuteUpdate(conn, $"drop database if exists {dbName}");
UtilsTools.ExecuteUpdate(conn, $"create database if not exists {dbName} keep 3650");
UtilsTools.ExecuteUpdate(conn, $"use {dbName}");
return conn;
}
//get taos.cfg file based on different os
public static string GetConfigPath()
{
string configDir = "";
if (OperatingSystem.IsOSPlatform("Windows"))
{
configDir = "C:/TDengine/cfg";
}
else if (OperatingSystem.IsOSPlatform("Linux"))
{
configDir = "/etc/taos";
}
else if (OperatingSystem.IsOSPlatform("macOS"))
{
configDir = "/usr/local/etc/taos";
}
return configDir;
}
public static IntPtr ExecuteQuery(IntPtr conn, String sql)
{
IntPtr res = TDengine.Query(conn, sql);
if (!IsValidResult(res))
{
Console.Write(sql.ToString() + " failure, ");
ExitProgram();
}
else
{
Console.WriteLine(sql.ToString() + " success");
}
return res;
}
public static IntPtr ExecuteErrorQuery(IntPtr conn, String sql)
{
IntPtr res = TDengine.Query(conn, sql);
if (!IsValidResult(res))
{
Console.Write(sql.ToString() + " failure, ");
ExitProgram();
}
else
{
Console.WriteLine(sql.ToString() + " success");
}
return res;
}
public static void ExecuteUpdate(IntPtr conn, String sql)
{
IntPtr res = TDengine.Query(conn, sql);
if (!IsValidResult(res))
{
Console.Write(sql.ToString() + " failure, ");
ExitProgram();
}
else
{
Console.WriteLine(sql.ToString() + " success");
}
TDengine.FreeResult(res);
}
public static void DisplayRes(IntPtr res)
{
if (!IsValidResult(res))
{
ExitProgram();
}
List<TDengineMeta> metaList = GetResField(res);
int fieldCount = metaList.Count;
// metaList.ForEach((item) => { Console.Write("{0} ({1}) \t|\t", item.name, item.size); });
List<Object> dataList = QueryRes(res, metaList);
for (int index = 0; index < dataList.Count; index++)
{
if (index % fieldCount == 0 && index != 0)
{
Console.WriteLine("");
}
Console.Write("{0} \t|\t", dataList[index].ToString());
}
Console.WriteLine("");
}
public static List<List<Object>> GetResultSet(IntPtr res)
{
List<List<Object>> result = new List<List<Object>>();
List<Object> colName = new List<Object>();
List<Object> dataRaw = new List<Object>();
if (!IsValidResult(res))
{
ExitProgram();
}
List<TDengineMeta> meta = GetResField(res);
result.Add(colName);
dataRaw = QueryRes(res, meta);
result.Add(dataRaw);
if (TDengine.ErrorNo(res) != 0)
{
Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res));
}
return result;
}
public static bool IsValidResult(IntPtr res)
{
if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
{
if (res != IntPtr.Zero)
{
Console.Write("reason: " + TDengine.Error(res));
return false;
}
Console.WriteLine("");
return false;
}
return true;
}
public static void CloseConnection(IntPtr conn)
{
ExecuteUpdate(conn, $"drop database if exists {globalDbName}");
if (conn != IntPtr.Zero)
{
TDengine.Close(conn);
Console.WriteLine("close connection success");
}
else
{
throw new Exception("connection if already null");
}
}
public static List<TDengineMeta> GetResField(IntPtr res)
{
List<TDengineMeta> meta = TDengine.FetchFields(res);
return meta;
}
public static void ExitProgram()
{
TDengine.Cleanup();
System.Environment.Exit(0);
}
public static List<Object> GetResData(IntPtr res)
{
List<Object> colName = new List<Object>();
List<Object> dataRaw = new List<Object>();
if (!IsValidResult(res))
{
ExitProgram();
}
List<TDengineMeta> meta = GetResField(res);
dataRaw = QueryRes(res, meta);
return dataRaw;
}
private static List<Object> QueryRes(IntPtr res, List<TDengineMeta> meta)
{
IntPtr taosRow;
List<Object> dataRaw = new List<Object>();
int fieldCount = meta.Count;
while ((taosRow = TDengine.FetchRows(res)) != IntPtr.Zero)
{
dataRaw.AddRange(FetchRow(taosRow, res));
}
if (TDengine.ErrorNo(res) != 0)
{
Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res));
}
// TDengine.FreeResult(res);
Console.WriteLine("");
return dataRaw;
}
public static List<Object> FetchRow(IntPtr taosRow, IntPtr taosRes)//, List<TDengineMeta> metaList, int numOfFiled
{
List<TDengineMeta> metaList = TDengine.FetchFields(taosRes);
int numOfFiled = TDengine.FieldCount(taosRes);
List<Object> dataRaw = new List<Object>();
IntPtr colLengthPrt = TDengine.FetchLengths(taosRes);
int[] colLengthArr = new int[numOfFiled];
Marshal.Copy(colLengthPrt, colLengthArr, 0, numOfFiled);
for (int i = 0; i < numOfFiled; i++)
{
TDengineMeta meta = metaList[i];
IntPtr data = Marshal.ReadIntPtr(taosRow, IntPtr.Size * i);
if (data == IntPtr.Zero)
{
dataRaw.Add("NULL");
continue;
}
switch ((TDengineDataType)meta.type)
{
case TDengineDataType.TSDB_DATA_TYPE_BOOL:
bool v1 = Marshal.ReadByte(data) == 0 ? false : true;
dataRaw.Add(v1);
break;
case TDengineDataType.TSDB_DATA_TYPE_TINYINT:
sbyte v2 = (sbyte)Marshal.ReadByte(data);
dataRaw.Add(v2);
break;
case TDengineDataType.TSDB_DATA_TYPE_SMALLINT:
short v3 = Marshal.ReadInt16(data);
dataRaw.Add(v3);
break;
case TDengineDataType.TSDB_DATA_TYPE_INT:
int v4 = Marshal.ReadInt32(data);
dataRaw.Add(v4);
break;
case TDengineDataType.TSDB_DATA_TYPE_BIGINT:
long v5 = Marshal.ReadInt64(data);
dataRaw.Add(v5);
break;
case TDengineDataType.TSDB_DATA_TYPE_FLOAT:
float v6 = (float)Marshal.PtrToStructure(data, typeof(float));
dataRaw.Add(v6);
break;
case TDengineDataType.TSDB_DATA_TYPE_DOUBLE:
double v7 = (double)Marshal.PtrToStructure(data, typeof(double));
dataRaw.Add(v7);
break;
case TDengineDataType.TSDB_DATA_TYPE_BINARY:
string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
dataRaw.Add(v8);
break;
case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP:
long v9 = Marshal.ReadInt64(data);
dataRaw.Add(v9);
break;
case TDengineDataType.TSDB_DATA_TYPE_NCHAR:
string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
dataRaw.Add(v10);
break;
case TDengineDataType.TSDB_DATA_TYPE_UTINYINT:
byte v12 = Marshal.ReadByte(data);
dataRaw.Add(v12.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_USMALLINT:
ushort v13 = (ushort)Marshal.ReadInt16(data);
dataRaw.Add(v13);
break;
case TDengineDataType.TSDB_DATA_TYPE_UINT:
uint v14 = (uint)Marshal.ReadInt32(data);
dataRaw.Add(v14);
break;
case TDengineDataType.TSDB_DATA_TYPE_UBIGINT:
ulong v15 = (ulong)Marshal.ReadInt64(data);
dataRaw.Add(v15);
break;
case TDengineDataType.TSDB_DATA_TYPE_JSONTAG:
string v16 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
dataRaw.Add(v16);
break;
default:
dataRaw.Add("nonsupport data type");
break;
}
}
return dataRaw;
}
}
}
/*
* 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.Collections.Generic;
using System.Runtime.InteropServices;
/// <summary>
/// TDengine C# Driver.
/// </summary>
namespace TDengineDriver
{
/// <summary>
/// The enum indicate the data types and their code that TDengine supports.
/// </summary>
public enum TDengineDataType
{
TSDB_DATA_TYPE_NULL = 0, // 1 bytes
TSDB_DATA_TYPE_BOOL = 1, // 1 bytes
TSDB_DATA_TYPE_TINYINT = 2, // 1 bytes
TSDB_DATA_TYPE_SMALLINT = 3, // 2 bytes
TSDB_DATA_TYPE_INT = 4, // 4 bytes
TSDB_DATA_TYPE_BIGINT = 5, // 8 bytes
TSDB_DATA_TYPE_FLOAT = 6, // 4 bytes
TSDB_DATA_TYPE_DOUBLE = 7, // 8 bytes
TSDB_DATA_TYPE_BINARY = 8, // string
TSDB_DATA_TYPE_TIMESTAMP = 9,// 8 bytes
TSDB_DATA_TYPE_NCHAR = 10, // Unicode string
TSDB_DATA_TYPE_UTINYINT = 11,// 1 byte
TSDB_DATA_TYPE_USMALLINT = 12,// 2 bytes
TSDB_DATA_TYPE_UINT = 13, // 4 bytes
TSDB_DATA_TYPE_UBIGINT = 14, // 8 bytes
TSDB_DATA_TYPE_JSONTAG = 15 //4096 bytes
}
/// <summary>
/// Options that can be set before get TDegnine connection. Can set like locale,char-set,timezone,taos.cfg Dir
/// and connection active time.
/// </summary>
public enum TDengineInitOption
{
TSDB_OPTION_LOCALE = 0,
TSDB_OPTION_CHARSET = 1,
TSDB_OPTION_TIMEZONE = 2,
TSDB_OPTION_CONFIGDIR = 3,
TSDB_OPTION_SHELL_ACTIVITY_TIMER = 4
}
/// <summary>
/// This enum is used to indicate different TDengine's different schemaless protocol.
/// </summary>
public enum TDengineSchemalessProtocol
{
TSDB_SML_UNKNOWN_PROTOCOL = 0,
/// <summary>
/// Same as InfluxDB's line protocol.
/// </summary>
TSDB_SML_LINE_PROTOCOL = 1,
/// <summary>
/// Same as OpenTSDB's telnet protocol.
/// </summary>
TSDB_SML_TELNET_PROTOCOL = 2,
/// <summary>
/// Same as OpenTSDB's json protocol,can insert json format data.
/// </summary>
TSDB_SML_JSON_PROTOCOL = 3
}
/// <summary>
/// Precision string of the timestamps in the text data while using schemaless insert.
/// </summary>
public enum TDengineSchemalessPrecision
{
TSDB_SML_TIMESTAMP_NOT_CONFIGURED = 0,
TSDB_SML_TIMESTAMP_HOURS = 1,
TSDB_SML_TIMESTAMP_MINUTES = 2,
TSDB_SML_TIMESTAMP_SECONDS = 3,
TSDB_SML_TIMESTAMP_MILLI_SECONDS = 4,
TSDB_SML_TIMESTAMP_MICRO_SECONDS = 5,
TSDB_SML_TIMESTAMP_NANO_SECONDS = 6
}
enum TaosField
{
STRUCT_SIZE = 68,
NAME_LENGTH = 65,
TYPE_OFFSET = 65,
BYTES_OFFSET = 66,
}
/// <summary>
/// TDengine's meta info.
/// </summary>
public class TDengineMeta
{
/// <summary>
/// Retrieve result's column name.
/// </summary>
public string name;
/// <summary>
/// Column's length.(Unit bytes)
/// </summary>
public short size;
/// <summary>
/// Column type code from retrieved result. Correspond with <see cref="TDengineDataType"/>
/// </summary>
public byte type;
/// <summary>
/// Get the type name from retrieved result.
/// </summary>
/// <returns></returns>
public string TypeName()
{
switch ((TDengineDataType)type)
{
case TDengineDataType.TSDB_DATA_TYPE_BOOL:
return "BOOL";
case TDengineDataType.TSDB_DATA_TYPE_TINYINT:
return "TINYINT";
case TDengineDataType.TSDB_DATA_TYPE_SMALLINT:
return "SMALLINT";
case TDengineDataType.TSDB_DATA_TYPE_INT:
return "INT";
case TDengineDataType.TSDB_DATA_TYPE_BIGINT:
return "BIGINT";
case TDengineDataType.TSDB_DATA_TYPE_UTINYINT:
return "TINYINT UNSIGNED";
case TDengineDataType.TSDB_DATA_TYPE_USMALLINT:
return "SMALLINT UNSIGNED";
case TDengineDataType.TSDB_DATA_TYPE_UINT:
return "INT UNSIGNED";
case TDengineDataType.TSDB_DATA_TYPE_UBIGINT:
return "BIGINT UNSIGNED";
case TDengineDataType.TSDB_DATA_TYPE_FLOAT:
return "FLOAT";
case TDengineDataType.TSDB_DATA_TYPE_DOUBLE:
return "DOUBLE";
case TDengineDataType.TSDB_DATA_TYPE_BINARY:
return "BINARY";
case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP:
return "TIMESTAMP";
case TDengineDataType.TSDB_DATA_TYPE_NCHAR:
return "NCHAR";
case TDengineDataType.TSDB_DATA_TYPE_JSONTAG:
return "JSON";
default:
return "undefined";
}
}
}
/// <summary>
/// <c>TAOS_BIND</c> struct, used to hold a parameter(one value) while using "stmt insert".
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TAOS_BIND
{
/// <summary>
/// Indicate the <see cref="TDengineDataType"/> of data you want to bind.
/// </summary>
public int buffer_type;
/// <summary>
/// A reference point to the value you want to bind.
/// </summary>
public IntPtr buffer;
/// <summary>
/// Unused,but need to allocate space.
/// </summary>
public Int32 buffer_length;
/// <summary>
/// Actual value length in <see cref="buffer"/>.
/// </summary>
public IntPtr length;
/// <summary>
/// A reference to an variable to indicate if the column value is null or not
/// </summary>
public IntPtr is_null;
/// <summary>
/// Unused,but need to allocate space.
/// </summary>
public int is_unsigned;
/// <summary>
/// Unused,but need to allocate space.
/// </summary>
public IntPtr error;
/// <summary>
/// Unused,but need to allocate space.
/// </summary>
public Int64 u;
/// <summary>
/// Unused,but need to allocate space.
/// </summary>
public uint allocated;
}
/// <summary>
/// <c>TAOS_MULTI_BIND</c>struct,used to hold a multiple values while using "stmt bind".
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct TAOS_MULTI_BIND
{
/// <summary>
/// Indicate the <see cref="TDengineDataType"/> of data you want to bind.
/// </summary>
public int buffer_type;
/// <summary>
/// The reference point to the array which stores multiple lines column values you want to bind.
/// </summary>
public IntPtr buffer;
/// <summary>
/// Actual value length in <see cref="buffer"/>.
/// </summary>
public ulong buffer_length;
/// <summary>
/// A reference point to the array which stores actual data length for each value.
/// </summary>
public IntPtr length;
/// <summary>
/// A reference point to the array which stores identifies to indicate each value is null or not.
/// </summary>
public IntPtr is_null;
/// <summary>
/// Line number or the count of values in buffer.
/// </summary>
public int num;
}
/// <summary>
/// User defined callback function for interface <c><see cref="TDengine.QueryAsync(IntPtr, string, QueryAsyncCallback, IntPtr)"/></c>,actually is a delegate in .Net.
/// This function aim to handle the <c>taoRes</c> which points to the caller method's SQL result set.
/// </summary>
/// <param name="param">This parameter will sent by caller method (<see cref="TDengine.QueryAsync(IntPtr, string, QueryAsyncCallback, IntPtr)"/>)</param>
/// <param name="taoRes">This is the retrieved by caller method's SQL.</param>
/// <param name="code">0 for indicate operation success and negative for operation fail.</param>
public delegate void QueryAsyncCallback(IntPtr param, IntPtr taoRes, int code);
/// <summary>
/// User defined callback function for interface <c><see cref="TDengine.FetchRowAsync(IntPtr, FetchRowAsyncCallback, IntPtr)"/></c>,actually is a delegate in .Net.
/// This callback allow applications to get each row of the batch records by calling <c><see cref="TDengine.FetchRowAsync(IntPtr, FetchRowAsyncCallback, IntPtr)"/></c>
/// forward iteration.After reading all the records in a block, the application needs to continue calling
/// <c><see cref="TDengine.FetchRowAsync(IntPtr, FetchRowAsyncCallback, IntPtr)"/></c> in this callback function to obtain the next batch of records for
/// processing until the number of records is zero.
/// </summary>
/// <param name="param">The parameter passed by <c><see cref="TDengine.FetchRowAsync(IntPtr, FetchRowAsyncCallback, IntPtr)"/></c></param>
/// <param name="taoRes">Query Result.</param>
/// <param name="numOfRows"> The number of rows of data obtained (not a function of
/// the entire query result set). When the number is zero (the result is returned)
/// or the number of records is negative (the query fails).</param>
public delegate void FetchRowAsyncCallback(IntPtr param, IntPtr taoRes, int numOfRows);
/// <summary>
/// In asynchronous subscribe mode, the prototype of the callback function.
/// </summary>
/// <param name="subscribe">Subscription object return by <c><see cref="TDengine.Subscribe(IntPtr, bool, string, string, SubscribeCallback, IntPtr, int)"/></c></param>
/// <param name="tasRes">Query retrieve result set. (Note there may be no record in the result set.)</param>
/// <param name="param">Additional parameters supplied by the client when <c><see cref="TDengine.Subscribe(IntPtr, bool, string, string, SubscribeCallback, IntPtr, int)"/> is called.</c></param>
/// <param name="code">Error code.</param>
public delegate void SubscribeCallback(IntPtr subscribe, IntPtr tasRes, IntPtr param, int code);
/// <summary>
/// Defined this Driver's mainly APIs
/// </summary>
public class TDengine
{
/// <summary>
/// The success code return by major of this <c><see cref="TDengineDriver"/></c>'s operators.
/// </summary>
public const int TSDB_CODE_SUCCESS = 0;
/// <summary>
/// Initialize the running environment.
/// If the application does not actively call the API, the API will be automatically called when the application call
/// <c><see cref="Connect"/></c>, so the application generally does not need to call the API manually.
/// </summary>
[DllImport("taos", EntryPoint = "taos_init", CallingConvention = CallingConvention.Cdecl)]
static extern public void Init();
/// <summary>
/// Clean up the running environment and call this API before the application exits.
/// </summary>
[DllImport("taos", EntryPoint = "taos_cleanup", CallingConvention = CallingConvention.Cdecl)]
static extern public void Cleanup();
/// <summary>
/// Set client options, currently only time zone setting (_TSDB_OPTIONTIMEZONE)and encoding setting (_TSDB_OPTIONLOCALE) are supported.
/// The time zone and encoding default to the current operating system settings.
/// </summary>
/// <param name="option"></param>
/// <param name="value">When the return value is 0, it means success, and when it is -1, it means failure.</param>
[DllImport("taos", EntryPoint = "taos_options", CallingConvention = CallingConvention.Cdecl)]
static extern public void Options(int option, string value);
/// <summary>
/// Create a database connection and initialize the connection context. The parameters that need to be provided by user.
/// </summary>
/// <param name="ip"> FQDN used by TDengine to manage the master node.</param>
/// <param name="user">User name.</param>
/// <param name="password">Password</param>
/// <param name="db">Database name. If user does not provide it, it can be connected normally,
/// means user can create a new database through this connection.
/// If user provides a database name, means the user has created the database and the database is used by default</param>
/// <param name="port">Port number</param>
/// <returns>A null return value indicates a failure.
/// The application needs to save the returned parameters for subsequent API calls.
/// Note: The same process can connect to multiple taosd processes based on ip/port</returns>
[DllImport("taos", EntryPoint = "taos_connect", CallingConvention = CallingConvention.Cdecl)]
static extern public IntPtr Connect(string ip, string user, string password, string db, short port);
/// <summary>
/// Private function.Get the reason why the last API call failed, and the return value is a string.
/// Also see<seealso cref="Error"/>.
/// </summary>
/// <param name="res">Reference return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c></param>
/// <returns>Error reason.</returns>
[DllImport("taos", EntryPoint = "taos_errstr", CallingConvention = CallingConvention.Cdecl)]
static extern private IntPtr taos_errstr(IntPtr res);
/// <summary>
/// Public function,calling <c><see cref="taos_errstr"/></c> inside.Get the reason why the last API call failed, and the return value is a string.
/// Also see <c><seealso cref="taos_errstr"/></c>.
/// </summary>
/// <param name="res">Reference return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c>.</param>
/// <returns>Error reason.</returns>
static public string Error(IntPtr res)
{
IntPtr errPtr = taos_errstr(res);
return Marshal.PtrToStringAnsi(errPtr);
}
/// <summary>
/// Get the reason why the last API call failed, and the return value is the error code.
/// </summary>
/// <param name="res">Reference return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c>.</param>
/// <returns>Error code.</returns>
[DllImport("taos", EntryPoint = "taos_errno", CallingConvention = CallingConvention.Cdecl)]
static extern public int ErrorNo(IntPtr res);
/// <summary>
/// Private function.
/// This API is used to execute SQL statements, which can be DQL, DML or DDL statements.
/// </summary>
/// <param name="conn">The database connection returned by calling <c><see cref="Connect(string, string, string, string, short)"/></c>.</param>
/// <param name="byteArr">The SQL statement needed to execute.</param>
/// <returns>A reference point to the result.</returns>
[DllImport("taos", EntryPoint = "taos_query", CallingConvention = CallingConvention.Cdecl)]
// static extern public IntPtr Query(IntPtr conn, string sqlstr);
static extern private IntPtr Query(IntPtr conn, IntPtr byteArr);
/// <summary>
/// Public function.
/// This API is used to execute SQL statements, which can be DQL, DML or DDL statements.
/// Change the SQL command to UTF-8 to avoid error under Windows.
/// </summary>
/// <param name="conn">The database connection returned by calling <c><see cref="Connect(string, string, string, string, short)"/></c></param>
/// <param name="command">The SQL statement needed to execute.</param>
/// <returns>A reference point to the result.</returns>
static public IntPtr Query(IntPtr conn, string command)
{
IntPtr res = IntPtr.Zero;
IntPtr commandBuffer = Marshal.StringToCoTaskMemUTF8(command);
res = Query(conn, commandBuffer);
Marshal.FreeCoTaskMem(commandBuffer);
return res;
}
/// <summary>
/// Get the number of rows affected by the executed SQL statement.
/// </summary>
/// <param name="res">Result return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c>.</param>
/// <returns>Number of row have been affected.</returns>
[DllImport("taos", EntryPoint = "taos_affected_rows", CallingConvention = CallingConvention.Cdecl)]
static extern public int AffectRows(IntPtr res);
/// <summary>
/// Get the number of columns in the query result set.
/// </summary>
/// <param name="res">Result return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c>.</param>
/// <returns>Number of columns in the query result set</returns>
[DllImport("taos", EntryPoint = "taos_field_count", CallingConvention = CallingConvention.Cdecl)]
static extern public int FieldCount(IntPtr res);
/// <summary>
/// Get the attributes (data type, name, number of bytes) of each column of data in the query result set,
/// which can be used in conjunction with taos_num_files to parse the data of a tuple (one row) returned
/// by <c><see cref="FetchRows(IntPtr)"/></c>.
/// </summary>
/// <param name="res">Result return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c>.</param>
/// <returns>A reference point to the attributes (data type, name, number of bytes) of each column of data in the query result set.</returns>
[DllImport("taos", EntryPoint = "taos_fetch_fields", CallingConvention = CallingConvention.Cdecl)]
static extern private IntPtr taos_fetch_fields(IntPtr res);
/// <summary>
/// Get the attributes (data type, name, number of bytes) of each column of data in the query result set,
/// which can be used in conjunction with taos_num_files to parse the data of a tuple (one row) returned
/// by <c><see cref="FetchRows(IntPtr)"/></c>
/// </summary>
/// <param name="res">Result return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c>.</param>
/// <returns>A list of <see cref="TDengineMeta"/></returns>
static public List<TDengineMeta> FetchFields(IntPtr res)
{
List<TDengineMeta> metaList = new List<TDengineMeta>();
if (res == IntPtr.Zero)
{
return metaList;
}
int fieldCount = FieldCount(res);
IntPtr fieldsPtr = taos_fetch_fields(res);
for (int i = 0; i < fieldCount; ++i)
{
int offset = i * (int)TaosField.STRUCT_SIZE;
TDengineMeta meta = new TDengineMeta();
meta.name = Marshal.PtrToStringAnsi(fieldsPtr + offset);
meta.type = Marshal.ReadByte(fieldsPtr + offset + (int)TaosField.TYPE_OFFSET);
meta.size = Marshal.ReadInt16(fieldsPtr + offset + (int)TaosField.BYTES_OFFSET);
metaList.Add(meta);
}
return metaList;
}
/// <summary>
/// Get the data in the query result set by rows.
/// </summary>
/// <param name="res">Result return by APIs like <c><see cref="Query(IntPtr, IntPtr)"/></c>.</param>
/// <returns>Reference point to the query result set.</returns>
[DllImport("taos", EntryPoint = "taos_fetch_row", CallingConvention = CallingConvention.Cdecl)]
static extern public IntPtr FetchRows(IntPtr res);
/// <summary>
/// Release the query result set and related resources.
/// After the query is completed, be sure to call the API to release resources,
/// otherwise it may lead to application memory leakage. However,
/// it should also be noted that after releasing resources,
/// if you call functions such as <c><see cref="Consume(IntPtr)"/></c> to obtain query results,
/// it will lead the application to Crash.
/// </summary>
/// <param name="res">Reference point to the query result set.</param>
[DllImport("taos", EntryPoint = "taos_free_result", CallingConvention = CallingConvention.Cdecl)]
static extern public void FreeResult(IntPtr res);
/// <summary>
/// Close the connection.
/// </summary>
/// <param name="taos">Pointer returned by <c><see cref="Connect(string, string, string, string, short)"/></c> function.</param>
[DllImport("taos", EntryPoint = "taos_close", CallingConvention = CallingConvention.Cdecl)]
static extern public void Close(IntPtr taos);
//get precision of restultset
/// <summary>
/// The precision of the timestamp field in the returned result set.
/// </summary>
/// <param name="taos">Pointer returned by <c><see cref="Connect(string, string, string, string, short)"/></c> function.</param>
/// <returns> 0 for milliseconds, 1 for microseconds, and 2 for nanoseconds.</returns>
[DllImport("taos", EntryPoint = "taos_result_precision", CallingConvention = CallingConvention.Cdecl)]
static extern public int ResultPrecision(IntPtr taos);
//schemaless API
/// <summary>
/// In addition to writing data using SQL or using the parameter binding API, writing can also be done using Schemaless,
/// which eliminates the need to create a super table/data sub-table data structure in advance and writes data directly,
/// while the TDengine system automatically creates and maintains the required table structure based on the written data
/// content.
/// </summary>
/// <param name="taos">Database connection, the database connection established by <c><see cref="Connect(string, string, string, string, short)"/></c> function.</param>
/// <param name="lines">A pattern-free text string that meets the parsing format requirements.</param>
/// <param name="numLines">The number of lines of the text data, cannot be 0.</param>
/// <param name="protocol">The protocol type <c><seealso cref="TDengineSchemalessProtocol"/></c> of the lines, used to identify the format of the text data.</param>
/// <param name="precision">Precision <c><seealso cref="TDengineSchemalessPrecision"/></c> string of the timestamps in the text data.</param>
/// <returns></returns>
[DllImport("taos", SetLastError = true, EntryPoint = "taos_schemaless_insert", CallingConvention = CallingConvention.Cdecl)]
static extern public IntPtr SchemalessInsert(IntPtr taos, string[] lines, int numLines, int protocol, int precision);
//stmt APIs:
/// <summary>
/// init a TAOS_STMT object for later use.
/// </summary>
/// <param name="taos">a valid taos connection</param>
/// <returns>
/// Not NULL returned for success, NULL for failure. And it should be freed with taos_stmt_close.
/// </returns>
[DllImport("taos", EntryPoint = "taos_stmt_init", CallingConvention = CallingConvention.Cdecl)]
static extern public IntPtr StmtInit(IntPtr taos);
/// <summary>
/// prepare a sql statement,'sql' should be a valid INSERT/SELECT statement.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <param name="sql">sql string,used to bind parameters with</param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_prepare", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtPrepare(IntPtr stmt, string sql);
/// <summary>
/// For INSERT only. Used to bind table name as a parmeter for the input stmt object.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <param name="name">table name you want to bind</param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_set_tbname", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtSetTbname(IntPtr stmt, string name);
/// <summary>
/// For INSERT only.
/// Set a table name for binding table name as parameter. Only used for binding all tables
/// in one stable, user application must call 'loadTableInfo' API to load all table
/// meta before calling this API. If the table meta is not cached locally, it will return error.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <param name="name">table name which is belong to an stable</param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_set_sub_tbname", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtSetSubTbname(IntPtr stmt, string name);
/// <summary>
/// For INSERT only.
/// set a table name for binding table name as parameter and tag values for all tag parameters.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <param name="name">use to set table name</param>
/// <param name="tags">
/// is an array contains all tag values,each item in the array represents a tag column's value.
/// the item number and sequence should keep consistence with that in stable tag definition.
/// </param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_set_tbname_tags", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtSetTbnameTags(IntPtr stmt, string name, TAOS_BIND[] tags);
/// <summary>
/// For both INSERT and SELECT.
/// bind a whole line data.
/// The usage of structure TAOS_BIND is the same with MYSQL_BIND in MySQL.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <param name="bind">
/// points to an array contains the whole line data.
/// the item number and sequence should keep consistence with columns in sql statement.
/// </param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_bind_param", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
static extern public int StmtBindParam(IntPtr stmt, TAOS_BIND[] bind);
/// <summary>
/// bind a single column's data, INTERNAL used and for INSERT only.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <param name="bind">points to a column's data which could be the one or more lines. </param>
/// <param name="colIdx">the column's index in prepared sql statement, it starts from 0.</param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_bind_single_param_batch", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtBindSingleParamBatch(IntPtr stmt, ref TAOS_MULTI_BIND bind, int colIdx);
/// <summary>
/// for INSERT only
/// bind one or multiple lines data. The parameter 'bind'
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <param name="bind">
/// points to an array contains one or more lines data.Each item in array represents a column's value(s),
/// the item number and sequence should keep consistence with columns in sql statement.
/// </param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_bind_param_batch", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtBindParamBatch(IntPtr stmt, [In, Out] TAOS_MULTI_BIND[] bind);
/// <summary>
/// For INSERT only.
/// add all current bound parameters to batch process. Must be called after each call to
/// StmtBindParam/StmtBindSingleParamBatch, or all columns binds for one or more lines
/// with StmtBindSingleParamBatch. User application can call any bind parameter
/// API again to bind more data lines after calling to this API.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_add_batch", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtAddBatch(IntPtr stmt);
/// <summary>
/// actually execute the INSERT/SELECT sql statement.
/// User application can continue to bind new data after calling to this API.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <returns></returns>
[DllImport("taos", EntryPoint = "taos_stmt_execute", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtExecute(IntPtr stmt);
/// <summary>
/// For SELECT only,getting the query result. User application should free it with API 'FreeResult' at the end.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <returns>Not NULL for success, NULL for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_use_result", CallingConvention = CallingConvention.Cdecl)]
static extern public IntPtr StmtUseResult(IntPtr stmt);
/// <summary>
/// close STMT object and free resources.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <returns>0 for success, non-zero for failure.</returns>
[DllImport("taos", EntryPoint = "taos_stmt_close", CallingConvention = CallingConvention.Cdecl)]
static extern public int StmtClose(IntPtr stmt);
/// <summary>
/// user application must call this API to load all tables meta.
/// </summary>
/// <param name="taos">taos connection</param>
/// <param name="tableList">tablelist</param>
/// <returns></returns>
[DllImport("taos", EntryPoint = "taos_load_table_info", CallingConvention = CallingConvention.Cdecl)]
static extern private int LoadTableInfoDll(IntPtr taos, string tableList);
/// <summary>
/// user application call this API to load all tables meta,this method call the native
/// method LoadTableInfoDll.
/// this method must be called before StmtSetSubTbname(IntPtr stmt, string name);
/// </summary>
/// <param name="taos">taos connection</param>
/// <param name="tableList">tables need to load meta info are form in an array</param>
/// <returns></returns>
static public int LoadTableInfo(IntPtr taos, string[] tableList)
{
string listStr = string.Join(",", tableList);
return LoadTableInfoDll(taos, listStr);
}
/// <summary>
/// get detail error message when got failure for any stmt API call. If not failure, the result
/// returned in this API is unknown.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <returns>point the error message</returns>
[DllImport("taos", EntryPoint = "taos_stmt_errstr", CallingConvention = CallingConvention.Cdecl)]
static extern private IntPtr StmtErrPtr(IntPtr stmt);
/// <summary>
/// get detail error message when got failure for any stmt API call. If not failure, the result
/// returned in this API is unknown.
/// </summary>
/// <param name="stmt">could be the value returned by 'StmtInit', that may be a valid object or NULL.</param>
/// <returns>error string</returns>
static public string StmtErrorStr(IntPtr stmt)
{
IntPtr stmtErrPrt = StmtErrPtr(stmt);
return Marshal.PtrToStringAnsi(stmtErrPrt);
}
[DllImport("taos", EntryPoint = "taos_fetch_lengths", CallingConvention = CallingConvention.Cdecl)]
static extern public IntPtr FetchLengths(IntPtr taos);
// Async Query
/// <summary>
/// This API uses non-blocking call mode.
/// Application can open multiple tables and manipulate(query or insert) opened table concurrently.
/// So applications must ensure that opetations on the same table is completely serialized.
/// Because that will cause some query and insert operations cannot be performed.
/// </summary>
/// <param name="taos"> A taos connection return by Connect()</param>
/// <param name="sql">sql command need to execute</param>
/// <param name="fq">User-defined callback function. <see cref="QueryAsyncCallback"/></param>
/// <param name="param">the parameter for callback</param>
[DllImport("taos", EntryPoint = "taos_query_a", CallingConvention = CallingConvention.Cdecl)]
static extern public void QueryAsync(IntPtr taos, string sql, QueryAsyncCallback fq, IntPtr param);
/// <summary>
/// Get the result set of asynchronous queries in batch,
/// which can only be used with QueryAsync().<c>FetchRowAsyncCallback</c>
/// </summary>
/// <param name="taoRes"> The result set returned when backcall QueryAsyncCallback </param>
/// <param name="fq"> Callback function.<see cref="FetchRowAsyncCallback"/></param>
/// <param name="param"> The parameter for callback FetchRowAsyncCallback </param>
[DllImport("taos", EntryPoint = "taos_fetch_rows_a", CallingConvention = CallingConvention.Cdecl)]
static extern public void FetchRowAsync(IntPtr taoRes, FetchRowAsyncCallback fq, IntPtr param);
// Subscribe
/// <summary>
/// This function is used for start subscription service.
/// </summary>
/// <param name="taos"> taos connection return by <see cref = "Connect"></see></param>
/// <param name="restart">If the subscription is already exists, to decide whether to
/// start over or continue with previous subscription.</param>
/// <param name="topic"> The name of the subscription.(This is the unique identification of the subscription).</param>
/// <param name="sql">The subscribe statement(select only).Only query original data and in positive time sequence.</param>
/// <param name="fq">The callback function when the query result is received.</param>
/// <param name="param"> Additional parameter when calling callback function. System API will pass it to
/// callback function without any operations.It is only used when calling asynchronously,
/// and this parameter should be passed to NULL when calling synchronously</param>
/// <param name="interval">Polling period in milliseconds. During asynchronous call, the callback function will be
/// called periodically according to this parameter; In order to avoid affecting system
/// performance, it is not recommended to set this parameter too small; When calling synchronously,
/// if the interval between two calls to taos_consume is less than this period, the API will block
/// until the interval exceeds this period.</param>
/// <returns>Return null for failure, return subscribe object for success.</returns>
[DllImport("taos", EntryPoint = "taos_subscribe", CallingConvention = CallingConvention.Cdecl)]
static extern private IntPtr Subscribe(IntPtr taos, int restart, string topic, string sql, SubscribeCallback fq, IntPtr param, int interval);
/// <summary>
/// This function is used for start subscription service.
/// </summary>
/// <param name="taos"> taos connection return by <see cref = "Connect"></see></param>
/// <param name="restart">If the subscription is already exists, to decide whether to
/// start over or continue with previous subscription.</param>
/// <param name="topic"> The name of the subscription.(This is the unique identification of the subscription).</param>
/// <param name="sql">The subscribe statement(select only).Only query original data and in positive time sequence.</param>
/// <param name="fq">The callback function <c><see cref="TDengineDriver.SubscribeCallback"/></c>when the query result is received.</param>
/// <param name="param"> Additional parameter when calling callback function. System API will pass it to
/// callback function without any operations.It is only used when calling asynchronously,
/// and this parameter should be passed to NULL when calling synchronously</param>
/// <param name="interval">Polling period in milliseconds. During asynchronous call, the callback function will be
/// called periodically according to this parameter; In order to avoid affecting system
/// performance, it is not recommended to set this parameter too small; When calling synchronously,
/// if the interval between two calls to taos_consume is less than this period, the API will block
/// until the interval exceeds this period.</param>
/// <returns>Return null for failure, return subscribe object for success.</returns>
/// <exception cref="Exception"></exception>
static public IntPtr Subscribe(IntPtr taos, bool restart, string topic, string sql, SubscribeCallback fq, IntPtr param, int interval)
{
if (taos == IntPtr.Zero)
{
Console.WriteLine("taos connect is null,subscribe failed");
throw new Exception("taos connect is null");
}
else
{
IntPtr subPtr = Subscribe(taos, restart == true ? 1 : 0, topic, sql, fq, param, interval);
return subPtr;
}
}
/// <summary>
/// Only synchronous mode, this function is used to get the result of subscription.
/// If the interval between two calls to taos_consume is less than the polling
/// cycle of the subscription, the API will block until the interval exceeds this
/// cycle. If a new record arrives in the database, the API will return the latest
/// record, otherwise it will return an empty result set with no records.
/// If the return value is NULL, it indicates a system error.
/// </summary>
/// <param name="subscribe"> Subscription object return by <c><see cref="Subscribe(IntPtr, bool, string, string, SubscribeCallback, IntPtr, int)"/></c> </param>
/// <returns>A result set. The data retrieve by consumer.</returns>
[DllImport("taos", EntryPoint = "taos_consume", CallingConvention = CallingConvention.Cdecl)]
static extern private IntPtr TaosConsume(IntPtr subscribe);
/// <summary>
/// Only synchronous mode, this function is used to get the result of subscription.
/// If the interval between two calls to taos_consume is less than the polling
/// cycle of the subscription, the API will block until the interval exceeds this
/// cycle. If a new record arrives in the database, the API will return the latest
/// record, otherwise it will return an empty result set with no records.
/// If the return value is NULL, it indicates a system error.
/// </summary>
/// <param name="subscribe"> Subscription object return by <c><see cref="Subscribe(IntPtr, bool, string, string, SubscribeCallback, IntPtr, int)"/></c> </param>
/// <returns></returns>
static public IntPtr Consume(IntPtr subscribe)
{
IntPtr res = IntPtr.Zero;
if (subscribe == IntPtr.Zero)
{
Console.WriteLine("Object subscribe is null,please subscribe first.");
throw new Exception("Object subscribe is null");
}
else
{
res = TaosConsume(subscribe);
}
return res;
}
/// <summary>
/// Unsubscribe.
/// </summary>
/// <param name="subscribe"> Subscription object return by "Subscribe" </param>
/// <param name="keep"> If it is not 0, the API will keep the progress of subscription,
/// and the and the subsequent call to taos_subscribe can continue
/// based on this progress; otherwise, the progress information will
/// be deleted and the data can only be read again.
/// </param>
[DllImport("taos", EntryPoint = "taos_unsubscribe", CallingConvention = CallingConvention.Cdecl)]
static extern private void Unsubscribe(IntPtr subscribe, int keep);
/// <summary>
/// Unsubscribe.
/// </summary>
/// <param name="subscribe"> Subscription object return by "Subscribe" </param>
/// <param name="keep"> If it is not true, the API will keep the progress of subscription,
/// and the and the subsequent call to taos_subscribe can continue
/// based on this progress; otherwise, the progress information will
/// be deleted and the data can only be read again.
/// </param>
/// <exception cref="Exception"></exception>
static public void Unsubscribe(IntPtr subscribe, bool keep)
{
if (subscribe == IntPtr.Zero)
{
Console.WriteLine("subscribe is null, close Unsubscribe failed");
throw new Exception("Object subscribe is null");
}
else
{
Unsubscribe(subscribe, keep == true ? 1 : 0);
Console.WriteLine("Unsubscribe success.");
}
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net5;netstandard2.1;</TargetFrameworks>
<PackageId>TDengine.Connector</PackageId>
<PackageIcon>logo.jpg</PackageIcon>
<Version>1.0.6</Version>
<Authors>taosdata</Authors>
<Company>www.taosdata.com</Company>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>Taos;Data;Microsoft.NET.Sdk;IOT;bigdata;TDengine;taosdata</PackageTags>
<Description>
This is the C# connector's classlib that lets you connect to TDengine.
This C # connector supports: Linux 64/Windows x64/Windows x86.
more information please visit: https://www.taosdata.com
</Description>
<RepositoryUrl>https://github.com/taosdata/TDengine/tree/develop/src/connector/C%2523/src/TDengineDriver</RepositoryUrl>
<NoWarn>CS1591;CS0168;CS1587</NoWarn>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>.\doc\TDengineDriver.XML</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<None Include="resource\logo.jpg" Pack="true" PackagePath="\" />
</ItemGroup>
</Project>
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace TDengineDriver
{
/// <summary>
/// this class used to get an instance of struct of TAO_BIND or TAOS_MULTI_BIND
/// And the instance is corresponding with TDengine data type. For example, calling
/// "bindBinary" will return a TAOS_BIND object that is corresponding with TDengine's
/// binary type.
/// </summary>
public class TaosBind
{
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_BOOL"/></c>.
/// </summary>
/// <param name="val">A not null boolean value.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindBool(bool val)
{
TAOS_BIND bind = new TAOS_BIND();
byte[] boolByteArr = BitConverter.GetBytes(val);
int boolByteArrSize = Marshal.SizeOf(boolByteArr[0]) * boolByteArr.Length;
IntPtr c_bool = Marshal.AllocHGlobal(1);
Marshal.Copy(boolByteArr, 0, c_bool, boolByteArr.Length);
int length = sizeof(Boolean);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BOOL;
bind.buffer = c_bool;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_TINYINT"/></c>.
/// </summary>
/// <param name="val">A not null sbyte. </param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindTinyInt(sbyte val)
{
TAOS_BIND bind = new TAOS_BIND();
byte[] tinyIntByteArr = BitConverter.GetBytes(val);
int tinyIntByteArrSize = Marshal.SizeOf(tinyIntByteArr[0]) * tinyIntByteArr.Length;
IntPtr c_tinyint = Marshal.AllocHGlobal(tinyIntByteArrSize);
Marshal.Copy(tinyIntByteArr, 0, c_tinyint, tinyIntByteArr.Length);
int length = sizeof(sbyte);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TINYINT;
bind.buffer = c_tinyint;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_SMALLINT"/></c>.
/// </summary>
/// <param name="val">A not null short value.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindSmallInt(short val)
{
TAOS_BIND bind = new TAOS_BIND();
IntPtr c_smallint = Marshal.AllocHGlobal(sizeof(short));
Marshal.WriteInt16(c_smallint, val);
int length = sizeof(short);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_SMALLINT;
bind.buffer = c_smallint;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_INT"/></c>.
/// </summary>
/// <param name="val">A not null int value.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindInt(int val)
{
TAOS_BIND bind = new TAOS_BIND();
IntPtr c_int = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(c_int, val);
int length = sizeof(int);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_INT;
bind.buffer = c_int;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_BIGINT"/></c>.
/// </summary>
/// <param name="val">A not null long value.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindBigInt(long val)
{
TAOS_BIND bind = new TAOS_BIND();
IntPtr c_bigint = Marshal.AllocHGlobal(sizeof(long));
Marshal.WriteInt64(c_bigint, val);
int length = sizeof(long);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BIGINT;
bind.buffer = c_bigint;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_UTINYINT"/></c>.
/// </summary>
/// <param name="val">An unsigned byte and can be null.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindUTinyInt(byte val)
{
TAOS_BIND bind = new TAOS_BIND();
IntPtr c_unsigned_tinyint = Marshal.AllocHGlobal(sizeof(byte));
Marshal.WriteByte(c_unsigned_tinyint, val);
int length = sizeof(byte);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UTINYINT;
bind.buffer = c_unsigned_tinyint;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_USMALLINT"/></c>.
/// </summary>
/// <param name="val">A not null Uint16.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindUSmallInt(UInt16 val)
{
TAOS_BIND bind = new TAOS_BIND();
byte[] uSmallIntByteArr = BitConverter.GetBytes(val);
int usmallSize = Marshal.SizeOf(uSmallIntByteArr[0]) * uSmallIntByteArr.Length;
IntPtr c_unsigned_smallint = Marshal.AllocHGlobal(usmallSize);
Marshal.Copy(uSmallIntByteArr, 0, c_unsigned_smallint, uSmallIntByteArr.Length);
int length = sizeof(UInt16);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_USMALLINT;
bind.buffer = c_unsigned_smallint;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_UINT"/></c>.
/// </summary>
/// <param name="val">A not null uint.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindUInt(uint val)
{
TAOS_BIND bind = new TAOS_BIND();
byte[] byteArr = BitConverter.GetBytes(val);
int usmallSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length;
IntPtr c_unsigned_int = Marshal.AllocHGlobal(usmallSize);
Marshal.Copy(byteArr, 0, c_unsigned_int, byteArr.Length);
int length = sizeof(uint);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UINT;
bind.buffer = c_unsigned_int;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_UBIGINT"/></c>.
/// </summary>
/// <param name="val">A not null ulong.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindUBigInt(ulong val)
{
TAOS_BIND bind = new TAOS_BIND();
byte[] byteArr = BitConverter.GetBytes(val);
int usmallSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length;
IntPtr c_unsigned_bigint = Marshal.AllocHGlobal(usmallSize);
Marshal.Copy(byteArr, 0, c_unsigned_bigint, byteArr.Length);
int length = sizeof(ulong);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UBIGINT;
bind.buffer = c_unsigned_bigint;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_FLOAT"/></c>.
/// </summary>
/// <param name="val">A not null float.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindFloat(float val)
{
TAOS_BIND bind = new TAOS_BIND();
byte[] byteArr = BitConverter.GetBytes(val);
int floatByteArrSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length;
IntPtr c_float = Marshal.AllocHGlobal(floatByteArrSize);
Marshal.Copy(byteArr, 0, c_float, byteArr.Length);
int length = sizeof(float);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_FLOAT;
bind.buffer = c_float;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_DOUBLE"/></c>.
/// </summary>
/// <param name="val">A not null double.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindDouble(Double val)
{
TAOS_BIND bind = new TAOS_BIND();
byte[] byteArr = BitConverter.GetBytes(val);
int doubleByteArrSize = Marshal.SizeOf(byteArr[0]) * byteArr.Length;
IntPtr c_double = Marshal.AllocHGlobal(doubleByteArrSize);
Marshal.Copy(byteArr, 0, c_double, byteArr.Length);
int length = sizeof(Double);
IntPtr lengthPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_DOUBLE;
bind.buffer = c_double;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_BINARY"/></c>.
/// </summary>
/// <param name="val">A not null string.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindBinary(String val)
{
TAOS_BIND bind = new TAOS_BIND();
// IntPtr unmanagedBinary = Marshal.StringToHGlobalAnsi(val);
IntPtr c_str = Marshal.StringToCoTaskMemUTF8(val);
var strToBytes = System.Text.Encoding.UTF8.GetBytes(val);
int length = strToBytes.Length;
IntPtr lenPtr = Marshal.AllocHGlobal(sizeof(ulong));
Marshal.WriteInt64(lenPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BINARY;
bind.buffer = c_str;
bind.buffer_length = length;
bind.length = lenPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_NCHAR"/></c>.
/// </summary>
/// <param name="val">A not null string.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindNchar(String val)
{
TAOS_BIND bind = new TAOS_BIND();
var strToBytes = System.Text.Encoding.UTF8.GetBytes(val);
// IntPtr unmanagedNchar = (IntPtr)Marshal.StringToHGlobalAnsi(val);
IntPtr c_str = (IntPtr)Marshal.StringToCoTaskMemUTF8(val);
int length = strToBytes.Length;
IntPtr lenPtr = Marshal.AllocHGlobal(sizeof(ulong));
Marshal.WriteInt64(lenPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_NCHAR;
bind.buffer = c_str;
bind.buffer_length = length;
bind.length = lenPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_NULL"/></c>.
/// </summary>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindNil()
{
TAOS_BIND bind = new TAOS_BIND();
int isNull = 1;//IntPtr.Size;
IntPtr lenPtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(lenPtr, isNull);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_NULL;
bind.is_null = lenPtr;
return bind;
}
/// <summary>
/// Used to bind TDengine's <c><see cref="TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP"/></c>.
/// </summary>
/// <param name="ts">A not null long.</param>
/// <returns><c><see cref="TAOS_BIND"/></c></returns>
public static TAOS_BIND BindTimestamp(long ts)
{
TAOS_BIND bind = new TAOS_BIND();
IntPtr c_long = Marshal.AllocHGlobal(sizeof(long));
Marshal.WriteInt64(c_long, ts);
int length = sizeof(long);
IntPtr lengthPtr = Marshal.AllocHGlobal(4);
Marshal.WriteInt32(lengthPtr, length);
bind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP;
bind.buffer = c_long;
bind.buffer_length = length;
bind.length = lengthPtr;
bind.is_null = IntPtr.Zero;
return bind;
}
/// <summary>
/// Used to free allocated unmanaged memory.
/// </summary>
/// <param name="binds">An array of <see cref="TAOS_BIND"/></param>
public static void FreeTaosBind(TAOS_BIND[] binds)
{
foreach (TAOS_BIND bind in binds)
{
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
if (bind.is_null != IntPtr.Zero)
{
// Console.WriteLine(bind.is_null);
Marshal.FreeHGlobal(bind.is_null);
}
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace TDengineDriver
{
/// <summary>
/// Using to bind different columns types in multiple rows.
/// </summary>
public class TaosMultiBind
{
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_BOOL"/></c> values.
/// </summary>
/// <param name="arr">A nullable boolean array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindBool(bool?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
//the size of buffer array element
int typeSize = sizeof(bool);
//size of int
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//TAOS_MULTI_BIND.buffer
IntPtr c_bool_ptr = Marshal.AllocHGlobal(elementCount * typeSize);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteByte(c_bool_ptr, typeSize * i, Convert.ToByte(arr[i] ?? false));
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BOOL;
multiBind.buffer = c_bool_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_TINYINT"/></c> values.
/// </summary>
/// <param name="arr">A nullable sbyte array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindTinyInt(sbyte?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
//the size of buffer array element
int typeSize = sizeof(byte);
int byteSize = sizeof(byte);
//size of int
int intSize = sizeof(int);
//TAOS_MULTI_BIND.buffer
IntPtr c_tinyint_ptr = Marshal.AllocHGlobal(elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(intSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
Byte[] toByteArr = BitConverter.GetBytes(arr[i] ?? sbyte.MinValue);
//set TAOS_MULTI_BIND.buffer
Marshal.WriteByte(c_tinyint_ptr, typeSize * i, toByteArr[0]);
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TINYINT;
multiBind.buffer = c_tinyint_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_SMALLINT"/></c> values.
/// </summary>
/// <param name="arr">A nullable short array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindSmallInt(short?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
//the size of buffer array element
int typeSize = sizeof(short);
//size of int
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//TAOS_MULTI_BIND.buffer
IntPtr c_smallint_ptr = Marshal.AllocHGlobal(elementCount * typeSize);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteInt16(c_smallint_ptr, typeSize * i, arr[i] ?? short.MinValue);
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_SMALLINT;
multiBind.buffer = c_smallint_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_INT"/></c> values.
/// </summary>
/// <param name="arr">A nullable int array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindInt(int?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(int);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//TAOS_MULTI_BIND.buffer
IntPtr c_int_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteInt32(c_int_ptr, typeSize * i, arr[i] ?? int.MinValue);
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_INT;
multiBind.buffer = c_int_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_BIGINT"/></c> values.
/// </summary>
/// <param name="arr">A nullable long array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindBigint(long?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(long);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//TAOS_MULTI_BIND.buffer
IntPtr c_long_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteInt64(c_long_ptr, typeSize * i, arr[i] ?? long.MinValue);
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BIGINT;
multiBind.buffer = c_long_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_FLOAT"/></c> values.
/// </summary>
/// <param name="arr">A nullable float array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindFloat(float?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(float);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//used to replace null
float[] arrTmp = new float[elementCount];
//TAOS_MULTI_BIND.buffer
IntPtr c_float_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
arrTmp[i] = arr[i] ?? float.MinValue;
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//set TAOS_MULTI_BIND.buffer
Marshal.Copy(arrTmp, 0, c_float_ptr, elementCount);
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_FLOAT;
multiBind.buffer = c_float_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_DOUBLE"/></c> values.
/// </summary>
/// <param name="arr">A nullable double array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindDouble(double?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(double);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//used to replace null
double[] arrTmp = new double[elementCount];
//TAOS_MULTI_BIND.buffer
IntPtr c_double_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
arrTmp[i] = arr[i] ?? double.MinValue;
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//set TAOS_MULTI_BIND.buffer
Marshal.Copy(arrTmp, 0, c_double_ptr, elementCount);
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_DOUBLE;
multiBind.buffer = c_double_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_UTINYINT"/></c> values.
/// </summary>
/// <param name="arr">A nullable byte array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindUTinyInt(byte?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(byte);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//used to replace null
//TAOS_MULTI_BIND.buffer
IntPtr c_unsigned_tinyint_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteByte(c_unsigned_tinyint_ptr, typeSize * i, arr[i] ?? byte.MaxValue);
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UTINYINT;
multiBind.buffer = c_unsigned_tinyint_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_USMALLINT"/></c> values.
/// </summary>
/// <param name="arr">A nullable ushort array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindUSmallInt(ushort?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(ushort);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//used to replace null
//TAOS_MULTI_BIND.buffer
IntPtr c_unsigned_smallint_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
byte[] byteArr = BitConverter.GetBytes(arr[i] ?? ushort.MaxValue);
for (int j = 0; j < byteArr.Length; j++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteByte(c_unsigned_smallint_ptr, typeSize * i + j * byteSize, byteArr[j]);
}
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_USMALLINT;
multiBind.buffer = c_unsigned_smallint_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_UINT"/></c> values.
/// </summary>
/// <param name="arr">A nullable uint array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindUInt(uint?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(uint);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//used to replace null
//TAOS_MULTI_BIND.buffer
IntPtr c_unsigned_int_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
byte[] byteArr = BitConverter.GetBytes(arr[i] ?? uint.MaxValue);
for (int j = 0; j < byteArr.Length; j++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteByte(c_unsigned_int_ptr, typeSize * i + j * byteSize, byteArr[j]);
}
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UINT;
multiBind.buffer = c_unsigned_int_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_UBIGINT"/></c> values.
/// </summary>
/// <param name="arr">A nullable ulong array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindUBigInt(ulong?[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(ulong);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//used to replace null
//TAOS_MULTI_BIND.buffer
IntPtr c_unsigned_bigint_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
byte[] byteArr = BitConverter.GetBytes(arr[i] ?? ulong.MaxValue);
for (int j = 0; j < byteArr.Length; j++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteByte(c_unsigned_bigint_ptr, typeSize * i + j * byteSize, byteArr[j]);
}
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(arr[i].Equals(null) ? 1 : 0));
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_UBIGINT;
multiBind.buffer = c_unsigned_bigint_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_BINARY"/></c> values.
/// </summary>
/// <param name="arr">A nullable string array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindBinary(string[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
//TypeSize represent the Max element length of the comming arr
//The size of the buffer is typeSize * elementCount
//This buffer is used to store TAOS_MULTI_BIND.buffer
int typeSize = MaxElementLength(arr);
//This intSize is used to calculate buffer size of the struct TAOS_MULTI_BIND's
//length. The buffer is intSize * elementCount,which is used to store TAOS_MULTI_BIND.length
int intSize = sizeof(int);
//This byteSize is used to calculate the buffer size of the struct TAOS_MULTI_BIND.is_null
//This buffer size is byteSize * elementCount
int byteSize = sizeof(byte);
StringBuilder arrStrBuilder = new StringBuilder(); ;
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
//TAOS_MULTI_BIND.buffer
IntPtr c_char_prt = Marshal.AllocHGlobal(typeSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
int itemLength = 0;
byte[] decodeByte = GetStringEncodeByte(arr[i]);
itemLength = decodeByte.Length;
if (!String.IsNullOrEmpty(arr[i]))
{
for (int j = 0; j < itemLength; j++)
{
//Read byte after byte
Marshal.WriteByte(c_char_prt, i * typeSize + j, decodeByte[j]);
}
}
//Set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, itemLength);
//Set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(String.IsNullOrEmpty(arr[i]) ? 1 : 0));
}
//Config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_BINARY;
multiBind.buffer = c_char_prt;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_NCHAR"/></c> values.
/// </summary>
/// <param name="arr">A nullable string array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindNchar(string[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
//TypeSize represent the Max element length of the comming arr
//The size of the buffer is typeSize * elementCount
//This buffer is used to store TAOS_MULTI_BIND.buffer
int typeSize = MaxElementLength(arr);
//This intSize is used to calculate buffer size of the struct TAOS_MULTI_BIND's
//length. The buffer is intSize * elementCount,which is used to store TAOS_MULTI_BIND.length
int intSize = sizeof(int);
//This byteSize is used to calculate the buffer size of the struct TAOS_MULTI_BIND.is_null
//This buffer size is byteSize * elementCount
int byteSize = sizeof(byte);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
//TAOS_MULTI_BIND.buffer
IntPtr c_char_prt = Marshal.AllocHGlobal(typeSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
int itemLength = 0;
byte[] decodeByte = GetStringEncodeByte(arr[i]);
itemLength = decodeByte.Length;
if (!String.IsNullOrEmpty(arr[i]))
{
for (int j = 0; j < itemLength; j++)
{
//Read byte after byte
Marshal.WriteByte(c_char_prt, i * typeSize + j, decodeByte[j]);
}
}
//Set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, itemLength);
//Set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, Convert.ToByte(String.IsNullOrEmpty(arr[i]) ? 1 : 0));
}
//Config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_NCHAR;
multiBind.buffer = c_char_prt;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Using to bind a array of <c><see cref="TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP"/></c> values.
/// </summary>
/// <param name="arr">A nullable long array.</param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static TAOS_MULTI_BIND MultiBindTimestamp(long[] arr)
{
TAOS_MULTI_BIND multiBind = new TAOS_MULTI_BIND();
int elementCount = arr.Length;
int typeSize = sizeof(long);
int intSize = sizeof(int);
int byteSize = sizeof(byte);
//TAOS_MULTI_BIND.buffer
IntPtr c_long_ptr = Marshal.AllocHGlobal(typeSize * elementCount);
//TAOS_MULTI_BIND.length
IntPtr lengthArr = Marshal.AllocHGlobal(intSize * elementCount);
//TAOS_MULTI_BIND.is_null
IntPtr nullArr = Marshal.AllocHGlobal(byteSize * elementCount);
for (int i = 0; i < elementCount; i++)
{
//set TAOS_MULTI_BIND.buffer
Marshal.WriteInt64(c_long_ptr, typeSize * i, arr[i]);
//set TAOS_MULTI_BIND.length
Marshal.WriteInt32(lengthArr, intSize * i, typeSize);
//set TAOS_MULTI_BIND.is_null
Marshal.WriteByte(nullArr, byteSize * i, 0);
}
//config TAOS_MULTI_BIND
multiBind.buffer_type = (int)TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP;
multiBind.buffer = c_long_ptr;
multiBind.buffer_length = (ulong)typeSize;
multiBind.length = lengthArr;
multiBind.is_null = nullArr;
multiBind.num = elementCount;
return multiBind;
}
/// <summary>
/// Used to free allocated unmanaged memory.
/// </summary>
/// <param name="mBinds">The <c><see cref="TAOS_MULTI_BIND"/></c> array have been instantiated. </param>
/// <returns><see cref="TAOS_MULTI_BIND"/></returns>
public static void FreeTaosBind(TAOS_MULTI_BIND[] mBinds)
{
foreach (TAOS_MULTI_BIND bind in mBinds)
{
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
Marshal.FreeHGlobal(bind.is_null);
}
}
/// <summary>
/// Used to initial a char array with given length.
/// </summary>
/// <param name="length">The length you want to initial.</param>
/// <returns>A char array.</returns>
private static char[] AlignCharArr(int length)
{
char[] alignChar = new char[length];
for (int i = 0; i < length; i++)
{
alignChar[i] = char.MinValue;
}
return alignChar;
}
/// <summary>
/// Calculate the max length of the element in the string array.
/// </summary>
/// <param name="strArr">A string array.</param>
/// <returns>Max length.</returns>
private static int MaxElementLength(String[] strArr)
{
int max = 0;
for (int i = 0; i < strArr.Length; i++)
{
int tmpLength = GetStringEncodeByte(strArr[i]).Length;
if (!String.IsNullOrEmpty(strArr[i]) && max < tmpLength)
{
max = tmpLength;
}
}
return max;
}
/// <summary>
/// Change the string to Byte Array.
/// </summary>
/// <param name="str">string</param>
/// <returns>Byte array.</returns>
private static Byte[] GetStringEncodeByte(string str)
{
Byte[] strToBytes = null;
if (String.IsNullOrEmpty(str))
{
strToBytes = System.Text.Encoding.Default.GetBytes(String.Empty);
}
else
{
strToBytes = System.Text.Encoding.Default.GetBytes(str);
}
return strToBytes;
}
}
}
\ No newline at end of file
using System;
using Test.UtilsTools;
using TDengineDriver;
using System.Collections.Generic;
namespace Test.UtilsTools.DataSource
{
public class DataSource
{
public static long[] tsArr = new long[5] { 1637064040000, 1637064041000, 1637064042000, 1637064043000, 1637064044000 };
public static bool?[] boolArr = new bool?[5] { true, false, null, true, true };
public static sbyte?[] tinyIntArr = new sbyte?[5] { -127, 0, null, 8, 127 };
public static short?[] shortArr = new short?[5] { short.MinValue + 1, -200, null, 100, short.MaxValue };
public static int?[] intArr = new int?[5] { -200, -100, null, 0, 300 };
public static long?[] longArr = new long?[5] { long.MinValue + 1, -2000, null, 1000, long.MaxValue };
public static float?[] floatArr = new float?[5] { float.MinValue + 1, -12.1F, null, 0F, float.MaxValue };
public static double?[] doubleArr = new double?[5] { double.MinValue + 1, -19.112D, null, 0D, double.MaxValue };
public static byte?[] uTinyIntArr = new byte?[5] { byte.MinValue, 12, null, 89, byte.MaxValue - 1 };
public static ushort?[] uShortArr = new ushort?[5] { ushort.MinValue, 200, null, 400, ushort.MaxValue - 1 };
public static uint?[] uIntArr = new uint?[5] { uint.MinValue, 100, null, 2, uint.MaxValue - 1 };
public static ulong?[] uLongArr = new ulong?[5] { ulong.MinValue, 2000, null, 1000, long.MaxValue - 1 };
public static string[] binaryArr = new string[5] { "1234567890~!@#$%^&*()_+=-`[]{}:,./<>?", String.Empty, null, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890~!@#$%^&*()_+=-`[]{}:,./<>?" };
public static string[] ncharArr = new string[5] { "1234567890~!@#$%^&*()_+=-`[]{}:,./<>?", null, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890~!@#$%^&*()_+=-`[]{}:,./<>?", string.Empty };
public static string[] binaryArrCn = new string[5] { "涛思数据", String.Empty, null, "taosdata涛思数据", "涛思数据TDengine" };
public static string[] NcharArrCn = new string[5] { "涛思数据", null, "taosdata涛思数据", "涛思数据TDengine", String.Empty };
// Construct a TAOS_BIND array which contains normal character.
// For stmt bind tags,this will be used as tag info
public static TAOS_BIND[] GetTags()
{
TAOS_BIND[] binds = new TAOS_BIND[13];
binds[0] = TaosBind.BindBool(true);
binds[1] = TaosBind.BindTinyInt(-2);
binds[2] = TaosBind.BindSmallInt(short.MaxValue);
binds[3] = TaosBind.BindInt(int.MaxValue);
binds[4] = TaosBind.BindBigInt(Int64.MaxValue);
binds[5] = TaosBind.BindUTinyInt(byte.MaxValue - 1);
binds[6] = TaosBind.BindUSmallInt(UInt16.MaxValue - 1);
binds[7] = TaosBind.BindUInt(uint.MinValue + 1);
binds[8] = TaosBind.BindUBigInt(UInt64.MinValue + 1);
binds[9] = TaosBind.BindFloat(11.11F);
binds[10] = TaosBind.BindDouble(22.22D);
binds[11] = TaosBind.BindBinary("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}");
binds[12] = TaosBind.BindNchar("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}");
return binds;
}
// Get the tag data within and string list
// Which will be retrieved as a string List
private static List<String> GetTagData()
{
List<String> tagData = new List<String>();
tagData.Add(true.ToString());
tagData.Add((-2).ToString());
tagData.Add((short.MaxValue).ToString());
tagData.Add((int.MaxValue).ToString());
tagData.Add((Int64.MaxValue).ToString());
tagData.Add((byte.MaxValue - 1).ToString());
tagData.Add((UInt16.MaxValue - 1).ToString());
tagData.Add((uint.MinValue + 1).ToString());
tagData.Add((UInt64.MinValue + 1).ToString());
tagData.Add((11.11F).ToString());
tagData.Add((22.22D).ToString());
tagData.Add("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}");
tagData.Add("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}");
return tagData;
}
public static List<string> GetMultiBindStableRowData()
{
List<string> rowData = new List<String>();
List<string> tagData = GetTagData();
for (int i = 0; i < tsArr.Length; i++)
{
rowData.Add(tsArr[i].ToString());
rowData.Add(boolArr[i].Equals(null) ? "NULL" : boolArr[i].ToString());
rowData.Add(tinyIntArr[i].Equals(null) ? "NULL" : tinyIntArr[i].ToString());
rowData.Add(shortArr[i].Equals(null) ? "NULL" : shortArr[i].ToString());
rowData.Add(intArr[i].Equals(null) ? "NULL" : intArr[i].ToString());
rowData.Add(longArr[i].Equals(null) ? "NULL" : longArr[i].ToString());
rowData.Add(floatArr[i].Equals(null) ? "NULL" : floatArr[i].ToString());
rowData.Add(doubleArr[i].Equals(null) ? "NULL" : doubleArr[i].ToString());
rowData.Add(uTinyIntArr[i].Equals(null) ? "NULL" : uTinyIntArr[i].ToString());
rowData.Add(uShortArr[i].Equals(null) ? "NULL" : uShortArr[i].ToString());
rowData.Add(uIntArr[i].Equals(null) ? "NULL" : uIntArr[i].ToString());
rowData.Add(uLongArr[i].Equals(null) ? "NULL" : uLongArr[i].ToString());
rowData.Add(String.IsNullOrEmpty(binaryArr[i]) ? "NULL" : binaryArr[i]);
rowData.Add(String.IsNullOrEmpty(ncharArr[i]) ? "NULL" : ncharArr[i]);
rowData.AddRange(tagData);
// Console.WriteLine("binaryArrCn[{0}]:{1},ncharArr[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? "NULL" : binaryArrCn[i],String.IsNullOrEmpty(ncharArr[i]) ? "NULL" : NcharArrCn[i]);
// Console.WriteLine("binaryArrCn[{0}]:{1},ncharArr[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? 0 :binaryArrCn[i].Length, String.IsNullOrEmpty(ncharArr[i]) ? 0 : NcharArrCn[i].Length);
// Console.WriteLine("========");
}
return rowData;
}
// Construct a TAOS_BIND array which contains chinese character.
// For stmt bind tags,this will be used as tag info
public static TAOS_BIND[] GetCNTags()
{
TAOS_BIND[] binds = new TAOS_BIND[13];
binds[0] = TaosBind.BindBool(true);
binds[1] = TaosBind.BindTinyInt(-2);
binds[2] = TaosBind.BindSmallInt(short.MaxValue - 1);
binds[3] = TaosBind.BindInt(int.MaxValue - 1);
binds[4] = TaosBind.BindBigInt(Int64.MaxValue - 1);
binds[5] = TaosBind.BindUTinyInt(byte.MaxValue - 1);
binds[6] = TaosBind.BindUSmallInt(UInt16.MaxValue - 1);
binds[7] = TaosBind.BindUInt(uint.MinValue + 1);
binds[8] = TaosBind.BindUBigInt(UInt64.MinValue + 1);
binds[9] = TaosBind.BindFloat(11.11F);
binds[10] = TaosBind.BindDouble(22.22D);
binds[11] = TaosBind.BindBinary("TDengine涛思数据");
binds[12] = TaosBind.BindNchar("涛思数据taos");
return binds;
}
// Get the tag data within and string list
// Which will be retrieved as a string List
private static List<String> GetTagCNData()
{
List<String> tagData = new List<String>();
tagData.Add(true.ToString());
tagData.Add((-2).ToString());
tagData.Add((short.MaxValue - 1).ToString());
tagData.Add((int.MaxValue - 1).ToString());
tagData.Add((Int64.MaxValue - 1).ToString());
tagData.Add((byte.MaxValue - 1).ToString());
tagData.Add((UInt16.MaxValue - 1).ToString());
tagData.Add((uint.MinValue + 1).ToString());
tagData.Add((UInt64.MinValue + 1).ToString());
tagData.Add((11.11F).ToString());
tagData.Add((22.22D).ToString());
tagData.Add("TDengine涛思数据");
tagData.Add("涛思数据taos");
return tagData;
}
// A line of data that's without CN character.
// Which is construct as an TAOS_BIND array
public static TAOS_BIND[] GetNTableCNRow()
{
TAOS_BIND[] binds = new TAOS_BIND[15];
binds[0] = TaosBind.BindTimestamp(1637064040000);
binds[1] = TaosBind.BindTinyInt(-2);
binds[2] = TaosBind.BindSmallInt(short.MaxValue);
binds[3] = TaosBind.BindInt(int.MaxValue);
binds[4] = TaosBind.BindBigInt(Int64.MaxValue);
binds[5] = TaosBind.BindUTinyInt(byte.MaxValue - 1);
binds[6] = TaosBind.BindUSmallInt(UInt16.MaxValue - 1);
binds[7] = TaosBind.BindUInt(uint.MinValue + 1);
binds[8] = TaosBind.BindUBigInt(UInt64.MinValue + 1);
binds[9] = TaosBind.BindFloat(11.11F);
binds[10] = TaosBind.BindDouble(22.22D);
binds[11] = TaosBind.BindBinary("TDengine数据");
binds[12] = TaosBind.BindNchar("taosdata涛思数据");
binds[13] = TaosBind.BindBool(true);
binds[14] = TaosBind.BindNil();
return binds;
}
//Get and list data that will be insert into table
public static List<String> GetNTableCNRowData()
{
var data = new List<string>{
"1637064040000",
"-2",
short.MaxValue.ToString(),
int.MaxValue.ToString(),
Int64.MaxValue.ToString(),
(byte.MaxValue - 1).ToString(),
(UInt16.MaxValue - 1).ToString(),
(uint.MinValue + 1).ToString(),
(UInt64.MinValue + 1).ToString(),
(11.11F).ToString(),
(22.22D).ToString(),
"TDengine数据",
"taosdata涛思数据",
"True",
"NULL"
};
return data;
}
// Get the data value and tag values which have chinese characters
// And retrieved as a string list.This is single Line.
public static List<String> GetSTableCNRowData()
{
List<String> columnData = GetNTableCNRowData();
List<String> tagData = GetTagCNData();
columnData.AddRange(tagData);
return columnData;
}
// A line of data that's without CN character
public static TAOS_BIND[] GetNTableRow()
{
TAOS_BIND[] binds = new TAOS_BIND[15];
binds[0] = TaosBind.BindTimestamp(1637064040000);
binds[1] = TaosBind.BindTinyInt(-2);
binds[2] = TaosBind.BindSmallInt(short.MaxValue);
binds[3] = TaosBind.BindInt(int.MaxValue);
binds[4] = TaosBind.BindBigInt(Int64.MaxValue);
binds[5] = TaosBind.BindUTinyInt(byte.MaxValue - 1);
binds[6] = TaosBind.BindUSmallInt(UInt16.MaxValue - 1);
binds[7] = TaosBind.BindUInt(uint.MinValue + 1);
binds[8] = TaosBind.BindUBigInt(UInt64.MinValue + 1);
binds[9] = TaosBind.BindFloat(11.11F);
binds[10] = TaosBind.BindDouble(22.22D);
binds[11] = TaosBind.BindBinary("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}");
binds[12] = TaosBind.BindNchar("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}");
binds[13] = TaosBind.BindBool(true);
binds[14] = TaosBind.BindNil();
return binds;
}
// A List of data ,use as expectResData. The value is equal to getNTableRow()
public static List<String> GetNTableRowData()
{
var data = new List<string>{
"1637064040000",
"-2",
short.MaxValue.ToString(),
int.MaxValue.ToString(),
(Int64.MaxValue).ToString(),
(byte.MaxValue - 1).ToString(),
(UInt16.MaxValue - 1).ToString(),
(uint.MinValue + 1).ToString(),
(UInt64.MinValue + 1).ToString(),
(11.11F).ToString(),
(22.22D).ToString(),
"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}",
"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKZXCVBNM`1234567890-=+_)(*&^%$#@!~[];,./<>?:{}",
true.ToString(),
"NULL"
};
return data;
}
// Five lines of data, that is construct as taos_multi_bind array.
// There aren't any CN character
public static TAOS_MULTI_BIND[] GetMultiBindArr()
{
TAOS_MULTI_BIND[] mBinds = new TAOS_MULTI_BIND[14];
mBinds[0] = TaosMultiBind.MultiBindTimestamp(tsArr);
mBinds[1] = TaosMultiBind.MultiBindBool(boolArr);
mBinds[2] = TaosMultiBind.MultiBindTinyInt(tinyIntArr);
mBinds[3] = TaosMultiBind.MultiBindSmallInt(shortArr);
mBinds[4] = TaosMultiBind.MultiBindInt(intArr);
mBinds[5] = TaosMultiBind.MultiBindBigint(longArr);
mBinds[6] = TaosMultiBind.MultiBindFloat(floatArr);
mBinds[7] = TaosMultiBind.MultiBindDouble(doubleArr);
mBinds[8] = TaosMultiBind.MultiBindUTinyInt(uTinyIntArr);
mBinds[9] = TaosMultiBind.MultiBindUSmallInt(uShortArr);
mBinds[10] = TaosMultiBind.MultiBindUInt(uIntArr);
mBinds[11] = TaosMultiBind.MultiBindUBigInt(uLongArr);
mBinds[12] = TaosMultiBind.MultiBindBinary(binaryArr);
mBinds[13] = TaosMultiBind.MultiBindNchar(ncharArr);
return mBinds;
}
// A List of data ,use as expectResData. The value is equal to GetMultiBindCNArr()
public static List<string> GetMultiBindResData()
{
var rowData = new List<string>();
for (int i = 0; i < tsArr.Length; i++)
{
rowData.Add(tsArr[i].ToString());
rowData.Add(boolArr[i].Equals(null) ? "NULL" : boolArr[i].ToString());
rowData.Add(tinyIntArr[i].Equals(null) ? "NULL" : tinyIntArr[i].ToString());
rowData.Add(shortArr[i].Equals(null) ? "NULL" : shortArr[i].ToString());
rowData.Add(intArr[i].Equals(null) ? "NULL" : intArr[i].ToString());
rowData.Add(longArr[i].Equals(null) ? "NULL" : longArr[i].ToString());
rowData.Add(floatArr[i].Equals(null) ? "NULL" : floatArr[i].ToString());
rowData.Add(doubleArr[i].Equals(null) ? "NULL" : doubleArr[i].ToString());
rowData.Add(uTinyIntArr[i].Equals(null) ? "NULL" : uTinyIntArr[i].ToString());
rowData.Add(uShortArr[i].Equals(null) ? "NULL" : uShortArr[i].ToString());
rowData.Add(uIntArr[i].Equals(null) ? "NULL" : uIntArr[i].ToString());
rowData.Add(uLongArr[i].Equals(null) ? "NULL" : uLongArr[i].ToString());
rowData.Add(String.IsNullOrEmpty(binaryArr[i]) ? "NULL" : binaryArr[i]);
rowData.Add(String.IsNullOrEmpty(ncharArr[i]) ? "NULL" : ncharArr[i]);
// Console.WriteLine("binaryArrCn[{0}]:{1},NcharArrCn[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? "NULL" : binaryArrCn[i],String.IsNullOrEmpty(NcharArrCn[i]) ? "NULL" : NcharArrCn[i]);
// Console.WriteLine("binaryArrCn[{0}]:{1},NcharArrCn[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? 0 :binaryArrCn[i].Length, String.IsNullOrEmpty(NcharArrCn[i]) ? 0 : NcharArrCn[i].Length);
// Console.WriteLine("========");
}
return rowData;
}
// Five lines of data, that is construct as taos_multi_bind array.
// There are some CN characters and letters.
public static TAOS_MULTI_BIND[] GetMultiBindCNArr()
{
TAOS_MULTI_BIND[] mBinds = new TAOS_MULTI_BIND[14];
mBinds[0] = TaosMultiBind.MultiBindTimestamp(tsArr);
mBinds[1] = TaosMultiBind.MultiBindBool(boolArr);
mBinds[2] = TaosMultiBind.MultiBindTinyInt(tinyIntArr);
mBinds[3] = TaosMultiBind.MultiBindSmallInt(shortArr);
mBinds[4] = TaosMultiBind.MultiBindInt(intArr);
mBinds[5] = TaosMultiBind.MultiBindBigint(longArr);
mBinds[6] = TaosMultiBind.MultiBindFloat(floatArr);
mBinds[7] = TaosMultiBind.MultiBindDouble(doubleArr);
mBinds[8] = TaosMultiBind.MultiBindUTinyInt(uTinyIntArr);
mBinds[9] = TaosMultiBind.MultiBindUSmallInt(uShortArr);
mBinds[10] = TaosMultiBind.MultiBindUInt(uIntArr);
mBinds[11] = TaosMultiBind.MultiBindUBigInt(uLongArr);
mBinds[12] = TaosMultiBind.MultiBindBinary(binaryArrCn);
mBinds[13] = TaosMultiBind.MultiBindNchar(NcharArrCn);
return mBinds;
}
// A List of data ,use as expectResData. The value is equal to GetMultiBindCNArr()
public static List<string> GetMultiBindCNRowData()
{
var rowData = new List<string>();
for (int i = 0; i < tsArr.Length; i++)
{
rowData.Add(tsArr[i].ToString());
rowData.Add(boolArr[i].Equals(null) ? "NULL" : boolArr[i].ToString());
rowData.Add(tinyIntArr[i].Equals(null) ? "NULL" : tinyIntArr[i].ToString());
rowData.Add(shortArr[i].Equals(null) ? "NULL" : shortArr[i].ToString());
rowData.Add(intArr[i].Equals(null) ? "NULL" : intArr[i].ToString());
rowData.Add(longArr[i].Equals(null) ? "NULL" : longArr[i].ToString());
rowData.Add(floatArr[i].Equals(null) ? "NULL" : floatArr[i].ToString());
rowData.Add(doubleArr[i].Equals(null) ? "NULL" : doubleArr[i].ToString());
rowData.Add(uTinyIntArr[i].Equals(null) ? "NULL" : uTinyIntArr[i].ToString());
rowData.Add(uShortArr[i].Equals(null) ? "NULL" : uShortArr[i].ToString());
rowData.Add(uIntArr[i].Equals(null) ? "NULL" : uIntArr[i].ToString());
rowData.Add(uLongArr[i].Equals(null) ? "NULL" : uLongArr[i].ToString());
rowData.Add(String.IsNullOrEmpty(binaryArrCn[i]) ? "NULL" : binaryArrCn[i]);
rowData.Add(String.IsNullOrEmpty(NcharArrCn[i]) ? "NULL" : NcharArrCn[i]);
// Console.WriteLine("binaryArrCn[{0}]:{1},NcharArrCn[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? "NULL" : binaryArrCn[i],String.IsNullOrEmpty(NcharArrCn[i]) ? "NULL" : NcharArrCn[i]);
// Console.WriteLine("binaryArrCn[{0}]:{1},NcharArrCn[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? 0 :binaryArrCn[i].Length, String.IsNullOrEmpty(NcharArrCn[i]) ? 0 : NcharArrCn[i].Length);
// Console.WriteLine("========");
}
return rowData;
}
public static List<String> GetMultiBindStableCNRowData()
{
List<String> columnData = new List<string>();
List<String> tagData = GetTagCNData();
for (int i = 0; i < tsArr.Length; i++)
{
columnData.Add(tsArr[i].ToString());
columnData.Add(boolArr[i].Equals(null) ? "NULL" : boolArr[i].ToString());
columnData.Add(tinyIntArr[i].Equals(null) ? "NULL" : tinyIntArr[i].ToString());
columnData.Add(shortArr[i].Equals(null) ? "NULL" : shortArr[i].ToString());
columnData.Add(intArr[i].Equals(null) ? "NULL" : intArr[i].ToString());
columnData.Add(longArr[i].Equals(null) ? "NULL" : longArr[i].ToString());
columnData.Add(floatArr[i].Equals(null) ? "NULL" : floatArr[i].ToString());
columnData.Add(doubleArr[i].Equals(null) ? "NULL" : doubleArr[i].ToString());
columnData.Add(uTinyIntArr[i].Equals(null) ? "NULL" : uTinyIntArr[i].ToString());
columnData.Add(uShortArr[i].Equals(null) ? "NULL" : uShortArr[i].ToString());
columnData.Add(uIntArr[i].Equals(null) ? "NULL" : uIntArr[i].ToString());
columnData.Add(uLongArr[i].Equals(null) ? "NULL" : uLongArr[i].ToString());
columnData.Add(String.IsNullOrEmpty(binaryArrCn[i]) ? "NULL" : binaryArrCn[i]);
columnData.Add(String.IsNullOrEmpty(NcharArrCn[i]) ? "NULL" : NcharArrCn[i]);
columnData.AddRange(tagData);
// Console.WriteLine("binaryArrCn[{0}]:{1},NcharArrCn[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? "NULL" : binaryArrCn[i],String.IsNullOrEmpty(NcharArrCn[i]) ? "NULL" : NcharArrCn[i]);
// Console.WriteLine("binaryArrCn[{0}]:{1},NcharArrCn[{0}]:{2}",i,String.IsNullOrEmpty(binaryArrCn[i]) ? 0 :binaryArrCn[i].Length, String.IsNullOrEmpty(NcharArrCn[i]) ? 0 : NcharArrCn[i].Length);
// Console.WriteLine("========");
}
return columnData;
}
public static TAOS_BIND[] GetQueryCondition()
{
TAOS_BIND[] queryCondition = new TAOS_BIND[2];
queryCondition[0] = TaosBind.BindTinyInt(0);
queryCondition[1] = TaosBind.BindInt(1000);
return queryCondition;
}
public static void FreeTaosBind(TAOS_BIND[] binds)
{
TaosBind.FreeTaosBind(binds);
}
public static void FreeTaosMBind(TAOS_MULTI_BIND[] mBinds)
{
TaosMultiBind.FreeTaosBind(mBinds);
}
//Get the TDengineMeta list from the ddl either normal table or stable
public static List<TDengineMeta> GetMetaFromDDL(string dllStr)
{
var expectResMeta = new List<TDengineMeta>();
//"CREATE TABLE meters(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS(location BINARY(30), groupId INT);";
int bracketInd = dllStr.IndexOf("(");
//(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS(location BINARY(30), groupId INT);
string subDllStr = dllStr.Substring(bracketInd);
String[] stableSeparators = new String[] { "tags", "TAGS" };
//(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT)
//(location BINARY(30), groupId INT)
String[] dllStrElements = subDllStr.Split(stableSeparators, StringSplitOptions.RemoveEmptyEntries);
//(ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT)
dllStrElements[0] = dllStrElements[0].Substring(1, dllStrElements[0].Length - 2);
String[] finalStr1 = dllStrElements[0].Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (string item in finalStr1)
{
//ts TIMESTAMP
string[] itemArr = item.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
// Console.WriteLine("GetMetaFromDLL():{0},{1}",itemArr[0],itemArr[1]);
expectResMeta.Add(UtilsTools.ConstructTDengineMeta(itemArr[0], itemArr[1]));
}
if (dllStr.Contains("TAGS") || dllStr.Contains("tags"))
{
//location BINARY(30), groupId INT
dllStrElements[1] = dllStrElements[1].Substring(1, dllStrElements[1].Length - 2);
//location BINARY(30) groupId INT
String[] finalStr2 = dllStrElements[1].Split(',', StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("========");
foreach (string item in finalStr2)
{
//location BINARY(30)
string[] itemArr = item.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
// Console.WriteLine("GetMetaFromDLL():{0},{1}",itemArr[0],itemArr[1]);
expectResMeta.Add(UtilsTools.ConstructTDengineMeta(itemArr[0], itemArr[1]));
}
}
return expectResMeta;
}
}
}
\ No newline at end of file
using System;
using Test.UtilsTools;
using TDengineDriver;
using System.Collections.Generic;
using Xunit;
using Test.UtilsTools.ResultSet;
using Test.Fixture;
using Test.Case.Attributes;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
[Collection("Database collection")]
public class FetchFieldCases
{
DatabaseFixture database;
public FetchFieldCases(DatabaseFixture fixture)
{
this.database = fixture;
}
/// <author>xiaolei</author>
/// <Name>FetchFieldsCases.TestFetchFieldsJsonTag</Name>
/// <describe>test taos_fetch_fields(), check the meta data</describe>
/// <filename>FetchFields.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "FetchFieldsCases.TestFetchFieldJsonTag()"), TestExeOrder(1), Trait("Category", "FetchFieldJsonTag")]
public void TestFetchFieldJsonTag()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
string tableName = "fetch_fields";
var expectResMeta = new List<TDengineMeta> {
UtilsTools.ConstructTDengineMeta("ts", "timestamp"),
UtilsTools.ConstructTDengineMeta("b", "bool"),
UtilsTools.ConstructTDengineMeta("v1", "tinyint"),
UtilsTools.ConstructTDengineMeta("v2", "smallint"),
UtilsTools.ConstructTDengineMeta("v4", "int"),
UtilsTools.ConstructTDengineMeta("v8", "bigint"),
UtilsTools.ConstructTDengineMeta("f4", "float"),
UtilsTools.ConstructTDengineMeta("f8", "double"),
UtilsTools.ConstructTDengineMeta("u1", "tinyint unsigned"),
UtilsTools.ConstructTDengineMeta("u2", "smallint unsigned"),
UtilsTools.ConstructTDengineMeta("u4", "int unsigned"),
UtilsTools.ConstructTDengineMeta("u8", "bigint unsigned"),
UtilsTools.ConstructTDengineMeta("bin", "binary(200)"),
UtilsTools.ConstructTDengineMeta("blob", "nchar(200)"),
UtilsTools.ConstructTDengineMeta("jsontag", "json"),
};
var expectResData = new List<String> { "1637064040000", "true", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "XI", "XII", "{\"k1\": \"v1\"}" };
String dropTb = "drop table if exists " + tableName;
String createTb = "create stable " + tableName
+ " (ts timestamp" +
",b bool" +
",v1 tinyint" +
",v2 smallint" +
",v4 int" +
",v8 bigint" +
",f4 float" +
",f8 double" +
",u1 tinyint unsigned" +
",u2 smallint unsigned" +
",u4 int unsigned" +
",u8 bigint unsigned" +
",bin binary(200)" +
",blob nchar(200)" +
")" +
"tags" +
"(jsontag json);";
String insertSql = "insert into " + tableName + "_t1 using " + tableName +
" tags('{\"k1\": \"v1\"}') " +
"values(1637064040000,true,1,2,3,4,5,6,7,8,9,10,'XI','XII')";
String selectSql = "select * from " + tableName;
String dropSql = "drop table " + tableName;
UtilsTools.ExecuteUpdate(conn, dropTb);
UtilsTools.ExecuteUpdate(conn, createTb);
UtilsTools.ExecuteUpdate(conn, insertSql);
_res = UtilsTools.ExecuteQuery(conn, selectSql);
ResultSet actualResult = new ResultSet(_res);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
}
}
}
using System;
using Test.UtilsTools;
using System.Collections.Generic;
using Xunit;
using TDengineDriver;
using Test.UtilsTools.ResultSet;
using Test.Case.Attributes;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
public class FetchLengthCase
{
/// <author>xiaolei</author>
/// <Name>TestRetrieveBinary</Name>
/// <describe>TD-12103 C# connector fetch_row with binary data retrieving error</describe>
/// <filename>FetchLength.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "FetchLengthCase.TestRetrieveBinary()"), TestExeOrder(1)]
public void TestRetrieveBinary()
{
IntPtr conn = UtilsTools.TDConnection();
var expectData = new List<string> { "log", "test", "db02", "db3" };
var expectMeta = new List<TDengineMeta>{
UtilsTools.ConstructTDengineMeta("ts","timestamp"),
UtilsTools.ConstructTDengineMeta("name","binary(10)"),
UtilsTools.ConstructTDengineMeta("n","int")
};
string sql0 = "drop table if exists stb1;";
string sql1 = "create stable if not exists stb1 (ts timestamp, name binary(10)) tags(n int);";
string sql2 = $"insert into tb1 using stb1 tags(1) values(now, '{expectData[0]}');";
string sql3 = $"insert into tb2 using stb1 tags(2) values(now, '{expectData[1]}');";
string sql4 = $"insert into tb3 using stb1 tags(3) values(now, '{expectData[2]}');";
string sql5 = $"insert into tb4 using stb1 tags(4) values(now, '{expectData[3]}');";
string sql6 = "select distinct(name) from stb1;";
UtilsTools.ExecuteQuery(conn, sql0);
UtilsTools.ExecuteQuery(conn, sql1);
UtilsTools.ExecuteQuery(conn, sql2);
UtilsTools.ExecuteQuery(conn, sql3);
UtilsTools.ExecuteQuery(conn, sql4);
UtilsTools.ExecuteQuery(conn, sql5);
IntPtr resPtr = IntPtr.Zero;
resPtr = UtilsTools.ExecuteQuery(conn, sql6);
ResultSet actualResult = new ResultSet(resPtr);
List<string> actualData = actualResult.GetResultData();
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
// Make expected data and retrieved data in same order
expectData.Sort();
actualData.Sort();
// Assert meta data
Assert.Equal(expectMeta[1].name, actualMeta[0].name);
Assert.Equal(expectMeta[1].size, actualMeta[0].size);
Assert.Equal(expectMeta[1].type, actualMeta[0].type);
// Assert retrieved data
for (int i = 0; i < actualData.Count; i++)
{
// Console.WriteLine($"expectData[{i}]:{expectData[i]},, actualData[{i}]:{actualData[i]}" );
Assert.Equal(expectData[i].ToString(), actualData[i]);
}
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<IsPackable>false</IsPackable>
<NoWarn>CS1591;CS0168</NoWarn>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>..\doc\FunctionTest.XML</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\TDengineDriver\TDengineDriver.csproj" />
</ItemGroup>
</Project>
using System;
using Test.UtilsTools;
using TDengineDriver;
using Test.UtilsTools.DataSource;
using Xunit;
using System.Collections.Generic;
using Test.UtilsTools.ResultSet;
using Test.Case.Attributes;
using Test.Fixture;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
[Collection("Database collection")]
public class InsertCNCases
{
DatabaseFixture database;
public InsertCNCases(DatabaseFixture fixture)
{
this.database = fixture;
}
/// <author>xiaolei</author>
/// <Name>InsertCNCases.TestNTable</Name>
/// <describe>Test insert Chinese characters into normal table's nchar column</describe>
/// <filename>InsertCn.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "InsertCNCases.TestNTable"), TestExeOrder(1)]
public void TestNTable()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
string tableName = "cn_insert_nchar_ntable";
// var expectResData = new List<String> { "1637064040000", "true", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "XI", "XII", "{\"k1\": \"v1\"}" };
var colData = new List<Object>{1637064040000,1,"涛思数据",
1637064041000,2,"涛思数据taosdata",
1637064042000,3,"TDegnine涛思数据",
1637064043000,4,"4涛思数据",
1637064044000,5,"涛思数据5",
1637064045000,6,"taos涛思数据6",
1637064046000,7,"7涛思数据taos",
1637064047000,8,"8&涛思数据taos",
1637064048000,9,"&涛思数据taos9"
};
String dropTb = "drop table if exists " + tableName;
String createTb = $"create table if not exists {tableName} (ts timestamp,v4 int,blob nchar(200));";
String insertSql = UtilsTools.ConstructInsertSql(tableName, "", colData, null, 9);
String selectSql = "select * from " + tableName;
String dropSql = "drop table " + tableName;
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
UtilsTools.ExecuteUpdate(conn, dropTb);
UtilsTools.ExecuteUpdate(conn, createTb);
UtilsTools.ExecuteUpdate(conn, insertSql);
_res = UtilsTools.ExecuteQuery(conn, selectSql);
ResultSet actualResult = new ResultSet(_res);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
List<String> actualResData = actualResult.GetResultData();
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(colData[i].ToString(), actualResData[i]);
}
}
/// <author>xiaolei</author>
/// <Name>InsertCNCases.TestSTable</Name>
/// <describe>test insert Chinese character into stable's nchar column,both tag and column</describe>
/// <filename>InsertCn.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "InsertCNCases.TestSTable()"), TestExeOrder(2)]
public void TestSTable()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
string tableName = "cn_insert_nchar_stable";
var colData = new List<Object>{1637064040000,1,"涛思数据",
1637064041000,2,"涛思数据taosdata",
1637064042000,3,"TDegnine涛思数据",
1637064043000,4,"4涛思数据",
1637064044000,5,"涛思数据5",
1637064045000,6,"taos涛思数据6",
1637064046000,7,"7涛思数据taos",
1637064047000,8,"8&涛思数据taos",
1637064048000,9,"&涛思数据taos9"
};
var tagData = new List<Object> { 1, "涛思数据", };
String dropTb = "drop table if exists " + tableName;
String createTb = $"create table {tableName} (ts timestamp,v4 int,blob nchar(200))tags(id int,name nchar(50));";
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_sub1", tableName, colData, tagData, 9);
String selectSql = "select * from " + tableName;
String dropSql = "drop table " + tableName;
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 9);
UtilsTools.ExecuteUpdate(conn, dropTb);
UtilsTools.ExecuteUpdate(conn, createTb);
UtilsTools.ExecuteUpdate(conn, insertSql);
_res = UtilsTools.ExecuteQuery(conn, selectSql);
ResultSet actualResult = new ResultSet(_res);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
List<String> actualResData = actualResult.GetResultData();
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i].ToString(), actualResData[i]);
}
}
/// <author>xiaolei</author>
/// <Name>InsertCNCases.TestInsertMultiNTable</Name>
/// <describe>test insert Chinese character into normal table's multiple nchar columns</describe>
/// <filename>InsertCn.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "InsertCNCases.TestInsertMultiNTable()"), TestExeOrder(3)]
public void TestInsertMultiNTable()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
string tableName = "cn_multi_insert_nchar_ntable";
var colData = new List<Object>{1637064040000,1,"涛思数据","保利广场","Beijing","China",
1637064041000,2,"涛思数据taosdata","保利广场baoli","Beijing","China",
1637064042000,3,"TDegnine涛思数据","time广场","NewYork","US",
1637064043000,4,"4涛思数据","4广场南部","London","UK",
1637064044000,5,"涛思数据5","!广场路中部123","Tokyo","JP",
1637064045000,6,"taos涛思数据6","青年广场123号!","Washin","DC",
1637064046000,7,"7涛思数据taos","asdf#壮年广场%#endregion","NewYork","US",
1637064047000,8,"8&涛思数据taos","incluse阿斯顿发","NewYork","US",
1637064048000,9,"&涛思数据taos9","123黑化肥werq会挥……&¥%发!afsdfa","NewYork","US",
};
String dropTb = "drop table if exists " + tableName;
String createTb = $"create table if not exists {tableName} (ts timestamp,v4 int,blob nchar(200),location nchar(200),city binary(100),coutry binary(200));";
String insertSql = UtilsTools.ConstructInsertSql(tableName, "", colData, null, 9);
String selectSql = "select * from " + tableName;
String dropSql = "drop table " + tableName;
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
UtilsTools.ExecuteUpdate(conn, dropTb);
UtilsTools.ExecuteUpdate(conn, createTb);
UtilsTools.ExecuteUpdate(conn, insertSql);
_res = UtilsTools.ExecuteQuery(conn, selectSql);
ResultSet actualResult = new ResultSet(_res);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
List<String> actualResData = actualResult.GetResultData();
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(colData[i].ToString(), actualResData[i]);
}
}
/// <author>xiaolei</author>
/// <Name>InsertCNCases.TestInsertMultiSTable</Name>
/// <describe>test insert Chinese character into stable's multiple nchar columns</describe>
/// <filename>InsertCn.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "InsertCNCases.TestInsertMultiSTable()"), TestExeOrder(4)]
public void TestInsertMultiSTable()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
string tableName = "cn_multi_insert_nchar_stable";
var colData = new List<Object>{1637064040000,1,"涛思数据","保利广场","Beijing","China",
1637064041000,2,"涛思数据taosdata","保利广场baoli","Beijing","China",
1637064042000,3,"TDegnine涛思数据","time广场","NewYork","US",
1637064043000,4,"4涛思数据","4广场南部","London","UK",
1637064044000,5,"涛思数据5","!广场路中部123","Tokyo","JP",
1637064045000,6,"taos涛思数据6","青年广场123号!","Washin","DC",
1637064046000,7,"7涛思数据taos","asdf#壮年广场%#endregion","NewYork","US",
1637064047000,8,"8&涛思数据taos","incluse阿斯顿发","NewYork","US",
1637064048000,9,"&涛思数据taos9","123黑化肥werq会挥……&¥%发!afsdfa","NewYork","US",
};
var tagData = new List<Object> { 1, "涛思数据", "中国北方&南方长江黄河!49wq", "tdengine" };
String dropTb = "drop table if exists " + tableName;
String createTb = $"create table if not exists {tableName} (ts timestamp," +
$"v4 int," +
$"blob nchar(200)," +
$"locate nchar(200)," +
$"country nchar(200)," +
$"city nchar(50)" +
$")tags(" +
$"id int," +
$"name nchar(50)," +
$"addr nchar(200)," +
$"en_name binary(200));";
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_sub1", tableName, colData, tagData, 9);
String selectSql = "select * from " + tableName;
String dropSql = "drop table " + tableName;
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 9);
UtilsTools.ExecuteUpdate(conn, dropTb);
UtilsTools.ExecuteUpdate(conn, createTb);
UtilsTools.ExecuteUpdate(conn, insertSql);
_res = UtilsTools.ExecuteQuery(conn, selectSql);
ResultSet actualResult = new ResultSet(_res);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
List<String> actualResData = actualResult.GetResultData();
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i].ToString(), actualResData[i]);
}
}
}
}
using TDengineDriver;
using Test.UtilsTools;
using System;
using Xunit;
using System.Collections.Generic;
using Test.UtilsTools.DataSource;
using Test.UtilsTools.ResultSet;
using Xunit.Abstractions;
using Test.Fixture;
using Test.Case.Attributes;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
[Collection("Database collection")]
public class QueryAsyncCases
{
DatabaseFixture database;
private readonly ITestOutputHelper output;
public QueryAsyncCases(DatabaseFixture fixture, ITestOutputHelper output)
{
this.database = fixture;
this.output = output;
}
/// <author>xiaolei</author>
/// <Name>QueryAsyncCases.QueryAsyncCases</Name>
/// <describe>Test query without condition</describe>
/// <filename>QueryAsync.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "QueryAsyncCases.QueryWithoutCondition()"), TestExeOrder(1), Trait("Category", "QueryAWithoutCondition")]
public void QueryWithoutCondition()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
var tableName = "query_a_without_condition";
var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))";
var dropSql = $"drop table if exists {tableName}";
var colData = new List<Object>{1646150410100,true,1,11,1111,11111111,"value one","值壹",
1646150410200,true,2,22,2222,22222222,"value two","值贰",
1646150410300,false,3,33,3333,33333333,"value three","值三",
};
var tagData = new List<Object> { 1, "tag_one", "标签壹" };
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3);
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3);
var querySql = $"select * from {tableName}";
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
UtilsTools.ExecuteUpdate(conn, insertSql);
QueryAsyncCallback fq = new QueryAsyncCallback(QueryCallback);
TDengine.QueryAsync(conn, querySql, fq, IntPtr.Zero);
void QueryCallback(IntPtr param, IntPtr taosRes, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchCallback);
TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param);
}
else
{
Console.WriteLine($"async query data failed, failed code {code}");
}
}
void FetchCallback(IntPtr param, IntPtr taosRes, int numOfRows)
{
if (numOfRows > 0)
{
ResultSet actualResult = new ResultSet(taosRes);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
List<String> actualResData = actualResult.GetResultData();
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// Console.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]);
Assert.Equal(expectResData[i].ToString(), actualResData[i]);
}
TDengine.FetchRowAsync(taosRes, FetchCallback, param);
}
else
{
if (numOfRows == 0)
{
Console.WriteLine("async retrieve complete.");
}
else
{
Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}");
}
TDengine.FreeResult(taosRes);
}
}
}
/// <author>xiaolei</author>
/// <Name>QueryAsyncCases.QueryWithCondition</Name>
/// <describe>Test query with condition</describe>
/// <filename>QueryAsync.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "QueryAsyncCases.QueryWithCondition()"), TestExeOrder(2), Trait("Category", "QueryAWithCondition")]
public void QueryWithCondition()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
var tableName = "query_a_with_condition";
var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))";
var dropSql = $"drop table if exists {tableName}";
var colData = new List<Object>{1646150410100,true,1,11,1111,11111111,"value one","值壹",
1646150410200,true,2,22,2222,22222222,"value two","值贰",
1646150410300,false,3,33,3333,33333333,"value three","值三",
};
var colDataActual = colData.GetRange(8, 8);
var tagData = new List<Object> { 1, "tag_one", "标签壹" };
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3);
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colDataActual, tagData, 1);
colDataActual.ForEach((item) => { Console.Write("{0}\t", item); });
var querySql = $"select * from {tableName} where bl=true and t_bnr='tag_one' and i8>1 and t_nchr = '标签壹'";
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
UtilsTools.ExecuteUpdate(conn, insertSql);
QueryAsyncCallback fq = new QueryAsyncCallback(QueryCallback);
TDengine.QueryAsync(conn, querySql, fq, IntPtr.Zero);
void QueryCallback(IntPtr param, IntPtr taosRes, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchCallback);
TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param);
}
else
{
Console.WriteLine($"async query data failed, failed code {code}");
}
}
void FetchCallback(IntPtr param, IntPtr taosRes, int numOfRows)
{
if (numOfRows > 0)
{
ResultSet actualResult = new ResultSet(taosRes);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
List<String> actualResData = actualResult.GetResultData();
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// Console.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]);
Assert.Equal(expectResData[i].ToString(), actualResData[i]);
}
TDengine.FetchRowAsync(taosRes, FetchCallback, param);
}
else
{
if (numOfRows == 0)
{
Console.WriteLine("async retrieve complete.");
}
else
{
Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}");
}
TDengine.FreeResult(taosRes);
}
}
}
/// <author>xiaolei</author>
/// <Name>QueryAsyncCases.QueryWithJsonCondition</Name>
/// <describe>Test query with condition</describe>
/// <filename>QueryAsync.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "QueryAsyncCases.QueryWithJsonCondition()"), TestExeOrder(3), Trait("Category", "QueryAWithJsonCondition")]
public void QueryWithJsonCondition()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
var tableName = "query_a_json_condition";
var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(jtag json)";
var dropSql = $"drop table if exists {tableName}";
var colData1 = new List<Object>{1646150410100,true,1,11,1111,11111111,"value one","值壹",
1646150410200,true,2,22,2222,22222222,"value two","值贰",
1646150410300,false,3,33,3333,33333333,"value three","值三",
};
var colData2 = new List<Object>{1646150410400,false,4,44,4444,44444444,"value three","值肆",
1646150410500,true,5,55,5555,55555555,"value one","值伍",
1646150410600,true,6,66,6666,66666666,"value two","值陆",
};
var tagData1 = new List<Object> { "{\"t_bnr\":\"tag1\",\"t_i32\":1,\"t_nchr\":\"标签壹\"}" };
var tagData2 = new List<Object> { "{\"t_bnr\":\"tag2\",\"t_i32\":2,\"t_nchar\":\"标签贰\"}" };
var querySql = $"select * from {tableName} where jtag->'t_bnr'='tag1';";
String insertSql1 = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData1, tagData1, 3);
String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData1, tagData2, 3);
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData1, tagData1, 3);
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
UtilsTools.ExecuteUpdate(conn, insertSql1);
UtilsTools.ExecuteUpdate(conn, insertSql2);
QueryAsyncCallback fq = new QueryAsyncCallback(QueryCallback);
TDengine.QueryAsync(conn, querySql, fq, IntPtr.Zero);
void QueryCallback(IntPtr param, IntPtr taosRes, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
FetchRowAsyncCallback fetchRowAsyncCallback = new FetchRowAsyncCallback(FetchCallback);
TDengine.FetchRowAsync(taosRes, fetchRowAsyncCallback, param);
}
else
{
Console.WriteLine($"async query data failed, failed code {code}");
}
}
void FetchCallback(IntPtr param, IntPtr taosRes, int numOfRows)
{
if (numOfRows > 0)
{
ResultSet actualResult = new ResultSet(taosRes);
List<TDengineMeta> actualMeta = actualResult.GetResultMeta();
List<String> actualResData = actualResult.GetResultData();
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// Console.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]);
Assert.Equal(expectResData[i].ToString(), actualResData[i]);
}
TDengine.FetchRowAsync(taosRes, FetchCallback, param);
}
else
{
if (numOfRows == 0)
{
Console.WriteLine("async retrieve complete.");
}
else
{
Console.WriteLine($"FetchRowAsync callback error, error code {numOfRows}");
}
TDengine.FreeResult(taosRes);
}
}
}
}
}
using System;
using Test.UtilsTools;
using TDengineDriver;
using Test.UtilsTools.DataSource;
using Xunit;
using System.Collections.Generic;
using Test.UtilsTools.ResultSet;
using Test.Fixture;
using Test.Case.Attributes;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
[Collection("Database collection")]
public class NormalTableStmtCases
{
DatabaseFixture database;
public NormalTableStmtCases(DatabaseFixture fixture)
{
this.database = fixture;
}
/// <author>xiaolei</author>
/// <Name>NormalTableStmtCases.TestBindSingleLineCN</Name>
/// <describe>Test stmt insert single line of chinese character into normal table by column after column </describe>
/// <filename>StmtNormalTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "NormalTableStmtCases.TestBindSingleLineCN()"), TestExeOrder(2), Trait("Category", "bindParamCN")]
public void TestBindSingleLineCN()
{
string tableName = "ntb_stmt_cases_test_bind_single_line_cn";
String createTb = $"create table if not exists {tableName} (" +
"ts timestamp," +
"tt tinyint," +
"si smallint," +
"ii int," +
"bi bigint," +
"tu tinyint unsigned," +
"su smallint unsigned," +
"iu int unsigned," +
"bu bigint unsigned," +
"ff float," +
"dd double," +
"bb binary(200)," +
"nc nchar(200)," +
"bo bool," +
"nullval int" +
");";
string insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
string dropSql = $"drop table if exists {tableName}";
string querySql = "select * from " + tableName;
TAOS_BIND[] _valuesRow = DataSource.GetNTableCNRow();
List<string> expectResData = DataSource.GetNTableCNRowData();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createTb);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableName(stmt, tableName);
StmtUtilTools.BindParam(stmt, _valuesRow);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(_valuesRow);
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>NormalTableStmtCases.TestBindColumnCN</Name>
/// <describe>Test stmt insert single line of chinese character into normal table by column after column </describe>
/// <filename>StmtNormalTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "NormalTableStmtCases.TestBindColumnCN()"), TestExeOrder(4), Trait("Category", "bindSingleColumnCN")]
public void TestBindColumnCN()
{
string tableName = "ntb_stmt_cases_test_bind_column_cn";
String createTb = $"create table if not exists {tableName} " +
" (" +
"ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
");";
String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName} ";
List<string> expectResData = DataSource.GetMultiBindCNRowData();
TAOS_MULTI_BIND[] mBind = DataSource.GetMultiBindCNArr();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createTb);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableName(stmt, tableName);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[0], 0);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[1], 1);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[2], 2);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[3], 3);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[4], 4);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[5], 5);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[6], 6);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[7], 7);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[8], 8);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[9], 9);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[10], 10);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[11], 11);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[12], 12);
StmtUtilTools.BindSingleParamBatch(stmt, mBind[13], 13);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosMBind(mBind);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>NormalTableStmtCases.TestBindMultiLineCN</Name>
/// <describe>Test stmt insert single line of chinese character into normal table by column after column </describe>
/// <filename>StmtNormalTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "NormalTableStmtCases.TestBindMultiLineCN()"), TestExeOrder(6), Trait("Category", "bindParamBatchCN")]
public void TestBindMultiLineCN()
{
string tableName = "ntb_stmt_cases_test_bind_multi_lines_cn";
TAOS_MULTI_BIND[] mBind = DataSource.GetMultiBindCNArr();
String createTb = $"create table if not exists {tableName} " +
" (" +
"ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
");";
String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName} ";
List<string> expectResData = DataSource.GetMultiBindCNRowData();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
IntPtr conn = database.conn; ;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createTb);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableName(stmt, tableName);
StmtUtilTools.BindParamBatch(stmt, mBind);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosMBind(mBind);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
Assert.Equal(expectResMeta.Count, actualResMeta.Count);
Assert.Equal(expectResData.Count, actualResData.Count);
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>NormalTableStmtCases.TestBindSingleLine</Name>
/// <describe>Test stmt insert single line data into normal table</describe>
/// <filename>StmtNormalTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "NormalTableStmtCases.TestBindSingleLine"), TestExeOrder(3), Trait("Category", "BindSingleColumn")]
public void TestBindSingleLine()
{
string tableName = "ntb_stmt_cases_test_bind_single_line";
String createTb = $"create table if not exists {tableName} (" +
"ts timestamp," +
"tt tinyint," +
"si smallint," +
"ii int," +
"bi bigint," +
"tu tinyint unsigned," +
"su smallint unsigned," +
"iu int unsigned," +
"bu bigint unsigned," +
"ff float," +
"dd double," +
"bb binary(200)," +
"nc nchar(200)," +
"bo bool," +
"nullval int" +
");";
string insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
string dropSql = $"drop table if exists {tableName}";
string querySql = "select * from " + tableName;
TAOS_BIND[] valuesRow = DataSource.GetNTableRow();
List<string> expectResData = DataSource.GetNTableRowData();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
IntPtr conn = database.conn;
UtilsTools.ExecuteQuery(conn, dropSql);
UtilsTools.ExecuteQuery(conn, createTb);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableName(stmt, tableName);
StmtUtilTools.BindParam(stmt, valuesRow);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(valuesRow);
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
Assert.Equal(expectResMeta.Count, actualResMeta.Count);
Assert.Equal(expectResData.Count, actualResData.Count);
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>NormalTableStmtCases.TestBindMultiLine</Name>
/// <describe>Test stmt insert multiple rows of data into normal table</describe>
/// <filename>StmtNormalTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "NormalTableStmtCases.TestBindMultiLine()"), TestExeOrder(5), Trait("Category", "bindParamBatch")]
public void TestBindMultiLine()
{
string tableName = "ntb_stmt_case_test_bind_multi_lines";
String createTb = $"create table if not exists {tableName} " +
" (" +
"ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
");";
String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName} ";
List<string> expectResData = DataSource.GetMultiBindResData();
TAOS_MULTI_BIND[] mBind = DataSource.GetMultiBindArr();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createTb);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableName(stmt, tableName);
StmtUtilTools.BindParamBatch(stmt, mBind);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosMBind(mBind);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
Assert.Equal(expectResMeta.Count, actualResMeta.Count);
Assert.Equal(expectResData.Count, actualResData.Count);
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>NormalTableStmtCases.TestBindColumn</Name>
/// <describe>Test stmt insert multiple rows of data into normal table by column after column </describe>
/// <filename>StmtNormalTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "NormalTableStmtCases.TestBindColumn()"), TestExeOrder(1), Trait("Category", "bindParam")]
public void TestBindColumn()
{
string tableName = "ntb_stmt_cases_test_bind_column";
DataSource data = new DataSource();
String createTb = $"create table if not exists {tableName} " +
" (" +
"ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
");";
String insertSql = "insert into ? values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName} ";
List<string> expectResData = DataSource.GetMultiBindResData();
TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindArr();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createTb);
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createTb);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableName(stmt, tableName);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[0], 0);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[1], 1);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[2], 2);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[3], 3);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[4], 4);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[5], 5);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[6], 6);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[7], 7);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[8], 8);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[9], 9);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[10], 10);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[11], 11);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[12], 12);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[13], 13);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosMBind(mBinds);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
Assert.Equal(expectResMeta.Count, actualResMeta.Count);
Assert.Equal(expectResData.Count, actualResData.Count);
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
}
}
\ No newline at end of file
using System;
using Test.UtilsTools;
using TDengineDriver;
using Test.UtilsTools.DataSource;
namespace Cases
{
public class StmtSTableQuery
{
public void Test(IntPtr conn, string tableName)
{
string selectSql = "SELECT * FROM " + tableName + " WHERE v1 > ? AND v4 < ?";
TAOS_BIND[] queryCondition = DataSource.GetQueryCondition();
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, selectSql);
StmtUtilTools.BindParam(stmt, queryCondition);
StmtUtilTools.StmtExecute(stmt);
IntPtr res = StmtUtilTools.StmtUseResult(stmt);
UtilsTools.DisplayRes(res);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(queryCondition);
}
}
public class StmtNTableQuery
{
public void Test(IntPtr conn, string tableName)
{
string selectSql = "SELECT * FROM " + tableName + " WHERE v1 > ? AND v4 < ?";
TAOS_BIND[] queryCondition = DataSource.GetQueryCondition();
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, selectSql);
StmtUtilTools.BindParam(stmt, queryCondition);
StmtUtilTools.StmtExecute(stmt);
IntPtr res = StmtUtilTools.StmtUseResult(stmt);
UtilsTools.DisplayRes(res);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(queryCondition);
}
}
}
\ No newline at end of file
using System;
using Test.UtilsTools;
using TDengineDriver;
using Test.UtilsTools.DataSource;
using System.Collections.Generic;
using Test.UtilsTools.ResultSet;
using Xunit;
using Test.Fixture;
using Test.Case.Attributes;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
[Collection("Database collection")]
public class StableStmtCases
{
DatabaseFixture database;
public StableStmtCases(DatabaseFixture fixture)
{
this.database = fixture;
}
/// <author>xiaolei</author>
/// <Name>StableStmtCases.TestBindSingleLineCN</Name>
/// <describe>Test stmt insert single line of chinese character into stable by column after column </describe>
/// <filename>StmtSTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "StableStmtCases.TestBindSingleLineCN()"), TestExeOrder(2), Trait("Category", "BindParamCN")]
public void TestBindSingleLineCN()
{
string tableName = "stb_stmt_cases_test_bind_single_line_cn";
String createSql = $"create stable if not exists {tableName} " +
" (ts timestamp," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"f4 float," +
"f8 double," +
"bin binary(200)," +
"blob nchar(200)," +
"b bool," +
"nilcol int)" +
"tags" +
"(bo bool," +
"tt tinyint," +
"si smallint," +
"ii int," +
"bi bigint," +
"tu tinyint unsigned," +
"su smallint unsigned," +
"iu int unsigned," +
"bu bigint unsigned," +
"ff float," +
"dd double," +
"bb binary(200)," +
"nc nchar(200)" +
");";
String insertSql = $"insert into ? using {tableName} tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName} ;";
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<String> expectResData = DataSource.GetSTableCNRowData();
TAOS_BIND[] tags = DataSource.GetCNTags();
TAOS_BIND[] binds = DataSource.GetNTableCNRow();
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags);
StmtUtilTools.BindParam(stmt, binds);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(tags);
DataSource.FreeTaosBind(binds);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>StableStmtCases.TestBindColumnCN</Name>
/// <describe>Test stmt insert single line of chinese character into stable by column after column </describe>
/// <filename>StmtSTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "StableStmtCases.TestBindColumnCN()"), TestExeOrder(4), Trait("Category", "BindParamColumnCN")]
public void TestBindColumnCN()
{
string tableName = "stb_stmt_cases_test_bindcolumn_cn";
String createSql = $"create stable if not exists {tableName} " +
"(ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
")" +
"tags" +
"(bo bool," +
"tt tinyint," +
"si smallint," +
"ii int," +
"bi bigint," +
"tu tinyint unsigned," +
"su smallint unsigned," +
"iu int unsigned," +
"bu bigint unsigned," +
"ff float," +
"dd double," +
"bb binary(200)," +
"nc nchar(200)" +
");";
String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName};";
TAOS_BIND[] tags = DataSource.GetCNTags();
TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindCNArr();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<String> expectResData = DataSource.GetMultiBindStableCNRowData();
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[0], 0);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[1], 1);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[2], 2);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[3], 3);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[4], 4);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[5], 5);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[6], 6);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[7], 7);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[8], 8);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[9], 9);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[10], 10);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[11], 11);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[12], 12);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[13], 13);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(tags);
DataSource.FreeTaosMBind(mBinds);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>StableStmtCases.TestBindMultiLineCN</Name>
/// <describe>Test stmt insert single line of chinese character into stable by column after column </describe>
/// <filename>StmtSTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "StableStmtCases.TestBindMultiLineCN()"), TestExeOrder(6), Trait("Category", "BindParamBatchCN")]
public void TestBindMultiLineCN()
{
string tableName = "stb_stmt_cases_test_bind_multi_line_cn";
String createSql = $"create stable if not exists {tableName} " +
"(ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
")" +
"tags" +
"(bo bool," +
"tt tinyint," +
"si smallint," +
"ii int," +
"bi bigint," +
"tu tinyint unsigned," +
"su smallint unsigned," +
"iu int unsigned," +
"bu bigint unsigned," +
"ff float," +
"dd double," +
"bb binary(200)," +
"nc nchar(200)" +
");";
String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName};";
TAOS_BIND[] tags = DataSource.GetCNTags();
TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindCNArr();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<String> expectResData = DataSource.GetMultiBindStableCNRowData();
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags);
StmtUtilTools.BindParamBatch(stmt, mBinds);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(tags);
DataSource.FreeTaosMBind(mBinds);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>StableStmtCases.TestBindMultiLine</Name>
/// <describe>Test stmt insert single line into stable by column after column </describe>
/// <filename>StmtSTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "StableStmtCases.TestBindMultiLine()"), TestExeOrder(5), Trait("Category", "BindParamBatch")]
public void TestBindMultiLine()
{
string tableName = "stb_stmt_cases_test_bind_multi_line";
string createSql = $"create stable if not exists {tableName} " +
"(ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
")" +
"tags" +
"(bo bool," +
"tt tinyint," +
"si smallint," +
"ii int," +
"bi bigint," +
"tu tinyint unsigned," +
"su smallint unsigned," +
"iu int unsigned," +
"bu bigint unsigned," +
"ff float," +
"dd double," +
"bb binary(200)," +
"nc nchar(200)" +
");";
String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName};";
TAOS_BIND[] tags = DataSource.GetTags();
TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindArr();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<String> expectResData = DataSource.GetMultiBindStableRowData();
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags);
StmtUtilTools.BindParamBatch(stmt, mBinds);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(tags);
DataSource.FreeTaosMBind(mBinds);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// Assert.Equal(expectResData[i],actualResData[i]);
if (expectResData[i] != actualResData[i])
{
Console.WriteLine("{0}==>,expectResData:{1},actualResData:{2}", i, expectResData[i], actualResData[i]);
}
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
/// <author>xiaolei</author>
/// <Name>StableStmtCases.TestBindColumn</Name>
/// <describe>Test stmt insert single line of chinese character into stable by column after column </describe>
/// <filename>StmtSTable.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "StableStmtCases.TestBindColumn()"), TestExeOrder(3), Trait("Category", "BindParamColumn")]
public void TestBindColumn()
{
string tableName = "stb_stmt_cases_test_bindcolumn";
string createSql = $"create stable if not exists {tableName} " +
"(ts timestamp," +
"b bool," +
"v1 tinyint," +
"v2 smallint," +
"v4 int," +
"v8 bigint," +
"f4 float," +
"f8 double," +
"u1 tinyint unsigned," +
"u2 smallint unsigned," +
"u4 int unsigned," +
"u8 bigint unsigned," +
"bin binary(200)," +
"blob nchar(200)" +
")" +
"tags" +
"(bo bool," +
"tt tinyint," +
"si smallint," +
"ii int," +
"bi bigint," +
"tu tinyint unsigned," +
"su smallint unsigned," +
"iu int unsigned," +
"bu bigint unsigned," +
"ff float," +
"dd double," +
"bb binary(200)," +
"nc nchar(200)" +
");";
String insertSql = "insert into ? using " + tableName + " tags(?,?,?,?,?,?,?,?,?,?,?,?,?) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
String dropSql = $"drop table if exists {tableName};";
TAOS_BIND[] tags = DataSource.GetTags();
TAOS_MULTI_BIND[] mBinds = DataSource.GetMultiBindArr();
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<String> expectResData = DataSource.GetMultiBindStableRowData();
IntPtr conn = database.conn;
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
IntPtr stmt = StmtUtilTools.StmtInit(conn);
StmtUtilTools.StmtPrepare(stmt, insertSql);
StmtUtilTools.SetTableNameTags(stmt, tableName + "_t1", tags);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[0], 0);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[1], 1);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[2], 2);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[3], 3);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[4], 4);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[5], 5);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[6], 6);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[7], 7);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[8], 8);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[9], 9);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[10], 10);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[11], 11);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[12], 12);
StmtUtilTools.BindSingleParamBatch(stmt, mBinds[13], 13);
StmtUtilTools.AddBatch(stmt);
StmtUtilTools.StmtExecute(stmt);
StmtUtilTools.StmtClose(stmt);
DataSource.FreeTaosBind(tags);
DataSource.FreeTaosMBind(mBinds);
string querySql = "select * from " + tableName;
IntPtr res = UtilsTools.ExecuteQuery(conn, querySql);
ResultSet actualResult = new ResultSet(res);
List<TDengineMeta> actualResMeta = actualResult.GetResultMeta();
List<string> actualResData = actualResult.GetResultData();
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
Assert.Equal(expectResData[i], actualResData[i]);
}
// Assert metadata
for (int i = 0; i < actualResMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualResMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualResMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualResMeta[i].size);
}
}
}
}
\ No newline at end of file
using TDengineDriver;
using Test.UtilsTools;
using System;
using System.Collections.Generic;
using Xunit;
using Test.UtilsTools.DataSource;
using System.Threading;
using Xunit.Abstractions;
using Test.Fixture;
using Test.Case.Attributes;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
[Collection("Database collection")]
public class SubscribeCases
{
DatabaseFixture database;
private readonly ITestOutputHelper output;
public SubscribeCases(DatabaseFixture fixture, ITestOutputHelper output)
{
this.database = fixture;
this.output = output;
}
/// <author>xiaolei</author>
/// <Name>SubscribeCases.ConsumeFromBegin</Name>
/// <describe>Subscribe a table and consume from beginning.</describe>
/// <filename>Subscribe.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "SubscribeCases.ConsumeFromBegin()"), TestExeOrder(1), Trait("Category", "Without callback")]
public void ConsumeFromBegin()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
var tableName = "subscribe_from_begin";
var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))";
var dropSql = $"drop table if exists {tableName}";
var colData = new List<Object>{1646150410100,true,1,11,1111,11111111,"value one","值壹",
1646150410200,true,2,22,2222,22222222,"value two","值贰",
1646150410300,false,3,33,3333,33333333,"value three","值三",
};
var colData2 = new List<Object>{1646150410400,false,4,44,4444,44444444,"value three","值肆",
1646150410500,true,5,55,5555,55555555,"value one","值伍",
1646150410600,true,6,66,6666,66666666,"value two","值陆",
};
var tagData = new List<Object> { 1, "tag_one", "标签壹" };
var tagData2 = new List<Object> { 2, "tag_two", "标签贰" };
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3);
String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3);
// Then
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3);
List<Object> expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3);
expectResData.AddRange(expectResData2);
var querySql = $"select * from {tableName}";
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
UtilsTools.ExecuteUpdate(conn, insertSql);
IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, null, IntPtr.Zero, 0);
_res = TDengine.Consume(subscribe);
// need to call fetch TAOS_RES
UtilsTools.GetResDataWithoutFree(_res);
TDengine.Unsubscribe(subscribe, true);
UtilsTools.ExecuteUpdate(conn, insertSql2);
Thread.Sleep(100);
subscribe = TDengine.Subscribe(conn, true, tableName, querySql, null, IntPtr.Zero, 0);
_res = TDengine.Consume(subscribe);
List<TDengineMeta> actualMeta = UtilsTools.GetResField(_res);
List<String> actualResData = UtilsTools.GetResDataWithoutFree(_res);
TDengine.Unsubscribe(subscribe, false);
Assert.Equal(expectResData.Count, actualResData.Count);
output.WriteLine("Assert Meta data");
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
output.WriteLine("Assert retrieve data");
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// output.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]);
Assert.Equal(expectResData[i].ToString(), actualResData[i]);
}
}
/// <author>xiaolei</author>
/// <Name>SubscribeCases.ConsumeFromLastProgress</Name>
/// <describe>Subscribe table from the last progress.</describe>
/// <filename>Subscribe.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "SubscribeCases.ConsumeFromLastProgress()"), TestExeOrder(2), Trait("Category", "Without callback")]
public void ConsumeFromLastProgress()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
var tableName = "subscribe_from_progress";
var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))";
var dropSql = $"drop table if exists {tableName}";
var colData = new List<Object>{1646150410100,true,1,11,1111,11111111,"value one","值壹",
1646150410200,true,2,22,2222,22222222,"value two","值贰",
1646150410300,false,3,33,3333,33333333,"value three","值叁",
};
var colData2 = new List<Object>{1646150410400,false,4,44,4444,44444444,"value three","值肆",
1646150410500,true,5,55,5555,55555555,"value one","值伍",
1646150410600,true,6,66,6666,66666666,"value two","值陆",
};
var tagData = new List<Object> { 1, "tag_one", "标签壹" };
var tagData2 = new List<Object> { 2, "tag_two", "标签贰" };
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3);
String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3);
// Then
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3);
List<Object> expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3);
var querySql = $"select * from {tableName}";
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
UtilsTools.ExecuteUpdate(conn, insertSql);
// First time subscribe
IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, null, IntPtr.Zero, 20);
_res = TDengine.Consume(subscribe);
// need to call fetch TAOS_RES
UtilsTools.GetResDataWithoutFree(_res);
// Close subscribe and save progress.
TDengine.Unsubscribe(subscribe, true);
// Insert new data.
UtilsTools.ExecuteUpdate(conn, insertSql2);
Thread.Sleep(1000);
subscribe = TDengine.Subscribe(conn, false, tableName, querySql, null, IntPtr.Zero, 20);
_res = TDengine.Consume(subscribe);
List<TDengineMeta> actualMeta = UtilsTools.GetResField(_res);
List<String> actualResData = UtilsTools.GetResDataWithoutFree(_res);
TDengine.Unsubscribe(subscribe, true);
output.WriteLine("Assert Meta data");
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
output.WriteLine("Assert retrieve data");
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// output.WriteLine("{0},{1},{2}", i, expectResData[i], actualResData[i]);
Assert.Equal(expectResData2[i].ToString(), actualResData[i]);
}
}
}
}
\ No newline at end of file
using TDengineDriver;
using Test.UtilsTools;
using System;
using System.Collections.Generic;
using Xunit;
using Test.UtilsTools.DataSource;
using System.Threading;
using Xunit.Abstractions;
using Test.Fixture;
using Test.Case.Attributes;
namespace Cases
{
[TestCaseOrderer("XUnit.Case.Orderers.TestExeOrderer", "Cases.ExeOrder")]
[Collection("Database collection")]
public class SubscribeAsyncCases
{
DatabaseFixture database;
private readonly ITestOutputHelper output;
public SubscribeAsyncCases(DatabaseFixture fixture, ITestOutputHelper output)
{
this.database = fixture;
this.output = output;
}
/// <author>xiaolei</author>
/// <Name>SubscribeAsyncCases.ConsumeFromBegin</Name>
/// <describe>Subscribe a table and consume through callback and the beginning record of the table</describe>
/// <filename>Subscribe.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "SubscribeAsyncCases.ConsumeFromBegin()"), TestExeOrder(1), Trait("Category", "With callback")]
public void ConsumeFromBegin()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
var tableName = "subscribe_async_from_begin";
var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))";
var dropSql = $"drop table if exists {tableName}";
var colData = new List<Object>{1646150410100,true,1,11,1111,11111111,"value one","值壹",
1646150410200,true,2,22,2222,22222222,"value two","值贰",
1646150410300,false,3,33,3333,33333333,"value three","值三",
};
var colData2 = new List<Object>{1646150410400,false,4,44,4444,44444444,"value three","值肆",
1646150410500,true,5,55,5555,55555555,"value one","值伍",
1646150410600,true,6,66,6666,66666666,"value two","值陆",
};
var tagData = new List<Object> { 1, "tag_one", "标签壹" };
var tagData2 = new List<Object> { 2, "tag_two", "标签贰" };
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3);
String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3);
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3);
List<Object> expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3);
expectResData.AddRange(expectResData2);
var querySql = $"select * from {tableName}";
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
UtilsTools.ExecuteUpdate(conn, insertSql);
SubscribeCallback subscribeCallback1 = new SubscribeCallback(SubCallback1);
SubscribeCallback subscribeCallback2 = new SubscribeCallback(SubCallback2);
IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, subscribeCallback1, IntPtr.Zero, 200);
UtilsTools.ExecuteUpdate(conn, insertSql2);
Thread.Sleep(1000);
TDengine.Unsubscribe(subscribe, true);
subscribe = TDengine.Subscribe(conn, true, tableName, querySql, subscribeCallback2, IntPtr.Zero, 200);
Thread.Sleep(1000);
TDengine.Unsubscribe(subscribe, false);
void SubCallback1(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
// cannot free taosRes using taosRes, otherwise will cause crash.
UtilsTools.GetResDataWithoutFree(taosRes);
}
else
{
output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}");
}
}
void SubCallback2(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
List<TDengineMeta> actualMeta = UtilsTools.GetResField(taosRes);
List<String> actualResData = UtilsTools.GetResDataWithoutFree(taosRes);
// UtilsTools.DisplayRes(taosRes);
if (actualResData.Count == 0)
{
output.WriteLine($"consume in subscribe callback without data");
}
else
{
output.WriteLine($"consume in subscribe callback with data");
Assert.Equal(expectResData.Count, actualResData.Count);
output.WriteLine("Assert Meta data");
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
output.WriteLine("Assert retrieve data");
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// output.WriteLine("index:{0},expectResData:{1},actualResData:{2}", i, expectResData[i], actualResData[i]);
Assert.Equal(expectResData[i].ToString(), actualResData[i]);
}
}
}
else
{
output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}");
}
}
}
/// <author>xiaolei</author>
/// <Name>SubscribeAsyncCases.ConsumeFromLastProgress</Name>
/// <describe>Subscribe a table and consume through callback and from last consume progress.</describe>
/// <filename>Subscribe.cs</filename>
/// <result>pass or failed </result>
[Fact(DisplayName = "SubscribeAsyncCases.ConsumeFromLastProgress()"), TestExeOrder(2), Trait("Category", "With callback")]
public void ConsumeFromLastProgress()
{
IntPtr conn = database.conn;
IntPtr _res = IntPtr.Zero;
var tableName = "subscribe_async_from_begin";
var createSql = $"create table if not exists {tableName}(ts timestamp,bl bool,i8 tinyint,i16 smallint,i32 int,i64 bigint,bnr binary(50),nchr nchar(50))tags(t_i32 int,t_bnr binary(50),t_nchr nchar(50))";
var dropSql = $"drop table if exists {tableName}";
var colData = new List<Object>{1646150410100,true,1,11,1111,11111111,"value one","值壹",
1646150410200,true,2,22,2222,22222222,"value two","值贰",
1646150410300,false,3,33,3333,33333333,"value three","值三",
};
var colData2 = new List<Object>{1646150410400,false,4,44,4444,44444444,"value three","值肆",
1646150410500,true,5,55,5555,55555555,"value one","值伍",
1646150410600,true,6,66,6666,66666666,"value two","值陆",
};
var tagData = new List<Object> { 1, "tag_one", "标签壹" };
var tagData2 = new List<Object> { 2, "tag_two", "标签贰" };
String insertSql = UtilsTools.ConstructInsertSql(tableName + "_s01", tableName, colData, tagData, 3);
String insertSql2 = UtilsTools.ConstructInsertSql(tableName + "_s02", tableName, colData2, tagData2, 3);
List<TDengineMeta> expectResMeta = DataSource.GetMetaFromDDL(createSql);
List<Object> expectResData = UtilsTools.CombineColAndTagData(colData, tagData, 3);
List<Object> expectResData2 = UtilsTools.CombineColAndTagData(colData2, tagData2, 3);
var querySql = $"select * from {tableName}";
UtilsTools.ExecuteUpdate(conn, dropSql);
UtilsTools.ExecuteUpdate(conn, createSql);
UtilsTools.ExecuteUpdate(conn, insertSql);
SubscribeCallback subscribeCallback1 = new SubscribeCallback(SubCallback1);
SubscribeCallback subscribeCallback2 = new SubscribeCallback(SubCallback2);
IntPtr subscribe = TDengine.Subscribe(conn, true, tableName, querySql, subscribeCallback1, IntPtr.Zero, 200);
Thread.Sleep(1000);
TDengine.Unsubscribe(subscribe, true);
UtilsTools.ExecuteUpdate(conn, insertSql2);
subscribe = TDengine.Subscribe(conn, false, tableName, querySql, subscribeCallback2, IntPtr.Zero, 200);
Thread.Sleep(1000);
TDengine.Unsubscribe(subscribe, false);
void SubCallback1(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
// cannot free taosRes using taosRes, otherwise will cause crash.
UtilsTools.GetResDataWithoutFree(taosRes);
}
else if (taosRes != IntPtr.Zero)
{
output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}");
}
}
void SubCallback2(IntPtr subscribe, IntPtr taosRes, IntPtr param, int code)
{
if (code == 0 && taosRes != IntPtr.Zero)
{
List<TDengineMeta> actualMeta = UtilsTools.GetResField(taosRes);
List<String> actualResData = UtilsTools.GetResDataWithoutFree(taosRes);
UtilsTools.DisplayRes(taosRes);
if (actualResData.Count == 0)
{
output.WriteLine($"consume in subscribe callback without data");
}
else
{
output.WriteLine($"consume in subscribe callback with data");
Assert.Equal(expectResData2.Count, actualResData.Count);
output.WriteLine("Assert Meta data");
//Assert Meta data
for (int i = 0; i < actualMeta.Count; i++)
{
Assert.Equal(expectResMeta[i].name, actualMeta[i].name);
Assert.Equal(expectResMeta[i].type, actualMeta[i].type);
Assert.Equal(expectResMeta[i].size, actualMeta[i].size);
}
output.WriteLine("Assert retrieve data");
// Assert retrieve data
for (int i = 0; i < actualResData.Count; i++)
{
// output.WriteLine("index:{0},expectResData:{1},actualResData:{2}", i, expectResData[i], actualResData[i]);
Assert.Equal(expectResData2[i].ToString(), actualResData[i]);
}
}
}
else
{
output.WriteLine($"async query data failed, failed code:{code}, reason:{TDengine.Error(taosRes)}");
}
}
}
}
}
\ No newline at end of file
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using TDengineDriver;
namespace Test.Fixture
{
public class DatabaseFixture : IDisposable
{
public IntPtr conn { get; set; }
private string user = "root";
private string password = "taosdata";
private string ip = "127.0.0.1";
private short port = 0;
private string db = "xunit_test_fixture";
public DatabaseFixture()
{
conn = TDengine.Connect(ip, user, password, "", port);
IntPtr res;
if (conn != IntPtr.Zero)
{
if ((res = TDengine.Query(conn, $"create database if not exists {db} keep 3650")) != IntPtr.Zero)
{
if ((res = TDengine.Query(conn, $"use {db}")) != IntPtr.Zero)
{
Console.WriteLine("Get connection success");
}
else
{
throw new Exception(TDengine.Error(res));
}
}
else
{
throw new Exception(TDengine.Error(res));
}
}
else
{
throw new Exception("Get TDConnection failed");
}
}
// public IntPtr TDConnection { get; }
public void Dispose()
{
IntPtr res;
if (conn != IntPtr.Zero)
{
if ((res = TDengine.Query(conn, $"drop database if exists {db}")) != IntPtr.Zero)
{
TDengine.Close(conn);
Console.WriteLine("close connection success");
}
else
{
throw new Exception(TDengine.Error(res));
}
}
else
{
throw new Exception("connection if already null");
}
}
}
}
using Xunit;
using Test.Fixture;
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
\ No newline at end of file
using System;
using TDengineDriver;
using System.Collections.Generic;
namespace Test.UtilsTools.ResultSet
{
public class ResultSet
{
private List<TDengineMeta> resultMeta;
private List<String> resultData;
// private bool isValidResult = false;
public ResultSet(IntPtr res)
{
resultMeta = UtilsTools.GetResField(res);
resultData = UtilsTools.GetResData(res);
}
public ResultSet(List<TDengineMeta> meta, List<String> data)
{
resultMeta = meta;
resultData = data;
}
public List<String> GetResultData()
{
return resultData;
}
public List<TDengineMeta> GetResultMeta()
{
return resultMeta;
}
}
}
\ No newline at end of file
using System;
using TDengineDriver;
using System.Runtime.InteropServices;
namespace Test.UtilsTools
{
public class StmtUtilTools
{
public static IntPtr StmtInit(IntPtr conn)
{
IntPtr stmt = TDengine.StmtInit(conn);
if (stmt == IntPtr.Zero)
{
Console.WriteLine("Init stmt failed");
UtilsTools.CloseConnection(conn);
UtilsTools.ExitProgram();
}
else
{
Console.WriteLine("Init stmt success");
}
return stmt;
}
public static void StmtPrepare(IntPtr stmt, string sql)
{
int res = TDengine.StmtPrepare(stmt, sql);
if (res == 0)
{
Console.WriteLine("stmt prepare success");
}
else
{
Console.WriteLine("stmt prepare failed " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void SetTableName(IntPtr stmt, String tableName)
{
int res = TDengine.StmtSetTbname(stmt, tableName);
if (res == 0)
{
Console.WriteLine("set_tbname success");
}
else
{
Console.Write("set_tbname failed, " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void SetTableNameTags(IntPtr stmt, String tableName, TAOS_BIND[] tags)
{
int res = TDengine.StmtSetTbnameTags(stmt, tableName, tags);
if (res == 0)
{
Console.WriteLine("set tbname && tags success");
}
else
{
Console.Write("set tbname && tags failed, " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void SetSubTableName(IntPtr stmt, string name)
{
int res = TDengine.StmtSetSubTbname(stmt, name);
if (res == 0)
{
Console.WriteLine("set subtable name success");
}
else
{
Console.Write("set subtable name failed, " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void BindParam(IntPtr stmt, TAOS_BIND[] binds)
{
int res = TDengine.StmtBindParam(stmt, binds);
if (res == 0)
{
Console.WriteLine("bind para success");
}
else
{
Console.Write("bind para failed, " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void BindSingleParamBatch(IntPtr stmt, TAOS_MULTI_BIND bind, int index)
{
int res = TDengine.StmtBindSingleParamBatch(stmt, ref bind, index);
if (res == 0)
{
Console.WriteLine("single bind batch success");
}
else
{
Console.Write("single bind batch failed: " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void BindParamBatch(IntPtr stmt, TAOS_MULTI_BIND[] bind)
{
int res = TDengine.StmtBindParamBatch(stmt, bind);
if (res == 0)
{
Console.WriteLine("bind parameter batch success");
}
else
{
Console.WriteLine("bind parameter batch failed, " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void AddBatch(IntPtr stmt)
{
int res = TDengine.StmtAddBatch(stmt);
if (res == 0)
{
Console.WriteLine("stmt add batch success");
}
else
{
Console.Write("stmt add batch failed,reason: " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void StmtExecute(IntPtr stmt)
{
int res = TDengine.StmtExecute(stmt);
if (res == 0)
{
Console.WriteLine("Execute stmt success");
}
else
{
Console.Write("Execute stmt failed,reason: " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static void StmtClose(IntPtr stmt)
{
int res = TDengine.StmtClose(stmt);
if (res == 0)
{
Console.WriteLine("close stmt success");
}
else
{
Console.WriteLine("close stmt failed, " + TDengine.StmtErrorStr(stmt));
StmtClose(stmt);
}
}
public static IntPtr StmtUseResult(IntPtr stmt)
{
IntPtr res = TDengine.StmtUseResult(stmt);
if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
{
if (res != IntPtr.Zero)
{
Console.Write("reason: " + TDengine.Error(res));
}
Console.WriteLine("");
StmtClose(stmt);
}
else
{
Console.WriteLine("StmtUseResult success");
}
return res;
}
public static void loadTableInfo(IntPtr conn, string[] arr)
{
if (TDengine.LoadTableInfo(conn, arr) == 0)
{
Console.WriteLine("load table info success");
}
else
{
Console.WriteLine("load table info failed");
}
}
}
}
\ No newline at end of file
using System;
namespace Test.Case.Attributes
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class TestExeOrderAttribute : Attribute
{
public int ExeOrder { get; private set; }
public TestExeOrderAttribute(int exeOrder) => ExeOrder = exeOrder;
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Linq;
using Xunit.Abstractions;
using Xunit.Sdk;
using Test.Case.Attributes;
namespace XUnit.Case.Orderers
{
public class TestExeOrderer : ITestCaseOrderer
{
public IEnumerable<TTestCase> OrderTestCases<TTestCase>(
IEnumerable<TTestCase> testCases) where TTestCase : ITestCase
{
string assemblyName = typeof(TestExeOrderAttribute).AssemblyQualifiedName!;
var sortedMethods = new SortedDictionary<int, List<TTestCase>>();
foreach (TTestCase testCase in testCases)
{
int exeOrder = testCase.TestMethod.Method
.GetCustomAttributes(assemblyName)
.FirstOrDefault()
?.GetNamedArgument<int>(nameof(TestExeOrderAttribute.ExeOrder)) ?? 0;
GetOrCreate(sortedMethods, exeOrder).Add(testCase);
}
foreach (TTestCase testCase in
sortedMethods.Keys.SelectMany(
exeOrder => sortedMethods[exeOrder].OrderBy(
testCase => testCase.TestMethod.Method.Name)))
{
yield return testCase;
}
}
private static TValue GetOrCreate<TKey, TValue>(
IDictionary<TKey, TValue> dictionary, TKey key)
where TKey : struct
where TValue : new() =>
dictionary.TryGetValue(key, out TValue result)
? result
: (dictionary[key] = new TValue());
}
}
\ No newline at end of file
using System;
using TDengineDriver;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using Xunit.Abstractions;
namespace Test.UtilsTools
{
public class UtilsTools
{
static string ip = "127.0.0.1";
static string user = "root";
static string password = "taosdata";
static string db = "";
static short port = 0;
//get a TDengine connection
public static IntPtr TDConnection()
{
TDengine.Options((int)TDengineInitOption.TSDB_OPTION_CONFIGDIR, GetConfigPath());
TDengine.Options((int)TDengineInitOption.TSDB_OPTION_SHELL_ACTIVITY_TIMER, "60");
TDengine.Init();
IntPtr conn = TDengine.Connect(ip, user, password, db, port);
// UtilsTools.ExecuteUpdate(conn, "drop database if exists csharp");
UtilsTools.ExecuteUpdate(conn, "create database if not exists csharp keep 3650");
UtilsTools.ExecuteUpdate(conn, "use csharp");
return conn;
}
//get taos.cfg file based on different os
public static string GetConfigPath()
{
string configDir = "";
if (OperatingSystem.IsOSPlatform("Windows"))
{
configDir = "C:/TDengine/cfg";
}
else if (OperatingSystem.IsOSPlatform("Linux"))
{
configDir = "/etc/taos";
}
else if (OperatingSystem.IsOSPlatform("macOS"))
{
configDir = "/usr/local/etc/taos";
}
return configDir;
}
public static IntPtr ExecuteQuery(IntPtr conn, String sql)
{
IntPtr res = TDengine.Query(conn, sql);
if (!IsValidResult(res))
{
Console.Write(sql.ToString() + " failure, ");
ExitProgram();
}
else
{
Console.WriteLine(sql.ToString() + " success");
}
return res;
}
public static IntPtr ExecuteErrorQuery(IntPtr conn, String sql)
{
IntPtr res = TDengine.Query(conn, sql);
if (!IsValidResult(res))
{
Console.Write(sql.ToString() + " failure, ");
ExitProgram();
}
else
{
Console.WriteLine(sql.ToString() + " success");
}
return res;
}
public static void ExecuteUpdate(IntPtr conn, String sql)
{
IntPtr res = TDengine.Query(conn, sql);
if (!IsValidResult(res))
{
Console.Write(sql.ToString() + " failure, ");
ExitProgram();
}
else
{
Console.WriteLine(sql.ToString() + " success");
}
TDengine.FreeResult(res);
}
public static void DisplayRes(IntPtr res)
{
if (!IsValidResult(res))
{
ExitProgram();
}
List<TDengineMeta> metaList = GetResField(res);
int fieldCount = metaList.Count;
IntPtr rowdata;
List<string> dataList = QueryRes(res, metaList);
for (int i = 0; i < dataList.Count; i += metaList.Count)
{
for (int j = 0; j < metaList.Count; j++)
{
Console.Write(" {0} \t|", dataList[i + j]);
}
Console.WriteLine("");
}
}
public static List<List<string>> GetResultSet(IntPtr res)
{
List<List<string>> result = new List<List<string>>();
List<string> colName = new List<string>();
List<string> dataRaw = new List<string>();
if (!IsValidResult(res))
{
ExitProgram();
}
List<TDengineMeta> metaList = GetResField(res);
result.Add(colName);
dataRaw = QueryRes(res, metaList);
result.Add(dataRaw);
if (TDengine.ErrorNo(res) != 0)
{
Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res));
}
return result;
}
public static bool IsValidResult(IntPtr res)
{
if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
{
if (res != IntPtr.Zero)
{
Console.Write("reason: " + TDengine.Error(res));
return false;
}
Console.WriteLine("");
return false;
}
return true;
}
public static void CloseConnection(IntPtr conn)
{
ExecuteUpdate(conn, "drop database if exists csharp");
if (conn != IntPtr.Zero)
{
TDengine.Close(conn);
Console.WriteLine("close connection success");
}
else
{
throw new Exception("connection if already null");
}
}
public static List<TDengineMeta> GetResField(IntPtr res)
{
List<TDengineMeta> metaList = TDengine.FetchFields(res);
return metaList;
}
public static void AssertEqual(string expectVal, string actualVal)
{
if (expectVal == actualVal)
{
Console.WriteLine("{0}=={1} pass", expectVal, actualVal);
}
else
{
Console.WriteLine("{0}=={1} failed", expectVal, actualVal);
ExitProgram();
}
}
public static void ExitProgram()
{
TDengine.Cleanup();
System.Environment.Exit(0);
}
public static List<String> GetResData(IntPtr res)
{
List<string> dataRaw = GetResDataWithoutFree(res);
FreeResult(res);
return dataRaw;
}
public static TDengineMeta ConstructTDengineMeta(string name, string type)
{
TDengineMeta _meta = new TDengineMeta();
_meta.name = name;
char[] separators = new char[] { '(', ')' };
string[] subs = type.Split(separators, StringSplitOptions.RemoveEmptyEntries);
switch (subs[0].ToUpper())
{
case "BOOL":
_meta.type = 1;
_meta.size = 1;
break;
case "TINYINT":
_meta.type = 2;
_meta.size = 1;
break;
case "SMALLINT":
_meta.type = 3;
_meta.size = 2;
break;
case "INT":
_meta.type = 4;
_meta.size = 4;
break;
case "BIGINT":
_meta.type = 5;
_meta.size = 8;
break;
case "TINYINT UNSIGNED":
_meta.type = 11;
_meta.size = 1;
break;
case "SMALLINT UNSIGNED":
_meta.type = 12;
_meta.size = 2;
break;
case "INT UNSIGNED":
_meta.type = 13;
_meta.size = 4;
break;
case "BIGINT UNSIGNED":
_meta.type = 14;
_meta.size = 8;
break;
case "FLOAT":
_meta.type = 6;
_meta.size = 4;
break;
case "DOUBLE":
_meta.type = 7;
_meta.size = 8;
break;
case "BINARY":
_meta.type = 8;
_meta.size = short.Parse(subs[1]);
break;
case "TIMESTAMP":
_meta.type = 9;
_meta.size = 8;
break;
case "NCHAR":
_meta.type = 10;
_meta.size = short.Parse(subs[1]);
break;
case "JSON":
_meta.type = 15;
_meta.size = 4096;
break;
default:
_meta.type = byte.MaxValue;
_meta.size = 0;
break;
}
return _meta;
}
private static List<string> QueryRes(IntPtr res, List<TDengineMeta> meta)
{
IntPtr taosRow;
List<string> dataRaw = new List<string>();
int fieldCount = meta.Count;
while ((taosRow = TDengine.FetchRows(res)) != IntPtr.Zero)
{
dataRaw.AddRange(FetchRow(taosRow, res));
}
if (TDengine.ErrorNo(res) != 0)
{
Console.Write("Query is not complete, Error {0:G}", TDengine.ErrorNo(res), TDengine.Error(res));
}
Console.WriteLine("");
return dataRaw;
}
// Generate insert sql for the with the coldata and tag data
public static string ConstructInsertSql(string table, string stable, List<Object> colData, List<Object> tagData, int numOfRows)
{
int numOfFields = colData.Count / numOfRows;
StringBuilder insertSql;
if (stable == "")
{
insertSql = new StringBuilder($"insert into {table} values(");
}
else
{
insertSql = new StringBuilder($"insert into {table} using {stable} tags(");
for (int j = 0; j < tagData.Count; j++)
{
if (tagData[j] is String)
{
insertSql.Append('\'');
insertSql.Append(tagData[j]);
insertSql.Append('\'');
}
else
{
insertSql.Append(tagData[j]);
}
if (j + 1 != tagData.Count)
{
insertSql.Append(',');
}
}
insertSql.Append(")values(");
}
for (int i = 0; i < colData.Count; i++)
{
if (colData[i] is String)
{
insertSql.Append('\'');
insertSql.Append(colData[i]);
insertSql.Append('\'');
}
else
{
insertSql.Append(colData[i]);
}
if ((i + 1) % numOfFields == 0 && (i + 1) != colData.Count)
{
insertSql.Append(")(");
}
else if ((i + 1) == colData.Count)
{
insertSql.Append(')');
}
else
{
insertSql.Append(',');
}
}
insertSql.Append(';');
//Console.WriteLine(insertSql.ToString());
return insertSql.ToString();
}
public static List<object> CombineColAndTagData(List<object> colData, List<object> tagData, int numOfRows)
{
var list = new List<Object>();
for (int i = 0; i < colData.Count; i++)
{
list.Add(colData[i]);
if ((i + 1) % (colData.Count / numOfRows) == 0)
{
for (int j = 0; j < tagData.Count; j++)
{
list.Add(tagData[j]);
}
}
}
return list;
}
/// <summary>
/// Using this method to free TAOS_RES,otherwise will lead memory
/// leak.Notice do not call this method while subscribe/consume until
/// end of the program.
/// </summary>
/// <param name="res">TAOS_RES, the resultset usually is return by taos_query()</param>
public static void FreeResult(IntPtr res)
{
TDengine.FreeResult(res);
}
/// <summary>
/// Using to parse TAOS_ROW.
/// </summary>
/// <param name="taosRow">This is TAOS_RES pointer</param>
/// <param name="taosRes"> This is TAOS_ROW pointer</param>
/// <returns></returns>
public static List<string> FetchRow(IntPtr taosRow, IntPtr taosRes)
{
List<TDengineMeta> metaList = TDengine.FetchFields(taosRes);
int numOfFiled = TDengine.FieldCount(taosRes);
List<String> dataRaw = new List<string>();
IntPtr colLengthPrt = TDengine.FetchLengths(taosRes);
int[] colLengthArr = new int[numOfFiled];
Marshal.Copy(colLengthPrt, colLengthArr, 0, numOfFiled);
for (int i = 0; i < numOfFiled; i++)
{
TDengineMeta meta = metaList[i];
IntPtr data = Marshal.ReadIntPtr(taosRow, IntPtr.Size * i);
if (data == IntPtr.Zero)
{
dataRaw.Add("NULL");
continue;
}
switch ((TDengineDataType)meta.type)
{
case TDengineDataType.TSDB_DATA_TYPE_BOOL:
bool v1 = Marshal.ReadByte(data) == 0 ? false : true;
dataRaw.Add(v1.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_TINYINT:
sbyte v2 = (sbyte)Marshal.ReadByte(data);
dataRaw.Add(v2.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_SMALLINT:
short v3 = Marshal.ReadInt16(data);
dataRaw.Add(v3.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_INT:
int v4 = Marshal.ReadInt32(data);
dataRaw.Add(v4.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_BIGINT:
long v5 = Marshal.ReadInt64(data);
dataRaw.Add(v5.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_FLOAT:
float v6 = (float)Marshal.PtrToStructure(data, typeof(float));
dataRaw.Add(v6.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_DOUBLE:
double v7 = (double)Marshal.PtrToStructure(data, typeof(double));
dataRaw.Add(v7.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_BINARY:
string v8 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
dataRaw.Add(v8);
break;
case TDengineDataType.TSDB_DATA_TYPE_TIMESTAMP:
long v9 = Marshal.ReadInt64(data);
dataRaw.Add(v9.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_NCHAR:
string v10 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
dataRaw.Add(v10);
break;
case TDengineDataType.TSDB_DATA_TYPE_UTINYINT:
byte v12 = Marshal.ReadByte(data);
dataRaw.Add(v12.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_USMALLINT:
ushort v13 = (ushort)Marshal.ReadInt16(data);
dataRaw.Add(v13.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_UINT:
uint v14 = (uint)Marshal.ReadInt32(data);
dataRaw.Add(v14.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_UBIGINT:
ulong v15 = (ulong)Marshal.ReadInt64(data);
dataRaw.Add(v15.ToString());
break;
case TDengineDataType.TSDB_DATA_TYPE_JSONTAG:
string v16 = Marshal.PtrToStringUTF8(data, colLengthArr[i]);
dataRaw.Add(v16);
break;
default:
dataRaw.Add("nonsupport data type value");
break;
}
}
return dataRaw;
}
/// <summary>
/// Get the result data from TAO_RES but this interface will
/// not free the TAO_RES at the end. Remember to free the TAOS_RES
/// when you need to do so.
/// </summary>
/// <param name="res"> This is a TAOS_RES pointer.</param>
/// <returns></returns>
public static List<String> GetResDataWithoutFree(IntPtr res)
{
List<string> colName = new List<string>();
List<string> dataRaw = new List<string>();
if (!IsValidResult(res))
{
ExitProgram();
}
List<TDengineMeta> meta = GetResField(res);
dataRaw = QueryRes(res, meta);
return dataRaw;
}
}
}
using System;
using Xunit;
using TDengineDriver;
namespace TDengineDriver.Test
{
public class TestTDengineMeta
{
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameBool</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's bool meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameBool()
{
string typeName = "BOOL";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 1;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameTINYINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's TinnyInt's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameTINYINT()
{
string typeName = "TINYINT";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 2;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameSMALLINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's SMALLINT's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameSMALLINT()
{
string typeName = "SMALLINT";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 3;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's INT's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameINT()
{
string typeName = "INT";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 4;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameBIGINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's BIGINT's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameBIGINT()
{
string typeName = "BIGINT";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 5;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameUTINYINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's TINYINT UNSIGNED's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameUTINYINT()
{
string typeName = "TINYINT UNSIGNED";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 11;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameUSMALLINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's SMALLINT UNSIGNED's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameUSMALLINT()
{
string typeName = "SMALLINT UNSIGNED";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 12;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameUINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's INT UNSIGNED's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameUINT()
{
string typeName = "INT UNSIGNED";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 13;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameUBIGINT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's BIGINT UNSIGNED's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameUBIGINT()
{
string typeName = "BIGINT UNSIGNED";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 14;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameFLOAT</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's FLOAT's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameFLOAT()
{
string typeName = "FLOAT";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 6;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameDOUBLE</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's DOUBLE's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameDOUBLE()
{
string typeName = "DOUBLE";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 7;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameSTRING</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's BINARY's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameSTRING()
{
string typeName = "BINARY";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 8;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameTIMESTAMP</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's TIMESTAMP's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameTIMESTAMP()
{
string typeName = "TIMESTAMP";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 9;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameNCHAR</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's NCHAR's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameNCHAR()
{
string typeName = "NCHAR";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
meta.type = 10;
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
/// <author>xiaolei</author>
/// <Name>TestTDengineMeta.TestTypeNameUndefined</Name>
/// <describe>Unit test for object TDengineDriver.TDengineMeta's undefine's meta info</describe>
/// <filename>TestTDengineMeta.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestTypeNameUndefined()
{
string typeName = "undefine";
TDengineDriver.TDengineMeta meta = new TDengineDriver.TDengineMeta();
string metaTypeName = meta.TypeName();
Assert.Equal(metaTypeName, typeName);
}
}
}
using System;
using Xunit;
using TDengineDriver;
using System.Runtime.InteropServices;
namespace TDengineDriver.Test
{
public class TestTaosBind
{
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBoolTrue</Name>
/// <describe>Unit test for binding boolean true value using TAOS_BIND struct through stmt</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBoolTrue()
{
int bufferType = 1;
bool buffer = true;
int bufferLength = sizeof(bool);
int length = sizeof(bool);
TDengineDriver.TAOS_BIND bind = TaosBind.BindBool(true);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
bool bindBuffer = Convert.ToBoolean(Marshal.ReadByte(bind.buffer));
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBoolFalse</Name>
/// <describe>Unit test for binding boolean false value using TAOS_BIND struct through stmt</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBoolFalse()
{
int bufferType = 1;
bool buffer = false;
int bufferLength = sizeof(bool);
int length = sizeof(bool);
TDengineDriver.TAOS_BIND bind = TaosBind.BindBool(false);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
bool bindBuffer = Convert.ToBoolean(Marshal.ReadByte(bind.buffer));
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindTinyIntZero</Name>
/// <describe>Unit test for binding tinny int zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindTinyIntZero()
{
int bufferType = 2;
sbyte buffer = 0;
int bufferLength = sizeof(sbyte);
int length = sizeof(sbyte);
TDengineDriver.TAOS_BIND bind = TaosBind.BindTinyInt(0);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
sbyte bindBuffer = Convert.ToSByte(Marshal.ReadByte(bind.buffer));
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindTinyIntPositive</Name>
/// <describe>Unit test for binding tinny int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindTinyIntPositive()
{
int bufferType = 2;
sbyte buffer = sbyte.MaxValue;
int bufferLength = sizeof(sbyte);
int length = sizeof(sbyte);
TDengineDriver.TAOS_BIND bind = TaosBind.BindTinyInt(sbyte.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
sbyte bindBuffer = Convert.ToSByte(Marshal.ReadByte(bind.buffer));
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindTinyIntNegative</Name>
/// <describe>Unit test for binding tinny int negative value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindTinyIntNegative()
{
int bufferType = 2;
short buffer = sbyte.MinValue;
int bufferLength = sizeof(sbyte);
int length = sizeof(sbyte);
TDengineDriver.TAOS_BIND bind = TaosBind.BindTinyInt(sbyte.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
short bindBuffer = Marshal.ReadInt16(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindSmallIntNegative</Name>
/// <describe>Unit test for binding small int negative value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindSmallIntNegative()
{
int bufferType = 3;
short buffer = short.MinValue;
int bufferLength = sizeof(short);
int length = sizeof(short);
TDengineDriver.TAOS_BIND bind = TaosBind.BindSmallInt(short.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
short bindBuffer = Marshal.ReadInt16(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindSmallIntZero</Name>
/// <describe>Unit test for binding small int zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindSmallIntZero()
{
int bufferType = 3;
short buffer = 0;
int bufferLength = sizeof(short);
int length = sizeof(short);
TDengineDriver.TAOS_BIND bind = TaosBind.BindSmallInt(0);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
short bindBuffer = Marshal.ReadInt16(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindSmallIntPositive</Name>
/// <describe>Unit test for binding small int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindSmallIntPositive()
{
int bufferType = 3;
short buffer = short.MaxValue;
int bufferLength = sizeof(short);
int length = sizeof(short);
TDengineDriver.TAOS_BIND bind = TaosBind.BindSmallInt(short.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
short bindBuffer = Marshal.ReadInt16(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindIntNegative</Name>
/// <describe>Unit test for binding small int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindIntNegative()
{
int bufferType = 4;
int buffer = int.MinValue;
int bufferLength = sizeof(int);
int length = sizeof(int);
TDengineDriver.TAOS_BIND bind = TaosBind.BindInt(int.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
int bindBuffer = Marshal.ReadInt32(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindIntZero</Name>
/// <describe>Unit test for binding int zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindIntZero()
{
int bufferType = 4;
int buffer = 0;
int bufferLength = sizeof(int);
int length = sizeof(int);
TDengineDriver.TAOS_BIND bind = TaosBind.BindInt(0);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
int bindBuffer = Marshal.ReadInt32(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindIntPositive</Name>
/// <describe>Unit test for binding int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindIntPositive()
{
int bufferType = 4;
int buffer = int.MaxValue;
int bufferLength = sizeof(int);
int length = sizeof(int);
TDengineDriver.TAOS_BIND bind = TaosBind.BindInt(int.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
int bindBuffer = Marshal.ReadInt32(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBigIntNegative</Name>
/// <describe>Unit test for binding int negative value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBigIntNegative()
{
int bufferType = 5;
long buffer = long.MinValue;
int bufferLength = sizeof(long);
int length = sizeof(long);
TDengineDriver.TAOS_BIND bind = TaosBind.BindBigInt(long.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
long bindBuffer = Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBigIntZero</Name>
/// <describe>Unit test for binding big int zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBigIntZero()
{
int bufferType = 5;
long buffer = 0;
int bufferLength = sizeof(long);
int length = sizeof(long);
TDengineDriver.TAOS_BIND bind = TaosBind.BindBigInt(0);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
long bindBuffer = Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBigIntPositive</Name>
/// <describe>Unit test for binding big int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBigIntPositive()
{
int bufferType = 5;
long buffer = long.MaxValue;
int bufferLength = sizeof(long);
int length = sizeof(long);
TDengineDriver.TAOS_BIND bind = TaosBind.BindBigInt(long.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
long bindBuffer = Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBigIntPositive</Name>
/// <describe>Unit test for binding big int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUTinyZero()
{
int bufferType = 11;
byte buffer = 0;
int bufferLength = sizeof(sbyte);
int length = sizeof(sbyte);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUTinyInt(0);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
byte bindBuffer = Marshal.ReadByte(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindUTinyPositive</Name>
/// <describe>Unit test for binding unsigned tinny int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUTinyPositive()
{
int bufferType = 11;
byte buffer = byte.MaxValue;
int bufferLength = sizeof(sbyte);
int length = sizeof(sbyte);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUTinyInt(byte.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
byte bindBuffer = Marshal.ReadByte(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindUSmallIntZero</Name>
/// <describe>Unit test for binding unsigned small int zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUSmallIntZero()
{
int bufferType = 12;
ushort buffer = ushort.MinValue;
int bufferLength = sizeof(ushort);
int length = sizeof(ushort);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUSmallInt(ushort.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
ushort bindBuffer = (ushort)Marshal.ReadInt16(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindUSmallIntPositive</Name>
/// <describe>Unit test for binding unsigned small int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUSmallIntPositive()
{
int bufferType = 12;
ushort buffer = ushort.MaxValue;
int bufferLength = sizeof(ushort);
int length = sizeof(ushort);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUSmallInt(ushort.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
ushort bindBuffer = (ushort)Marshal.ReadInt16(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindUIntZero</Name>
/// <describe>Unit test for binding unsigned int zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUIntZero()
{
int bufferType = 13;
uint buffer = uint.MinValue;
int bufferLength = sizeof(uint);
int length = sizeof(uint);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUInt(uint.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
uint bindBuffer = (uint)Marshal.ReadInt32(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindUIntPositive</Name>
/// <describe>Unit test for binding unsigned int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUIntPositive()
{
int bufferType = 13;
uint buffer = uint.MaxValue;
int bufferLength = sizeof(uint);
int length = sizeof(uint);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUInt(uint.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
uint bindBuffer = (uint)Marshal.ReadInt32(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindUBigIntZero</Name>
/// <describe>Unit test for binding unsigned big int zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUBigIntZero()
{
int bufferType = 14;
ulong buffer = ulong.MinValue;
int bufferLength = sizeof(ulong);
int length = sizeof(ulong);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUBigInt(ulong.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
ulong bindBuffer = (ulong)Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindUBigIntPositive</Name>
/// <describe>Unit test for binding unsigned big int positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindUBigIntPositive()
{
int bufferType = 14;
ulong buffer = ulong.MaxValue;
int bufferLength = sizeof(ulong);
int length = sizeof(ulong);
TDengineDriver.TAOS_BIND bind = TaosBind.BindUBigInt(ulong.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
ulong bindBuffer = (ulong)Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindFloatNegative</Name>
/// <describe>Unit test for binding float negative value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindFloatNegative()
{
int bufferType = 6;
float buffer = float.MinValue;
int bufferLength = sizeof(float);
int length = sizeof(float);
TDengineDriver.TAOS_BIND bind = TaosBind.BindFloat(float.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
float[] bindBufferArr = new float[1];
Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBufferArr[0], buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindFloatNegative</Name>
/// <describe>Unit test for binding float zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindFloatZero()
{
int bufferType = 6;
float buffer = 0;
int bufferLength = sizeof(float);
int length = sizeof(float);
TDengineDriver.TAOS_BIND bind = TaosBind.BindFloat(0F);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
float[] bindBufferArr = new float[1];
Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBufferArr[0], buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindFloatPositive</Name>
/// <describe>Unit test for binding float positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindFloatPositive()
{
int bufferType = 6;
float buffer = float.MaxValue;
int bufferLength = sizeof(float);
int length = sizeof(float);
TDengineDriver.TAOS_BIND bind = TaosBind.BindFloat(float.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
float[] bindBufferArr = new float[1];
Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBufferArr[0], buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindDoubleZero</Name>
/// <describe>Unit test for binding double zero value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindDoubleZero()
{
int bufferType = 7;
double buffer = 0;
int bufferLength = sizeof(double);
int length = sizeof(double);
TDengineDriver.TAOS_BIND bind = TaosBind.BindDouble(0D);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
double[] bindBufferArr = new double[1];
Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBufferArr[0], buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindDoublePositive</Name>
/// <describe>Unit test for binding double positive value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindDoublePositive()
{
int bufferType = 7;
double buffer = double.MaxValue;
int bufferLength = sizeof(double);
int length = sizeof(double);
TDengineDriver.TAOS_BIND bind = TaosBind.BindDouble(double.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
double[] bindBufferArr = new double[1];
Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBufferArr[0], buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindDoubleNegative</Name>
/// <describe>Unit test for binding double negative value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindDoubleNegative()
{
int bufferType = 7;
double buffer = double.MinValue;
int bufferLength = sizeof(double);
int length = sizeof(double);
TDengineDriver.TAOS_BIND bind = TaosBind.BindDouble(double.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
double[] bindBufferArr = new double[1];
Marshal.Copy(bind.buffer, bindBufferArr, 0, bindBufferArr.Length);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBufferArr[0], buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBinaryEn</Name>
/// <describe>Unit test for binding binary character without CN character using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBinaryEn()
{
int bufferType = 8;
String buffer = "qwertyuiopasdghjklzxcvbnm<>?:\"{}+_)(*&^%$#@!~QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./`1234567890-=";
int bufferLength = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
TDengineDriver.TAOS_BIND bind = TaosBind.BindBinary("qwertyuiopasdghjklzxcvbnm<>?:\"{}+_)(*&^%$#@!~QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./`1234567890-=");
int bindLengthPtr = Marshal.ReadInt32(bind.length);
string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBinaryCn</Name>
/// <describe>Unit test for binding binary character with CN character using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBinaryCn()
{
int bufferType = 8;
String buffer = "一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./";
int bufferLength = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
TDengineDriver.TAOS_BIND bind = TaosBind.BindBinary("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./");
int bindLengthPtr = Marshal.ReadInt32(bind.length);
string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindBinaryCnAndEn</Name>
/// <describe>Unit test for binding binary characters with CN and other characters using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindBinaryCnAndEn()
{
int bufferType = 8;
String buffer = "一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
int bufferLength = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
TDengineDriver.TAOS_BIND bind = TaosBind.BindBinary("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM");
int bindLengthPtr = Marshal.ReadInt32(bind.length);
string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindNcharEn</Name>
/// <describe>Unit test for binding nchar characters without cn using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindNcharEn()
{
int bufferType = 10;
String buffer = "qwertyuiopasdghjklzxcvbnm<>?:\"{}+_)(*&^%$#@!~QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./`1234567890-=";
int bufferLength = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
TDengineDriver.TAOS_BIND bind = TaosBind.BindNchar("qwertyuiopasdghjklzxcvbnm<>?:\"{}+_)(*&^%$#@!~QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./`1234567890-=");
int bindLengthPtr = Marshal.ReadInt32(bind.length);
string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindNcharCn</Name>
/// <describe>Unit test for binding nchar characters with cn using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindNcharCn()
{
int bufferType = 10;
String buffer = "一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./";
int bufferLength = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
TDengineDriver.TAOS_BIND bind = TaosBind.BindNchar("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./");
int bindLengthPtr = Marshal.ReadInt32(bind.length);
string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindNcharCnAndEn</Name>
/// <describe>Unit test for binding nchar with cn characters and other characters using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindNcharCnAndEn()
{
int bufferType = 10;
String buffer = "一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
int bufferLength = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
int length = System.Text.Encoding.UTF8.GetBytes(buffer).Length;
TDengineDriver.TAOS_BIND bind = TaosBind.BindNchar("一二两三四五六七八九十廿毛另壹贰叁肆伍陆柒捌玖拾佰仟万亿元角分零整1234567890`~!@#$%^&*()_+[]{};':<>?,./qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM");
int bindLengthPtr = Marshal.ReadInt32(bind.length);
string bindBuffer = Marshal.PtrToStringUTF8(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindNil</Name>
/// <describe>Unit test for binding null value using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindNil()
{
int bufferType = 0;
int isNull = 1;
TDengineDriver.TAOS_BIND bind = TaosBind.BindNil();
int bindIsNull = Marshal.ReadInt32(bind.is_null);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindIsNull, isNull);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindTimestampNegative</Name>
/// <describe>Unit test for binding negative timestamp using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindTimestampNegative()
{
int bufferType = 9;
long buffer = long.MinValue;
int bufferLength = sizeof(long);
int length = sizeof(long);
TDengineDriver.TAOS_BIND bind = TaosBind.BindTimestamp(long.MinValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
long bindBuffer = Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindTimestampZero</Name>
/// <describe>Unit test for binding zero timestamp using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindTimestampZero()
{
int bufferType = 9;
long buffer = 0;
int bufferLength = sizeof(long);
int length = sizeof(long);
TDengineDriver.TAOS_BIND bind = TaosBind.BindTimestamp(0);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
long bindBuffer = Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
/// <author>xiaolei</author>
/// <Name>TestTaosBind.TestBindTimestampPositive</Name>
/// <describe>Unit test for binding positive timestamp using TAOS_BIND struct through stmt.</describe>
/// <filename>TestTaosBind.cs</filename>
/// <result>pass or failed </result>
[Fact]
public void TestBindTimestampPositive()
{
int bufferType = 9;
long buffer = long.MaxValue;
int bufferLength = sizeof(long);
int length = sizeof(long);
TDengineDriver.TAOS_BIND bind = TaosBind.BindTimestamp(long.MaxValue);
int bindLengthPtr = Marshal.ReadInt32(bind.length);
long bindBuffer = Marshal.ReadInt64(bind.buffer);
Assert.Equal(bind.buffer_type, bufferType);
Assert.Equal(bindBuffer, buffer);
Assert.Equal(bind.buffer_length, bufferLength);
Assert.Equal(bindLengthPtr, length);
Marshal.FreeHGlobal(bind.buffer);
Marshal.FreeHGlobal(bind.length);
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<IsPackable>false</IsPackable>
<NoWarn>CS1591</NoWarn>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<DocumentationFile>..\doc\UnitTest.XML</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.msbuild" Version="3.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\TDengineDriver\TDengineDriver.csproj" />
</ItemGroup>
</Project>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册