diff --git a/docs/examples/R/connect_native.r b/docs/examples/R/connect_native.r new file mode 100644 index 0000000000000000000000000000000000000000..3c5c9e199b61263b785e86238d277bef70070b28 --- /dev/null +++ b/docs/examples/R/connect_native.r @@ -0,0 +1,16 @@ +if (! "RJDBC" %in% installed.packages()[, "Package"]) { + install.packages('RJDBC', repos='http://cran.us.r-project.org') +} + +# ANCHOR: demo +library("DBI") +library("rJava") +library("RJDBC") + +args<- commandArgs(trailingOnly = TRUE) +driver_path = args[1] # path to jdbc-driver for example: "/root/taos-jdbcdriver-3.0.0-dist.jar" +driver = JDBC("com.taosdata.jdbc.TSDBDriver", driver_path) +conn = dbConnect(driver, "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata") +dbGetQuery(conn, "SELECT server_version()") +dbDisconnect(conn) +# ANCHOR_END: demo diff --git a/docs/examples/R/connect_rest.r b/docs/examples/R/connect_rest.r new file mode 100644 index 0000000000000000000000000000000000000000..5ceec572fc26575dfc597983eeac3233bc4488ab --- /dev/null +++ b/docs/examples/R/connect_rest.r @@ -0,0 +1,12 @@ +if (! "RJDBC" %in% installed.packages()[, "Package"]) { + install.packages('RJDBC', repos='http://cran.us.r-project.org') +} + +library("DBI") +library("rJava") +library("RJDBC") +driver_path = "/home/debug/build/lib/taos-jdbcdriver-2.0.38-dist.jar" +driver = JDBC("com.taosdata.jdbc.rs.RestfulDriver", driver_path) +conn = dbConnect(driver, "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata") +dbGetQuery(conn, "SELECT server_version()") +dbDisconnect(conn) \ No newline at end of file diff --git a/docs/examples/c/.gitignore b/docs/examples/c/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..afe974314989a1e3aa4eee703738a9a960c18577 --- /dev/null +++ b/docs/examples/c/.gitignore @@ -0,0 +1,3 @@ +* +!*.c +!.gitignore diff --git a/docs/examples/c/async_query_example.c b/docs/examples/c/async_query_example.c new file mode 100644 index 0000000000000000000000000000000000000000..b370420b124a21b05f8e0b4041fb1461b1e2478a --- /dev/null +++ b/docs/examples/c/async_query_example.c @@ -0,0 +1,195 @@ +// compile with: +// gcc -o async_query_example async_query_example.c -ltaos + +#include +#include +#include +#include +#include +#include + +typedef int16_t VarDataLenT; + +#define TSDB_NCHAR_SIZE sizeof(int32_t) +#define VARSTR_HEADER_SIZE sizeof(VarDataLenT) + +#define GET_FLOAT_VAL(x) (*(float *)(x)) +#define GET_DOUBLE_VAL(x) (*(double *)(x)) + +#define varDataLen(v) ((VarDataLenT *)(v))[0] + +int printRow(char *str, TAOS_ROW row, TAOS_FIELD *fields, int numFields) { + int len = 0; + char split = ' '; + + for (int i = 0; i < numFields; ++i) { + if (i > 0) { + str[len++] = split; + } + + if (row[i] == NULL) { + len += sprintf(str + len, "%s", "NULL"); + continue; + } + + switch (fields[i].type) { + case TSDB_DATA_TYPE_TINYINT: + len += sprintf(str + len, "%d", *((int8_t *)row[i])); + break; + + case TSDB_DATA_TYPE_UTINYINT: + len += sprintf(str + len, "%u", *((uint8_t *)row[i])); + break; + + case TSDB_DATA_TYPE_SMALLINT: + len += sprintf(str + len, "%d", *((int16_t *)row[i])); + break; + + case TSDB_DATA_TYPE_USMALLINT: + len += sprintf(str + len, "%u", *((uint16_t *)row[i])); + break; + + case TSDB_DATA_TYPE_INT: + len += sprintf(str + len, "%d", *((int32_t *)row[i])); + break; + + case TSDB_DATA_TYPE_UINT: + len += sprintf(str + len, "%u", *((uint32_t *)row[i])); + break; + + case TSDB_DATA_TYPE_BIGINT: + len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i])); + break; + + case TSDB_DATA_TYPE_UBIGINT: + len += sprintf(str + len, "%" PRIu64, *((uint64_t *)row[i])); + break; + + case TSDB_DATA_TYPE_FLOAT: { + float fv = 0; + fv = GET_FLOAT_VAL(row[i]); + len += sprintf(str + len, "%f", fv); + } break; + + case TSDB_DATA_TYPE_DOUBLE: { + double dv = 0; + dv = GET_DOUBLE_VAL(row[i]); + len += sprintf(str + len, "%lf", dv); + } break; + + case TSDB_DATA_TYPE_BINARY: + case TSDB_DATA_TYPE_NCHAR: { + int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE); + memcpy(str + len, row[i], charLen); + len += charLen; + } break; + + case TSDB_DATA_TYPE_TIMESTAMP: + len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i])); + break; + + case TSDB_DATA_TYPE_BOOL: + len += sprintf(str + len, "%d", *((int8_t *)row[i])); + default: + break; + } + } + + return len; +} + +void printHeader(TAOS_RES *res) { + int numFields = taos_num_fields(res); + TAOS_FIELD *fields = taos_fetch_fields(res); + char header[256] = {0}; + int len = 0; + for (int i = 0; i < numFields; ++i) { + len += sprintf(header + len, "%s ", fields[i].name); + } + puts(header); +} + +// ANCHOR: demo + +/** + * @brief call back function of taos_fetch_row_a + * + * @param param : the third parameter you passed to taos_fetch_row_a + * @param res : pointer of TAOS_RES + * @param numOfRow : number of rows fetched in this batch. will be 0 if there is no more data. + * @return void* + */ +void *fetch_row_callback(void *param, TAOS_RES *res, int numOfRow) { + printf("numOfRow = %d \n", numOfRow); + int numFields = taos_num_fields(res); + TAOS_FIELD *fields = taos_fetch_fields(res); + TAOS *_taos = (TAOS *)param; + if (numOfRow > 0) { + for (int i = 0; i < numOfRow; ++i) { + TAOS_ROW row = taos_fetch_row(res); + char temp[256] = {0}; + printRow(temp, row, fields, numFields); + puts(temp); + } + taos_fetch_rows_a(res, fetch_row_callback, _taos); + } else { + printf("no more data, close the connection.\n"); + taos_free_result(res); + taos_close(_taos); + taos_cleanup(); + } +} + +/** + * @brief callback function of taos_query_a + * + * @param param: the fourth parameter you passed to taos_query_a + * @param res : the result set + * @param code : status code + * @return void* + */ +void *select_callback(void *param, TAOS_RES *res, int code) { + printf("query callback ...\n"); + TAOS *_taos = (TAOS *)param; + if (code == 0 && res) { + printHeader(res); + taos_fetch_rows_a(res, fetch_row_callback, _taos); + } else { + printf("failed to execute taos_query. error: %s\n", taos_errstr(res)); + taos_free_result(res); + taos_close(_taos); + taos_cleanup(); + exit(EXIT_FAILURE); + } +} + +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", "power", 6030); + if (taos == NULL) { + puts("failed to connect to server"); + exit(EXIT_FAILURE); + } + // param one is the connection returned by taos_connect. + // param two is the SQL to execute. + // param three is the callback function. + // param four can be any pointer. It will be passed to your callback function as the first parameter. we use taos + // here, because we want to close it after getting data. + taos_query_a(taos, "SELECT * FROM meters", select_callback, taos); + sleep(1); +} + +// output: +// query callback ... +// ts current voltage phase location groupid +// numOfRow = 8 +// 1538548685500 11.800000 221 0.280000 california.losangeles 2 +// 1538548696600 13.400000 223 0.290000 california.losangeles 2 +// 1538548685000 10.800000 223 0.290000 california.losangeles 3 +// 1538548686500 11.500000 221 0.350000 california.losangeles 3 +// 1538548685000 10.300000 219 0.310000 california.sanfrancisco 2 +// 1538548695000 12.600000 218 0.330000 california.sanfrancisco 2 +// 1538548696800 12.300000 221 0.310000 california.sanfrancisco 2 +// 1538548696650 10.300000 218 0.250000 california.sanfrancisco 3 +// numOfRow = 0 +// no more data, close the connection. +// ANCHOR_END: demo \ No newline at end of file diff --git a/docs/examples/c/connect_example.c b/docs/examples/c/connect_example.c new file mode 100644 index 0000000000000000000000000000000000000000..1a23df4806d7ff986898734e1971f6e0cd7c5360 --- /dev/null +++ b/docs/examples/c/connect_example.c @@ -0,0 +1,24 @@ +// compile with +// gcc connect_example.c -o connect_example -ltaos +#include +#include +#include "taos.h" + +int main() { + const char *host = "localhost"; + const char *user = "root"; + const char *passwd = "taosdata"; + // if don't want to connect to a default db, set it to NULL or "" + const char *db = NULL; + uint16_t port = 0; // 0 means use the default port + TAOS *taos = taos_connect(host, user, passwd, db, port); + if (taos == NULL) { + int errno = taos_errno(NULL); + char *msg = taos_errstr(NULL); + printf("%d, %s\n", errno, msg); + } else { + printf("connected\n"); + taos_close(taos); + } + taos_cleanup(); +} diff --git a/docs/examples/c/error_handle_example.c b/docs/examples/c/error_handle_example.c new file mode 100644 index 0000000000000000000000000000000000000000..e7dedb263df250f6634aa15fab2729cbaf4e5972 --- /dev/null +++ b/docs/examples/c/error_handle_example.c @@ -0,0 +1,24 @@ +// compile with +// gcc error_handle_example.c -o error_handle_example -ltaos +#include +#include +#include "taos.h" + +int main() { + const char *host = "localhost"; + const char *user = "root"; + const char *passwd = "taosdata"; + // if don't want to connect to a default db, set it to NULL or "" + const char *db = "notexist"; + uint16_t port = 0; // 0 means use the default port + TAOS *taos = taos_connect(host, user, passwd, db, port); + if (taos == NULL) { + int errno = taos_errno(NULL); + char *msg = taos_errstr(NULL); + printf("%d, %s\n", errno, msg); + } else { + printf("connected\n"); + taos_close(taos); + } + taos_cleanup(); +} diff --git a/docs/examples/c/insert_example.c b/docs/examples/c/insert_example.c new file mode 100644 index 0000000000000000000000000000000000000000..ce8fdc5b9372aec7b02d3c9254ec25c4c4f62adc --- /dev/null +++ b/docs/examples/c/insert_example.c @@ -0,0 +1,51 @@ +// compile with +// gcc -o insert_example insert_example.c -ltaos +#include +#include +#include "taos.h" + + +/** + * @brief execute sql and print affected rows. + * + * @param taos + * @param sql + */ +void executeSQL(TAOS *taos, const char *sql) { + TAOS_RES *res = taos_query(taos, sql); + int code = taos_errno(res); + if (code != 0) { + printf("Error code: %d; Message: %s\n", code, taos_errstr(res)); + taos_free_result(res); + taos_close(taos); + exit(EXIT_FAILURE); + } + int affectedRows = taos_affected_rows(res); + printf("affected rows %d\n", affectedRows); + taos_free_result(res); +} + + + +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030); + if (taos == NULL) { + printf("failed to connect to server\n"); + exit(EXIT_FAILURE); + } + executeSQL(taos, "CREATE DATABASE power"); + executeSQL(taos, "USE power"); + executeSQL(taos, "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); + executeSQL(taos, "INSERT INTO d1001 USING meters TAGS(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000)" + "d1002 USING meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)" + "d1003 USING meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000)" + "d1004 USING meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)"); + taos_close(taos); + taos_cleanup(); +} + +// output: +// affected rows 0 +// affected rows 0 +// affected rows 0 +// affected rows 8 \ No newline at end of file diff --git a/docs/examples/c/json_protocol_example.c b/docs/examples/c/json_protocol_example.c new file mode 100644 index 0000000000000000000000000000000000000000..9d276127a64c3d74322e30587ab2e319c29cbf65 --- /dev/null +++ b/docs/examples/c/json_protocol_example.c @@ -0,0 +1,52 @@ +// compile with +// gcc -o json_protocol_example json_protocol_example.c -ltaos +#include +#include +#include +#include "taos.h" + +void executeSQL(TAOS *taos, const char *sql) { + TAOS_RES *res = taos_query(taos, sql); + int code = taos_errno(res); + if (code != 0) { + printf("%s\n", taos_errstr(res)); + taos_free_result(res); + taos_close(taos); + exit(EXIT_FAILURE); + } + taos_free_result(res); +} + +// ANCHOR: main +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 6030); + if (taos == NULL) { + printf("failed to connect to server\n"); + exit(EXIT_FAILURE); + } + executeSQL(taos, "DROP DATABASE IF EXISTS test"); + executeSQL(taos, "CREATE DATABASE test"); + executeSQL(taos, "USE test"); + char *line = + "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": " + "\"California.SanFrancisco\", \"groupid\": 2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, " + "\"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}},{\"metric\": \"meters.current\", " + "\"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": " + "2}},{\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": " + "\"California.LosAngeles\", \"groupid\": 1}}]"; + + char *lines[] = {line}; + TAOS_RES *res = taos_schemaless_insert(taos, lines, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + if (taos_errno(res) != 0) { + printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res)); + } else { + int affectedRow = taos_affected_rows(res); + printf("successfully inserted %d rows\n", affectedRow); + } + taos_free_result(res); + taos_close(taos); + taos_cleanup(); +} +// output: +// successfully inserted 4 rows +// ANCHOR_END: main diff --git a/docs/examples/c/line_example.c b/docs/examples/c/line_example.c new file mode 100644 index 0000000000000000000000000000000000000000..ce39f8d9df744082a450ce246529bf56adebd1e0 --- /dev/null +++ b/docs/examples/c/line_example.c @@ -0,0 +1,47 @@ +// compile with +// gcc -o line_example line_example.c -ltaos +#include +#include +#include +#include "taos.h" + +void executeSQL(TAOS *taos, const char *sql) { + TAOS_RES *res = taos_query(taos, sql); + int code = taos_errno(res); + if (code != 0) { + printf("%s\n", taos_errstr(res)); + taos_free_result(res); + taos_close(taos); + exit(EXIT_FAILURE); + } + taos_free_result(res); +} + +// ANCHOR: main +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 0); + if (taos == NULL) { + printf("failed to connect to server\n"); + exit(EXIT_FAILURE); + } + executeSQL(taos, "DROP DATABASE IF EXISTS test"); + executeSQL(taos, "CREATE DATABASE test"); + executeSQL(taos, "USE test"); + char *lines[] = {"meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250"}; + TAOS_RES *res = taos_schemaless_insert(taos, lines, 4, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS); + if (taos_errno(res) != 0) { + printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res)); + } else { + int affectedRows = taos_affected_rows(res); + printf("successfully inserted %d rows\n", affectedRows); + } + taos_free_result(res); + taos_close(taos); + taos_cleanup(); +} +// output: +// successfully inserted 4 rows +// ANCHOR_END: main \ No newline at end of file diff --git a/docs/examples/c/multi_bind_example.c b/docs/examples/c/multi_bind_example.c new file mode 100644 index 0000000000000000000000000000000000000000..02e6568e9e88ac8703a4993ed406e770d23c2438 --- /dev/null +++ b/docs/examples/c/multi_bind_example.c @@ -0,0 +1,147 @@ +// compile with +// gcc -o multi_bind_example multi_bind_example.c -ltaos +#include +#include +#include +#include "taos.h" + +/** + * @brief execute sql only and ignore result set + * + * @param taos + * @param sql + */ +void executeSQL(TAOS *taos, const char *sql) { + TAOS_RES *res = taos_query(taos, sql); + int code = taos_errno(res); + if (code != 0) { + printf("%s\n", taos_errstr(res)); + taos_free_result(res); + taos_close(taos); + exit(EXIT_FAILURE); + } + taos_free_result(res); +} + +/** + * @brief exit program when error occur. + * + * @param stmt + * @param code + * @param msg + */ +void checkErrorCode(TAOS_STMT *stmt, int code, const char *msg) { + if (code != 0) { + printf("%s. error: %s\n", msg, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } +} + +/** + * @brief insert data using stmt API + * + * @param taos + */ +void insertData(TAOS *taos) { + // init + TAOS_STMT *stmt = taos_stmt_init(taos); + // prepare + const char *sql = "INSERT INTO ? USING meters TAGS(?, ?) values(?, ?, ?, ?)"; + int code = taos_stmt_prepare(stmt, sql, 0); + checkErrorCode(stmt, code, "failed to execute taos_stmt_prepare"); + // bind table name and tags + TAOS_BIND tags[2]; + char *location = "California.SanFrancisco"; + int groupId = 2; + tags[0].buffer_type = TSDB_DATA_TYPE_BINARY; + tags[0].buffer_length = strlen(location); + tags[0].length = &tags[0].buffer_length; + tags[0].buffer = location; + tags[0].is_null = NULL; + + tags[1].buffer_type = TSDB_DATA_TYPE_INT; + tags[1].buffer_length = sizeof(int); + tags[1].length = &tags[1].buffer_length; + tags[1].buffer = &groupId; + tags[1].is_null = NULL; + + code = taos_stmt_set_tbname_tags(stmt, "d1001", tags); + checkErrorCode(stmt, code, "failed to execute taos_stmt_set_tbname_tags"); + + // highlight-start + // insert two rows with multi binds + TAOS_MULTI_BIND params[4]; + // values to bind + int64_t ts[] = {1648432611249, 1648432611749}; + float current[] = {10.3, 12.6}; + int voltage[] = {219, 218}; + float phase[] = {0.31, 0.33}; + // is_null array + char is_null[2] = {0}; + // length array + int32_t int64Len[2] = {sizeof(int64_t)}; + int32_t floatLen[2] = {sizeof(float)}; + int32_t intLen[2] = {sizeof(int)}; + + params[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; + params[0].buffer_length = sizeof(int64_t); + params[0].buffer = ts; + params[0].length = int64Len; + params[0].is_null = is_null; + params[0].num = 2; + + params[1].buffer_type = TSDB_DATA_TYPE_FLOAT; + params[1].buffer_length = sizeof(float); + params[1].buffer = current; + params[1].length = floatLen; + params[1].is_null = is_null; + params[1].num = 2; + + params[2].buffer_type = TSDB_DATA_TYPE_INT; + params[2].buffer_length = sizeof(int); + params[2].buffer = voltage; + params[2].length = intLen; + params[2].is_null = is_null; + params[2].num = 2; + + params[3].buffer_type = TSDB_DATA_TYPE_FLOAT; + params[3].buffer_length = sizeof(float); + params[3].buffer = phase; + params[3].length = floatLen; + params[3].is_null = is_null; + params[3].num = 2; + + code = taos_stmt_bind_param_batch(stmt, params); // bind batch + checkErrorCode(stmt, code, "failed to execute taos_stmt_bind_param_batch"); + code = taos_stmt_add_batch(stmt); // add batch + checkErrorCode(stmt, code, "failed to execute taos_stmt_add_batch"); + // highlight-end + // execute + code = taos_stmt_execute(stmt); + checkErrorCode(stmt, code, "failed to execute taos_stmt_execute"); + int affectedRows = taos_stmt_affected_rows(stmt); + printf("successfully inserted %d rows\n", affectedRows); + // close + taos_stmt_close(stmt); +} + +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030); + if (taos == NULL) { + printf("failed to connect to server\n"); + exit(EXIT_FAILURE); + } + executeSQL(taos, "DROP DATABASE IF EXISTS power"); + executeSQL(taos, "CREATE DATABASE power"); + executeSQL(taos, "USE power"); + executeSQL(taos, + "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), " + "groupId INT)"); + insertData(taos); + taos_close(taos); + taos_cleanup(); +} + +// output: +// successfully inserted 2 rows \ No newline at end of file diff --git a/docs/examples/c/query_example.c b/docs/examples/c/query_example.c new file mode 100644 index 0000000000000000000000000000000000000000..fcae95bcd45a282eaa3ae911b4115e6300c6af8e --- /dev/null +++ b/docs/examples/c/query_example.c @@ -0,0 +1,143 @@ +// compile with: +// gcc -o query_example query_example.c -ltaos +#include +#include +#include +#include +#include + +typedef int16_t VarDataLenT; + +#define TSDB_NCHAR_SIZE sizeof(int32_t) +#define VARSTR_HEADER_SIZE sizeof(VarDataLenT) + +#define GET_FLOAT_VAL(x) (*(float *)(x)) +#define GET_DOUBLE_VAL(x) (*(double *)(x)) + +#define varDataLen(v) ((VarDataLenT *)(v))[0] + +int printRow(char *str, TAOS_ROW row, TAOS_FIELD *fields, int numFields) { + int len = 0; + char split = ' '; + + for (int i = 0; i < numFields; ++i) { + if (i > 0) { + str[len++] = split; + } + + if (row[i] == NULL) { + len += sprintf(str + len, "%s", "NULL"); + continue; + } + + switch (fields[i].type) { + case TSDB_DATA_TYPE_TINYINT: + len += sprintf(str + len, "%d", *((int8_t *)row[i])); + break; + + case TSDB_DATA_TYPE_UTINYINT: + len += sprintf(str + len, "%u", *((uint8_t *)row[i])); + break; + + case TSDB_DATA_TYPE_SMALLINT: + len += sprintf(str + len, "%d", *((int16_t *)row[i])); + break; + + case TSDB_DATA_TYPE_USMALLINT: + len += sprintf(str + len, "%u", *((uint16_t *)row[i])); + break; + + case TSDB_DATA_TYPE_INT: + len += sprintf(str + len, "%d", *((int32_t *)row[i])); + break; + + case TSDB_DATA_TYPE_UINT: + len += sprintf(str + len, "%u", *((uint32_t *)row[i])); + break; + + case TSDB_DATA_TYPE_BIGINT: + len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i])); + break; + + case TSDB_DATA_TYPE_UBIGINT: + len += sprintf(str + len, "%" PRIu64, *((uint64_t *)row[i])); + break; + + case TSDB_DATA_TYPE_FLOAT: { + float fv = 0; + fv = GET_FLOAT_VAL(row[i]); + len += sprintf(str + len, "%f", fv); + } break; + + case TSDB_DATA_TYPE_DOUBLE: { + double dv = 0; + dv = GET_DOUBLE_VAL(row[i]); + len += sprintf(str + len, "%lf", dv); + } break; + + case TSDB_DATA_TYPE_BINARY: + case TSDB_DATA_TYPE_NCHAR: { + int32_t charLen = varDataLen((char *)row[i] - VARSTR_HEADER_SIZE); + memcpy(str + len, row[i], charLen); + len += charLen; + } break; + + case TSDB_DATA_TYPE_TIMESTAMP: + len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i])); + break; + + case TSDB_DATA_TYPE_BOOL: + len += sprintf(str + len, "%d", *((int8_t *)row[i])); + default: + break; + } + } + + return len; +} + +/** + * @brief print column name and values of each row + * + * @param res + * @return int + */ +static int printResult(TAOS_RES *res) { + int numFields = taos_num_fields(res); + TAOS_FIELD *fields = taos_fetch_fields(res); + char header[256] = {0}; + int len = 0; + for (int i = 0; i < numFields; ++i) { + len += sprintf(header + len, "%s ", fields[i].name); + } + puts(header); + + TAOS_ROW row = NULL; + while ((row = taos_fetch_row(res))) { + char temp[256] = {0}; + printRow(temp, row, fields, numFields); + puts(temp); + } +} + +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", "power", 6030); + if (taos == NULL) { + puts("failed to connect to server"); + exit(EXIT_FAILURE); + } + TAOS_RES *res = taos_query(taos, "SELECT * FROM meters LIMIT 2"); + if (taos_errno(res) != 0) { + printf("failed to execute taos_query. error: %s\n", taos_errstr(res)); + exit(EXIT_FAILURE); + } + printResult(res); + taos_free_result(res); + taos_close(taos); + taos_cleanup(); +} + +// output: +// ts current voltage phase location groupid +// 1648432611249 10.300000 219 0.310000 California.SanFrancisco 2 +// 1648432611749 12.600000 218 0.330000 California.SanFrancisco 2 \ No newline at end of file diff --git a/docs/examples/c/stmt_example.c b/docs/examples/c/stmt_example.c new file mode 100644 index 0000000000000000000000000000000000000000..28dae5f9d5ea2faec0aa3c0a784d39e252651c65 --- /dev/null +++ b/docs/examples/c/stmt_example.c @@ -0,0 +1,141 @@ +// compile with +// gcc -o stmt_example stmt_example.c -ltaos +#include +#include +#include +#include "taos.h" + +/** + * @brief execute sql only. + * + * @param taos + * @param sql + */ +void executeSQL(TAOS *taos, const char *sql) { + TAOS_RES *res = taos_query(taos, sql); + int code = taos_errno(res); + if (code != 0) { + printf("%s\n", taos_errstr(res)); + taos_free_result(res); + taos_close(taos); + exit(EXIT_FAILURE); + } + taos_free_result(res); +} + +/** + * @brief check return status and exit program when error occur. + * + * @param stmt + * @param code + * @param msg + */ +void checkErrorCode(TAOS_STMT *stmt, int code, const char* msg) { + if (code != 0) { + printf("%s. error: %s\n", msg, taos_stmt_errstr(stmt)); + taos_stmt_close(stmt); + exit(EXIT_FAILURE); + } +} + +typedef struct { + int64_t ts; + float current; + int voltage; + float phase; +} Row; + +/** + * @brief insert data using stmt API + * + * @param taos + */ +void insertData(TAOS *taos) { + // init + TAOS_STMT *stmt = taos_stmt_init(taos); + // prepare + const char *sql = "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)"; + int code = taos_stmt_prepare(stmt, sql, 0); + checkErrorCode(stmt, code, "failed to execute taos_stmt_prepare"); + // bind table name and tags + TAOS_BIND tags[2]; + char* location = "California.SanFrancisco"; + int groupId = 2; + tags[0].buffer_type = TSDB_DATA_TYPE_BINARY; + tags[0].buffer_length = strlen(location); + tags[0].length = &tags[0].buffer_length; + tags[0].buffer = location; + tags[0].is_null = NULL; + + tags[1].buffer_type = TSDB_DATA_TYPE_INT; + tags[1].buffer_length = sizeof(int); + tags[1].length = &tags[1].buffer_length; + tags[1].buffer = &groupId; + tags[1].is_null = NULL; + + code = taos_stmt_set_tbname_tags(stmt, "d1001", tags); + checkErrorCode(stmt, code, "failed to execute taos_stmt_set_tbname_tags"); + + // insert two rows + Row rows[2] = { + {1648432611249, 10.3, 219, 0.31}, + {1648432611749, 12.6, 218, 0.33}, + }; + + TAOS_BIND values[4]; + values[0].buffer_type = TSDB_DATA_TYPE_TIMESTAMP; + values[0].buffer_length = sizeof(int64_t); + values[0].length = &values[0].buffer_length; + values[0].is_null = NULL; + + values[1].buffer_type = TSDB_DATA_TYPE_FLOAT; + values[1].buffer_length = sizeof(float); + values[1].length = &values[1].buffer_length; + values[1].is_null = NULL; + + values[2].buffer_type = TSDB_DATA_TYPE_INT; + values[2].buffer_length = sizeof(int); + values[2].length = &values[2].buffer_length; + values[2].is_null = NULL; + + values[3].buffer_type = TSDB_DATA_TYPE_FLOAT; + values[3].buffer_length = sizeof(float); + values[3].length = &values[3].buffer_length; + values[3].is_null = NULL; + + for (int i = 0; i < 2; ++i) { + values[0].buffer = &rows[i].ts; + values[1].buffer = &rows[i].current; + values[2].buffer = &rows[i].voltage; + values[3].buffer = &rows[i].phase; + code = taos_stmt_bind_param(stmt, values); // bind param + checkErrorCode(stmt, code, "failed to execute taos_stmt_bind_param"); + code = taos_stmt_add_batch(stmt); // add batch + checkErrorCode(stmt, code, "failed to execute taos_stmt_add_batch"); + } + // execute + code = taos_stmt_execute(stmt); + checkErrorCode(stmt, code, "failed to execute taos_stmt_execute"); + int affectedRows = taos_stmt_affected_rows(stmt); + printf("successfully inserted %d rows\n", affectedRows); + // close + taos_stmt_close(stmt); +} + +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030); + if (taos == NULL) { + printf("failed to connect to server\n"); + exit(EXIT_FAILURE); + } + executeSQL(taos, "CREATE DATABASE power"); + executeSQL(taos, "USE power"); + executeSQL(taos, "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); + insertData(taos); + taos_close(taos); + taos_cleanup(); +} + + +// output: +// successfully inserted 2 rows \ No newline at end of file diff --git a/docs/examples/c/subscribe_demo.c b/docs/examples/c/subscribe_demo.c new file mode 100644 index 0000000000000000000000000000000000000000..2fe62c24eb92d2f57c24b40fc16f47d62ea5e378 --- /dev/null +++ b/docs/examples/c/subscribe_demo.c @@ -0,0 +1,66 @@ +// A simple demo for asynchronous subscription. +// compile with: +// gcc -o subscribe_demo subscribe_demo.c -ltaos + +#include +#include +#include +#include + +int nTotalRows; + +/** + * @brief callback function of subscription. + * + * @param tsub + * @param res + * @param param. the additional parameter passed to taos_subscribe + * @param code. error code + */ +void subscribe_callback(TAOS_SUB* tsub, TAOS_RES* res, void* param, int code) { + if (code != 0) { + printf("error: %d\n", code); + exit(EXIT_FAILURE); + } + + TAOS_ROW row = NULL; + int num_fields = taos_num_fields(res); + TAOS_FIELD* fields = taos_fetch_fields(res); + int nRows = 0; + + while ((row = taos_fetch_row(res))) { + char buf[4096] = {0}; + taos_print_row(buf, row, fields, num_fields); + puts(buf); + nRows++; + } + + nTotalRows += nRows; + printf("%d rows consumed.\n", nRows); +} + +int main() { + TAOS* taos = taos_connect("localhost", "root", "taosdata", NULL, 6030); + if (taos == NULL) { + printf("failed to connect to server\n"); + exit(EXIT_FAILURE); + } + + int restart = 1; // if the topic already exists, where to subscribe from the begin. + const char* topic = "topic-meter-current-bg-10"; + const char* sql = "select * from power.meters where current > 10"; + void* param = NULL; // additional parameter. + int interval = 2000; // consumption interval in microseconds. + TAOS_SUB* tsub = taos_subscribe(taos, restart, topic, sql, subscribe_callback, NULL, interval); + + // wait for insert from others process. you can open TDengine CLI to insert some records for test. + + getchar(); // press Enter to stop + + printf("total rows consumed: %d\n", nTotalRows); + int keep = 0; // whether to keep subscribe process + taos_unsubscribe(tsub, keep); + + taos_close(taos); + taos_cleanup(); +} diff --git a/docs/examples/c/telnet_line_example.c b/docs/examples/c/telnet_line_example.c new file mode 100644 index 0000000000000000000000000000000000000000..da62da4ba492856b0d73a564c1bf9cdd60b5b742 --- /dev/null +++ b/docs/examples/c/telnet_line_example.c @@ -0,0 +1,54 @@ +// compile with +// gcc -o telnet_line_example telnet_line_example.c -ltaos +#include +#include +#include +#include "taos.h" + +void executeSQL(TAOS *taos, const char *sql) { + TAOS_RES *res = taos_query(taos, sql); + int code = taos_errno(res); + if (code != 0) { + printf("%s\n", taos_errstr(res)); + taos_free_result(res); + taos_close(taos); + exit(EXIT_FAILURE); + } + taos_free_result(res); +} + +// ANCHOR: main +int main() { + TAOS *taos = taos_connect("localhost", "root", "taosdata", "", 6030); + if (taos == NULL) { + printf("failed to connect to server\n"); + exit(EXIT_FAILURE); + } + executeSQL(taos, "DROP DATABASE IF EXISTS test"); + executeSQL(taos, "CREATE DATABASE test"); + executeSQL(taos, "USE test"); + char *lines[] = { + "meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", + "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", + "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", + "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3", + }; + TAOS_RES *res = taos_schemaless_insert(taos, lines, 8, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + if (taos_errno(res) != 0) { + printf("failed to insert schema-less data, reason: %s\n", taos_errstr(res)); + } else { + int affectedRow = taos_affected_rows(res); + printf("successfully inserted %d rows\n", affectedRow); + } + + taos_free_result(res); + taos_close(taos); + taos_cleanup(); +} +// output: +// successfully inserted 8 rows +// ANCHOR_END: main diff --git a/docs/examples/c/tmq_example.c b/docs/examples/c/tmq_example.c new file mode 100644 index 0000000000000000000000000000000000000000..2eaa8ed5eb904a1fa2c00d7068aff06482f9f809 --- /dev/null +++ b/docs/examples/c/tmq_example.c @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2019 TAOS Data, Inc. + * + * 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 . + */ + +#include +#include +#include +#include +#include +#include "taos.h" + +static int running = 1; +static char dbName[64] = "tmqdb"; +static char stbName[64] = "stb"; +static char topicName[64] = "topicname"; + +static int32_t msg_process(TAOS_RES* msg) { + char buf[1024]; + int32_t rows = 0; + + const char* topicName = tmq_get_topic_name(msg); + const char* dbName = tmq_get_db_name(msg); + int32_t vgroupId = tmq_get_vgroup_id(msg); + + printf("topic: %s\n", topicName); + printf("db: %s\n", dbName); + printf("vgroup id: %d\n", vgroupId); + + while (1) { + TAOS_ROW row = taos_fetch_row(msg); + if (row == NULL) break; + + TAOS_FIELD* fields = taos_fetch_fields(msg); + int32_t numOfFields = taos_field_count(msg); + int32_t* length = taos_fetch_lengths(msg); + int32_t precision = taos_result_precision(msg); + rows++; + taos_print_row(buf, row, fields, numOfFields); + printf("row content: %s\n", buf); + } + + return rows; +} + +static int32_t init_env() { + TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); + if (pConn == NULL) { + return -1; + } + + TAOS_RES* pRes; + // drop database if exists + printf("create database\n"); + pRes = taos_query(pConn, "drop database if exists tmqdb"); + if (taos_errno(pRes) != 0) { + printf("error in drop tmqdb, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + // create database + pRes = taos_query(pConn, "create database tmqdb"); + if (taos_errno(pRes) != 0) { + printf("error in create tmqdb, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + // create super table + printf("create super table\n"); + pRes = taos_query( + pConn, "create table tmqdb.stb (ts timestamp, c1 int, c2 float, c3 varchar(16)) tags(t1 int, t3 varchar(16))"); + if (taos_errno(pRes) != 0) { + printf("failed to create super table stb, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + // create sub tables + printf("create sub tables\n"); + pRes = taos_query(pConn, "create table tmqdb.ctb0 using tmqdb.stb tags(0, 'subtable0')"); + if (taos_errno(pRes) != 0) { + printf("failed to create super table ctb0, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "create table tmqdb.ctb1 using tmqdb.stb tags(1, 'subtable1')"); + if (taos_errno(pRes) != 0) { + printf("failed to create super table ctb1, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "create table tmqdb.ctb2 using tmqdb.stb tags(2, 'subtable2')"); + if (taos_errno(pRes) != 0) { + printf("failed to create super table ctb2, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "create table tmqdb.ctb3 using tmqdb.stb tags(3, 'subtable3')"); + if (taos_errno(pRes) != 0) { + printf("failed to create super table ctb3, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + // insert data + printf("insert data into sub tables\n"); + pRes = taos_query(pConn, "insert into tmqdb.ctb0 values(now, 0, 0, 'a0')(now+1s, 0, 0, 'a00')"); + if (taos_errno(pRes) != 0) { + printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "insert into tmqdb.ctb1 values(now, 1, 1, 'a1')(now+1s, 11, 11, 'a11')"); + if (taos_errno(pRes) != 0) { + printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "insert into tmqdb.ctb2 values(now, 2, 2, 'a1')(now+1s, 22, 22, 'a22')"); + if (taos_errno(pRes) != 0) { + printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "insert into tmqdb.ctb3 values(now, 3, 3, 'a1')(now+1s, 33, 33, 'a33')"); + if (taos_errno(pRes) != 0) { + printf("failed to insert into ctb0, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + taos_close(pConn); + return 0; +} + +int32_t create_topic() { + printf("create topic\n"); + TAOS_RES* pRes; + TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0); + if (pConn == NULL) { + return -1; + } + + pRes = taos_query(pConn, "use tmqdb"); + if (taos_errno(pRes) != 0) { + printf("error in use tmqdb, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + pRes = taos_query(pConn, "create topic topicname as select ts, c1, c2, c3, tbname from tmqdb.stb where c1 > 1"); + if (taos_errno(pRes) != 0) { + printf("failed to create topic topicname, reason:%s\n", taos_errstr(pRes)); + return -1; + } + taos_free_result(pRes); + + taos_close(pConn); + return 0; +} + +void tmq_commit_cb_print(tmq_t* tmq, int32_t code, void* param) { + printf("tmq_commit_cb_print() code: %d, tmq: %p, param: %p\n", code, tmq, param); +} + +tmq_t* build_consumer() { + tmq_conf_res_t code; + tmq_conf_t* conf = tmq_conf_new(); + code = tmq_conf_set(conf, "enable.auto.commit", "true"); + if (TMQ_CONF_OK != code) return NULL; + code = tmq_conf_set(conf, "auto.commit.interval.ms", "1000"); + if (TMQ_CONF_OK != code) return NULL; + code = tmq_conf_set(conf, "group.id", "cgrpName"); + if (TMQ_CONF_OK != code) return NULL; + code = tmq_conf_set(conf, "client.id", "user defined name"); + if (TMQ_CONF_OK != code) return NULL; + code = tmq_conf_set(conf, "td.connect.user", "root"); + if (TMQ_CONF_OK != code) return NULL; + code = tmq_conf_set(conf, "td.connect.pass", "taosdata"); + if (TMQ_CONF_OK != code) return NULL; + code = tmq_conf_set(conf, "auto.offset.reset", "earliest"); + if (TMQ_CONF_OK != code) return NULL; + code = tmq_conf_set(conf, "experimental.snapshot.enable", "false"); + if (TMQ_CONF_OK != code) return NULL; + + tmq_conf_set_auto_commit_cb(conf, tmq_commit_cb_print, NULL); + + tmq_t* tmq = tmq_consumer_new(conf, NULL, 0); + tmq_conf_destroy(conf); + return tmq; +} + +tmq_list_t* build_topic_list() { + tmq_list_t* topicList = tmq_list_new(); + int32_t code = tmq_list_append(topicList, "topicname"); + if (code) { + return NULL; + } + return topicList; +} + +void basic_consume_loop(tmq_t* tmq) { + int32_t totalRows = 0; + int32_t msgCnt = 0; + int32_t timeout = 5000; + while (running) { + TAOS_RES* tmqmsg = tmq_consumer_poll(tmq, timeout); + if (tmqmsg) { + msgCnt++; + totalRows += msg_process(tmqmsg); + taos_free_result(tmqmsg); + } else { + break; + } + } + + fprintf(stderr, "%d msg consumed, include %d rows\n", msgCnt, totalRows); +} + +int main(int argc, char* argv[]) { + int32_t code; + + if (init_env() < 0) { + return -1; + } + + if (create_topic() < 0) { + return -1; + } + + tmq_t* tmq = build_consumer(); + if (NULL == tmq) { + fprintf(stderr, "%% build_consumer() fail!\n"); + return -1; + } + + tmq_list_t* topic_list = build_topic_list(); + if (NULL == topic_list) { + return -1; + } + + if ((code = tmq_subscribe(tmq, topic_list))) { + fprintf(stderr, "%% Failed to tmq_subscribe(): %s\n", tmq_err2str(code)); + } + tmq_list_destroy(topic_list); + + basic_consume_loop(tmq); + + code = tmq_consumer_close(tmq); + if (code) { + fprintf(stderr, "%% Failed to close consumer: %s\n", tmq_err2str(code)); + } else { + fprintf(stderr, "%% Consumer closed\n"); + } + + return 0; +} diff --git a/docs/examples/csharp/.gitignore b/docs/examples/csharp/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b3aff79f3706e23aa74199a7f521f7912d2b0e45 --- /dev/null +++ b/docs/examples/csharp/.gitignore @@ -0,0 +1,4 @@ +bin +obj +.vs +*.sln \ No newline at end of file diff --git a/docs/examples/csharp/AsyncQueryExample.cs b/docs/examples/csharp/AsyncQueryExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..0d47325932e2f01fec8d55cfdb64c636258f4a03 --- /dev/null +++ b/docs/examples/csharp/AsyncQueryExample.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using TDengineDriver; +using TDengineDriver.Impl; +using System.Runtime.InteropServices; + +namespace TDengineExample +{ + public class AsyncQueryExample + { + static void Main() + { + IntPtr conn = GetConnection(); + QueryAsyncCallback queryAsyncCallback = new QueryAsyncCallback(QueryCallback); + TDengine.QueryAsync(conn, "select * from meters", queryAsyncCallback, IntPtr.Zero); + Thread.Sleep(2000); + TDengine.Close(conn); + TDengine.Cleanup(); + } + + static void QueryCallback(IntPtr param, IntPtr taosRes, int code) + { + if (code == 0 && taosRes != IntPtr.Zero) + { + FetchRawBlockAsyncCallback fetchRowAsyncCallback = new FetchRawBlockAsyncCallback(FetchRawBlockCallback); + TDengine.FetchRawBlockAsync(taosRes, fetchRowAsyncCallback, param); + } + else + { + Console.WriteLine($"async query data failed, failed code {code}"); + } + } + + // Iteratively call this interface until "numOfRows" is no greater than 0. + static void FetchRawBlockCallback(IntPtr param, IntPtr taosRes, int numOfRows) + { + if (numOfRows > 0) + { + Console.WriteLine($"{numOfRows} rows async retrieved"); + IntPtr pdata = TDengine.GetRawBlock(taosRes); + List metaList = TDengine.FetchFields(taosRes); + List dataList = LibTaos.ReadRawBlock(pdata, metaList, numOfRows); + + for (int i = 0; i < dataList.Count; i++) + { + if (i != 0 && (i+1) % metaList.Count == 0) + { + Console.WriteLine("{0}\t|", dataList[i]); + } + else + { + Console.Write("{0}\t|", dataList[i]); + } + } + Console.WriteLine(""); + TDengine.FetchRawBlockAsync(taosRes, FetchRawBlockCallback, param); + } + else + { + if (numOfRows == 0) + { + Console.WriteLine("async retrieve complete."); + } + else + { + Console.WriteLine($"FetchRawBlockCallback callback error, error code {numOfRows}"); + } + TDengine.FreeResult(taosRes); + } + } + + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = "power"; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + } +} + +// //output: +// // Connect to TDengine success +// // 8 rows async retrieved + +// // 1538548685500 | 11.8 | 221 | 0.28 | california.losangeles | 2 | +// // 1538548696600 | 13.4 | 223 | 0.29 | california.losangeles | 2 | +// // 1538548685000 | 10.8 | 223 | 0.29 | california.losangeles | 3 | +// // 1538548686500 | 11.5 | 221 | 0.35 | california.losangeles | 3 | +// // 1538548685000 | 10.3 | 219 | 0.31 | california.sanfrancisco | 2 | +// // 1538548695000 | 12.6 | 218 | 0.33 | california.sanfrancisco | 2 | +// // 1538548696800 | 12.3 | 221 | 0.31 | california.sanfrancisco | 2 | +// // 1538548696650 | 10.3 | 218 | 0.25 | california.sanfrancisco | 3 | +// // async retrieve complete. \ No newline at end of file diff --git a/docs/examples/csharp/ConnectExample.cs b/docs/examples/csharp/ConnectExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..f3548ee65daab8a59695499339a8f89b0aa33a10 --- /dev/null +++ b/docs/examples/csharp/ConnectExample.cs @@ -0,0 +1,29 @@ +using TDengineDriver; + +namespace TDengineExample +{ + + internal class ConnectExample + { + static void Main(String[] args) + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + TDengine.Close(conn); + TDengine.Cleanup(); + } + } +} diff --git a/docs/examples/csharp/InfluxDBLineExample.cs b/docs/examples/csharp/InfluxDBLineExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..7b4453f4ac0b14dd76d166e395bdacb46a5d3fbc --- /dev/null +++ b/docs/examples/csharp/InfluxDBLineExample.cs @@ -0,0 +1,77 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class InfluxDBLineExample + { + static void Main() + { + IntPtr conn = GetConnection(); + PrepareDatabase(conn); + string[] lines = { + "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250" + }; + IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + else + { + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows"); + } + TDengine.FreeResult(res); + ExitProgram(conn, 0); + + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + TDengine.Cleanup(); + Environment.Exit(1); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void PrepareDatabase(IntPtr conn) + { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to create database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + res = TDengine.Query(conn, "USE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to change database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } + +} diff --git a/docs/examples/csharp/OptsJsonExample.cs b/docs/examples/csharp/OptsJsonExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..2c41acc5c9628befda7eb4ad5c30af5b921de948 --- /dev/null +++ b/docs/examples/csharp/OptsJsonExample.cs @@ -0,0 +1,76 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class OptsJsonExample + { + static void Main() + { + IntPtr conn = GetConnection(); + PrepareDatabase(conn); + string[] lines = { "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}, " + + "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}]" + }; + + IntPtr res = TDengine.SchemalessInsert(conn, lines, 1, (int)TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + else + { + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows"); + } + TDengine.FreeResult(res); + ExitProgram(conn, 0); + + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + TDengine.Cleanup(); + Environment.Exit(1); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void PrepareDatabase(IntPtr conn) + { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to create database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + res = TDengine.Query(conn, "USE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to change database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } +} diff --git a/docs/examples/csharp/OptsTelnetExample.cs b/docs/examples/csharp/OptsTelnetExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..bb752db1afbbb2ef68df9ca25314c8b91cd9a266 --- /dev/null +++ b/docs/examples/csharp/OptsTelnetExample.cs @@ -0,0 +1,80 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class OptsTelnetExample + { + static void Main() + { + IntPtr conn = GetConnection(); + PrepareDatabase(conn); + string[] lines = { + "meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", + "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", + "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", + "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3", + }; + IntPtr res = TDengine.SchemalessInsert(conn, lines, lines.Length, (int)TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL, (int)TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("SchemalessInsert failed since " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + else + { + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine($"SchemalessInsert success, affected {affectedRows} rows"); + } + TDengine.FreeResult(res); + ExitProgram(conn, 0); + + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + TDengine.Cleanup(); + Environment.Exit(1); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void PrepareDatabase(IntPtr conn) + { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to create database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + res = TDengine.Query(conn, "USE test"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("failed to change database, reason: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } +} diff --git a/docs/examples/csharp/QueryExample.cs b/docs/examples/csharp/QueryExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..d75bb8d6611f5b3899485eb1a63a42ed6995847d --- /dev/null +++ b/docs/examples/csharp/QueryExample.cs @@ -0,0 +1,82 @@ +using TDengineDriver; +using TDengineDriver.Impl; +using System.Runtime.InteropServices; + +namespace TDengineExample +{ + internal class QueryExample + { + static void Main() + { + IntPtr conn = GetConnection(); + // run query + IntPtr res = TDengine.Query(conn, "SELECT * FROM meters LIMIT 2"); + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine("Failed to query since: " + TDengine.Error(res)); + TDengine.Close(conn); + TDengine.Cleanup(); + return; + } + + // get filed count + int fieldCount = TDengine.FieldCount(res); + Console.WriteLine("fieldCount=" + fieldCount); + + // print column names + List metas = LibTaos.GetMeta(res); + for (int i = 0; i < metas.Count; i++) + { + Console.Write(metas[i].name + "\t"); + } + Console.WriteLine(); + + // print values + List resData = LibTaos.GetData(res); + for (int i = 0; i < resData.Count; i++) + { + Console.Write($"|{resData[i].ToString()} \t"); + if (((i + 1) % metas.Count == 0)) + { + Console.WriteLine(""); + } + } + Console.WriteLine(); + + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine($"Query is not complete, Error {TDengine.ErrorNo(res)} {TDengine.Error(res)}"); + } + // exit + TDengine.FreeResult(res); + TDengine.Close(conn); + TDengine.Cleanup(); + } + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = "power"; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + System.Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + } +} + +// output: +// Connect to TDengine success +// fieldCount=6 +// ts current voltage phase location groupid +// 1648432611249 10.3 219 0.31 California.SanFrancisco 2 +// 1648432611749 12.6 218 0.33 California.SanFrancisco 2 \ No newline at end of file diff --git a/docs/examples/csharp/SQLInsertExample.cs b/docs/examples/csharp/SQLInsertExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..192ea96d5713bbf7f37f2208687c41e3e66d473b --- /dev/null +++ b/docs/examples/csharp/SQLInsertExample.cs @@ -0,0 +1,69 @@ +using TDengineDriver; + + +namespace TDengineExample +{ + internal class SQLInsertExample + { + + static void Main() + { + IntPtr conn = GetConnection(); + IntPtr res = TDengine.Query(conn, "CREATE DATABASE power"); + CheckRes(conn, res, "failed to create database"); + res = TDengine.Query(conn, "USE power"); + CheckRes(conn, res, "failed to change database"); + res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); + CheckRes(conn, res, "failed to create stable"); + var sql = "INSERT INTO d1001 USING meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) " + + "d1002 USING power.meters TAGS('California.SanFrancisco', 3) VALUES('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) " + + "d1003 USING power.meters TAGS('California.LosAngeles', 2) VALUES('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) " + + "d1004 USING power.meters TAGS('California.LosAngeles', 3) VALUES('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000)('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)"; + res = TDengine.Query(conn, sql); + CheckRes(conn, res, "failed to insert data"); + int affectedRows = TDengine.AffectRows(res); + Console.WriteLine("affectedRows " + affectedRows); + ExitProgram(conn, 0); + } + + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + static void CheckRes(IntPtr conn, IntPtr res, String errorMsg) + { + if (TDengine.ErrorNo(res) != 0) + { + Console.Write(errorMsg + " since: " + TDengine.Error(res)); + ExitProgram(conn, 1); + } + } + + static void ExitProgram(IntPtr conn, int exitCode) + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(exitCode); + } + } +} + +// output: +// Connect to TDengine success +// affectedRows 8 diff --git a/docs/examples/csharp/StmtInsertExample.cs b/docs/examples/csharp/StmtInsertExample.cs new file mode 100644 index 0000000000000000000000000000000000000000..0a4098091f6371a674eee6f158e1c57bff2b6862 --- /dev/null +++ b/docs/examples/csharp/StmtInsertExample.cs @@ -0,0 +1,115 @@ +using TDengineDriver; + +namespace TDengineExample +{ + internal class StmtInsertExample + { + private static IntPtr conn; + private static IntPtr stmt; + static void Main() + { + conn = GetConnection(); + PrepareSTable(); + // 1. init and prepare + stmt = TDengine.StmtInit(conn); + if (stmt == IntPtr.Zero) + { + Console.WriteLine("failed to init stmt, " + TDengine.Error(stmt)); + ExitProgram(); + } + int res = TDengine.StmtPrepare(stmt, "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)"); + CheckStmtRes(res, "failed to prepare stmt"); + + // 2. bind table name and tags + TAOS_MULTI_BIND[] tags = new TAOS_MULTI_BIND[2] { TaosMultiBind.MultiBindBinary(new string[]{"California.SanFrancisco"}), TaosMultiBind.MultiBindInt(new int?[] {2}) }; + res = TDengine.StmtSetTbnameTags(stmt, "d1001", tags); + CheckStmtRes(res, "failed to bind table name and tags"); + + // 3. bind values + TAOS_MULTI_BIND[] values = new TAOS_MULTI_BIND[4] { + TaosMultiBind.MultiBindTimestamp(new long[2] { 1648432611249, 1648432611749}), + TaosMultiBind.MultiBindFloat(new float?[2] { 10.3f, 12.6f}), + TaosMultiBind.MultiBindInt(new int?[2] { 219, 218}), + TaosMultiBind.MultiBindFloat(new float?[2]{ 0.31f, 0.33f}) + }; + res = TDengine.StmtBindParamBatch(stmt, values); + CheckStmtRes(res, "failed to bind params"); + + // 4. add batch + res = TDengine.StmtAddBatch(stmt); + CheckStmtRes(res, "failed to add batch"); + + // 5. execute + res = TDengine.StmtExecute(stmt); + CheckStmtRes(res, "faild to execute"); + + // 6. free + TaosMultiBind.FreeTaosBind(tags); + TaosMultiBind.FreeTaosBind(values); + TDengine.Close(conn); + TDengine.Cleanup(); + } + + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = ""; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + + + + static void PrepareSTable() + { + IntPtr res = TDengine.Query(conn, "CREATE DATABASE power"); + CheckResPtr(res, "failed to create database"); + res = TDengine.Query(conn, "USE power"); + CheckResPtr(res, "failed to change database"); + res = TDengine.Query(conn, "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"); + CheckResPtr(res, "failed to create stable"); + } + + static void CheckStmtRes(int res, string errorMsg) + { + if (res != 0) + { + Console.WriteLine(errorMsg + ", " + TDengine.StmtErrorStr(stmt)); + int code = TDengine.StmtClose(stmt); + if (code != 0) + { + Console.WriteLine($"falied to close stmt, {code} reason: {TDengine.StmtErrorStr(stmt)} "); + } + ExitProgram(); + } + } + + static void CheckResPtr(IntPtr res, string errorMsg) + { + if (TDengine.ErrorNo(res) != 0) + { + Console.WriteLine(errorMsg + " since:" + TDengine.Error(res)); + ExitProgram(); + } + } + + static void ExitProgram() + { + TDengine.Close(conn); + TDengine.Cleanup(); + Environment.Exit(1); + } + } +} diff --git a/docs/examples/csharp/SubscribeDemo.cs b/docs/examples/csharp/SubscribeDemo.cs new file mode 100644 index 0000000000000000000000000000000000000000..b62ff12e5ea38eb27ae5de8e8027aa41b1873d23 --- /dev/null +++ b/docs/examples/csharp/SubscribeDemo.cs @@ -0,0 +1,100 @@ +using System; +using TDengineTMQ; +using TDengineDriver; +using System.Runtime.InteropServices; + +namespace TMQExample +{ + internal class SubscribeDemo + { + static void Main(string[] args) + { + IntPtr conn = GetConnection(); + string topic = "topic_example"; + Console.WriteLine($"create topic if not exist {topic} as select * from meters"); + //create topic + IntPtr res = TDengine.Query(conn, $"create topic if not exists {topic} as select * from meters"); + + if (res == IntPtr.Zero) + { + throw new Exception($"create topic failed, reason:{TDengine.Error(res)}"); + } + + var cfg = new ConsumerConfig + { + GourpId = "group_1", + TDConnectUser = "root", + TDConnectPasswd = "taosdata", + MsgWithTableName = "true", + TDConnectIp = "127.0.0.1", + }; + + // create consumer + var consumer = new ConsumerBuilder(cfg) + .Build(); + + // subscribe + consumer.Subscribe(topic); + + // consume + for (int i = 0; i < 5; i++) + { + var consumeRes = consumer.Consume(300); + // print consumeResult + foreach (KeyValuePair kv in consumeRes.Message) + { + Console.WriteLine("topic partitions:\n{0}", kv.Key.ToString()); + + kv.Value.Metas.ForEach(meta => + { + Console.Write("{0} {1}({2}) \t|", meta.name, meta.TypeName(), meta.size); + }); + Console.WriteLine(""); + kv.Value.Datas.ForEach(data => + { + Console.WriteLine(data.ToString()); + }); + } + + consumer.Commit(consumeRes); + Console.WriteLine("\n================ {0} done ", i); + + } + + // retrieve topic list + List topics = consumer.Subscription(); + topics.ForEach(t => Console.WriteLine("topic name:{0}", t)); + + + // unsubscribe + consumer.Unsubscribe(); + + // close consumer after use.Otherwise will lead memory leak. + consumer.Close(); + TDengine.Close(conn); + + + } + + static IntPtr GetConnection() + { + string host = "localhost"; + short port = 6030; + string username = "root"; + string password = "taosdata"; + string dbname = "power"; + var conn = TDengine.Connect(host, username, password, dbname, port); + if (conn == IntPtr.Zero) + { + Console.WriteLine("Connect to TDengine failed"); + System.Environment.Exit(0); + } + else + { + Console.WriteLine("Connect to TDengine success"); + } + return conn; + } + } + +} diff --git a/docs/examples/csharp/asyncquery.csproj b/docs/examples/csharp/asyncquery.csproj new file mode 100644 index 0000000000000000000000000000000000000000..045969edd7febbd11cc6577c8ba958669a5a7e3b --- /dev/null +++ b/docs/examples/csharp/asyncquery.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.AsyncQueryExample + + + + + + + diff --git a/docs/examples/csharp/connect.csproj b/docs/examples/csharp/connect.csproj new file mode 100644 index 0000000000000000000000000000000000000000..3a912f8987ace6ae540726886d901c8d32a7b81b --- /dev/null +++ b/docs/examples/csharp/connect.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.ConnectExample + + + + + + + diff --git a/docs/examples/csharp/influxdbline.csproj b/docs/examples/csharp/influxdbline.csproj new file mode 100644 index 0000000000000000000000000000000000000000..58bca485088e409fe1d387c6020418bbc2bf871b --- /dev/null +++ b/docs/examples/csharp/influxdbline.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.InfluxDBLineExample + + + + + + + diff --git a/docs/examples/csharp/optsjson.csproj b/docs/examples/csharp/optsjson.csproj new file mode 100644 index 0000000000000000000000000000000000000000..da16025dcd45f8e5c4ba6e242524c2e56191e93c --- /dev/null +++ b/docs/examples/csharp/optsjson.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.OptsJsonExample + + + + + + + diff --git a/docs/examples/csharp/optstelnet.csproj b/docs/examples/csharp/optstelnet.csproj new file mode 100644 index 0000000000000000000000000000000000000000..194de21bcc74653a2267b29681ece6243fd401fc --- /dev/null +++ b/docs/examples/csharp/optstelnet.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.OptsTelnetExample + + + + + + + diff --git a/docs/examples/csharp/query.csproj b/docs/examples/csharp/query.csproj new file mode 100644 index 0000000000000000000000000000000000000000..39fc135d5ab9f5a8397b412e2307a2306abd4f2a --- /dev/null +++ b/docs/examples/csharp/query.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.QueryExample + + + + + + + diff --git a/docs/examples/csharp/sqlinsert.csproj b/docs/examples/csharp/sqlinsert.csproj new file mode 100644 index 0000000000000000000000000000000000000000..ab0e5e717a78faad07c949b434b0d0b8a26c7211 --- /dev/null +++ b/docs/examples/csharp/sqlinsert.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.SQLInsertExample + + + + + + + diff --git a/docs/examples/csharp/stmtinsert.csproj b/docs/examples/csharp/stmtinsert.csproj new file mode 100644 index 0000000000000000000000000000000000000000..3d459fbeda02ab03dc40dac2ecae290724cccbcc --- /dev/null +++ b/docs/examples/csharp/stmtinsert.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TDengineExample.StmtInsertExample + + + + + + + diff --git a/docs/examples/csharp/subscribe.csproj b/docs/examples/csharp/subscribe.csproj new file mode 100644 index 0000000000000000000000000000000000000000..eff29b3bf42bde521aae70bfd1ed555ac72bfce9 --- /dev/null +++ b/docs/examples/csharp/subscribe.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + enable + TMQExample.SubscribeDemo + + + + + + + diff --git a/docs/examples/go/.gitignore b/docs/examples/go/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b6128386c306834cddeb425f365720bb9c9ce790 --- /dev/null +++ b/docs/examples/go/.gitignore @@ -0,0 +1,3 @@ +.idea +.vscode +tmp/ \ No newline at end of file diff --git a/docs/examples/go/connect/afconn/main.go b/docs/examples/go/connect/afconn/main.go new file mode 100644 index 0000000000000000000000000000000000000000..bb2574a01b0f16f75f6ae42ad7b1085a28cb525e --- /dev/null +++ b/docs/examples/go/connect/afconn/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "log" + + "github.com/taosdata/driver-go/v3/af" +) + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + defer conn.Close() + if err != nil { + log.Fatalln("failed to connect, err:", err) + } else { + fmt.Println("connected") + } +} diff --git a/docs/examples/go/connect/cgoexample/main.go b/docs/examples/go/connect/cgoexample/main.go new file mode 100644 index 0000000000000000000000000000000000000000..881cf15ee3098d0582efffcb0cb9168224126c04 --- /dev/null +++ b/docs/examples/go/connect/cgoexample/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "database/sql" + "fmt" + "log" + + _ "github.com/taosdata/driver-go/v3/taosSql" +) + +func main() { + var taosDSN = "root:taosdata@tcp(localhost:6030)/" + taos, err := sql.Open("taosSql", taosDSN) + if err != nil { + log.Fatalln("failed to connect TDengine, err:", err) + return + } + fmt.Println("Connected") + defer taos.Close() +} + +// use +// var taosDSN = "root:taosdata@tcp(localhost:6030)/dbName" +// if you want to connect a specified database named "dbName". diff --git a/docs/examples/go/connect/restexample/main.go b/docs/examples/go/connect/restexample/main.go new file mode 100644 index 0000000000000000000000000000000000000000..67a129bf9c6d934a5fee3666d3f180a5efe56fc9 --- /dev/null +++ b/docs/examples/go/connect/restexample/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "database/sql" + "fmt" + "log" + + _ "github.com/taosdata/driver-go/v3/taosRestful" +) + +func main() { + var taosDSN = "root:taosdata@http(localhost:6041)/" + taos, err := sql.Open("taosRestful", taosDSN) + if err != nil { + log.Fatalln("failed to connect TDengine, err:", err) + return + } + fmt.Println("Connected") + defer taos.Close() +} + +// use +// var taosDSN = "root:taosdata@http(localhost:6041)/dbName" +// if you want to connect a specified database named "dbName". diff --git a/docs/examples/go/go.mod b/docs/examples/go/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..2bc1a74cb6ef14221fa384701773dc73fe3b161d --- /dev/null +++ b/docs/examples/go/go.mod @@ -0,0 +1,6 @@ +module goexample + +go 1.17 + +require github.com/taosdata/driver-go/v3 3.0 + diff --git a/docs/examples/go/insert/json/main.go b/docs/examples/go/insert/json/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e470cc6bd463327f9805caaa996e968c29af48a7 --- /dev/null +++ b/docs/examples/go/insert/json/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "log" + + "github.com/taosdata/driver-go/v3/af" +) + +func prepareDatabase(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE test") + if err != nil { + panic(err) + } + _, err = conn.Exec("USE test") + if err != nil { + panic(err) + } +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + if err != nil { + log.Fatalln("fail to connect, err:", err) + } + defer conn.Close() + prepareDatabase(conn) + + payload := `[{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "California.SanFrancisco", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, "tags": {"location": "California.LosAngeles", "groupid": 1}}, + {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, "tags": {"location": "California.SanFrancisco", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "California.LosAngeles", "groupid": 1}}]` + + err = conn.OpenTSDBInsertJsonPayload(payload) + if err != nil { + log.Fatalln("insert error:", err) + } +} diff --git a/docs/examples/go/insert/line/main.go b/docs/examples/go/insert/line/main.go new file mode 100644 index 0000000000000000000000000000000000000000..a270ab2633d1afc41c62d0f6adb74fd879fc9c7d --- /dev/null +++ b/docs/examples/go/insert/line/main.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "log" + + "github.com/taosdata/driver-go/v3/af" +) + +func prepareDatabase(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE test") + if err != nil { + panic(err) + } + _, err = conn.Exec("USE test") + if err != nil { + panic(err) + } +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + if err != nil { + fmt.Println("fail to connect, err:", err) + } + defer conn.Close() + prepareDatabase(conn) + var lines = []string{ + "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250", + } + + err = conn.InfluxDBInsertLines(lines, "ms") + if err != nil { + log.Fatalln("insert error:", err) + } +} diff --git a/docs/examples/go/insert/sql/main.go b/docs/examples/go/insert/sql/main.go new file mode 100644 index 0000000000000000000000000000000000000000..57f881314c87de1e16106ec707106b1159b2b9a0 --- /dev/null +++ b/docs/examples/go/insert/sql/main.go @@ -0,0 +1,47 @@ +package main + +import ( + "database/sql" + "fmt" + "log" + + _ "github.com/taosdata/driver-go/v3/taosRestful" +) + +func createStable(taos *sql.DB) { + _, err := taos.Exec("CREATE DATABASE power") + if err != nil { + log.Fatalln("failed to create database, err:", err) + } + _, err = taos.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)") + if err != nil { + log.Fatalln("failed to create stable, err:", err) + } +} + +func insertData(taos *sql.DB) { + sql := `INSERT INTO power.d1001 USING power.meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS('California.SanFrancisco', 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) + power.d1003 USING power.meters TAGS('California.LosAngeles', 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) + power.d1004 USING power.meters TAGS('California.LosAngeles', 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)` + result, err := taos.Exec(sql) + if err != nil { + log.Fatalln("failed to insert, err:", err) + } + rowsAffected, err := result.RowsAffected() + if err != nil { + log.Fatalln("failed to get affected rows, err:", err) + } + fmt.Println("RowsAffected", rowsAffected) +} + +func main() { + var taosDSN = "root:taosdata@http(localhost:6041)/" + taos, err := sql.Open("taosRestful", taosDSN) + if err != nil { + log.Fatalln("failed to connect TDengine, err:", err) + } + defer taos.Close() + createStable(taos) + insertData(taos) +} diff --git a/docs/examples/go/insert/stmt/main.go b/docs/examples/go/insert/stmt/main.go new file mode 100644 index 0000000000000000000000000000000000000000..bcbb8e632bd476a45e869d22d8e818273b214139 --- /dev/null +++ b/docs/examples/go/insert/stmt/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "fmt" + "time" + + "github.com/taosdata/driver-go/v3/af" + "github.com/taosdata/driver-go/v3/common" + "github.com/taosdata/driver-go/v3/common/param" +) + +func checkErr(err error, prompt string) { + if err != nil { + fmt.Printf("%s\n", prompt) + panic(err) + } +} + +func prepareStable(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE power") + checkErr(err, "failed to create database") + _, err = conn.Exec("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)") + checkErr(err, "failed to create stable") + _, err = conn.Exec("USE power") + checkErr(err, "failed to change database") +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + checkErr(err, "fail to connect") + defer conn.Close() + prepareStable(conn) + // create stmt + stmt := conn.InsertStmt() + defer stmt.Close() + err = stmt.Prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)") + checkErr(err, "failed to create prepare statement") + + // bind table name and tags + tagParams := param.NewParam(2).AddBinary([]byte("California.SanFrancisco")).AddInt(2) + err = stmt.SetTableNameWithTags("d1001", tagParams) + checkErr(err, "failed to execute SetTableNameWithTags") + + // specify ColumnType + var bindType *param.ColumnType = param.NewColumnType(4).AddTimestamp().AddFloat().AddInt().AddFloat() + + // bind values. note: can only bind one row each time. + valueParams := []*param.Param{ + param.NewParam(1).AddTimestamp(time.Unix(1648432611, 249300000), common.PrecisionMilliSecond), + param.NewParam(1).AddFloat(10.3), + param.NewParam(1).AddInt(219), + param.NewParam(1).AddFloat(0.31), + } + err = stmt.BindParam(valueParams, bindType) + checkErr(err, "BindParam error") + err = stmt.AddBatch() + checkErr(err, "AddBatch error") + + // bind one more row + valueParams = []*param.Param{ + param.NewParam(1).AddTimestamp(time.Unix(1648432611, 749300000), common.PrecisionMilliSecond), + param.NewParam(1).AddFloat(12.6), + param.NewParam(1).AddInt(218), + param.NewParam(1).AddFloat(0.33), + } + err = stmt.BindParam(valueParams, bindType) + checkErr(err, "BindParam error") + err = stmt.AddBatch() + checkErr(err, "AddBatch error") + // execute + err = stmt.Execute() + checkErr(err, "Execute batch error") +} diff --git a/docs/examples/go/insert/telnet/main.go b/docs/examples/go/insert/telnet/main.go new file mode 100644 index 0000000000000000000000000000000000000000..63e9a56dbf1c9546199fa91a477303b934c5ac19 --- /dev/null +++ b/docs/examples/go/insert/telnet/main.go @@ -0,0 +1,42 @@ +package main + +import ( + "log" + + "github.com/taosdata/driver-go/v3/af" +) + +func prepareDatabase(conn *af.Connector) { + _, err := conn.Exec("CREATE DATABASE test") + if err != nil { + panic(err) + } + _, err = conn.Exec("USE test") + if err != nil { + panic(err) + } +} + +func main() { + conn, err := af.Open("localhost", "root", "taosdata", "", 6030) + if err != nil { + log.Fatalln("fail to connect, err:", err) + } + defer conn.Close() + prepareDatabase(conn) + var lines = []string{ + "meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", + "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", + "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", + "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3", + } + + err = conn.OpenTSDBInsertTelnetLines(lines) + if err != nil { + log.Fatalln("insert error:", err) + } +} diff --git a/docs/examples/go/query/async/main.go b/docs/examples/go/query/async/main.go new file mode 100644 index 0000000000000000000000000000000000000000..7776ec8d3f268a3ef393d2097b71dc5681cf48d9 --- /dev/null +++ b/docs/examples/go/query/async/main.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("hello world!") +} diff --git a/docs/examples/go/query/sync/main.go b/docs/examples/go/query/sync/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8156eea46ace2a6289b0c96b29ce1e9b82d6feb6 --- /dev/null +++ b/docs/examples/go/query/sync/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "database/sql" + "log" + "time" + + _ "github.com/taosdata/driver-go/v3/taosRestful" +) + +func main() { + var taosDSN = "root:taosdata@http(localhost:6041)/power" + taos, err := sql.Open("taosRestful", taosDSN) + if err != nil { + log.Fatalln("failed to connect TDengine, err:", err) + } + defer taos.Close() + rows, err := taos.Query("SELECT ts, current FROM meters LIMIT 2") + if err != nil { + log.Fatalln("failed to select from table, err:", err) + } + + defer rows.Close() + for rows.Next() { + var r struct { + ts time.Time + current float32 + } + err := rows.Scan(&r.ts, &r.current) + if err != nil { + log.Fatalln("scan error:\n", err) + return + } + log.Println(r.ts, r.current) + } +} diff --git a/docs/examples/go/rest/opentsdbjson/main.go b/docs/examples/go/rest/opentsdbjson/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f4f5792e29436e539f301c14ce76607ad3e5593d --- /dev/null +++ b/docs/examples/go/rest/opentsdbjson/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "time" +) + +type Tags struct { + Location string `json:"location"` + Groupid int32 `json:"groupid"` +} + +type Metric struct { + Metric string `json:"metric"` + Timestamp int64 `json:"timestamp"` + Value int32 `json:"value"` + Tags Tags `json:"tags"` +} + +func main() { + client := http.Client{} + for i := 0; i < 10; i++ { + metric := Metric{"voltage", time.Now().UnixMilli(), 1, Tags{"A", 1}} + json, err := json.Marshal(metric) + if err != nil { + panic(err) + } + req, err := http.NewRequest("POST", "http://localhost:6041/opentsdb/v1/put/json/rest_go", bytes.NewBuffer(json)) + if err != nil { + panic(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Basic cm9vdDp0YW9zZGF0YQ==") + resp, err := client.Do(req) + if err != nil { + panic(err) + } + fmt.Printf("%v\n", resp) + time.Sleep(time.Second) + + } +} diff --git a/docs/examples/go/sub/main.go b/docs/examples/go/sub/main.go new file mode 100644 index 0000000000000000000000000000000000000000..7721eed1346f254e104bb41a2135171ebd518e2c --- /dev/null +++ b/docs/examples/go/sub/main.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "time" + + "github.com/taosdata/driver-go/v3/af" + "github.com/taosdata/driver-go/v3/af/tmq" + "github.com/taosdata/driver-go/v3/common" + "github.com/taosdata/driver-go/v3/errors" + "github.com/taosdata/driver-go/v3/wrapper" +) + +func main() { + db, err := af.Open("", "root", "taosdata", "", 0) + if err != nil { + panic(err) + } + defer db.Close() + _, err = db.Exec("create database if not exists example_tmq") + if err != nil { + panic(err) + } + _, err = db.Exec("create topic if not exists example_tmq_topic with meta as DATABASE example_tmq") + if err != nil { + panic(err) + } + config := tmq.NewConfig() + defer config.Destroy() + err = config.SetGroupID("test") + if err != nil { + panic(err) + } + err = config.SetAutoOffsetReset("earliest") + if err != nil { + panic(err) + } + err = config.SetConnectIP("127.0.0.1") + if err != nil { + panic(err) + } + err = config.SetConnectUser("root") + if err != nil { + panic(err) + } + err = config.SetConnectPass("taosdata") + if err != nil { + panic(err) + } + err = config.SetConnectPort("6030") + if err != nil { + panic(err) + } + err = config.SetMsgWithTableName(true) + if err != nil { + panic(err) + } + err = config.EnableHeartBeat() + if err != nil { + panic(err) + } + err = config.EnableAutoCommit(func(result *wrapper.TMQCommitCallbackResult) { + if result.ErrCode != 0 { + errStr := wrapper.TMQErr2Str(result.ErrCode) + err := errors.NewError(int(result.ErrCode), errStr) + panic(err) + } + }) + if err != nil { + panic(err) + } + consumer, err := tmq.NewConsumer(config) + if err != nil { + panic(err) + } + err = consumer.Subscribe([]string{"example_tmq_topic"}) + if err != nil { + panic(err) + } + _, err = db.Exec("create table example_tmq.t1 (ts timestamp,v int)") + if err != nil { + panic(err) + } + for { + result, err := consumer.Poll(time.Second) + if err != nil { + panic(err) + } + if result.Type != common.TMQ_RES_TABLE_META { + panic("want message type 2 got " + strconv.Itoa(int(result.Type))) + } + data, _ := json.Marshal(result.Meta) + fmt.Println(string(data)) + consumer.Commit(context.Background(), result.Message) + consumer.FreeMessage(result.Message) + break + } + _, err = db.Exec("insert into example_tmq.t1 values(now,1)") + if err != nil { + panic(err) + } + for { + result, err := consumer.Poll(time.Second) + if err != nil { + panic(err) + } + if result.Type != common.TMQ_RES_DATA { + panic("want message type 1 got " + strconv.Itoa(int(result.Type))) + } + data, _ := json.Marshal(result.Data) + fmt.Println(string(data)) + consumer.Commit(context.Background(), result.Message) + consumer.FreeMessage(result.Message) + break + } + consumer.Close() +} diff --git a/docs/examples/java/pom.xml b/docs/examples/java/pom.xml index b07bd7b3d47e15e044079ad30fec7e1f62882546..634c3f75a8386db4caab5c1d598f89dc93926c54 100644 --- a/docs/examples/java/pom.xml +++ b/docs/examples/java/pom.xml @@ -21,7 +21,7 @@ com.taosdata.jdbc taos-jdbcdriver - 2.0.40 + 3.0.0 diff --git a/docs/examples/java/src/main/java/com/taos/example/JNIConnectExample.java b/docs/examples/java/src/main/java/com/taos/example/JNIConnectExample.java new file mode 100644 index 0000000000000000000000000000000000000000..84292f7e8682dbb8171c807da74a603f4ae8256e --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/JNIConnectExample.java @@ -0,0 +1,25 @@ +package com.taos.example; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +import com.taosdata.jdbc.TSDBDriver; + +public class JNIConnectExample { + public static void main(String[] args) throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + Properties connProps = new Properties(); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8"); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8"); + Connection conn = DriverManager.getConnection(jdbcUrl, connProps); + System.out.println("Connected"); + conn.close(); + } +} + +// use +// String jdbcUrl = "jdbc:TAOS://localhost:6030/dbName?user=root&password=taosdata"; +// if you want to connect a specified database named "dbName". \ No newline at end of file diff --git a/docs/examples/java/src/main/java/com/taos/example/JSONProtocolExample.java b/docs/examples/java/src/main/java/com/taos/example/JSONProtocolExample.java new file mode 100644 index 0000000000000000000000000000000000000000..c8e649482fbd747cdc238daa9e7a237cf63295b6 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/JSONProtocolExample.java @@ -0,0 +1,40 @@ +package com.taos.example; + +import com.taosdata.jdbc.SchemalessWriter; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class JSONProtocolExample { + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createDatabase(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS test"); + stmt.execute("USE test"); + } + } + + private static String getJSONData() { + return "[{\"metric\": \"meters.current\", \"timestamp\": 1648432611249, \"value\": 10.3, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611249, \"value\": 219, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}, " + + "{\"metric\": \"meters.current\", \"timestamp\": 1648432611250, \"value\": 12.6, \"tags\": {\"location\": \"California.SanFrancisco\", \"groupid\": 2}}," + + " {\"metric\": \"meters.voltage\", \"timestamp\": 1648432611250, \"value\": 221, \"tags\": {\"location\": \"California.LosAngeles\", \"groupid\": 1}}]"; + } + + public static void main(String[] args) throws SQLException { + try (Connection conn = getConnection()) { + createDatabase(conn); + SchemalessWriter writer = new SchemalessWriter(conn); + String jsonData = getJSONData(); + writer.write(jsonData, SchemalessProtocolType.JSON, SchemalessTimestampType.NOT_CONFIGURED); + } + } +} diff --git a/docs/examples/java/src/main/java/com/taos/example/LineProtocolExample.java b/docs/examples/java/src/main/java/com/taos/example/LineProtocolExample.java new file mode 100644 index 0000000000000000000000000000000000000000..09c3078e222c1da083c6ed0da19274b7772bba16 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/LineProtocolExample.java @@ -0,0 +1,42 @@ +package com.taos.example; + +import com.taosdata.jdbc.SchemalessWriter; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class LineProtocolExample { + // format: measurement,tag_set field_set timestamp + private static String[] lines = { + "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000", // micro + // seconds + "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500", + "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249300", + "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611249800", + }; + + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createDatabase(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + // the default precision is ms (millisecond), but we use us(microsecond) here. + stmt.execute("CREATE DATABASE IF NOT EXISTS test PRECISION 'us'"); + stmt.execute("USE test"); + } + } + + public static void main(String[] args) throws SQLException { + try (Connection conn = getConnection()) { + createDatabase(conn); + SchemalessWriter writer = new SchemalessWriter(conn); + writer.write(lines, SchemalessProtocolType.LINE, SchemalessTimestampType.MICRO_SECONDS); + } + } +} diff --git a/docs/examples/java/src/main/java/com/taos/example/Meters.java b/docs/examples/java/src/main/java/com/taos/example/Meters.java new file mode 100644 index 0000000000000000000000000000000000000000..0f1eadd55b5b197c8e9ecbc415e78fc28e2cb61b --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/Meters.java @@ -0,0 +1,62 @@ +package com.taos.example; + +import java.sql.Timestamp; + +public class Meters { + private Timestamp ts; + private float current; + private int voltage; + private int groupid; + private String location; + + public Timestamp getTs() { + return ts; + } + + public void setTs(Timestamp ts) { + this.ts = ts; + } + + public float getCurrent() { + return current; + } + + public void setCurrent(float current) { + this.current = current; + } + + public int getVoltage() { + return voltage; + } + + public void setVoltage(int voltage) { + this.voltage = voltage; + } + + public int getGroupid() { + return groupid; + } + + public void setGroupid(int groupid) { + this.groupid = groupid; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + @Override + public String toString() { + return "Meters{" + + "ts=" + ts + + ", current=" + current + + ", voltage=" + voltage + + ", groupid=" + groupid + + ", location='" + location + '\'' + + '}'; + } +} diff --git a/docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java b/docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java new file mode 100644 index 0000000000000000000000000000000000000000..9b7fa35e90fb4f66d2885af0b2a2f1a429a97127 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/MetersDeserializer.java @@ -0,0 +1,6 @@ +package com.taos.example; + +import com.taosdata.jdbc.tmq.ReferenceDeserializer; + +public class MetersDeserializer extends ReferenceDeserializer { +} \ No newline at end of file diff --git a/docs/examples/java/src/main/java/com/taos/example/RESTConnectExample.java b/docs/examples/java/src/main/java/com/taos/example/RESTConnectExample.java new file mode 100644 index 0000000000000000000000000000000000000000..9d077812e0ff9d0de2952d97aa12f870e6412885 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/RESTConnectExample.java @@ -0,0 +1,16 @@ +package com.taos.example; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class RESTConnectExample { + // ANCHOR: main + public static void main(String[] args) throws SQLException { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata"; + Connection conn = DriverManager.getConnection(jdbcUrl); + System.out.println("Connected"); + conn.close(); + } + // ANCHOR_END: main +} \ No newline at end of file diff --git a/docs/examples/java/src/main/java/com/taos/example/RestInsertExample.java b/docs/examples/java/src/main/java/com/taos/example/RestInsertExample.java new file mode 100644 index 0000000000000000000000000000000000000000..af97fe4373ca964260e5614f133f359e229b0e15 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/RestInsertExample.java @@ -0,0 +1,74 @@ +package com.taos.example; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; + + +public class RestInsertExample { + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static List getRawData() { + return Arrays.asList( + "d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,California.SanFrancisco,2", + "d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,California.SanFrancisco,2", + "d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,California.SanFrancisco,2", + "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,California.SanFrancisco,3", + "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,California.LosAngeles,2", + "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,California.LosAngeles,2", + "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,California.LosAngeles,3", + "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,California.LosAngeles,3" + ); + } + + + /** + * The generated SQL is: + * INSERT INTO power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES('2018-10-03 14:38:05.000',10.30000,219,0.31000) + * power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES('2018-10-03 14:38:15.000',12.60000,218,0.33000) + * power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES('2018-10-03 14:38:16.800',12.30000,221,0.31000) + * power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES('2018-10-03 14:38:16.650',10.30000,218,0.25000) + * power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES('2018-10-03 14:38:05.500',11.80000,221,0.28000) + * power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES('2018-10-03 14:38:16.600',13.40000,223,0.29000) + * power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES('2018-10-03 14:38:05.000',10.80000,223,0.29000) + * power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES('2018-10-03 14:38:06.500',11.50000,221,0.35000) + */ + private static String getSQL() { + StringBuilder sb = new StringBuilder("INSERT INTO "); + for (String line : getRawData()) { + String[] ps = line.split(","); + sb.append("power." + ps[0]).append(" USING power.meters TAGS(") + .append(ps[5]).append(", ") // tag: location + .append(ps[6]) // tag: groupId + .append(") VALUES(") + .append('\'').append(ps[1]).append('\'').append(",") // ts + .append(ps[2]).append(",") // current + .append(ps[3]).append(",") // voltage + .append(ps[4]).append(") "); // phase + } + return sb.toString(); + } + + public static void insertData() throws SQLException { + try (Connection conn = getConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE power KEEP 3650"); + stmt.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + + "TAGS (location BINARY(64), groupId INT)"); + String sql = getSQL(); + int rowCount = stmt.executeUpdate(sql); + System.out.println("rowCount=" + rowCount); // rowCount=8 + } + } + } + + public static void main(String[] args) throws SQLException { + insertData(); + } +} diff --git a/docs/examples/java/src/main/java/com/taos/example/RestQueryExample.java b/docs/examples/java/src/main/java/com/taos/example/RestQueryExample.java new file mode 100644 index 0000000000000000000000000000000000000000..a3581a1f4733e8bf3e3f561bb6cab5a725d8a1c0 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/RestQueryExample.java @@ -0,0 +1,55 @@ +package com.taos.example; + +import java.sql.*; + +public class RestQueryExample { + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041/power?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void printRow(ResultSet rs) throws SQLException { + ResultSetMetaData meta = rs.getMetaData(); + for (int i = 1; i <= meta.getColumnCount(); i++) { + String value = rs.getString(i); + System.out.print(value); + System.out.print("\t"); + } + System.out.println(); + } + + private static void printColName(ResultSet rs) throws SQLException { + ResultSetMetaData meta = rs.getMetaData(); + for (int i = 1; i <= meta.getColumnCount(); i++) { + String colLabel = meta.getColumnLabel(i); + System.out.print(colLabel); + System.out.print("\t"); + } + System.out.println(); + } + + private static void processResult(ResultSet rs) throws SQLException { + printColName(rs); + while (rs.next()) { + printRow(rs); + } + } + + private static void queryData() throws SQLException { + try (Connection conn = getConnection()) { + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery("SELECT AVG(voltage) FROM meters GROUP BY location"); + processResult(rs); + } + } + } + + public static void main(String[] args) throws SQLException { + queryData(); + } +} + +// possible output: +// avg(voltage) location +// 222.0 California.LosAngeles +// 219.0 California.SanFrancisco diff --git a/docs/examples/java/src/main/java/com/taos/example/StmtInsertExample.java b/docs/examples/java/src/main/java/com/taos/example/StmtInsertExample.java new file mode 100644 index 0000000000000000000000000000000000000000..bbcc92b22f67c31384b0fb7a082975eaac2ff2bc --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/StmtInsertExample.java @@ -0,0 +1,84 @@ +package com.taos.example; + +import com.taosdata.jdbc.TSDBPreparedStatement; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class StmtInsertExample { + private static ArrayList tsToLongArray(String ts) { + ArrayList result = new ArrayList<>(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); + LocalDateTime localDateTime = LocalDateTime.parse(ts, formatter); + result.add(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()); + return result; + } + + private static ArrayList toArray(T v) { + ArrayList result = new ArrayList<>(); + result.add(v); + return result; + } + + private static List getRawData() { + return Arrays.asList( + "d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,California.SanFrancisco,2", + "d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,California.SanFrancisco,2", + "d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,California.SanFrancisco,2", + "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,California.SanFrancisco,3", + "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,California.LosAngeles,2", + "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,California.LosAngeles,2", + "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,California.LosAngeles,3", + "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,California.LosAngeles,3" + ); + } + + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createTable(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE power KEEP 3650"); + stmt.executeUpdate("USE power"); + stmt.execute("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + + "TAGS (location BINARY(64), groupId INT)"); + } + } + + private static void insertData() throws SQLException { + try (Connection conn = getConnection()) { + createTable(conn); + String psql = "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)"; + try (TSDBPreparedStatement pst = (TSDBPreparedStatement) conn.prepareStatement(psql)) { + for (String line : getRawData()) { + String[] ps = line.split(","); + // bind table name and tags + pst.setTableName(ps[0]); + pst.setTagString(0, ps[5]); + pst.setTagInt(1, Integer.valueOf(ps[6])); + // bind values + pst.setTimestamp(0, tsToLongArray(ps[1])); //ps[1] looks like: 2018-10-03 14:38:05.000 + pst.setFloat(1, toArray(Float.valueOf(ps[2]))); + pst.setInt(2, toArray(Integer.valueOf(ps[3]))); + pst.setFloat(3, toArray(Float.valueOf(ps[4]))); + pst.columnDataAddBatch(); + } + pst.columnDataExecuteBatch(); + } + } + } + + public static void main(String[] args) throws SQLException { + insertData(); + } +} diff --git a/docs/examples/java/src/main/java/com/taos/example/SubscribeDemo.java b/docs/examples/java/src/main/java/com/taos/example/SubscribeDemo.java new file mode 100644 index 0000000000000000000000000000000000000000..50e8b357719fc6d1f4707e474afdf58fb4531970 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/SubscribeDemo.java @@ -0,0 +1,78 @@ +package com.taos.example; + +import com.taosdata.jdbc.tmq.ConsumerRecords; +import com.taosdata.jdbc.tmq.TMQConstants; +import com.taosdata.jdbc.tmq.TaosConsumer; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.atomic.AtomicBoolean; + +public class SubscribeDemo { + private static final String TOPIC = "tmq_topic"; + private static final String DB_NAME = "meters"; + private static final AtomicBoolean shutdown = new AtomicBoolean(false); + + public static void main(String[] args) { + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + public void run() { + shutdown.set(true); + } + }, 3_000); + try { + // prepare + Class.forName("com.taosdata.jdbc.TSDBDriver"); + String jdbcUrl = "jdbc:TAOS://127.0.0.1:6030/?user=root&password=taosdata"; + Connection connection = DriverManager.getConnection(jdbcUrl); + try (Statement statement = connection.createStatement()) { + statement.executeUpdate("drop topic if exists " + TOPIC); + statement.executeUpdate("drop database if exists " + DB_NAME); + statement.executeUpdate("create database " + DB_NAME); + statement.executeUpdate("use " + DB_NAME); + statement.executeUpdate( + "CREATE TABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT) TAGS (`groupid` INT, `location` BINARY(16))"); + statement.executeUpdate("CREATE TABLE `d0` USING `meters` TAGS(0, 'Los Angles')"); + statement.executeUpdate("INSERT INTO `d0` values(now - 10s, 0.32, 116)"); + statement.executeUpdate("INSERT INTO `d0` values(now - 8s, NULL, NULL)"); + statement.executeUpdate( + "INSERT INTO `d1` USING `meters` TAGS(1, 'San Francisco') values(now - 9s, 10.1, 119)"); + statement.executeUpdate( + "INSERT INTO `d1` values (now-8s, 10, 120) (now - 6s, 10, 119) (now - 4s, 11.2, 118)"); + // create topic + statement.executeUpdate("create topic " + TOPIC + " as select * from meters"); + } + + // create consumer + Properties properties = new Properties(); + properties.setProperty(TMQConstants.BOOTSTRAP_SERVERS, "127.0.0.1:6030"); + properties.setProperty(TMQConstants.MSG_WITH_TABLE_NAME, "true"); + properties.setProperty(TMQConstants.ENABLE_AUTO_COMMIT, "true"); + properties.setProperty(TMQConstants.GROUP_ID, "test"); + properties.setProperty(TMQConstants.VALUE_DESERIALIZER, + "com.taosdata.jdbc.MetersDeserializer"); + + // poll data + try (TaosConsumer consumer = new TaosConsumer<>(properties)) { + consumer.subscribe(Collections.singletonList(TOPIC)); + while (!shutdown.get()) { + ConsumerRecords meters = consumer.poll(Duration.ofMillis(100)); + for (Meters meter : meters) { + System.out.println(meter); + } + } + consumer.unsubscribe(); + } + } catch (ClassNotFoundException | SQLException e) { + e.printStackTrace(); + } + timer.cancel(); + } +} \ No newline at end of file diff --git a/docs/examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java b/docs/examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java new file mode 100644 index 0000000000000000000000000000000000000000..4c9368288df74f829121aeab5b925d1d083d29f0 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/TelnetLineProtocolExample.java @@ -0,0 +1,45 @@ +package com.taos.example; + +import com.taosdata.jdbc.SchemalessWriter; +import com.taosdata.jdbc.enums.SchemalessProtocolType; +import com.taosdata.jdbc.enums.SchemalessTimestampType; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; + +public class TelnetLineProtocolExample { + // format: =[ =] + private static String[] lines = { "meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", + "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", + "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", + "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3", + }; + + private static Connection getConnection() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + return DriverManager.getConnection(jdbcUrl); + } + + private static void createDatabase(Connection conn) throws SQLException { + try (Statement stmt = conn.createStatement()) { + // the default precision is ms (microsecond), but we use us(microsecond) here. + stmt.execute("CREATE DATABASE IF NOT EXISTS test precision 'us'"); + stmt.execute("USE test"); + } + } + + public static void main(String[] args) throws SQLException { + try (Connection conn = getConnection()) { + createDatabase(conn); + SchemalessWriter writer = new SchemalessWriter(conn); + writer.write(lines, SchemalessProtocolType.TELNET, SchemalessTimestampType.NOT_CONFIGURED); + } + } + +} diff --git a/docs/examples/java/src/main/java/com/taos/example/WSConnectExample.java b/docs/examples/java/src/main/java/com/taos/example/WSConnectExample.java new file mode 100644 index 0000000000000000000000000000000000000000..48d1dde593cc347632efb6612946aa16e82e8b94 --- /dev/null +++ b/docs/examples/java/src/main/java/com/taos/example/WSConnectExample.java @@ -0,0 +1,21 @@ +package com.taos.example; + +import com.taosdata.jdbc.TSDBDriver; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +public class WSConnectExample { + // ANCHOR: main + public static void main(String[] args) throws SQLException { + String jdbcUrl = "jdbc:TAOS-RS://localhost:6041?user=root&password=taosdata"; + Properties connProps = new Properties(); + connProps.setProperty(TSDBDriver.PROPERTY_KEY_BATCH_LOAD, "true"); + Connection conn = DriverManager.getConnection(jdbcUrl, connProps); + System.out.println("Connected"); + conn.close(); + } + // ANCHOR_END: main +} diff --git a/docs/examples/java/src/test/java/com/taos/test/TestAll.java b/docs/examples/java/src/test/java/com/taos/test/TestAll.java index 613bc47f2aaf09964dcbd3f7fe9440882e7df2e0..42db24485afec05298159f7b0c3a4e15835d98ed 100644 --- a/docs/examples/java/src/test/java/com/taos/test/TestAll.java +++ b/docs/examples/java/src/test/java/com/taos/test/TestAll.java @@ -1,20 +1,91 @@ package com.taos.test; -import com.taos.example.CloudTutorial; -import com.taos.example.ConnectCloudExample; +import com.taos.example.*; +import org.junit.FixMethodOrder; import org.junit.Test; -import java.sql.SQLException; +import java.sql.*; +@FixMethodOrder public class TestAll { + private String[] args = new String[]{}; + + public void dropDB(String dbName) throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + try (Connection conn = DriverManager.getConnection(jdbcUrl)) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("drop database if exists " + dbName); + } + } + } + + public void insertData() throws SQLException { + String jdbcUrl = "jdbc:TAOS://localhost:6030?user=root&password=taosdata"; + try (Connection conn = DriverManager.getConnection(jdbcUrl)) { + try (Statement stmt = conn.createStatement()) { + String sql = "INSERT INTO power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES('2018-10-03 14:38:05.000',10.30000,219,0.31000)\n" + + " power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES('2018-10-03 15:38:15.000',12.60000,218,0.33000)\n" + + " power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES('2018-10-03 15:38:16.800',12.30000,221,0.31000)\n" + + " power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES('2018-10-03 15:38:16.650',10.30000,218,0.25000)\n" + + " power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES('2018-10-03 15:38:05.500',11.80000,221,0.28000)\n" + + " power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES('2018-10-03 15:38:16.600',13.40000,223,0.29000)\n" + + " power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES('2018-10-03 15:38:05.000',10.80000,223,0.29000)\n" + + " power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES('2018-10-03 15:38:06.000',10.80000,223,0.29000)\n" + + " power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES('2018-10-03 15:38:07.000',10.80000,223,0.29000)\n" + + " power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES('2018-10-03 15:38:08.500',11.50000,221,0.35000)"; + + stmt.execute(sql); + } + } + } + + @Test + public void testJNIConnect() throws SQLException { + JNIConnectExample.main(args); + } + + @Test + public void testRestConnect() throws SQLException { + RESTConnectExample.main(args); + } + + @Test + public void testRestInsert() throws SQLException { + dropDB("power"); + RestInsertExample.main(args); + RestQueryExample.main(args); + } + + @Test + public void testStmtInsert() throws SQLException { + dropDB("power"); + StmtInsertExample.main(args); + } @Test - public void testConnectCloudExample() throws SQLException { - ConnectCloudExample.main(new String[]{}); + public void testSubscribe() { + + Thread thread = new Thread(() -> { + try { + Thread.sleep(1000); + insertData(); + } catch (SQLException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + thread.start(); + SubscribeDemo.main(args); } -// @Test -// public void testCloudTutorial() throws SQLException { -// CloudTutorial.main(new String[]{}); -// } + @Test + public void testSchemaless() throws SQLException { + LineProtocolExample.main(args); + TelnetLineProtocolExample.main(args); + // for json protocol, tags may be double type. but for telnet protocol tag must be nchar type. + // To avoid type mismatch, we delete database test. + dropDB("test"); + JSONProtocolExample.main(args); + } } diff --git a/docs/examples/node/nativeexample/async_query_example.js b/docs/examples/node/nativeexample/async_query_example.js new file mode 100644 index 0000000000000000000000000000000000000000..432d8b8f6c1e89ebe35adac55d4f97376d205cb6 --- /dev/null +++ b/docs/examples/node/nativeexample/async_query_example.js @@ -0,0 +1,20 @@ +const taos = require("@tdengine/client"); +const conn = taos.connect({ host: "localhost", database: "power" }); +const cursor = conn.cursor(); + +function queryExample() { + cursor + .query("SELECT ts, current FROM meters LIMIT 2") + .execute_a() + .then((result) => { + result.pretty(); + }); +} + +try { + queryExample(); +} finally { + setTimeout(() => { + conn.close(); + }, 2000); +} diff --git a/docs/examples/node/nativeexample/connect.js b/docs/examples/node/nativeexample/connect.js new file mode 100644 index 0000000000000000000000000000000000000000..7971cc2348993f508b8a04e44fd8e58def11bb1d --- /dev/null +++ b/docs/examples/node/nativeexample/connect.js @@ -0,0 +1,13 @@ +//A cursor also needs to be initialized in order to interact with TDengine from Node.js. +const taos = require("@tdengine/client"); +var conn = taos.connect({ + host: "127.0.0.1", + user: "root", + password: "taosdata", + config: "/etc/taos", + port: 0, +}); +var cursor = conn.cursor(); // Initializing a new cursor + +//Close a connection +conn.close(); \ No newline at end of file diff --git a/docs/examples/node/nativeexample/influxdb_line_example.js b/docs/examples/node/nativeexample/influxdb_line_example.js new file mode 100644 index 0000000000000000000000000000000000000000..57170770d8f128b034236b71d8ff7d46f31b3199 --- /dev/null +++ b/docs/examples/node/nativeexample/influxdb_line_example.js @@ -0,0 +1,34 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function createDatabase() { + cursor.execute("CREATE DATABASE test"); + cursor.execute("USE test"); +} + +function insertData() { + const lines = [ + "meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249", + "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611250", + "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249", + "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611250", + ]; + cursor.schemalessInsert( + lines, + taos.SCHEMALESS_PROTOCOL.TSDB_SML_LINE_PROTOCOL, + taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_MILLI_SECONDS + ); +} + +try { + createDatabase(); + insertData(); +} finally { + cursor.close(); + conn.close(); +} diff --git a/docs/examples/node/nativeexample/insert_example.js b/docs/examples/node/nativeexample/insert_example.js new file mode 100644 index 0000000000000000000000000000000000000000..42050fa251f3da5e5a4a28aed232aef418ff8f7e --- /dev/null +++ b/docs/examples/node/nativeexample/insert_example.js @@ -0,0 +1,31 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); +try { + cursor.execute("CREATE DATABASE power"); + cursor.execute("USE power"); + cursor.execute( + "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)" + ); + var sql = `INSERT INTO power.d1001 USING power.meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) +power.d1002 USING power.meters TAGS('California.SanFrancisco', 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) +power.d1003 USING power.meters TAGS('California.LosAngeles', 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) +power.d1004 USING power.meters TAGS('California.LosAngeles', 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)`; + cursor.execute(sql,{'quiet':false}); +} finally { + cursor.close(); + conn.close(); +} + +// run with: node insert_example.js +// output: +// Successfully connected to TDengine +// Query OK, 0 row(s) affected (0.00509570s) +// Query OK, 0 row(s) affected (0.00130880s) +// Query OK, 0 row(s) affected (0.00467900s) +// Query OK, 8 row(s) affected (0.04043550s) +// Connection is closed diff --git a/docs/examples/node/nativeexample/multi_bind_example.js b/docs/examples/node/nativeexample/multi_bind_example.js new file mode 100644 index 0000000000000000000000000000000000000000..6cc3993397990af9bb9c01e1b5bf844f8a242201 --- /dev/null +++ b/docs/examples/node/nativeexample/multi_bind_example.js @@ -0,0 +1,53 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function prepareSTable() { + cursor.execute("CREATE DATABASE power"); + cursor.execute("USE power"); + cursor.execute( + "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)" + ); +} + +//ANCHOR: insertData +function insertData() { + // init + cursor.stmtInit(); + // prepare + cursor.stmtPrepare( + "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)" + ); + + // bind table name and tags + let tagBind = new taos.TaosMultiBindArr(2); + tagBind.multiBindBinary(["California.SanFrancisco"]); + tagBind.multiBindInt([2]); + cursor.stmtSetTbnameTags("d1001", tagBind.getMultiBindArr()); + + // bind values + let valueBind = new taos.TaosMultiBindArr(4); + valueBind.multiBindTimestamp([1648432611249, 1648432611749]); + valueBind.multiBindFloat([10.3, 12.6]); + valueBind.multiBindInt([219, 218]); + valueBind.multiBindFloat([0.31, 0.33]); + cursor.stmtBindParamBatch(valueBind.getMultiBindArr()); + cursor.stmtAddBatch(); + + // execute + cursor.stmtExecute(); + cursor.stmtClose(); +} +//ANCHOR_END: insertData + +try { + prepareSTable(); + insertData(); +} finally { + cursor.close(); + conn.close(); +} diff --git a/docs/examples/node/nativeexample/opentsdb_json_example.js b/docs/examples/node/nativeexample/opentsdb_json_example.js new file mode 100644 index 0000000000000000000000000000000000000000..4ea36ca68be042bd6c114d44b70f390bf4e503e2 --- /dev/null +++ b/docs/examples/node/nativeexample/opentsdb_json_example.js @@ -0,0 +1,55 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function createDatabase() { + cursor.execute("CREATE DATABASE test"); + cursor.execute("USE test"); +} + +function insertData() { + const lines = [ + { + metric: "meters.current", + timestamp: 1648432611249, + value: 10.3, + tags: { location: "California.SanFrancisco", groupid: 2 }, + }, + { + metric: "meters.voltage", + timestamp: 1648432611249, + value: 219, + tags: { location: "California.LosAngeles", groupid: 1 }, + }, + { + metric: "meters.current", + timestamp: 1648432611250, + value: 12.6, + tags: { location: "California.SanFrancisco", groupid: 2 }, + }, + { + metric: "meters.voltage", + timestamp: 1648432611250, + value: 221, + tags: { location: "California.LosAngeles", groupid: 1 }, + }, + ]; + + cursor.schemalessInsert( + [JSON.stringify(lines)], + taos.SCHEMALESS_PROTOCOL.TSDB_SML_JSON_PROTOCOL, + taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_NOT_CONFIGURED + ); +} + +try { + createDatabase(); + insertData(); +} finally { + cursor.close(); + conn.close(); +} diff --git a/docs/examples/node/nativeexample/opentsdb_telnet_example.js b/docs/examples/node/nativeexample/opentsdb_telnet_example.js new file mode 100644 index 0000000000000000000000000000000000000000..8f5d17822b0feb9da06fbd7f419dbf1d8369e6a0 --- /dev/null +++ b/docs/examples/node/nativeexample/opentsdb_telnet_example.js @@ -0,0 +1,38 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function createDatabase() { + cursor.execute("CREATE DATABASE test"); + cursor.execute("USE test"); +} + +function insertData() { + const lines = [ + "meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", + "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", + "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", + "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3", + ]; + cursor.schemalessInsert( + lines, + taos.SCHEMALESS_PROTOCOL.TSDB_SML_TELNET_PROTOCOL, + taos.SCHEMALESS_PRECISION.TSDB_SML_TIMESTAMP_NOT_CONFIGURED + ); +} + +try { + createDatabase(); + insertData(); +} finally { + cursor.close(); + conn.close(); +} diff --git a/docs/examples/node/nativeexample/param_bind_example.js b/docs/examples/node/nativeexample/param_bind_example.js new file mode 100644 index 0000000000000000000000000000000000000000..efe422586fb75734073311d24f03e6c50d18ab28 --- /dev/null +++ b/docs/examples/node/nativeexample/param_bind_example.js @@ -0,0 +1,54 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ + host: "localhost", +}); + +const cursor = conn.cursor(); + +function prepareSTable() { + cursor.execute("CREATE DATABASE power"); + cursor.execute("USE power"); + cursor.execute( + "CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)" + ); +} + +function insertData() { + // init + cursor.stmtInit(); + // prepare + cursor.stmtPrepare( + "INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)" + ); + + // bind table name and tags + let tagBind = new taos.TaosMultiBindArr(2); + tagBind.multiBindBinary(["California.SanFrancisco"]); + tagBind.multiBindInt([2]); + cursor.stmtSetTbnameTags("d1001", tagBind.getMultiBindArr()); + + // bind values + let rows = [[1648432611249, 1648432611749], [10.3, 12.6], [219, 218], [0.31, 0.33]]; + + let valueBind = new taos.TaosMultiBindArr(4); + valueBind.multiBindTimestamp(rows[0]); + valueBind.multiBindFloat(rows[1]); + valueBind.multiBindInt(rows[2]); + valueBind.multiBindFloat(rows[3]); + cursor.stmtBindParamBatch(valueBind.getMultiBindArr()); + cursor.stmtAddBatch(); + + + // execute + cursor.stmtExecute(); + cursor.stmtClose(); +} + +try { + prepareSTable(); + insertData(); +} finally { + cursor.close(); + conn.close(); +} diff --git a/docs/examples/node/nativeexample/query_example.js b/docs/examples/node/nativeexample/query_example.js new file mode 100644 index 0000000000000000000000000000000000000000..11cfd9a6057eb8d645282a4f0cab945ba46f4a9b --- /dev/null +++ b/docs/examples/node/nativeexample/query_example.js @@ -0,0 +1,15 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ host: "localhost", database: "power" }); +const cursor = conn.cursor(); +const query = cursor.query("SELECT ts, current FROM meters LIMIT 2"); +query.execute().then(function (result) { + result.pretty(); +}); + +// output: +// Successfully connected to TDengine +// ts | current | +// ======================================================= +// 2018-10-03 14:38:05.000 | 10.3 | +// 2018-10-03 14:38:15.000 | 12.6 | diff --git a/docs/examples/node/nativeexample/subscribe_demo.js b/docs/examples/node/nativeexample/subscribe_demo.js new file mode 100644 index 0000000000000000000000000000000000000000..53cbe55d264a0e83b4d4b441b0b912872bbb7018 --- /dev/null +++ b/docs/examples/node/nativeexample/subscribe_demo.js @@ -0,0 +1,51 @@ +const taos = require("@tdengine/client"); + +const conn = taos.connect({ host: "localhost", database: "power" }); +var cursor = conn.cursor(); + +function runConsumer() { + + // create topic + cursor.execute("create topic topic_name_example as select * from meters"); + + let consumer = taos.consumer({ + 'group.id': 'tg2', + 'td.connect.user': 'root', + 'td.connect.pass': 'taosdata', + 'msg.with.table.name': 'true', + 'enable.auto.commit': 'true' + }); + + // subscribe the topic just created. + consumer.subscribe("topic_name_example"); + + // get subscribe topic list + let topicList = consumer.subscription(); + console.log(topicList); + + for (let i = 0; i < 5; i++) { + let msg = consumer.consume(100); + console.log(msg.topicPartition); + console.log(msg.block); + console.log(msg.fields) + consumer.commit(msg); + console.log(`=======consumer ${i} done`) + } + + consumer.unsubscribe(); + consumer.close(); + + // drop topic + cursor.execute("drop topic topic_name_example"); +} + + +try { + runConsumer(); +} finally { + + setTimeout(() => { + cursor.close(); + conn.close(); + }, 2000); +} diff --git a/docs/examples/node/package.json b/docs/examples/node/package.json index 51b9cf5172ff7db27e48133a3b0ee45c78ae335a..d00d71d99fdff89af68f31a50416681733a08274 100644 --- a/docs/examples/node/package.json +++ b/docs/examples/node/package.json @@ -4,6 +4,7 @@ "main": "index.js", "license": "MIT", "dependencies": { - "td2.0-rest-connector": "^1.0.5" + "@tdengine/client": "^3.0.1", + "@tdengine/rest": "^3.0.0" } } diff --git a/docs/examples/node/restexample/connect.js b/docs/examples/node/restexample/connect.js new file mode 100644 index 0000000000000000000000000000000000000000..bb027d4fe85f35e5a7047b1517caee00314e2153 --- /dev/null +++ b/docs/examples/node/restexample/connect.js @@ -0,0 +1,20 @@ +const { options, connect } = require("@tdengine/rest"); + +async function test() { + options.path = "/rest/sql"; + options.host = "localhost"; + let conn = connect(options); + let cursor = conn.cursor(); + try { + let res = await cursor.query("SELECT server_version()"); + res.toString(); + } catch (err) { + console.log(err); + } +} +test(); + +// output: +// server_version() | +// =================== +// 3.0.0.0 | diff --git a/docs/examples/php/connect.php b/docs/examples/php/connect.php new file mode 100644 index 0000000000000000000000000000000000000000..b825b447805a3923248042d2cdff79c51bdcdbe3 --- /dev/null +++ b/docs/examples/php/connect.php @@ -0,0 +1,20 @@ +connect(); +} catch (TDengineException $e) { + // throw exception + throw $e; +} diff --git a/docs/examples/php/insert.php b/docs/examples/php/insert.php new file mode 100644 index 0000000000000000000000000000000000000000..6e38fa0c46d31aa0a939d471ccbd255cfa453a16 --- /dev/null +++ b/docs/examples/php/insert.php @@ -0,0 +1,33 @@ +connect(); + + // insert + $connection->query('CREATE DATABASE if not exists power'); + $connection->query('CREATE STABLE if not exists meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)'); + $resource = $connection->query(<<<'SQL' + INSERT INTO power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) + power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) + power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000) + SQL); + + // get affected rows + var_dump($resource->affectedRows()); +} catch (TDengineException $e) { + // throw exception + throw $e; +} diff --git a/docs/examples/php/insert_stmt.php b/docs/examples/php/insert_stmt.php new file mode 100644 index 0000000000000000000000000000000000000000..c927a9b0ced46461daeda0f53b27e2f9d67d5860 --- /dev/null +++ b/docs/examples/php/insert_stmt.php @@ -0,0 +1,49 @@ +connect(); + + // insert + $connection->query('CREATE DATABASE if not exists power'); + $connection->query('CREATE STABLE if not exists meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)'); + $stmt = $connection->prepare('INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)'); + + // set table name and tags + $stmt->setTableNameTags('d1001', [ + // same format as parameter binding + [TDengine\TSDB_DATA_TYPE_BINARY, 'California.SanFrancisco'], + [TDengine\TSDB_DATA_TYPE_INT, 2], + ]); + + $stmt->bindParams([ + [TDengine\TSDB_DATA_TYPE_TIMESTAMP, 1648432611249], + [TDengine\TSDB_DATA_TYPE_FLOAT, 10.3], + [TDengine\TSDB_DATA_TYPE_INT, 219], + [TDengine\TSDB_DATA_TYPE_FLOAT, 0.31], + ]); + $stmt->bindParams([ + [TDengine\TSDB_DATA_TYPE_TIMESTAMP, 1648432611749], + [TDengine\TSDB_DATA_TYPE_FLOAT, 12.6], + [TDengine\TSDB_DATA_TYPE_INT, 218], + [TDengine\TSDB_DATA_TYPE_FLOAT, 0.33], + ]); + $resource = $stmt->execute(); + + // get affected rows + var_dump($resource->affectedRows()); +} catch (TDengineException $e) { + // throw exception + throw $e; +} diff --git a/docs/examples/php/query.php b/docs/examples/php/query.php new file mode 100644 index 0000000000000000000000000000000000000000..2607940ea06a70eaa30e4c165c05bd72aa89857c --- /dev/null +++ b/docs/examples/php/query.php @@ -0,0 +1,23 @@ +connect(); + + $resource = $connection->query('SELECT ts, current FROM meters LIMIT 2'); + var_dump($resource->fetch()); +} catch (TDengineException $e) { + // throw exception + throw $e; +} diff --git a/docs/examples/python/.gitignore b/docs/examples/python/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..723ef36f4e4f32c4560383aa5987c575a30c6535 --- /dev/null +++ b/docs/examples/python/.gitignore @@ -0,0 +1 @@ +.idea \ No newline at end of file diff --git a/docs/examples/python/async_query_example.py b/docs/examples/python/async_query_example.py new file mode 100644 index 0000000000000000000000000000000000000000..a78f44230a34d40a5326dea367bbad11a6e51da2 --- /dev/null +++ b/docs/examples/python/async_query_example.py @@ -0,0 +1,72 @@ +import time +from ctypes import * + +from taos import * + + +def fetch_callback(p_param, p_result, num_of_rows): + print("fetched ", num_of_rows, "rows") + p = cast(p_param, POINTER(Counter)) + result = TaosResult(p_result) + + if num_of_rows == 0: + print("fetching completed") + p.contents.done = True + result.close() + return + if num_of_rows < 0: + p.contents.done = True + result.check_error(num_of_rows) + result.close() + return None + + for row in result.rows_iter(num_of_rows): + print(row) + p.contents.count += result.row_count + result.fetch_rows_a(fetch_callback, p_param) + + +def query_callback(p_param, p_result, code): + if p_result is None: + return + result = TaosResult(p_result) + if code == 0: + result.fetch_rows_a(fetch_callback, p_param) + result.check_error(code) + + +class Counter(Structure): + _fields_ = [("count", c_int), ("done", c_bool)] + + def __str__(self): + return "{ count: %d, done: %s }" % (self.count, self.done) + + +def test_query(conn): + counter = Counter(count=0) + conn.query_a("select ts, current, voltage from power.meters", query_callback, byref(counter)) + + while not counter.done: + print(counter) + time.sleep(1) + print(counter) + conn.close() + + +if __name__ == "__main__": + test_query(connect()) + +# possible output: +# { count: 0, done: False } +# fetched 8 rows +# 1538548685000 10.300000 219 +# 1538548695000 12.600000 218 +# 1538548696800 12.300000 221 +# 1538548696650 10.300000 218 +# 1538548685500 11.800000 221 +# 1538548696600 13.400000 223 +# 1538548685500 10.800000 223 +# 1538548686500 11.500000 221 +# fetched 0 rows +# fetching completed +# { count: 8, done: True } diff --git a/docs/examples/python/bind_param_example.py b/docs/examples/python/bind_param_example.py new file mode 100644 index 0000000000000000000000000000000000000000..6a67434f876f159cf32069a55e9527ca19034640 --- /dev/null +++ b/docs/examples/python/bind_param_example.py @@ -0,0 +1,60 @@ +import taos +from datetime import datetime + +# note: lines have already been sorted by table name +lines = [('d1001', '2018-10-03 14:38:05.000', 10.30000, 219, 0.31000, 'California.SanFrancisco', 2), + ('d1001', '2018-10-03 14:38:15.000', 12.60000, 218, 0.33000, 'California.SanFrancisco', 2), + ('d1001', '2018-10-03 14:38:16.800', 12.30000, 221, 0.31000, 'California.SanFrancisco', 2), + ('d1002', '2018-10-03 14:38:16.650', 10.30000, 218, 0.25000, 'California.SanFrancisco', 3), + ('d1003', '2018-10-03 14:38:05.500', 11.80000, 221, 0.28000, 'California.LosAngeles', 2), + ('d1003', '2018-10-03 14:38:16.600', 13.40000, 223, 0.29000, 'California.LosAngeles', 2), + ('d1004', '2018-10-03 14:38:05.000', 10.80000, 223, 0.29000, 'California.LosAngeles', 3), + ('d1004', '2018-10-03 14:38:06.500', 11.50000, 221, 0.35000, 'California.LosAngeles', 3)] + + +def get_ts(ts: str): + dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S.%f') + return int(dt.timestamp() * 1000) + + +def create_stable(): + conn = taos.connect() + try: + conn.execute("CREATE DATABASE power") + conn.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + "TAGS (location BINARY(64), groupId INT)") + finally: + conn.close() + + +def bind_row_by_row(stmt: taos.TaosStmt): + tb_name = None + for row in lines: + if tb_name != row[0]: + tb_name = row[0] + tags: taos.TaosBind = taos.new_bind_params(2) # 2 is count of tags + tags[0].binary(row[5]) # location + tags[1].int(row[6]) # groupId + stmt.set_tbname_tags(tb_name, tags) + values: taos.TaosBind = taos.new_bind_params(4) # 4 is count of columns + values[0].timestamp(get_ts(row[1])) + values[1].float(row[2]) + values[2].int(row[3]) + values[3].float(row[4]) + stmt.bind_param(values) + + +def insert_data(): + conn = taos.connect(database="power") + try: + stmt = conn.statement("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)") + bind_row_by_row(stmt) + stmt.execute() + stmt.close() + finally: + conn.close() + + +if __name__ == '__main__': + create_stable() + insert_data() diff --git a/docs/examples/python/conn_native_pandas.py b/docs/examples/python/conn_native_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..56942ef57085766cd128b03cabb7a357587eab16 --- /dev/null +++ b/docs/examples/python/conn_native_pandas.py @@ -0,0 +1,19 @@ +import pandas +from sqlalchemy import create_engine + +engine = create_engine("taos://root:taosdata@localhost:6030/power") +df = pandas.read_sql("SELECT * FROM meters", engine) + +# print index +print(df.index) +# print data type of element in ts column +print(type(df.ts[0])) +print(df.head(3)) + +# output: +# RangeIndex(start=0, stop=8, step=1) +# +# ts current ... location groupid +# 0 2018-10-03 14:38:05.500 11.8 ... california.losangeles 2 +# 1 2018-10-03 14:38:16.600 13.4 ... california.losangeles 2 +# 2 2018-10-03 14:38:05.000 10.8 ... california.losangeles 3 diff --git a/docs/examples/python/conn_rest_pandas.py b/docs/examples/python/conn_rest_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..0164080cd5a05e72dce40b1d111ea423623ff9b2 --- /dev/null +++ b/docs/examples/python/conn_rest_pandas.py @@ -0,0 +1,19 @@ +import pandas +from sqlalchemy import create_engine + +engine = create_engine("taosrest://root:taosdata@localhost:6041") +df: pandas.DataFrame = pandas.read_sql("SELECT * FROM power.meters", engine) + +# print index +print(df.index) +# print data type of element in ts column +print(type(df.ts[0])) +print(df.head(3)) + +# output: +# RangeIndex(start=0, stop=8, step=1) +# +# ts current ... location groupid +# 0 2018-10-03 06:38:05.500000+00:00 11.8 ... california.losangeles 2 +# 1 2018-10-03 06:38:16.600000+00:00 13.4 ... california.losangeles 2 +# 2 2018-10-03 06:38:05+00:00 10.8 ... california.losangeles 3 diff --git a/docs/examples/python/connect_example.py b/docs/examples/python/connect_example.py new file mode 100644 index 0000000000000000000000000000000000000000..719af79fd12c14cc16e4e3e3c4d6362da5a7520d --- /dev/null +++ b/docs/examples/python/connect_example.py @@ -0,0 +1,19 @@ +import taos + + +def test_connection(): + # all parameters are optional. + # if database is specified, + # then it must exist. + conn = taos.connect(host="localhost", + port=6030, + user="root", + password="taosdata", + database="log") + print('client info:', conn.client_info) + print('server info:', conn.server_info) + conn.close() + + +if __name__ == "__main__": + test_connection() diff --git a/docs/examples/python/connect_native_reference.py b/docs/examples/python/connect_native_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..09b0685acef8c68b30153da5a1761d36b1cf9aae --- /dev/null +++ b/docs/examples/python/connect_native_reference.py @@ -0,0 +1,20 @@ +import taos + +conn: taos.TaosConnection = taos.connect(host="localhost", + user="root", + password="taosdata", + database="test", + port=6030, + config="/etc/taos", # for windows the default value is C:\TDengine\cfg + timezone="Asia/Shanghai") # default your host's timezone + +server_version = conn.server_info +print("server_version", server_version) +client_version = conn.client_info +print("client_version", client_version) # 3.0.0.0 + +conn.close() + +# possible output: +# 3.0.0.0 +# 3.0.0.0 diff --git a/docs/examples/python/connect_rest_examples.py b/docs/examples/python/connect_rest_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..900ec1022ec81ac2db761d918d1ec11c9bb26852 --- /dev/null +++ b/docs/examples/python/connect_rest_examples.py @@ -0,0 +1,43 @@ +# ANCHOR: connect +from taosrest import connect, TaosRestConnection, TaosRestCursor + +conn: TaosRestConnection = connect(url="http://localhost:6041", + user="root", + password="taosdata", + timeout=30) + +# ANCHOR_END: connect +# ANCHOR: basic +# create STable +cursor: TaosRestCursor = conn.cursor() +cursor.execute("DROP DATABASE IF EXISTS power") +cursor.execute("CREATE DATABASE power") +cursor.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)") + +# insert data +cursor.execute("""INSERT INTO power.d1001 USING power.meters TAGS(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) + power.d1003 USING power.meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) + power.d1004 USING power.meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)""") +print("inserted row count:", cursor.rowcount) + +# query data +cursor.execute("SELECT * FROM power.meters LIMIT 3") +# get total rows +print("queried row count:", cursor.rowcount) +# get column names from cursor +column_names = [meta[0] for meta in cursor.description] +# get rows +data: list[tuple] = cursor.fetchall() +print(column_names) +for row in data: + print(row) + +# output: +# inserted row count: 8 +# queried row count: 3 +# ['ts', 'current', 'voltage', 'phase', 'location', 'groupid'] +# [datetime.datetime(2018, 10, 3, 14, 38, 5, 500000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 11.8, 221, 0.28, 'california.losangeles', 2] +# [datetime.datetime(2018, 10, 3, 14, 38, 16, 600000, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 13.4, 223, 0.29, 'california.losangeles', 2] +# [datetime.datetime(2018, 10, 3, 14, 38, 5, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 10.8, 223, 0.29, 'california.losangeles', 3] +# ANCHOR_END: basic diff --git a/docs/examples/python/connection_usage_native_reference.py b/docs/examples/python/connection_usage_native_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..4803511e427bf4d906fd3a14ff6faf5a000da96c --- /dev/null +++ b/docs/examples/python/connection_usage_native_reference.py @@ -0,0 +1,45 @@ +import taos + +# ANCHOR: insert +conn = taos.connect() +# Execute a sql, ignore the result set, just get affected rows. It's useful for DDL and DML statement. +conn.execute("DROP DATABASE IF EXISTS test") +conn.execute("CREATE DATABASE test") +# change database. same as execute "USE db" +conn.select_db("test") +conn.execute("CREATE STABLE weather(ts TIMESTAMP, temperature FLOAT) TAGS (location INT)") +affected_row: int = conn.execute("INSERT INTO t1 USING weather TAGS(1) VALUES (now, 23.5) (now+1m, 23.5) (now+2m 24.4)") +print("affected_row", affected_row) +# output: +# affected_row 3 +# ANCHOR_END: insert + +# ANCHOR: query +# Execute a sql and get its result set. It's useful for SELECT statement +result: taos.TaosResult = conn.query("SELECT * from weather") + +# Get fields from result +fields: taos.field.TaosFields = result.fields +for field in fields: + print(field) # {name: ts, type: 9, bytes: 8} + +# output: +# {name: ts, type: 9, bytes: 8} +# {name: temperature, type: 6, bytes: 4} +# {name: location, type: 4, bytes: 4} + +# Get data from result as list of tuple +data = result.fetch_all() +print(data) +# output: +# [(datetime.datetime(2022, 4, 27, 9, 4, 25, 367000), 23.5, 1), (datetime.datetime(2022, 4, 27, 9, 5, 25, 367000), 23.5, 1), (datetime.datetime(2022, 4, 27, 9, 6, 25, 367000), 24.399999618530273, 1)] + +# Or get data from result as a list of dict +# map_data = result.fetch_all_into_dict() +# print(map_data) +# output: +# [{'ts': datetime.datetime(2022, 4, 27, 9, 1, 15, 343000), 'temperature': 23.5, 'location': 1}, {'ts': datetime.datetime(2022, 4, 27, 9, 2, 15, 343000), 'temperature': 23.5, 'location': 1}, {'ts': datetime.datetime(2022, 4, 27, 9, 3, 15, 343000), 'temperature': 24.399999618530273, 'location': 1}] +# ANCHOR_END: query + + +conn.close() diff --git a/docs/examples/python/cursor_usage_native_reference.py b/docs/examples/python/cursor_usage_native_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..a5103810f0199708f94b5c36e1dc080b7998e420 --- /dev/null +++ b/docs/examples/python/cursor_usage_native_reference.py @@ -0,0 +1,32 @@ +import taos + +conn = taos.connect() +cursor = conn.cursor() + +cursor.execute("DROP DATABASE IF EXISTS test") +cursor.execute("CREATE DATABASE test") +cursor.execute("USE test") +cursor.execute("CREATE STABLE weather(ts TIMESTAMP, temperature FLOAT) TAGS (location INT)") + +for i in range(1000): + location = str(i % 10) + tb = "t" + location + cursor.execute(f"INSERT INTO {tb} USING weather TAGS({location}) VALUES (now+{i}a, 23.5) (now+{i + 1}a, 23.5)") + +cursor.execute("SELECT count(*) FROM weather") +data = cursor.fetchall() +print("count:", data[0][0]) +cursor.execute("SELECT tbname, * FROM weather LIMIT 2") +col_names = [meta[0] for meta in cursor.description] +print(col_names) +rows = cursor.fetchall() +print(rows) + +cursor.close() +conn.close() + +# output: +# count: 2000 +# ['tbname', 'ts', 'temperature', 'location'] +# row_count: -1 +# [('t0', datetime.datetime(2022, 4, 27, 14, 54, 24, 392000), 23.5, 0), ('t0', datetime.datetime(2022, 4, 27, 14, 54, 24, 393000), 23.5, 0)] diff --git a/docs/examples/python/handle_exception.py b/docs/examples/python/handle_exception.py new file mode 100644 index 0000000000000000000000000000000000000000..59554465c0891c80f0507656fcc79538c3811fa7 --- /dev/null +++ b/docs/examples/python/handle_exception.py @@ -0,0 +1,19 @@ +import taos + +try: + conn = taos.connect() + conn.execute("CREATE TABLE 123") # wrong sql +except taos.Error as e: + print(e) + print("exception class: ", e.__class__.__name__) + print("error number:", e.errno) + print("error message:", e.msg) +except BaseException as other: + print("exception occur") + print(other) + +# output: +# [0x0216]: syntax error near 'Incomplete SQL statement' +# exception class: ProgrammingError +# error number: -2147483114 +# error message: syntax error near 'Incomplete SQL statement' diff --git a/docs/examples/python/json_protocol_example.py b/docs/examples/python/json_protocol_example.py new file mode 100644 index 0000000000000000000000000000000000000000..58b38f3ff667bcbbd902434d3409441a4d2c5b45 --- /dev/null +++ b/docs/examples/python/json_protocol_example.py @@ -0,0 +1,38 @@ +import json + +import taos +from taos import SmlProtocol, SmlPrecision + +lines = [{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "California.SanFrancisco", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219, + "tags": {"location": "California.LosAngeles", "groupid": 1}}, + {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6, + "tags": {"location": "California.SanFrancisco", "groupid": 2}}, + {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "California.LosAngeles", "groupid": 1}}] + + +def get_connection(): + return taos.connect() + + +def create_database(conn): + conn.execute("CREATE DATABASE test") + conn.execute("USE test") + + +def insert_lines(conn): + global lines + lines = json.dumps(lines) + # note: the first parameter must be a list with only one element. + affected_rows = conn.schemaless_insert( + [lines], SmlProtocol.JSON_PROTOCOL, SmlPrecision.NOT_CONFIGURED) + print(affected_rows) # 4 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs/examples/python/line_protocol_example.py b/docs/examples/python/line_protocol_example.py new file mode 100644 index 0000000000000000000000000000000000000000..735e8e7eb8aed1a8133de7a6de50bd50d076c472 --- /dev/null +++ b/docs/examples/python/line_protocol_example.py @@ -0,0 +1,34 @@ +import taos +from taos import SmlProtocol, SmlPrecision + +lines = ["meters,location=California.LosAngeles,groupid=2 current=11.8,voltage=221,phase=0.28 1648432611249000", + "meters,location=California.LosAngeles,groupid=2 current=13.4,voltage=223,phase=0.29 1648432611249500", + "meters,location=California.LosAngeles,groupid=3 current=10.8,voltage=223,phase=0.29 1648432611249300", + "meters,location=California.LosAngeles,groupid=3 current=11.3,voltage=221,phase=0.35 1648432611249800", + ] + + +def get_connection(): + # create connection use firstEP in taos.cfg. + return taos.connect() + + +def create_database(conn): + # the default precision is ms (microsecond), but we use us(microsecond) here. + conn.execute("CREATE DATABASE test precision 'us'") + conn.execute("USE test") + + +def insert_lines(conn): + affected_rows = conn.schemaless_insert( + lines, SmlProtocol.LINE_PROTOCOL, SmlPrecision.MICRO_SECONDS) + print(affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs/examples/python/multi_bind_example.py b/docs/examples/python/multi_bind_example.py new file mode 100644 index 0000000000000000000000000000000000000000..205ba69fb267ae1781415e4f0995b41f908ceb17 --- /dev/null +++ b/docs/examples/python/multi_bind_example.py @@ -0,0 +1,88 @@ +import taos +from datetime import datetime + +# ANCHOR: bind_batch +table_tags = { + "d1001": ('California.SanFrancisco', 2), + "d1002": ('California.SanFrancisco', 3), + "d1003": ('California.LosAngeles', 2), + "d1004": ('California.LosAngeles', 3) +} + +table_values = { + "d1001": [ + ['2018-10-03 14:38:05.000', '2018-10-03 14:38:15.000', '2018-10-03 14:38:16.800'], + [10.3, 12.6, 12.3], + [219, 218, 221], + [0.31, 0.33, 0.32] + ], + "d1002": [ + ['2018-10-03 14:38:16.650'], [10.3], [218], [0.25] + ], + "d1003": [ + ['2018-10-03 14:38:05.500', '2018-10-03 14:38:16.600'], + [11.8, 13.4], + [221, 223], + [0.28, 0.29] + ], + "d1004": [ + ['2018-10-03 14:38:05.500', '2018-10-03 14:38:06.500'], + [10.8, 11.5], + [223, 221], + [0.29, 0.35] + ] +} + + +def bind_multi_rows(stmt: taos.TaosStmt): + """ + batch bind example + """ + for tb_name in table_values.keys(): + tags = table_tags[tb_name] + tag_params = taos.new_bind_params(2) + tag_params[0].binary(tags[0]) + tag_params[1].int(tags[1]) + stmt.set_tbname_tags(tb_name, tag_params) + + values = table_values[tb_name] + value_params = taos.new_multi_binds(4) + value_params[0].timestamp([get_ts(t) for t in values[0]]) + value_params[1].float(values[1]) + value_params[2].int(values[2]) + value_params[3].float(values[3]) + stmt.bind_param_batch(value_params) + + +def insert_data(): + conn = taos.connect(database="power") + try: + stmt = conn.statement("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)") + bind_multi_rows(stmt) + stmt.execute() + stmt.close() + finally: + conn.close() + + +# ANCHOR_END: bind_batch + + +def create_stable(): + conn = taos.connect() + try: + conn.execute("CREATE DATABASE power") + conn.execute("CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + "TAGS (location BINARY(64), groupId INT)") + finally: + conn.close() + + +def get_ts(ts: str): + dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S.%f') + return int(dt.timestamp() * 1000) + + +if __name__ == '__main__': + create_stable() + insert_data() diff --git a/docs/examples/python/native_insert_example.py b/docs/examples/python/native_insert_example.py new file mode 100644 index 0000000000000000000000000000000000000000..94fd00a6e9d1dcd2119693c4b5c862d36c219a3d --- /dev/null +++ b/docs/examples/python/native_insert_example.py @@ -0,0 +1,60 @@ +import taos + +lines = ["d1001,2018-10-03 14:38:05.000,10.30000,219,0.31000,'California.SanFrancisco',2", + "d1004,2018-10-03 14:38:05.000,10.80000,223,0.29000,'California.LosAngeles',3", + "d1003,2018-10-03 14:38:05.500,11.80000,221,0.28000,'California.LosAngeles',2", + "d1004,2018-10-03 14:38:06.500,11.50000,221,0.35000,'California.LosAngeles',3", + "d1002,2018-10-03 14:38:16.650,10.30000,218,0.25000,'California.SanFrancisco',3", + "d1001,2018-10-03 14:38:15.000,12.60000,218,0.33000,'California.SanFrancisco',2", + "d1001,2018-10-03 14:38:16.800,12.30000,221,0.31000,'California.SanFrancisco',2", + "d1003,2018-10-03 14:38:16.600,13.40000,223,0.29000,'California.LosAngeles',2"] + + +def get_connection() -> taos.TaosConnection: + """ + create connection use firstEp in taos.cfg and use default user and password. + """ + return taos.connect() + + +def create_stable(conn: taos.TaosConnection): + conn.execute("CREATE DATABASE power") + conn.execute("USE power") + conn.execute("CREATE STABLE meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) " + "TAGS (location BINARY(64), groupId INT)") + + +# The generated SQL is: +# INSERT INTO d1001 USING meters TAGS(California.SanFrancisco, 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) +# d1002 USING meters TAGS(California.SanFrancisco, 3) VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) +# d1003 USING meters TAGS(California.LosAngeles, 2) VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) +# d1004 USING meters TAGS(California.LosAngeles, 3) VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000) + +def get_sql(): + global lines + lines = map(lambda line: line.split(','), lines) # [['d1001', ...]...] + lines = sorted(lines, key=lambda ls: ls[0]) # sort by table name + sql = "INSERT INTO " + tb_name = None + for ps in lines: + tmp_tb_name = ps[0] + if tb_name != tmp_tb_name: + tb_name = tmp_tb_name + sql += f"{tb_name} USING meters TAGS({ps[5]}, {ps[6]}) VALUES " + sql += f"('{ps[1]}', {ps[2]}, {ps[3]}, {ps[4]}) " + return sql + + +def insert_data(conn: taos.TaosConnection): + sql = get_sql() + affected_rows = conn.execute(sql) + print("affected_rows", affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_stable(connection) + insert_data(connection) + finally: + connection.close() diff --git a/docs/examples/python/query_example.py b/docs/examples/python/query_example.py new file mode 100644 index 0000000000000000000000000000000000000000..8afd7f07358d7e9c9a3677ee04f8eb92aae6856b --- /dev/null +++ b/docs/examples/python/query_example.py @@ -0,0 +1,42 @@ +import taos + + +# ANCHOR: iter +def query_api_demo(conn: taos.TaosConnection): + result: taos.TaosResult = conn.query("SELECT tbname, * FROM meters LIMIT 2") + print("field count:", result.field_count) + print("meta of fields[1]:", result.fields[1]) + print("======================Iterate on result=========================") + for row in result: + print(row) + + +# field count: 7 +# meta of fields[1]: {name: ts, type: 9, bytes: 8} +# ======================Iterate on result========================= +# ('d1003', datetime.datetime(2018, 10, 3, 14, 38, 5, 500000), 11.800000190734863, 221, 0.2800000011920929, 'california.losangeles', 2) +# ('d1003', datetime.datetime(2018, 10, 3, 14, 38, 16, 600000), 13.399999618530273, 223, 0.28999999165534973, 'california.losangeles', 2) +# ANCHOR_END: iter + +# ANCHOR: fetch_all +def fetch_all_demo(conn: taos.TaosConnection): + result: taos.TaosResult = conn.query("SELECT ts, current FROM meters LIMIT 2") + rows = result.fetch_all_into_dict() + print("row count:", result.row_count) + print("===============all data===================") + print(rows) + + +# row count: 2 +# ===============all data=================== +# [{'ts': datetime.datetime(2018, 10, 3, 14, 38, 5, 500000), 'current': 11.800000190734863}, +# {'ts': datetime.datetime(2018, 10, 3, 14, 38, 16, 600000), 'current': 13.399999618530273}] +# ANCHOR_END: fetch_all + +if __name__ == '__main__': + connection = taos.connect(database="power") + try: + query_api_demo(connection) + fetch_all_demo(connection) + finally: + connection.close() diff --git a/docs/examples/python/rest_client_example.py b/docs/examples/python/rest_client_example.py new file mode 100644 index 0000000000000000000000000000000000000000..59c629df95fdc7dcee8d764d061afeb360b51dfc --- /dev/null +++ b/docs/examples/python/rest_client_example.py @@ -0,0 +1,9 @@ +from taosrest import RestClient + +client = RestClient("http://localhost:6041", user="root", password="taosdata") +res: dict = client.sql("SELECT ts, current FROM power.meters LIMIT 1") +print(res) + +# output: +# {'status': 'succ', 'head': ['ts', 'current'], 'column_meta': [['ts', 9, 8], ['current', 6, 4]], 'data': [[datetime.datetime(2018, 10, 3, 14, 38, 5, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), '+08:00')), 10.3]], 'rows': 1} + diff --git a/docs/examples/python/result_set_examples.py b/docs/examples/python/result_set_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..6cba0d3f73cdaa408309de93652ed8f346c8f759 --- /dev/null +++ b/docs/examples/python/result_set_examples.py @@ -0,0 +1,33 @@ +import taos + +conn = taos.connect() +conn.execute("DROP DATABASE IF EXISTS test") +conn.execute("CREATE DATABASE test") +conn.select_db("test") +conn.execute("CREATE STABLE weather(ts TIMESTAMP, temperature FLOAT) TAGS (location INT)") +# prepare data +for i in range(2000): + location = str(i % 10) + tb = "t" + location + conn.execute(f"INSERT INTO {tb} USING weather TAGS({location}) VALUES (now+{i}a, 23.5) (now+{i + 1}a, 23.5)") + +result: taos.TaosResult = conn.query("SELECT * FROM weather") + +block_index = 0 +blocks: taos.TaosBlocks = result.blocks_iter() +for rows, length in blocks: + print("block ", block_index, " length", length) + print("first row in this block:", rows[0]) + block_index += 1 + +conn.close() + +# possible output: +# block 0 length 1200 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 46000), 23.5, 0) +# block 1 length 1200 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 76000), 23.5, 3) +# block 2 length 1200 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 99000), 23.5, 6) +# block 3 length 400 +# first row in this block: (datetime.datetime(2022, 4, 27, 15, 14, 52, 122000), 23.5, 9) diff --git a/docs/examples/python/telnet_line_protocol_example.py b/docs/examples/python/telnet_line_protocol_example.py new file mode 100644 index 0000000000000000000000000000000000000000..d812e186af86be6811ee7774f10458e46df1f39f --- /dev/null +++ b/docs/examples/python/telnet_line_protocol_example.py @@ -0,0 +1,38 @@ +import taos +from taos import SmlProtocol, SmlPrecision + +# format: =[ =] +lines = ["meters.current 1648432611249 10.3 location=California.SanFrancisco groupid=2", + "meters.current 1648432611250 12.6 location=California.SanFrancisco groupid=2", + "meters.current 1648432611249 10.8 location=California.LosAngeles groupid=3", + "meters.current 1648432611250 11.3 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611249 219 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611250 218 location=California.SanFrancisco groupid=2", + "meters.voltage 1648432611249 221 location=California.LosAngeles groupid=3", + "meters.voltage 1648432611250 217 location=California.LosAngeles groupid=3", + ] + + +# create connection use firstEp in taos.cfg. +def get_connection(): + return taos.connect() + + +def create_database(conn): + conn.execute("CREATE DATABASE test") + conn.execute("USE test") + + +def insert_lines(conn): + affected_rows = conn.schemaless_insert( + lines, SmlProtocol.TELNET_PROTOCOL, SmlPrecision.NOT_CONFIGURED) + print(affected_rows) # 8 + + +if __name__ == '__main__': + connection = get_connection() + try: + create_database(connection) + insert_lines(connection) + finally: + connection.close() diff --git a/docs/examples/python/tmq_example.py b/docs/examples/python/tmq_example.py new file mode 100644 index 0000000000000000000000000000000000000000..cee036454ec4d3f4809576a1eee8ac054fcba056 --- /dev/null +++ b/docs/examples/python/tmq_example.py @@ -0,0 +1,6 @@ +import taos +from taos.tmq import TaosConsumer +consumer = TaosConsumer('topic_ctb_column', group_id='vg2') +for msg in consumer: + for row in msg: + print(row) diff --git a/docs/examples/rust/nativeexample/Cargo.toml b/docs/examples/rust/nativeexample/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..cdf739d35774df37781ad6ea75bfb8214b21e6ea --- /dev/null +++ b/docs/examples/rust/nativeexample/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "nativeexample" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[dependencies] +anyhow = "1" +chrono = "0.4" +serde = { version = "1", features = ["derive"] } +tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] } + +taos = { version = "0.*" } diff --git a/docs/examples/rust/nativeexample/examples/connect.rs b/docs/examples/rust/nativeexample/examples/connect.rs new file mode 100644 index 0000000000000000000000000000000000000000..fb226d8710bb72abf3993663031fd9ea1a08b25b --- /dev/null +++ b/docs/examples/rust/nativeexample/examples/connect.rs @@ -0,0 +1,9 @@ +use taos::*; + +#[tokio::main] +async fn main() -> Result<(), Error> { + #[allow(unused_variables)] + let taos = TaosBuilder::from_dsn("taos://")?.build()?; + println!("Connected"); + Ok(()) +} diff --git a/docs/examples/rust/nativeexample/examples/stmt_example.rs b/docs/examples/rust/nativeexample/examples/stmt_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..26084746f20a3662383b417eb98016f09ad0913e --- /dev/null +++ b/docs/examples/rust/nativeexample/examples/stmt_example.rs @@ -0,0 +1,40 @@ +use taos::*; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let taos = TaosBuilder::from_dsn("taos://")?.build()?; + taos.create_database("power").await?; + taos.use_database("power").await?; + taos.exec("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)").await?; + + let mut stmt = Stmt::init(&taos)?; + stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)")?; + // bind table name and tags + stmt.set_tbname_tags( + "d1001", + &[Value::VarChar("San Fransico".into()), Value::Int(2)], + )?; + // bind values. + let values = vec![ + ColumnView::from_millis_timestamp(vec![1648432611249]), + ColumnView::from_floats(vec![10.3]), + ColumnView::from_ints(vec![219]), + ColumnView::from_floats(vec![0.31]), + ]; + stmt.bind(&values)?; + // bind one more row + let values2 = vec![ + ColumnView::from_millis_timestamp(vec![1648432611749]), + ColumnView::from_floats(vec![12.6]), + ColumnView::from_ints(vec![218]), + ColumnView::from_floats(vec![0.33]), + ]; + stmt.bind(&values2)?; + + stmt.add_batch()?; + + // execute. + let rows = stmt.execute()?; + assert_eq!(rows, 2); + Ok(()) +} diff --git a/docs/examples/rust/nativeexample/examples/subscribe_demo.rs b/docs/examples/rust/nativeexample/examples/subscribe_demo.rs new file mode 100644 index 0000000000000000000000000000000000000000..7e0a347948fc8450dead0babbbdd1eace2f06d1e --- /dev/null +++ b/docs/examples/rust/nativeexample/examples/subscribe_demo.rs @@ -0,0 +1,101 @@ +use std::time::Duration; + +use chrono::{DateTime, Local}; +use taos::*; + +// Query options 2, use deserialization with serde. +#[derive(Debug, serde::Deserialize)] +#[allow(dead_code)] +struct Record { + // deserialize timestamp to chrono::DateTime + ts: DateTime, + // float to f32 + current: Option, + // int to i32 + voltage: Option, + phase: Option, +} + +async fn prepare(taos: Taos) -> anyhow::Result<()> { + let inserted = taos.exec_many([ + // create child table + "CREATE TABLE `d0` USING `meters` TAGS(0, 'Los Angles')", + // insert into child table + "INSERT INTO `d0` values(now - 10s, 10, 116, 0.32)", + // insert with NULL values + "INSERT INTO `d0` values(now - 8s, NULL, NULL, NULL)", + // insert and automatically create table with tags if not exists + "INSERT INTO `d1` USING `meters` TAGS(1, 'San Francisco') values(now - 9s, 10.1, 119, 0.33)", + // insert many records in a single sql + "INSERT INTO `d1` values (now-8s, 10, 120, 0.33) (now - 6s, 10, 119, 0.34) (now - 4s, 11.2, 118, 0.322)", + ]).await?; + assert_eq!(inserted, 6); + Ok(()) +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let dsn = "taos://localhost:6030"; + let builder = TaosBuilder::from_dsn(dsn)?; + + let taos = builder.build()?; + let db = "tmq"; + + // prepare database + taos.exec_many([ + format!("DROP TOPIC IF EXISTS tmq_meters"), + format!("DROP DATABASE IF EXISTS `{db}`"), + format!("CREATE DATABASE `{db}`"), + format!("USE `{db}`"), + // create super table + format!("CREATE TABLE `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"), + // create topic for subscription + format!("CREATE TOPIC tmq_meters with META AS DATABASE {db}") + ]) + .await?; + + let task = tokio::spawn(prepare(taos)); + + tokio::time::sleep(Duration::from_secs(1)).await; + + // subscribe + let tmq = TmqBuilder::from_dsn("taos://localhost:6030/?group.id=test")?; + + let mut consumer = tmq.build()?; + consumer.subscribe(["tmq_meters"]).await?; + + { + let mut stream = consumer.stream(); + + while let Some((offset, message)) = stream.try_next().await? { + // get information from offset + + // the topic + let topic = offset.topic(); + // the vgroup id, like partition id in kafka. + let vgroup_id = offset.vgroup_id(); + println!("* in vgroup id {vgroup_id} of topic {topic}\n"); + + if let Some(data) = message.into_data() { + while let Some(block) = data.fetch_raw_block().await? { + // one block for one table, get table name if needed + let name = block.table_name(); + let records: Vec = block.deserialize().try_collect()?; + println!( + "** table: {}, got {} records: {:#?}\n", + name.unwrap(), + records.len(), + records + ); + } + } + consumer.commit(offset).await?; + } + } + + consumer.unsubscribe().await; + + task.await??; + + Ok(()) +} diff --git a/docs/examples/rust/nativeexample/src/main.rs b/docs/examples/rust/nativeexample/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..e7a11a969c037e00a796aafeff6258501ec15e9a --- /dev/null +++ b/docs/examples/rust/nativeexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/docs/examples/rust/restexample/Cargo.toml b/docs/examples/rust/restexample/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..5fffe215d439a84c9b0da86f6b0f5607abd20bcd --- /dev/null +++ b/docs/examples/rust/restexample/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "restexample" +version = "0.1.0" +edition = "2021" + +[dependencies] +anyhow = "1" +chrono = "0.4" +serde = { version = "1", features = ["derive"] } +tokio = { version = "1", features = ["rt", "macros", "rt-multi-thread"] } + +taos = { version = "0.*" } diff --git a/docs/examples/rust/restexample/examples/connect.rs b/docs/examples/rust/restexample/examples/connect.rs new file mode 100644 index 0000000000000000000000000000000000000000..fb226d8710bb72abf3993663031fd9ea1a08b25b --- /dev/null +++ b/docs/examples/rust/restexample/examples/connect.rs @@ -0,0 +1,9 @@ +use taos::*; + +#[tokio::main] +async fn main() -> Result<(), Error> { + #[allow(unused_variables)] + let taos = TaosBuilder::from_dsn("taos://")?.build()?; + println!("Connected"); + Ok(()) +} diff --git a/docs/examples/rust/restexample/examples/insert_example.rs b/docs/examples/rust/restexample/examples/insert_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..27b2bb4788615810d097b88f0dd616b96885538c --- /dev/null +++ b/docs/examples/rust/restexample/examples/insert_example.rs @@ -0,0 +1,29 @@ +use taos::*; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let dsn = "ws://"; + let taos = TaosBuilder::from_dsn(dsn)?.build()?; + + + taos.exec_many([ + "DROP DATABASE IF EXISTS power", + "CREATE DATABASE power", + "USE power", + "CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)" + ]).await?; + + let inserted = taos.exec("INSERT INTO + power.d1001 USING power.meters TAGS('San Francisco', 2) + VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) + ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) + power.d1002 USING power.meters TAGS('San Francisco', 3) + VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) + power.d1003 USING power.meters TAGS('Los Angeles', 2) + VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) + power.d1004 USING power.meters TAGS('Los Angeles', 3) + VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)").await?; + + assert_eq!(inserted, 8); + Ok(()) +} diff --git a/docs/examples/rust/restexample/examples/query_example.rs b/docs/examples/rust/restexample/examples/query_example.rs new file mode 100644 index 0000000000000000000000000000000000000000..1a11401bba869169203851c083b69ffaea68e200 --- /dev/null +++ b/docs/examples/rust/restexample/examples/query_example.rs @@ -0,0 +1,25 @@ +use taos::sync::*; + +fn main() -> anyhow::Result<()> { + let taos = TaosBuilder::from_dsn("ws:///power")?.build()?; + let mut result = taos.query("SELECT ts, current FROM meters LIMIT 2")?; + // print column names + let meta = result.fields(); + println!("{}", meta.iter().map(|field| field.name()).join("\t")); + + // print rows + let rows = result.rows(); + for row in rows { + let row = row?; + for (_name, value) in row { + print!("{}\t", value); + } + println!(); + } + Ok(()) +} + +// output(suppose you are in +8 timezone): +// ts current +// 2018-10-03T14:38:05+08:00 10.3 +// 2018-10-03T14:38:15+08:00 12.6 diff --git a/docs/examples/rust/restexample/src/main.rs b/docs/examples/rust/restexample/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..e7a11a969c037e00a796aafeff6258501ec15e9a --- /dev/null +++ b/docs/examples/rust/restexample/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +}