未验证 提交 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
| [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 写入的示例 |
| [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 实现的异步查询的示例 |
| [subscribe](https://github.com/taosdata/TDengine/blob/develop/src/connector/C%23/examples/SubscribeSample.cs) | 使用 TDengine.Connector 实现的订阅数据的示例 |
| [async query](https://github.com/taosdata/taos-connector-dotnet/blob/develop/examples/QueryAsyncSample.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;
}
}
}
<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 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;
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 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
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册