Merge pull request #27172 from taosdata/docs/sheyj-3.0
update conncetor log, keep same style
This commit is contained in:
commit
2c0a538f5c
|
@ -8,19 +8,15 @@ 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
|
||||
const char *db = NULL; // if don't want to connect to a default db, set it to NULL or ""
|
||||
uint16_t port = 6030; // 0 means use the default port
|
||||
TAOS *taos = taos_connect(host, user, passwd, db, port);
|
||||
if (taos == NULL) {
|
||||
int errno = taos_errno(NULL);
|
||||
const char *msg = taos_errstr(NULL);
|
||||
printf("%d, %s\n", errno, msg);
|
||||
printf("failed to connect to server %s, errno: %d, msg: %s\n", host, errno, msg);
|
||||
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
printf("success to connect server %s\n", host);
|
||||
printf("Connected to %s:%hu successfully.\n", host, port);
|
||||
|
||||
/* put your code here for read and write */
|
||||
|
||||
|
|
|
@ -22,58 +22,57 @@
|
|||
#include <string.h>
|
||||
#include "taos.h"
|
||||
|
||||
|
||||
static int DemoCreateDB() {
|
||||
// ANCHOR: create_db_and_table
|
||||
const char *ip = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
// ANCHOR: create_db_and_table
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
|
||||
// connect
|
||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
printf("success to connect server %s\n", ip);
|
||||
// connect
|
||||
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||
if (taos == NULL) {
|
||||
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL),
|
||||
taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
|
||||
// create database
|
||||
TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power");
|
||||
int code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("failed to create database power, reason: %s\n", taos_errstr(result));
|
||||
// create database
|
||||
TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power");
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("Failed to create database power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, code,
|
||||
taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(result);
|
||||
printf("Create database power successfully.\n");
|
||||
|
||||
// create table
|
||||
const char *sql =
|
||||
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId "
|
||||
"INT, location BINARY(24))";
|
||||
result = taos_query(taos, sql);
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("Failed to create stable power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code,
|
||||
taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(result);
|
||||
printf("Create stable power.meters successfully.\n");
|
||||
|
||||
// close & clean
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(result);
|
||||
printf("success to create database power\n");
|
||||
|
||||
// use database
|
||||
result = taos_query(taos, "USE power");
|
||||
taos_free_result(result);
|
||||
|
||||
// create table
|
||||
const char* sql = "CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))";
|
||||
result = taos_query(taos, sql);
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("failed to create stable meters, reason: %s\n", taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(result);
|
||||
printf("success to create table meters\n");
|
||||
|
||||
// close & clean
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return 0;
|
||||
// ANCHOR_END: create_db_and_table
|
||||
return 0;
|
||||
// ANCHOR_END: create_db_and_table
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
return DemoCreateDB();
|
||||
}
|
||||
int main(int argc, char *argv[]) { return DemoCreateDB(); }
|
||||
|
|
|
@ -24,22 +24,19 @@
|
|||
|
||||
static int DemoInsertData() {
|
||||
// ANCHOR: insert_data
|
||||
const char *ip = "localhost";
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
|
||||
// connect
|
||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
||||
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
||||
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
printf("success to connect server %s\n", ip);
|
||||
|
||||
// use database
|
||||
TAOS_RES *result = taos_query(taos, "USE power");
|
||||
taos_free_result(result);
|
||||
|
||||
// insert data, please make sure the database and table are already created
|
||||
const char* sql = "INSERT INTO " \
|
||||
|
@ -51,10 +48,10 @@ const char* sql = "INSERT INTO "
|
|||
"power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco') " \
|
||||
"VALUES " \
|
||||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||
result = taos_query(taos, sql);
|
||||
int code = taos_errno(result);
|
||||
TAOS_RES *result = taos_query(taos, sql);
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("failed to insert data to power.meters, ip: %s, reason: %s\n", ip, taos_errstr(result));
|
||||
printf("Failed to insert data to power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
|
@ -63,7 +60,7 @@ taos_free_result(result);
|
|||
|
||||
// you can check affectedRows here
|
||||
int rows = taos_affected_rows(result);
|
||||
printf("success to insert %d rows data to power.meters\n", rows);
|
||||
printf("Successfully inserted %d rows into power.meters.\n", rows);
|
||||
|
||||
// close & clean
|
||||
taos_close(taos);
|
||||
|
|
|
@ -25,29 +25,28 @@
|
|||
|
||||
static int DemoQueryData() {
|
||||
// ANCHOR: query_data
|
||||
const char *ip = "localhost";
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
|
||||
// connect
|
||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
||||
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
||||
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
printf("success to connect server %s\n", ip);
|
||||
|
||||
// use database
|
||||
TAOS_RES *result = taos_query(taos, "USE power");
|
||||
taos_free_result(result);
|
||||
|
||||
|
||||
// query data, please make sure the database and table are already created
|
||||
const char* sql = "SELECT ts, current, location FROM power.meters limit 100";
|
||||
result = taos_query(taos, sql);
|
||||
int code = taos_errno(result);
|
||||
TAOS_RES *result = taos_query(taos, sql);
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("failed to query data from power.meters, ip: %s, reason: %s\n", ip, taos_errstr(result));
|
||||
printf("Failed to query data from power.meters, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
|
@ -70,7 +69,6 @@ while ((row = taos_fetch_row(result))) {
|
|||
}
|
||||
printf("total rows: %d\n", rows);
|
||||
taos_free_result(result);
|
||||
printf("success to query data from power.meters\n");
|
||||
|
||||
// close & clean
|
||||
taos_close(taos);
|
||||
|
|
|
@ -24,33 +24,41 @@
|
|||
|
||||
static int DemoSmlInsert() {
|
||||
// ANCHOR: schemaless
|
||||
const char *ip = "localhost";
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
|
||||
// connect
|
||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
||||
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
||||
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
printf("success to connect server %s\n", ip);
|
||||
|
||||
// create database
|
||||
TAOS_RES *result = taos_query(taos, "CREATE DATABASE IF NOT EXISTS power");
|
||||
int code = taos_errno(result);
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("failed to create database power, reason: %s\n", taos_errstr(result));
|
||||
printf("Failed to create database power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(result);
|
||||
printf("success to create database power\n");
|
||||
printf("Create database power successfully.\n");
|
||||
|
||||
// use database
|
||||
result = taos_query(taos, "USE power");
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("Failed to execute use power, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(result);
|
||||
|
||||
// schemaless demo data
|
||||
|
@ -61,29 +69,31 @@ char * json_demo = "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"val
|
|||
// influxdb line protocol
|
||||
char *lines[] = {line_demo};
|
||||
result = taos_schemaless_insert(taos, lines, 1, TSDB_SML_LINE_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
||||
if (taos_errno(result) != 0) {
|
||||
printf("failed to insert schemaless line data, reason: %s\n", taos_errstr(result));
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("Failed to insert schemaless line data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
|
||||
int rows = taos_affected_rows(result);
|
||||
printf("success to insert %d rows of schemaless line data\n", rows);
|
||||
printf("Insert %d rows of schemaless line data successfully.\n", rows);
|
||||
taos_free_result(result);
|
||||
|
||||
// opentsdb telnet protocol
|
||||
char *telnets[] = {telnet_demo};
|
||||
result = taos_schemaless_insert(taos, telnets, 1, TSDB_SML_TELNET_PROTOCOL, TSDB_SML_TIMESTAMP_MILLI_SECONDS);
|
||||
if (taos_errno(result) != 0) {
|
||||
printf("failed to insert schemaless telnet data, reason: %s\n", taos_errstr(result));
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("Failed to insert schemaless telnet data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
|
||||
rows = taos_affected_rows(result);
|
||||
printf("success to insert %d rows of schemaless telnet data\n", rows);
|
||||
printf("Insert %d rows of schemaless telnet data successfully.\n", rows);
|
||||
taos_free_result(result);
|
||||
|
||||
// opentsdb json protocol
|
||||
|
@ -91,16 +101,17 @@ char *jsons[1] = {0};
|
|||
// allocate memory for json data. can not use static memory.
|
||||
jsons[0] = malloc(1024);
|
||||
if (jsons[0] == NULL) {
|
||||
printf("failed to allocate memory\n");
|
||||
printf("Failed to allocate memory\n");
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
(void)strncpy(jsons[0], json_demo, 1023);
|
||||
result = taos_schemaless_insert(taos, jsons, 1, TSDB_SML_JSON_PROTOCOL, TSDB_SML_TIMESTAMP_NOT_CONFIGURED);
|
||||
if (taos_errno(result) != 0) {
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
free(jsons[0]);
|
||||
printf("failed to insert schemaless json data, reason: %s\n", taos_errstr(result));
|
||||
printf("Failed to insert schemaless json data, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
|
@ -108,7 +119,7 @@ if (taos_errno(result) != 0) {
|
|||
free(jsons[0]);
|
||||
|
||||
rows = taos_affected_rows(result);
|
||||
printf("success to insert %d rows of schemaless json data\n", rows);
|
||||
printf("Insert %d rows of schemaless json data successfully.\n", rows);
|
||||
taos_free_result(result);
|
||||
|
||||
// close & clean
|
||||
|
|
|
@ -64,6 +64,7 @@ typedef struct {
|
|||
|
||||
int num_of_sub_table = 10;
|
||||
int num_of_row = 10;
|
||||
int total_affected = 0;
|
||||
/**
|
||||
* @brief insert data using stmt API
|
||||
*
|
||||
|
@ -72,10 +73,14 @@ int num_of_row = 10;
|
|||
void insertData(TAOS *taos) {
|
||||
// init
|
||||
TAOS_STMT *stmt = taos_stmt_init(taos);
|
||||
if (stmt == NULL) {
|
||||
printf("Failed to init taos_stmt, error: %s\n", taos_stmt_errstr(NULL));
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
// 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");
|
||||
checkErrorCode(stmt, code, "Failed to execute taos_stmt_prepare");
|
||||
for (int i = 1; i <= num_of_sub_table; i++) {
|
||||
char table_name[20];
|
||||
sprintf(table_name, "d_bind_%d", i);
|
||||
|
@ -99,7 +104,7 @@ void insertData(TAOS *taos) {
|
|||
tags[1].is_null = NULL;
|
||||
tags[1].num = 1;
|
||||
code = taos_stmt_set_tbname_tags(stmt, table_name, tags);
|
||||
checkErrorCode(stmt, code, "failed to set table name and tags\n");
|
||||
checkErrorCode(stmt, code, "Failed to set table name and tags\n");
|
||||
|
||||
// insert rows
|
||||
TAOS_MULTI_BIND params[4];
|
||||
|
@ -142,25 +147,31 @@ void insertData(TAOS *taos) {
|
|||
params[3].buffer = &phase;
|
||||
// bind param
|
||||
code = taos_stmt_bind_param(stmt, params);
|
||||
checkErrorCode(stmt, code, "failed to bind param");
|
||||
checkErrorCode(stmt, code, "Failed to bind param");
|
||||
}
|
||||
// add batch
|
||||
code = taos_stmt_add_batch(stmt);
|
||||
checkErrorCode(stmt, code, "failed to add batch");
|
||||
checkErrorCode(stmt, code, "Failed to add batch");
|
||||
// execute batch
|
||||
code = taos_stmt_execute(stmt);
|
||||
checkErrorCode(stmt, code, "failed to exec stmt");
|
||||
checkErrorCode(stmt, code, "Failed to exec stmt");
|
||||
// get affected rows
|
||||
int affected = taos_stmt_affected_rows_once(stmt);
|
||||
printf("table %s insert %d rows.\n", table_name, affected);
|
||||
total_affected += affected;
|
||||
}
|
||||
printf("Successfully inserted %d rows to power.meters.\n", total_affected);
|
||||
taos_stmt_close(stmt);
|
||||
}
|
||||
|
||||
int main() {
|
||||
TAOS *taos = taos_connect("localhost", "root", "taosdata", NULL, 6030);
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server\n");
|
||||
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
// create database and table
|
||||
|
|
|
@ -13,6 +13,8 @@
|
|||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// to compile: gcc -o tmq_demo tmq_demo.c -ltaos -lpthread
|
||||
|
||||
#include <assert.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
|
@ -26,9 +28,28 @@ volatile int thread_stop = 0;
|
|||
static int running = 1;
|
||||
const char* topic_name = "topic_meters";
|
||||
|
||||
typedef struct {
|
||||
const char* enable_auto_commit;
|
||||
const char* auto_commit_interval_ms;
|
||||
const char* group_id;
|
||||
const char* client_id;
|
||||
const char* td_connect_host;
|
||||
const char* td_connect_port;
|
||||
const char* td_connect_user;
|
||||
const char* td_connect_pass;
|
||||
const char* auto_offset_reset;
|
||||
} ConsumerConfig;
|
||||
|
||||
void* prepare_data(void* arg) {
|
||||
TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
TAOS *pConn = taos_connect(host, user, password, NULL, port);
|
||||
if (pConn == NULL) {
|
||||
fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
@ -45,13 +66,14 @@ void* prepare_data(void* arg) {
|
|||
i);
|
||||
|
||||
pRes = taos_query(pConn, buf);
|
||||
if (taos_errno(pRes) != 0) {
|
||||
printf("error in insert data to power.meters, reason:%s\n", taos_errstr(pRes));
|
||||
code = taos_errno(pRes);
|
||||
if (code != 0) {
|
||||
fprintf(stderr, "Failed to insert data to power.meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||
}
|
||||
taos_free_result(pRes);
|
||||
sleep(1);
|
||||
}
|
||||
printf("prepare data thread exit\n");
|
||||
fprintf(stdout, "Prepare data thread exit\n");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
@ -63,9 +85,9 @@ static int32_t msg_process(TAOS_RES* 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);
|
||||
fprintf(stdout, "topic: %s\n", topicName);
|
||||
fprintf(stdout, "db: %s\n", dbName);
|
||||
fprintf(stdout, "vgroup id: %d\n", vgroupId);
|
||||
|
||||
while (1) {
|
||||
// get one row data from message
|
||||
|
@ -81,11 +103,11 @@ static int32_t msg_process(TAOS_RES* msg) {
|
|||
rows++;
|
||||
// print the row content
|
||||
if (taos_print_row(buf, row, fields, numOfFields) < 0) {
|
||||
printf("failed to print row\n");
|
||||
fprintf(stderr, "Failed to print row\n");
|
||||
break;
|
||||
}
|
||||
// print the precision and row content to the console
|
||||
printf("precision: %d, row content: %s\n", precision, buf);
|
||||
fprintf(stdout, "precision: %d, data: %s\n", precision, buf);
|
||||
}
|
||||
|
||||
return rows;
|
||||
|
@ -93,42 +115,53 @@ static int32_t msg_process(TAOS_RES* msg) {
|
|||
// ANCHOR_END: msg_process
|
||||
|
||||
static int32_t init_env() {
|
||||
TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
TAOS *pConn = taos_connect(host, user, password, NULL, port);
|
||||
if (pConn == NULL) {
|
||||
fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
|
||||
TAOS_RES* pRes;
|
||||
// drop database if exists
|
||||
printf("create database\n");
|
||||
pRes = taos_query(pConn, "drop topic if exists topic_meters");
|
||||
if (taos_errno(pRes) != 0) {
|
||||
printf("error in drop topic_meters, reason:%s\n", taos_errstr(pRes));
|
||||
fprintf(stdout, "Create database.\n");
|
||||
pRes = taos_query(pConn, "DROP TOPIC IF EXISTS topic_meters");
|
||||
code = taos_errno(pRes);
|
||||
if (code != 0) {
|
||||
fprintf(stderr, "Failed to drop topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||
}
|
||||
taos_free_result(pRes);
|
||||
|
||||
pRes = taos_query(pConn, "drop database if exists power");
|
||||
if (taos_errno(pRes) != 0) {
|
||||
printf("error in drop power, reason:%s\n", taos_errstr(pRes));
|
||||
pRes = taos_query(pConn, "DROP DATABASE IF EXISTS power");
|
||||
code = taos_errno(pRes);
|
||||
if (code != 0) {
|
||||
fprintf(stderr, "Failed to drop database power, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||
}
|
||||
taos_free_result(pRes);
|
||||
|
||||
// create database
|
||||
pRes = taos_query(pConn, "create database power precision 'ms' WAL_RETENTION_PERIOD 3600");
|
||||
if (taos_errno(pRes) != 0) {
|
||||
printf("error in create tmqdb, reason:%s\n", taos_errstr(pRes));
|
||||
pRes = taos_query(pConn, "CREATE DATABASE power PRECISION 'ms' WAL_RETENTION_PERIOD 3600");
|
||||
code = taos_errno(pRes);
|
||||
if (code != 0) {
|
||||
fprintf(stderr, "Failed to create tmqdb, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||
goto END;
|
||||
}
|
||||
taos_free_result(pRes);
|
||||
|
||||
// create super table
|
||||
printf("create super table\n");
|
||||
fprintf(stdout, "Create super table.\n");
|
||||
pRes = taos_query(
|
||||
pConn,
|
||||
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS "
|
||||
"(groupId INT, location BINARY(24))");
|
||||
if (taos_errno(pRes) != 0) {
|
||||
printf("failed to create super table meters, reason:%s\n", taos_errstr(pRes));
|
||||
code = taos_errno(pRes);
|
||||
if (code != 0) {
|
||||
fprintf(stderr, "Failed to create super table meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||
goto END;
|
||||
}
|
||||
|
||||
|
@ -143,16 +176,24 @@ END:
|
|||
}
|
||||
|
||||
int32_t create_topic() {
|
||||
printf("create topic\n");
|
||||
fprintf(stdout, "Create topic.\n");
|
||||
TAOS_RES* pRes;
|
||||
TAOS* pConn = taos_connect("localhost", "root", "taosdata", NULL, 0);
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
TAOS *pConn = taos_connect(host, user, password, NULL, port);
|
||||
if (pConn == NULL) {
|
||||
fprintf(stderr, "Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
|
||||
pRes = taos_query(pConn, "use power");
|
||||
pRes = taos_query(pConn, "USE POWER");
|
||||
code = taos_errno(pRes);
|
||||
if (taos_errno(pRes) != 0) {
|
||||
printf("error in use tmqdb, reason:%s\n", taos_errstr(pRes));
|
||||
fprintf(stderr, "Failed to use tmqdb, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(pRes);
|
||||
|
@ -160,8 +201,9 @@ int32_t create_topic() {
|
|||
pRes = taos_query(
|
||||
pConn,
|
||||
"CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM meters");
|
||||
if (taos_errno(pRes) != 0) {
|
||||
printf("failed to create topic topic_meters, reason:%s\n", taos_errstr(pRes));
|
||||
code = taos_errno(pRes);
|
||||
if (code != 0) {
|
||||
fprintf(stderr, "Failed to create topic topic_meters, ErrCode: 0x%x, ErrMessage: %s.\n", code, taos_errstr(pRes));
|
||||
return -1;
|
||||
}
|
||||
taos_free_result(pRes);
|
||||
|
@ -171,11 +213,11 @@ int32_t create_topic() {
|
|||
}
|
||||
|
||||
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);
|
||||
fprintf(stdout, "tmq_commit_cb_print() code: %d, tmq: %p, param: %p\n", code, tmq, param);
|
||||
}
|
||||
|
||||
// ANCHOR: create_consumer_1
|
||||
tmq_t* build_consumer() {
|
||||
tmq_t* build_consumer(const ConsumerConfig* config) {
|
||||
tmq_conf_res_t code;
|
||||
tmq_t* tmq = NULL;
|
||||
|
||||
|
@ -183,37 +225,47 @@ tmq_t* build_consumer() {
|
|||
tmq_conf_t* conf = tmq_conf_new();
|
||||
|
||||
// set the configuration parameters
|
||||
code = tmq_conf_set(conf, "enable.auto.commit", "true");
|
||||
code = tmq_conf_set(conf, "enable.auto.commit", config->enable_auto_commit);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "auto.commit.interval.ms", "1000");
|
||||
code = tmq_conf_set(conf, "auto.commit.interval.ms", config->auto_commit_interval_ms);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "group.id", "group1");
|
||||
code = tmq_conf_set(conf, "group.id", config->group_id);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "client.id", "client1");
|
||||
code = tmq_conf_set(conf, "client.id", config->client_id);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "td.connect.user", "root");
|
||||
code = tmq_conf_set(conf, "td.connect.ip", config->td_connect_host);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "td.connect.pass", "taosdata");
|
||||
code = tmq_conf_set(conf, "td.connect.port", config->td_connect_port);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "auto.offset.reset", "latest");
|
||||
code = tmq_conf_set(conf, "td.connect.user", config->td_connect_user);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "td.connect.pass", config->td_connect_pass);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
}
|
||||
code = tmq_conf_set(conf, "auto.offset.reset", config->auto_offset_reset);
|
||||
if (TMQ_CONF_OK != code) {
|
||||
tmq_conf_destroy(conf);
|
||||
return NULL;
|
||||
|
@ -243,6 +295,7 @@ tmq_list_t* build_topic_list() {
|
|||
if (code) {
|
||||
// if failed, destroy the list and return NULL
|
||||
tmq_list_destroy(topicList);
|
||||
fprintf(stderr, "Failed to create topic_list, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||
return NULL;
|
||||
}
|
||||
// if success, return the list
|
||||
|
@ -285,7 +338,7 @@ void consume_repeatly(tmq_t* tmq) {
|
|||
// get the topic assignment
|
||||
int32_t code = tmq_get_topic_assignment(tmq, topic_name, &pAssign, &numOfAssignment);
|
||||
if (code != 0 || pAssign == NULL || numOfAssignment == 0) {
|
||||
fprintf(stderr, "failed to get assignment, reason:%s", tmq_err2str(code));
|
||||
fprintf(stderr, "Failed to get assignment, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -295,7 +348,9 @@ void consume_repeatly(tmq_t* tmq) {
|
|||
|
||||
code = tmq_offset_seek(tmq, topic_name, p->vgId, p->begin);
|
||||
if (code != 0) {
|
||||
fprintf(stderr, "failed to seek to %d, reason:%s", (int)p->begin, tmq_err2str(code));
|
||||
fprintf(stderr, "Failed to seek assignment %d to beginning %ld, ErrCode: 0x%x, ErrMessage: %s.\n", i, p->begin, code, tmq_err2str(code));
|
||||
} else {
|
||||
fprintf(stdout, "Seek assignment %d to beginning %ld successfully.\n", i, p->begin);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -324,10 +379,12 @@ void manual_commit(tmq_t* tmq) {
|
|||
int32_t code = tmq_commit_sync(tmq, tmqmsg);
|
||||
|
||||
if (code) {
|
||||
fprintf(stderr, "Failed to commit message: %s\n", tmq_err2str(code));
|
||||
fprintf(stderr, "Failed to commit message, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||
// free the message
|
||||
taos_free_result(tmqmsg);
|
||||
break;
|
||||
} else {
|
||||
fprintf(stdout, "Commit offset manually successfully.\n");
|
||||
}
|
||||
// free the message
|
||||
taos_free_result(tmqmsg);
|
||||
|
@ -339,7 +396,7 @@ void manual_commit(tmq_t* tmq) {
|
|||
}
|
||||
|
||||
// print the result: total messages and total rows consumed
|
||||
fprintf(stderr, "%d msg consumed, include %d rows\n", msgCnt, totalRows);
|
||||
fprintf(stderr, "%d msg consumed, include %d rows.\n", msgCnt, totalRows);
|
||||
}
|
||||
// ANCHOR_END: manual_commit
|
||||
|
||||
|
@ -356,28 +413,44 @@ int main(int argc, char* argv[]) {
|
|||
}
|
||||
|
||||
if (pthread_create(&thread_id, NULL, &prepare_data, NULL)) {
|
||||
fprintf(stderr, "create thread failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ANCHOR: create_consumer_2
|
||||
tmq_t* tmq = build_consumer();
|
||||
if (NULL == tmq) {
|
||||
fprintf(stderr, "build consumer to localhost fail!\n");
|
||||
fprintf(stderr, "Failed to create thread.\n");
|
||||
return -1;
|
||||
}
|
||||
printf("build consumer to localhost successfully \n");
|
||||
|
||||
ConsumerConfig config = {
|
||||
.enable_auto_commit = "true",
|
||||
.auto_commit_interval_ms = "1000",
|
||||
.group_id = "group1",
|
||||
.client_id = "client1",
|
||||
.td_connect_host = "localhost",
|
||||
.td_connect_port = "6030",
|
||||
.td_connect_user = "root",
|
||||
.td_connect_pass = "taosdata",
|
||||
.auto_offset_reset = "latest"
|
||||
};
|
||||
|
||||
// ANCHOR: create_consumer_2
|
||||
tmq_t* tmq = build_consumer(&config);
|
||||
if (NULL == tmq) {
|
||||
fprintf(stderr, "Failed to create native consumer, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, config.group_id, config.client_id);
|
||||
return -1;
|
||||
} else {
|
||||
fprintf(stdout, "Create consumer successfully, host: %s, groupId: %s, , clientId: %s.\n", config.td_connect_host, config.group_id, config.client_id);
|
||||
}
|
||||
|
||||
// ANCHOR_END: create_consumer_2
|
||||
|
||||
// ANCHOR: subscribe_3
|
||||
tmq_list_t* topic_list = build_topic_list();
|
||||
if (NULL == topic_list) {
|
||||
fprintf(stderr, "Failed to create topic_list.\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if ((code = tmq_subscribe(tmq, topic_list))) {
|
||||
fprintf(stderr, "Failed to tmq_subscribe(): %s\n", tmq_err2str(code));
|
||||
fprintf(stderr, "Failed to subscribe topic_list, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||
} else {
|
||||
fprintf(stdout, "Subscribe topics successfully.\n");
|
||||
}
|
||||
|
||||
tmq_list_destroy(topic_list);
|
||||
|
@ -393,13 +466,15 @@ int main(int argc, char* argv[]) {
|
|||
// unsubscribe the topic
|
||||
code = tmq_unsubscribe(tmq);
|
||||
if (code) {
|
||||
fprintf(stderr, "Failed to tmq_unsubscribe(): %s\n", tmq_err2str(code));
|
||||
fprintf(stderr, "Failed to unsubscribe consumer, ErrCode: 0x%x, ErrMessage: %s.\n", code, tmq_err2str(code));
|
||||
} else {
|
||||
fprintf(stderr, "Consumer unsubscribed successfully.\n");
|
||||
}
|
||||
fprintf(stderr, "Unsubscribed consumer successfully.\n");
|
||||
|
||||
// close the consumer
|
||||
code = tmq_consumer_close(tmq);
|
||||
if (code) {
|
||||
fprintf(stderr, "Failed to close consumer: %s\n", tmq_err2str(code));
|
||||
fprintf(stderr, "Failed to close consumer: %s.\n", tmq_err2str(code));
|
||||
} else {
|
||||
fprintf(stderr, "Consumer closed successfully.\n");
|
||||
}
|
||||
|
|
|
@ -23,55 +23,59 @@
|
|||
#include "taos.h"
|
||||
|
||||
static int DemoWithReqId() {
|
||||
// ANCHOR: with_reqid
|
||||
const char *ip = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
// ANCHOR: with_reqid
|
||||
const char *host = "localhost";
|
||||
const char *user = "root";
|
||||
const char *password = "taosdata";
|
||||
uint16_t port = 6030;
|
||||
int code = 0;
|
||||
|
||||
// connect
|
||||
TAOS *taos = taos_connect(ip, user, password, NULL, 0);
|
||||
if (taos == NULL) {
|
||||
printf("failed to connect to server %s, reason: %s\n", ip, taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
printf("success to connect server %s\n", ip);
|
||||
|
||||
const char *sql = "SELECT ts, current, location FROM power.meters limit 1";
|
||||
// query data with reqid
|
||||
TAOS_RES *result = taos_query_with_reqid(taos, sql, 3L);
|
||||
int code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("failed to query data from power.meters, ip: %s, reason: %s\n", ip, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
|
||||
TAOS_ROW row = NULL;
|
||||
int rows = 0;
|
||||
int num_fields = taos_field_count(result);
|
||||
TAOS_FIELD *fields = taos_fetch_fields(result);
|
||||
|
||||
printf("fields: %d\n", num_fields);
|
||||
printf("sql: %s, result:\n", sql);
|
||||
|
||||
// fetch the records row by row
|
||||
while ((row = taos_fetch_row(result))) {
|
||||
char temp[1024] = {0};
|
||||
rows++;
|
||||
taos_print_row(temp, row, fields, num_fields);
|
||||
printf("%s\n", temp);
|
||||
}
|
||||
printf("total rows: %d\n", rows);
|
||||
taos_free_result(result);
|
||||
printf("success to query data from power.meters\n");
|
||||
|
||||
// close & clean
|
||||
taos_close(taos);
|
||||
// connect
|
||||
TAOS *taos = taos_connect(host, user, password, NULL, port);
|
||||
if (taos == NULL) {
|
||||
printf("Failed to connect to %s:%hu, ErrCode: 0x%x, ErrMessage: %s.\n", host, port, taos_errno(NULL), taos_errstr(NULL));
|
||||
taos_cleanup();
|
||||
return 0;
|
||||
// ANCHOR_END: with_reqid
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char *sql = "SELECT ts, current, location FROM power.meters limit 1";
|
||||
// query data with reqid
|
||||
long reqid = 3L;
|
||||
TAOS_RES *result = taos_query_with_reqid(taos, sql, reqid);
|
||||
code = taos_errno(result);
|
||||
if (code != 0) {
|
||||
printf("Failed to execute sql with reqId: %ld, Server: %s:%hu, ErrCode: 0x%x, ErrMessage: %s\n.", reqid, host, port, code, taos_errstr(result));
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return -1;
|
||||
}
|
||||
|
||||
TAOS_ROW row = NULL;
|
||||
int rows = 0;
|
||||
int num_fields = taos_field_count(result);
|
||||
TAOS_FIELD *fields = taos_fetch_fields(result);
|
||||
|
||||
printf("fields: %d\n", num_fields);
|
||||
printf("sql: %s, result:\n", sql);
|
||||
|
||||
// fetch the records row by row
|
||||
while ((row = taos_fetch_row(result))) {
|
||||
char temp[1024] = {0};
|
||||
rows++;
|
||||
taos_print_row(temp, row, fields, num_fields);
|
||||
printf("%s\n", temp);
|
||||
}
|
||||
printf("total rows: %d\n", rows);
|
||||
taos_free_result(result);
|
||||
|
||||
// close & clean
|
||||
taos_close(taos);
|
||||
taos_cleanup();
|
||||
return 0;
|
||||
// ANCHOR_END: with_reqid
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
return DemoWithReqId();
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) { return DemoWithReqId(); }
|
||||
|
|
|
@ -5,9 +5,9 @@ namespace TDengineExample
|
|||
{
|
||||
internal class OptsJsonExample
|
||||
{
|
||||
// ANCHOR: main
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
// ANCHOR: main
|
||||
var host = "127.0.0.1";
|
||||
|
||||
var lineDemo =
|
||||
|
@ -38,20 +38,22 @@ namespace TDengineExample
|
|||
client.SchemalessInsert(new []{jsonDemo}, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
|
||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED, 0, ReqId.GetReqId());
|
||||
}
|
||||
|
||||
Console.WriteLine("Inserted data with schemaless successfully.");
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to insert data with schemaless; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to insert data with schemaless; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: main
|
||||
}
|
||||
// ANCHOR_END: main
|
||||
}
|
||||
}
|
|
@ -12,9 +12,10 @@ namespace TDengineExample
|
|||
var numOfSubTable = 10;
|
||||
var numOfRow = 10;
|
||||
var random = new Random();
|
||||
var connectionString = $"host={host};port=6030;username=root;password=taosdata";
|
||||
try
|
||||
{
|
||||
var builder = new ConnectionStringBuilder($"host={host};port=6030;username=root;password=taosdata");
|
||||
var builder = new ConnectionStringBuilder(connectionString);
|
||||
using (var client = DbDriver.Open(builder))
|
||||
{
|
||||
// create database
|
||||
|
@ -53,7 +54,7 @@ namespace TDengineExample
|
|||
stmt.Exec();
|
||||
// get affected rows
|
||||
var affectedRows = stmt.Affected();
|
||||
Console.WriteLine($"table {tableName} insert {affectedRows} rows.");
|
||||
Console.WriteLine($"Successfully inserted {affectedRows} rows to {tableName}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -61,13 +62,13 @@ namespace TDengineExample
|
|||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to insert to table meters using stmt; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to insert to table meters using stmt; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -64,6 +64,9 @@ namespace TMQExample
|
|||
{
|
||||
// ANCHOR: create_consumer
|
||||
// consumer config
|
||||
var host = "127.0.0.1";
|
||||
var groupId = "group1";
|
||||
var clientId = "client1";
|
||||
var cfg = new Dictionary<string, string>()
|
||||
{
|
||||
{ "td.connect.port", "6030" },
|
||||
|
@ -71,9 +74,9 @@ namespace TMQExample
|
|||
{ "msg.with.table.name", "true" },
|
||||
{ "enable.auto.commit", "true" },
|
||||
{ "auto.commit.interval.ms", "1000" },
|
||||
{ "group.id", "group1" },
|
||||
{ "client.id", "client1" },
|
||||
{ "td.connect.ip", "127.0.0.1" },
|
||||
{ "group.id", groupId },
|
||||
{ "client.id", clientId },
|
||||
{ "td.connect.ip", host },
|
||||
{ "td.connect.user", "root" },
|
||||
{ "td.connect.pass", "taosdata" },
|
||||
};
|
||||
|
@ -82,17 +85,20 @@ namespace TMQExample
|
|||
{
|
||||
// create consumer
|
||||
consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
|
||||
Console.WriteLine("Create consumer successfully, host: " + host + ", groupId: " + groupId +
|
||||
", clientId: " + clientId);
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to create consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to create native consumer, host : " + host + "; ErrCode:" + e.Code +
|
||||
"; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to create consumer; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to create native consumer, host : " + host + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
|
||||
|
@ -107,6 +113,7 @@ namespace TMQExample
|
|||
{
|
||||
// subscribe
|
||||
consumer.Subscribe(new List<string>() { "topic_meters" });
|
||||
Console.WriteLine("subscribe topics successfully");
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
// consume message with using block to ensure the result is disposed
|
||||
|
@ -117,7 +124,7 @@ namespace TMQExample
|
|||
{
|
||||
// handle message
|
||||
Console.WriteLine(
|
||||
$"data {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||
$"data: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
||||
}
|
||||
}
|
||||
|
@ -132,7 +139,7 @@ namespace TMQExample
|
|||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to poll data; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to poll data; ErrMessage:" + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: subscribe
|
||||
|
@ -145,40 +152,24 @@ namespace TMQExample
|
|||
{
|
||||
// get assignment
|
||||
var assignment = consumer.Assignment;
|
||||
Console.WriteLine($"now assignment: {assignment}");
|
||||
// seek to the beginning
|
||||
foreach (var topicPartition in assignment)
|
||||
{
|
||||
consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0));
|
||||
}
|
||||
Console.WriteLine("assignment seek to beginning successfully");
|
||||
// poll data again
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
// consume message with using block to ensure the result is disposed
|
||||
using (var cr = consumer.Consume(100))
|
||||
{
|
||||
if (cr == null) continue;
|
||||
foreach (var message in cr.Message)
|
||||
{
|
||||
// handle message
|
||||
Console.WriteLine(
|
||||
$"second data polled: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
Console.WriteLine("Assignment seek to beginning successfully");
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to seek; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Seek example failed; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to seek; Err:" + e.Message);
|
||||
Console.WriteLine("Seek example failed; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: seek
|
||||
|
@ -200,18 +191,19 @@ namespace TMQExample
|
|||
{
|
||||
cr.TopicPartitionOffset,
|
||||
});
|
||||
Console.WriteLine("Commit offset manually successfully.");
|
||||
}
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to commit offset; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to execute consumer functions. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to commit offset; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to execute consumer functions. ErrMessage:" + e.Message);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
@ -229,19 +221,20 @@ namespace TMQExample
|
|||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to unsubscribe consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to unsubscribe consumer. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to unsubscribe consumer; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to unsubscribe consumer. Err: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// close consumer
|
||||
consumer.Close();
|
||||
Console.WriteLine("Consumer closed successfully.");
|
||||
}
|
||||
// ANCHOR_END: close
|
||||
}
|
||||
|
|
|
@ -11,13 +11,15 @@ namespace Examples
|
|||
{
|
||||
try
|
||||
{
|
||||
var builder = new ConnectionStringBuilder("protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false;username=root;password=taosdata");
|
||||
var connectionString =
|
||||
"protocol=WebSocket;host=127.0.0.1;port=6041;useSSL=false;username=root;password=taosdata";
|
||||
var builder = new ConnectionStringBuilder(connectionString);
|
||||
using (var client = DbDriver.Open(builder))
|
||||
{
|
||||
CreateDatabaseAndTable(client);
|
||||
InsertData(client);
|
||||
QueryData(client);
|
||||
QueryWithReqId(client);
|
||||
CreateDatabaseAndTable(client,connectionString);
|
||||
InsertData(client,connectionString);
|
||||
QueryData(client,connectionString);
|
||||
QueryWithReqId(client,connectionString);
|
||||
}
|
||||
}
|
||||
catch (TDengineError e)
|
||||
|
@ -34,40 +36,40 @@ namespace Examples
|
|||
}
|
||||
}
|
||||
|
||||
private static void CreateDatabaseAndTable(ITDengineClient client)
|
||||
private static void CreateDatabaseAndTable(ITDengineClient client, string connectionString)
|
||||
{
|
||||
// ANCHOR: create_db_and_table
|
||||
try
|
||||
{
|
||||
// create database
|
||||
var affected = client.Exec("CREATE DATABASE IF NOT EXISTS power");
|
||||
Console.WriteLine($"Create database power, affected rows: {affected}");
|
||||
Console.WriteLine($"Create database power successfully, rowsAffected: {affected}");
|
||||
// create table
|
||||
affected = client.Exec(
|
||||
"CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||
Console.WriteLine($"Create table meters, affected rows: {affected}");
|
||||
Console.WriteLine($"Create stable power.meters successfully, rowsAffected: {affected}");
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to create db and table; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to create db and table,url:" + connectionString +"; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to create db and table; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to create db and table, url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: create_db_and_table
|
||||
}
|
||||
|
||||
private static void InsertData(ITDengineClient client)
|
||||
private static void InsertData(ITDengineClient client,string connectionString)
|
||||
{
|
||||
// ANCHOR: insert_data
|
||||
try
|
||||
{
|
||||
// insert data
|
||||
// insert data, please make sure the database and table are created before
|
||||
var insertQuery = "INSERT INTO " +
|
||||
"power.d1001 USING power.meters TAGS(2,'California.SanFrancisco') " +
|
||||
"VALUES " +
|
||||
|
@ -78,29 +80,29 @@ namespace Examples
|
|||
"VALUES " +
|
||||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||
var affectedRows = client.Exec(insertQuery);
|
||||
Console.WriteLine("insert " + affectedRows + " rows to power.meters successfully.");
|
||||
Console.WriteLine("Successfully inserted " + affectedRows + " rows to power.meters.");
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to insert data to power.meters; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to insert data to power.meters, url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to insert data to power.meters; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to insert data to power.meters, url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: insert_data
|
||||
}
|
||||
|
||||
private static void QueryData(ITDengineClient client)
|
||||
private static void QueryData(ITDengineClient client,string connectionString)
|
||||
{
|
||||
// ANCHOR: select_data
|
||||
try
|
||||
{
|
||||
// query data
|
||||
// query data, make sure the database and table are created before
|
||||
var query = "SELECT ts, current, location FROM power.meters limit 100";
|
||||
using (var rows = client.Query(query))
|
||||
{
|
||||
|
@ -117,27 +119,28 @@ namespace Examples
|
|||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to query data from power.meters; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to query data from power.meters, url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to query data from power.meters; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to query data from power.meters, url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: select_data
|
||||
}
|
||||
|
||||
private static void QueryWithReqId(ITDengineClient client)
|
||||
private static void QueryWithReqId(ITDengineClient client,string connectionString)
|
||||
{
|
||||
// ANCHOR: query_id
|
||||
var reqId = (long)3;
|
||||
try
|
||||
{
|
||||
// query data
|
||||
var query = "SELECT ts, current, location FROM power.meters limit 1";
|
||||
// query with request id 3
|
||||
using (var rows = client.Query(query,3))
|
||||
using (var rows = client.Query(query,reqId))
|
||||
{
|
||||
while (rows.Read())
|
||||
{
|
||||
|
@ -152,13 +155,13 @@ namespace Examples
|
|||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to execute sql with reqId; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", url:" + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to execute sql with reqId; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to execute sql with reqId: " + reqId + ", url:" + connectionString + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: query_id
|
||||
|
|
|
@ -13,9 +13,10 @@ namespace Examples
|
|||
var numOfSubTable = 10;
|
||||
var numOfRow = 10;
|
||||
var random = new Random();
|
||||
var connectionString = $"protocol=WebSocket;host={host};port=6041;useSSL=false;username=root;password=taosdata";
|
||||
try
|
||||
{
|
||||
var builder = new ConnectionStringBuilder($"protocol=WebSocket;host={host};port=6041;useSSL=false;username=root;password=taosdata");
|
||||
var builder = new ConnectionStringBuilder(connectionString);
|
||||
using (var client = DbDriver.Open(builder))
|
||||
{
|
||||
// create database
|
||||
|
@ -54,7 +55,7 @@ namespace Examples
|
|||
stmt.Exec();
|
||||
// get affected rows
|
||||
var affectedRows = stmt.Affected();
|
||||
Console.WriteLine($"table {tableName} insert {affectedRows} rows.");
|
||||
Console.WriteLine($"Successfully inserted {affectedRows} rows to {tableName}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -62,13 +63,13 @@ namespace Examples
|
|||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to insert to table meters using stmt; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to insert to table meters using stmt; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to insert to table meters using stmt, url: " + connectionString + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,26 +29,29 @@ namespace TDengineExample
|
|||
// use database
|
||||
client.Exec("USE power");
|
||||
// insert influx line protocol data
|
||||
client.SchemalessInsert(new[]{lineDemo}, TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL,
|
||||
client.SchemalessInsert(new[] { lineDemo }, TDengineSchemalessProtocol.TSDB_SML_LINE_PROTOCOL,
|
||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
|
||||
// insert opentsdb telnet protocol data
|
||||
client.SchemalessInsert(new[]{telnetDemo}, TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL,
|
||||
client.SchemalessInsert(new[] { telnetDemo }, TDengineSchemalessProtocol.TSDB_SML_TELNET_PROTOCOL,
|
||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_MILLI_SECONDS, 0, ReqId.GetReqId());
|
||||
// insert json data
|
||||
client.SchemalessInsert(new []{jsonDemo}, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
|
||||
client.SchemalessInsert(new[] { jsonDemo }, TDengineSchemalessProtocol.TSDB_SML_JSON_PROTOCOL,
|
||||
TDengineSchemalessPrecision.TSDB_SML_TIMESTAMP_NOT_CONFIGURED, 0, ReqId.GetReqId());
|
||||
}
|
||||
|
||||
Console.WriteLine("Inserted data with schemaless successfully.");
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to insert data with schemaless; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrCode:" + e.Code +
|
||||
"; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to insert data with schemaless; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,7 +10,9 @@ namespace TMQExample
|
|||
{
|
||||
try
|
||||
{
|
||||
var builder = new ConnectionStringBuilder("protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
||||
var builder =
|
||||
new ConnectionStringBuilder(
|
||||
"protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
||||
using (var client = DbDriver.Open(builder))
|
||||
{
|
||||
client.Exec("CREATE DATABASE IF NOT EXISTS power");
|
||||
|
@ -48,7 +50,9 @@ namespace TMQExample
|
|||
|
||||
static void InsertData()
|
||||
{
|
||||
var builder = new ConnectionStringBuilder("protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
||||
var builder =
|
||||
new ConnectionStringBuilder(
|
||||
"protocol=WebSocket;host=127.0.0.1;port=6041;username=root;password=taosdata");
|
||||
using (var client = DbDriver.Open(builder))
|
||||
{
|
||||
while (true)
|
||||
|
@ -64,17 +68,20 @@ namespace TMQExample
|
|||
{
|
||||
// ANCHOR: create_consumer
|
||||
// consumer config
|
||||
var host = "127.0.0.1";
|
||||
var groupId = "group1";
|
||||
var clientId = "client1";
|
||||
var cfg = new Dictionary<string, string>()
|
||||
{
|
||||
{"td.connect.type", "WebSocket"},
|
||||
{ "td.connect.type", "WebSocket" },
|
||||
{ "td.connect.port", "6041" },
|
||||
{ "auto.offset.reset", "latest" },
|
||||
{ "msg.with.table.name", "true" },
|
||||
{ "enable.auto.commit", "true" },
|
||||
{ "auto.commit.interval.ms", "1000" },
|
||||
{ "group.id", "group1" },
|
||||
{ "client.id", "client1" },
|
||||
{ "td.connect.ip", "127.0.0.1" },
|
||||
{ "group.id", groupId },
|
||||
{ "client.id", clientId },
|
||||
{ "td.connect.ip", host },
|
||||
{ "td.connect.user", "root" },
|
||||
{ "td.connect.pass", "taosdata" },
|
||||
};
|
||||
|
@ -83,17 +90,20 @@ namespace TMQExample
|
|||
{
|
||||
// create consumer
|
||||
consumer = new ConsumerBuilder<Dictionary<string, object>>(cfg).Build();
|
||||
Console.WriteLine("Create consumer successfully, host: " + host + ", groupId: " + groupId +
|
||||
", clientId: " + clientId);
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to create consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to create websocket consumer, host : " + host + "; ErrCode:" + e.Code +
|
||||
"; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to create consumer; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to create websocket consumer, host : " + host + "; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
|
||||
|
@ -108,6 +118,7 @@ namespace TMQExample
|
|||
{
|
||||
// subscribe
|
||||
consumer.Subscribe(new List<string>() { "topic_meters" });
|
||||
Console.WriteLine("Subscribe topics successfully");
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
// consume message with using block to ensure the result is disposed
|
||||
|
@ -118,7 +129,7 @@ namespace TMQExample
|
|||
{
|
||||
// handle message
|
||||
Console.WriteLine(
|
||||
$"data {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||
$"data: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
||||
}
|
||||
}
|
||||
|
@ -133,7 +144,7 @@ namespace TMQExample
|
|||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to poll data; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to poll data; ErrMessage:" + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: subscribe
|
||||
|
@ -146,40 +157,24 @@ namespace TMQExample
|
|||
{
|
||||
// get assignment
|
||||
var assignment = consumer.Assignment;
|
||||
Console.WriteLine($"Now assignment: {assignment}");
|
||||
// seek to the beginning
|
||||
foreach (var topicPartition in assignment)
|
||||
{
|
||||
consumer.Seek(new TopicPartitionOffset(topicPartition.Topic, topicPartition.Partition, 0));
|
||||
}
|
||||
Console.WriteLine("assignment seek to beginning successfully");
|
||||
// poll data again
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
// consume message with using block to ensure the result is disposed
|
||||
using (var cr = consumer.Consume(100))
|
||||
{
|
||||
if (cr == null) continue;
|
||||
foreach (var message in cr.Message)
|
||||
{
|
||||
// handle message
|
||||
Console.WriteLine(
|
||||
$"second data polled: {{{((DateTime)message.Value["ts"]).ToString("yyyy-MM-dd HH:mm:ss.fff")}, " +
|
||||
$"{message.Value["current"]}, {message.Value["voltage"]}, {message.Value["phase"]}}}");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
Console.WriteLine("Assignment seek to beginning successfully");
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to seek; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Seek example failed; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to seek; Err:" + e.Message);
|
||||
Console.WriteLine("Seek example failed; ErrMessage: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
// ANCHOR_END: seek
|
||||
|
@ -201,18 +196,19 @@ namespace TMQExample
|
|||
{
|
||||
cr.TopicPartitionOffset,
|
||||
});
|
||||
Console.WriteLine("Commit offset manually successfully.");
|
||||
}
|
||||
}
|
||||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to commit offset; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to execute consumer functions. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to commit offset; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to execute consumer functions. ErrMessage:" + e.Message);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
@ -230,19 +226,20 @@ namespace TMQExample
|
|||
catch (TDengineError e)
|
||||
{
|
||||
// handle TDengine error
|
||||
Console.WriteLine("Failed to unsubscribe consumer; ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
Console.WriteLine("Failed to unsubscribe consumer. ErrCode:" + e.Code + "; ErrMessage: " + e.Error);
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// handle other exceptions
|
||||
Console.WriteLine("Failed to unsubscribe consumer; Err:" + e.Message);
|
||||
Console.WriteLine("Failed to unsubscribe consumer. Err: " + e.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// close consumer
|
||||
consumer.Close();
|
||||
Console.WriteLine("Consumer closed successfully.");
|
||||
}
|
||||
// ANCHOR_END: close
|
||||
}
|
||||
|
|
|
@ -15,7 +15,7 @@ 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)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("Connected to " + taosDSN + " successfully.")
|
||||
defer taos.Close()
|
||||
|
|
|
@ -15,7 +15,7 @@ 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)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("Connected to " + taosDSN + " successfully.")
|
||||
defer taos.Close()
|
||||
|
|
|
@ -15,7 +15,7 @@ func main() {
|
|||
var taosDSN = "root:taosdata@ws(localhost:6041)/"
|
||||
taos, err := sql.Open("taosWS", taosDSN)
|
||||
if err != nil {
|
||||
log.Fatalln("failed to connect TDengine, err:", err)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("Connected to " + taosDSN + " successfully.")
|
||||
defer taos.Close()
|
||||
|
|
|
@ -11,19 +11,21 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
db, err := sql.Open("taosSql", "root:taosdata@tcp(localhost:6030)/")
|
||||
taosDSN := "root:taosdata@tcp(localhost:6030)/"
|
||||
db, err := sql.Open("taosSql", taosDSN)
|
||||
if err != nil {
|
||||
log.Fatal("Open database error: ", err)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer db.Close()
|
||||
initEnv(db)
|
||||
// ANCHOR: query_id
|
||||
// use context to set request id
|
||||
ctx := context.WithValue(context.Background(), "taos_req_id", int64(3))
|
||||
reqId := int64(3)
|
||||
ctx := context.WithValue(context.Background(), "taos_req_id", reqId)
|
||||
// execute query with context
|
||||
rows, err := db.QueryContext(ctx, "SELECT ts, current, location FROM power.meters limit 1")
|
||||
if err != nil {
|
||||
log.Fatal("Query error: ", err)
|
||||
log.Fatalf("Failed to execute sql with reqId: %d, url: %s; ErrMessage: %s\n", reqId, taosDSN, err.Error())
|
||||
}
|
||||
for rows.Next() {
|
||||
var (
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/taosdata/driver-go/v3/af"
|
||||
|
@ -14,30 +15,31 @@ func main() {
|
|||
|
||||
conn, err := af.Open(host, "root", "taosdata", "", 0)
|
||||
if err != nil {
|
||||
log.Fatal("failed to connect TDengine, err:", err)
|
||||
log.Fatalln("Failed to connect to host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer conn.Close()
|
||||
_, err = conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create database, err:", err)
|
||||
log.Fatalln("Failed to create db host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = conn.Exec("USE power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to use database, err:", err)
|
||||
log.Fatalln("Failed to use db host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// insert influxdb line protocol
|
||||
err = conn.InfluxDBInsertLines([]string{lineDemo}, "ms")
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert influxdb line protocol, err:", err)
|
||||
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// insert opentsdb telnet protocol
|
||||
err = conn.OpenTSDBInsertTelnetLines([]string{telnetDemo})
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert opentsdb telnet line protocol, err:", err)
|
||||
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// insert opentsdb json protocol
|
||||
err = conn.OpenTSDBInsertJsonPayload(jsonDemo)
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert opentsdb json format protocol, err:", err)
|
||||
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("Inserted data with schemaless successfully.")
|
||||
}
|
||||
|
|
|
@ -17,14 +17,15 @@ func main() {
|
|||
telnetDemo := "metric_telnet 1707095283260 4 host=host0 interface=eth0"
|
||||
jsonDemo := "{\"metric\": \"metric_json\",\"timestamp\": 1626846400,\"value\": 10.3, \"tags\": {\"groupid\": 2, \"location\": \"California.SanFrancisco\", \"id\": \"d1001\"}}"
|
||||
|
||||
db, err := sql.Open("taosWS", fmt.Sprintf("root:taosdata@ws(%s:6041)/", host))
|
||||
taosDSN := fmt.Sprintf("root:taosdata@ws(%s:6041)/", host)
|
||||
db, err := sql.Open("taosWS", taosDSN)
|
||||
if err != nil {
|
||||
log.Fatal("failed to connect TDengine, err:", err)
|
||||
log.Fatalln("Failed to connect to host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer db.Close()
|
||||
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create database, err:", err)
|
||||
log.Fatalln("Failed to create db host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
s, err := schemaless.NewSchemaless(schemaless.NewConfig("ws://localhost:6041", 1,
|
||||
schemaless.SetDb("power"),
|
||||
|
@ -34,21 +35,22 @@ func main() {
|
|||
schemaless.SetPassword("taosdata"),
|
||||
))
|
||||
if err != nil {
|
||||
log.Fatal("failed to create schemaless connection, err:", err)
|
||||
log.Fatalln("Failed to connect to host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// insert influxdb line protocol
|
||||
err = s.Insert(lineDemo, schemaless.InfluxDBLineProtocol, "ms", 0, common.GetReqID())
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert influxdb line protocol, err:", err)
|
||||
log.Fatalln("Failed to insert data with schemaless, host:" + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// insert opentsdb telnet line protocol
|
||||
err = s.Insert(telnetDemo, schemaless.OpenTSDBTelnetLineProtocol, "ms", 0, common.GetReqID())
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert opentsdb telnet line protocol, err:", err)
|
||||
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// insert opentsdb json format protocol
|
||||
err = s.Insert(jsonDemo, schemaless.OpenTSDBJsonFormatProtocol, "s", 0, common.GetReqID())
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert opentsdb json format protocol, err:", err)
|
||||
log.Fatalln("Failed to insert data with schemaless, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("Inserted data with schemaless successfully.")
|
||||
}
|
||||
|
|
|
@ -10,39 +10,35 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
db, err := sql.Open("taosSql", "root:taosdata@tcp(localhost:6030)/")
|
||||
var taosDSN = "root:taosdata@tcp(localhost:6030)/"
|
||||
db, err := sql.Open("taosSql", taosDSN)
|
||||
if err != nil {
|
||||
log.Fatal("open database failed:", err)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer db.Close()
|
||||
// ANCHOR: create_db_and_table
|
||||
// create database
|
||||
res, err := db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||
if err != nil {
|
||||
log.Fatal("create database failed:", err)
|
||||
log.Fatalln("Failed to create db, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
rowsAffected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
log.Fatal("get affected rows failed:", err)
|
||||
log.Fatalln("Failed to get create db rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("create database affected:", affected)
|
||||
// use database
|
||||
res, err = db.Exec("USE power")
|
||||
if err != nil {
|
||||
log.Fatal("use database failed:", err)
|
||||
}
|
||||
affected, err = res.RowsAffected()
|
||||
if err != nil {
|
||||
log.Fatal("get affected rows failed:", err)
|
||||
}
|
||||
fmt.Println("use database affected:", affected)
|
||||
// you can check rowsAffected here
|
||||
fmt.Println("Create database power successfully, rowsAffected: ", rowsAffected)
|
||||
// create table
|
||||
res, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||
affected, err = res.RowsAffected()
|
||||
if err != nil {
|
||||
log.Fatal("create table failed:", err)
|
||||
log.Fatalln("Failed to create db and table, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("create table affected:", affected)
|
||||
rowsAffected, err = res.RowsAffected()
|
||||
if err != nil {
|
||||
log.Fatalln("Failed to get create db rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// you can check rowsAffected here
|
||||
fmt.Println("Create stable power.meters successfully, rowsAffected:", rowsAffected)
|
||||
// ANCHOR_END: create_db_and_table
|
||||
// ANCHOR: insert_data
|
||||
// insert data, please make sure the database and table are created before
|
||||
|
@ -57,20 +53,20 @@ func main() {
|
|||
"(NOW + 1a, 10.30000, 218, 0.25000) "
|
||||
res, err = db.Exec(insertQuery)
|
||||
if err != nil {
|
||||
log.Fatal("insert data failed:", err)
|
||||
log.Fatal("Failed to insert data to power.meters, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
affected, err = res.RowsAffected()
|
||||
rowsAffected, err = res.RowsAffected()
|
||||
if err != nil {
|
||||
log.Fatal("get affected rows failed:", err)
|
||||
log.Fatal("Failed to get insert rowsAffected, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// you can check affectedRows here
|
||||
fmt.Println("insert data affected:", affected)
|
||||
fmt.Printf("Successfully inserted %d rows to power.meters.\n", rowsAffected)
|
||||
// ANCHOR_END: insert_data
|
||||
// ANCHOR: select_data
|
||||
// query data, make sure the database and table are created before
|
||||
rows, err := db.Query("SELECT ts, current, location FROM power.meters limit 100")
|
||||
if err != nil {
|
||||
log.Fatal("query data failed:", err)
|
||||
log.Fatal("Failed to query data from power.meters, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
for rows.Next() {
|
||||
var (
|
||||
|
@ -80,7 +76,7 @@ func main() {
|
|||
)
|
||||
err = rows.Scan(&ts, ¤t, &location)
|
||||
if err != nil {
|
||||
log.Fatal("scan data failed:", err)
|
||||
log.Fatal("Failed to scan data, url:" + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// you can check data here
|
||||
fmt.Printf("ts: %s, current: %f, location: %s\n", ts, current, location)
|
||||
|
|
|
@ -17,28 +17,28 @@ func main() {
|
|||
numOfRow := 10
|
||||
db, err := af.Open(host, "root", "taosdata", "", 0)
|
||||
if err != nil {
|
||||
log.Fatal("failed to connect TDengine, err:", err)
|
||||
log.Fatalln("Failed to connect to " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer db.Close()
|
||||
// prepare database and table
|
||||
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create database, err:", err)
|
||||
log.Fatalln("Failed to create db, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = db.Exec("USE power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to use database, err:", err)
|
||||
log.Fatalln("Failed to use db, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = db.Exec("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create table, err:", err)
|
||||
log.Fatalln("Failed to create table, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// prepare statement
|
||||
sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)"
|
||||
stmt := db.Stmt()
|
||||
err = stmt.Prepare(sql)
|
||||
if err != nil {
|
||||
log.Fatal("failed to prepare statement, err:", err)
|
||||
log.Fatalln("Failed to prepare sql, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
for i := 1; i <= numOfSubTable; i++ {
|
||||
tableName := fmt.Sprintf("d_bind_%d", i)
|
||||
|
@ -46,7 +46,7 @@ func main() {
|
|||
// set tableName and tags
|
||||
err = stmt.SetTableNameWithTags(tableName, tags)
|
||||
if err != nil {
|
||||
log.Fatal("failed to set table name and tags, err:", err)
|
||||
log.Fatalln("Failed to set table name and tags, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// bind column data
|
||||
current := time.Now()
|
||||
|
@ -58,23 +58,23 @@ func main() {
|
|||
AddFloat(rand.Float32())
|
||||
err = stmt.BindRow(row)
|
||||
if err != nil {
|
||||
log.Fatal("failed to bind row, err:", err)
|
||||
log.Fatalln("Failed to bind params, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
}
|
||||
// add batch
|
||||
err = stmt.AddBatch()
|
||||
if err != nil {
|
||||
log.Fatal("failed to add batch, err:", err)
|
||||
log.Fatalln("Failed to add batch, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// execute batch
|
||||
err = stmt.Execute()
|
||||
if err != nil {
|
||||
log.Fatal("failed to execute batch, err:", err)
|
||||
log.Fatalln("Failed to exec, host: " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// get affected rows
|
||||
affected := stmt.GetAffectedRows()
|
||||
// you can check exeResult here
|
||||
fmt.Printf("table %s insert %d rows.\n", tableName, affected)
|
||||
fmt.Printf("Successfully inserted %d rows to %s.\n", affected, tableName)
|
||||
}
|
||||
err = stmt.Close()
|
||||
if err != nil {
|
||||
|
|
|
@ -17,19 +17,21 @@ func main() {
|
|||
host := "127.0.0.1"
|
||||
numOfSubTable := 10
|
||||
numOfRow := 10
|
||||
db, err := sql.Open("taosRestful", fmt.Sprintf("root:taosdata@http(%s:6041)/", host))
|
||||
|
||||
taosDSN := fmt.Sprintf("root:taosdata@http(%s:6041)/", host)
|
||||
db, err := sql.Open("taosRestful", taosDSN)
|
||||
if err != nil {
|
||||
log.Fatal("failed to connect TDengine, err:", err)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer db.Close()
|
||||
// prepare database and table
|
||||
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create database, err:", err)
|
||||
log.Fatalln("Failed to create db, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = db.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create table, err:", err)
|
||||
log.Fatalln("Failed to create table, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
|
||||
config := stmt.NewConfig(fmt.Sprintf("ws://%s:6041", host), 0)
|
||||
|
@ -41,17 +43,17 @@ func main() {
|
|||
|
||||
connector, err := stmt.NewConnector(config)
|
||||
if err != nil {
|
||||
log.Fatal("failed to create stmt connector, err:", err)
|
||||
log.Fatalln("Failed to create stmt connector,url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// prepare statement
|
||||
sql := "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)"
|
||||
stmt, err := connector.Init()
|
||||
if err != nil {
|
||||
log.Fatal("failed to init stmt, err:", err)
|
||||
log.Fatalln("Failed to init stmt, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
err = stmt.Prepare(sql)
|
||||
if err != nil {
|
||||
log.Fatal("failed to prepare stmt, err:", err)
|
||||
log.Fatal("Failed to prepare sql, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
for i := 1; i <= numOfSubTable; i++ {
|
||||
tableName := fmt.Sprintf("d_bind_%d", i)
|
||||
|
@ -61,12 +63,12 @@ func main() {
|
|||
// set tableName
|
||||
err = stmt.SetTableName(tableName)
|
||||
if err != nil {
|
||||
log.Fatal("failed to set table name, err:", err)
|
||||
log.Fatal("Failed to set table name, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// set tags
|
||||
err = stmt.SetTags(tags, tagsType)
|
||||
if err != nil {
|
||||
log.Fatal("failed to set tags, err:", err)
|
||||
log.Fatal("Failed to set tags, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// bind column data
|
||||
current := time.Now()
|
||||
|
@ -78,26 +80,26 @@ func main() {
|
|||
columnData[3] = param.NewParam(1).AddFloat(rand.Float32())
|
||||
err = stmt.BindParam(columnData, columnType)
|
||||
if err != nil {
|
||||
log.Fatal("failed to bind param, err:", err)
|
||||
log.Fatal("Failed to bind params, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
}
|
||||
// add batch
|
||||
err = stmt.AddBatch()
|
||||
if err != nil {
|
||||
log.Fatal("failed to add batch, err:", err)
|
||||
log.Fatal("Failed to add batch, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// execute batch
|
||||
err = stmt.Exec()
|
||||
if err != nil {
|
||||
log.Fatal("failed to exec stmt, err:", err)
|
||||
log.Fatal("Failed to exec, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// get affected rows
|
||||
affected := stmt.GetAffectedRows()
|
||||
// you can check exeResult here
|
||||
fmt.Printf("table %s insert %d rows.\n", tableName, affected)
|
||||
fmt.Printf("Successfully inserted %d rows to %s.\n", affected, tableName)
|
||||
}
|
||||
err = stmt.Close()
|
||||
if err != nil {
|
||||
log.Fatal("failed to close stmt, err:", err)
|
||||
log.Fatal("Failed to close stmt, url: " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -15,9 +15,10 @@ var done = make(chan struct{})
|
|||
|
||||
func main() {
|
||||
// init env
|
||||
conn, err := sql.Open("taosSql", "root:taosdata@tcp(127.0.0.1:6030)/")
|
||||
taosDSN := "root:taosdata@tcp(127.0.0.1:6030)/"
|
||||
conn, err := sql.Open("taosSql", taosDSN)
|
||||
if err != nil {
|
||||
log.Fatal("failed to connect TDengine, err:", err)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer func() {
|
||||
conn.Close()
|
||||
|
@ -25,6 +26,9 @@ func main() {
|
|||
initEnv(conn)
|
||||
// ANCHOR: create_consumer
|
||||
// create consumer
|
||||
groupID := "group1"
|
||||
clientID := "client1"
|
||||
host := "127.0.0.1"
|
||||
consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{
|
||||
"td.connect.user": "root",
|
||||
"td.connect.pass": "taosdata",
|
||||
|
@ -32,18 +36,21 @@ func main() {
|
|||
"msg.with.table.name": "true",
|
||||
"enable.auto.commit": "true",
|
||||
"auto.commit.interval.ms": "1000",
|
||||
"group.id": "group1",
|
||||
"client.id": "client1",
|
||||
"group.id": groupID,
|
||||
"client.id": clientID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal("failed to create consumer, err:", err)
|
||||
log.Fatalln("Failed to create native consumer, host : " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
log.Println("Create consumer successfully, host: " + host + ", groupId: " + groupID + ", clientId: " + clientID)
|
||||
|
||||
// ANCHOR_END: create_consumer
|
||||
// ANCHOR: subscribe
|
||||
err = consumer.Subscribe("topic_meters", nil)
|
||||
if err != nil {
|
||||
log.Fatal("failed to subscribe, err:", err)
|
||||
log.Fatalln("Failed to subscribe, host : " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
log.Println("Subscribe topics successfully")
|
||||
for i := 0; i < 50; i++ {
|
||||
ev := consumer.Poll(100)
|
||||
if ev != nil {
|
||||
|
@ -53,23 +60,16 @@ func main() {
|
|||
fmt.Printf("data:%v\n", e)
|
||||
// ANCHOR: commit_offset
|
||||
// commit offset
|
||||
topicPartition, err := consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
||||
_, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
||||
if err != nil {
|
||||
log.Fatal("failed to commit offset, err:", err)
|
||||
log.Fatalln("Failed to commit offset, host : " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println(topicPartition)
|
||||
log.Println("Commit offset manually successfully.")
|
||||
// ANCHOR_END: commit_offset
|
||||
case tmqcommon.Error:
|
||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
||||
log.Fatal("failed to get message, err:", e)
|
||||
log.Fatalln("Failed to poll data, host : " + host + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// commit all offsets
|
||||
topicPartition, err := consumer.Commit()
|
||||
if err != nil {
|
||||
log.Fatal("failed to commit, err:", err)
|
||||
}
|
||||
fmt.Println(topicPartition)
|
||||
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: subscribe
|
||||
|
@ -77,10 +77,10 @@ func main() {
|
|||
// get assignment
|
||||
partitions, err := consumer.Assignment()
|
||||
if err != nil {
|
||||
log.Fatal("failed to get assignment, err:", err)
|
||||
log.Fatal("Failed to get assignment; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("Now assignment:", partitions)
|
||||
for i := 0; i < len(partitions); i++ {
|
||||
fmt.Println(partitions[i])
|
||||
// seek to the beginning
|
||||
err = consumer.Seek(tmqcommon.TopicPartition{
|
||||
Topic: partitions[i].Topic,
|
||||
|
@ -88,40 +88,21 @@ func main() {
|
|||
Offset: 0,
|
||||
}, 0)
|
||||
if err != nil {
|
||||
log.Fatal("failed to seek, err:", err)
|
||||
}
|
||||
}
|
||||
fmt.Println("assignment seek to beginning successfully")
|
||||
// poll data again
|
||||
gotData := false
|
||||
for i := 0; i < 50; i++ {
|
||||
if gotData {
|
||||
break
|
||||
}
|
||||
ev := consumer.Poll(100)
|
||||
if ev != nil {
|
||||
switch e := ev.(type) {
|
||||
case *tmqcommon.DataMessage:
|
||||
// process your data here
|
||||
fmt.Printf("second data polled:%v\n", e)
|
||||
gotData = true
|
||||
case tmqcommon.Error:
|
||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
||||
log.Fatal("failed to get message, err:", e)
|
||||
}
|
||||
log.Fatalln("Seek example failed; ErrMessage: " + err.Error())
|
||||
}
|
||||
}
|
||||
fmt.Println("Assignment seek to beginning successfully")
|
||||
// ANCHOR_END: seek
|
||||
// ANCHOR: close
|
||||
// unsubscribe
|
||||
err = consumer.Unsubscribe()
|
||||
if err != nil {
|
||||
log.Fatal("failed to unsubscribe, err:", err)
|
||||
log.Fatal("Failed to unsubscribe consumer. ErrMessage: " + err.Error())
|
||||
}
|
||||
// close consumer
|
||||
err = consumer.Close()
|
||||
if err != nil {
|
||||
log.Fatal("failed to close consumer, err:", err)
|
||||
log.Fatal("Failed to close consumer. ErrMessage: " + err.Error())
|
||||
}
|
||||
// ANCHOR_END: close
|
||||
<-done
|
||||
|
@ -130,22 +111,22 @@ func main() {
|
|||
func initEnv(conn *sql.DB) {
|
||||
_, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create database, err:", err)
|
||||
log.Fatal("Failed to create database. ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create stable, err:", err)
|
||||
log.Fatal("Failed to create stable. ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create topic, err:", err)
|
||||
log.Fatal("Failed to create topic. ErrMessage: " + err.Error())
|
||||
}
|
||||
go func() {
|
||||
for i := 0; i < 10; i++ {
|
||||
time.Sleep(time.Second)
|
||||
_, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)")
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert data, err:", err)
|
||||
log.Fatal("Failed to insert data. ErrMessage: " + err.Error())
|
||||
}
|
||||
}
|
||||
done <- struct{}{}
|
||||
|
|
|
@ -16,9 +16,10 @@ var done = make(chan struct{})
|
|||
|
||||
func main() {
|
||||
// init env
|
||||
conn, err := sql.Open("taosWS", "root:taosdata@ws(127.0.0.1:6041)/")
|
||||
taosDSN := "root:taosdata@ws(127.0.0.1:6041)/"
|
||||
conn, err := sql.Open("taosWS", taosDSN)
|
||||
if err != nil {
|
||||
log.Fatal("failed to connect TDengine, err:", err)
|
||||
log.Fatalln("Failed to connect to " + taosDSN + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
defer func() {
|
||||
conn.Close()
|
||||
|
@ -26,8 +27,11 @@ func main() {
|
|||
initEnv(conn)
|
||||
// ANCHOR: create_consumer
|
||||
// create consumer
|
||||
wsUrl := "ws://127.0.0.1:6041"
|
||||
groupID := "group1"
|
||||
clientID := "client1"
|
||||
consumer, err := tmq.NewConsumer(&tmqcommon.ConfigMap{
|
||||
"ws.url": "ws://127.0.0.1:6041",
|
||||
"ws.url": wsUrl,
|
||||
"ws.message.channelLen": uint(0),
|
||||
"ws.message.timeout": common.DefaultMessageTimeout,
|
||||
"ws.message.writeWait": common.DefaultWriteWait,
|
||||
|
@ -37,18 +41,21 @@ func main() {
|
|||
"msg.with.table.name": "true",
|
||||
"enable.auto.commit": "true",
|
||||
"auto.commit.interval.ms": "1000",
|
||||
"group.id": "group1",
|
||||
"client.id": "client1",
|
||||
"group.id": groupID,
|
||||
"client.id": clientID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal("failed to create consumer, err:", err)
|
||||
log.Fatalln("Failed to create websocket consumer, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
log.Println("Create consumer successfully, host: " + wsUrl + ", groupId: " + groupID + ", clientId: " + clientID)
|
||||
|
||||
// ANCHOR_END: create_consumer
|
||||
// ANCHOR: subscribe
|
||||
err = consumer.Subscribe("topic_meters", nil)
|
||||
if err != nil {
|
||||
log.Fatal("failed to subscribe, err:", err)
|
||||
log.Fatalln("Failed to subscribe, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
log.Println("Subscribe topics successfully")
|
||||
for i := 0; i < 50; i++ {
|
||||
ev := consumer.Poll(100)
|
||||
if ev != nil {
|
||||
|
@ -58,23 +65,16 @@ func main() {
|
|||
fmt.Printf("data:%v\n", e)
|
||||
// ANCHOR: commit_offset
|
||||
// commit offset
|
||||
topicPartition, err := consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
||||
_, err = consumer.CommitOffsets([]tmqcommon.TopicPartition{e.TopicPartition})
|
||||
if err != nil {
|
||||
log.Fatal("failed to commit offset, err:", err)
|
||||
log.Fatalln("Failed to commit offset, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println(topicPartition)
|
||||
log.Println("Commit offset manually successfully.")
|
||||
// ANCHOR_END: commit_offset
|
||||
case tmqcommon.Error:
|
||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
||||
log.Fatal("failed to get message, err:", e)
|
||||
log.Fatalln("Failed to poll data, host : " + wsUrl + "; ErrMessage: " + err.Error())
|
||||
}
|
||||
// commit all offsets
|
||||
topicPartition, err := consumer.Commit()
|
||||
if err != nil {
|
||||
log.Fatal("failed to commit, err:", err)
|
||||
}
|
||||
fmt.Println(topicPartition)
|
||||
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: subscribe
|
||||
|
@ -82,10 +82,10 @@ func main() {
|
|||
// get assignment
|
||||
partitions, err := consumer.Assignment()
|
||||
if err != nil {
|
||||
log.Fatal("failed to get assignment, err:", err)
|
||||
log.Fatal("Failed to get assignment; ErrMessage: " + err.Error())
|
||||
}
|
||||
fmt.Println("Now assignment:", partitions)
|
||||
for i := 0; i < len(partitions); i++ {
|
||||
fmt.Println(partitions[i])
|
||||
// seek to the beginning
|
||||
err = consumer.Seek(tmqcommon.TopicPartition{
|
||||
Topic: partitions[i].Topic,
|
||||
|
@ -93,40 +93,21 @@ func main() {
|
|||
Offset: 0,
|
||||
}, 0)
|
||||
if err != nil {
|
||||
log.Fatal("failed to seek, err:", err)
|
||||
}
|
||||
}
|
||||
fmt.Println("assignment seek to beginning successfully")
|
||||
// poll data again
|
||||
gotData := false
|
||||
for i := 0; i < 50; i++ {
|
||||
if gotData {
|
||||
break
|
||||
}
|
||||
ev := consumer.Poll(100)
|
||||
if ev != nil {
|
||||
switch e := ev.(type) {
|
||||
case *tmqcommon.DataMessage:
|
||||
// process your data here
|
||||
fmt.Printf("second data polled:%v\n", e)
|
||||
gotData = true
|
||||
case tmqcommon.Error:
|
||||
fmt.Printf("%% Error: %v: %v\n", e.Code(), e)
|
||||
log.Fatal("failed to get message, err:", e)
|
||||
}
|
||||
log.Fatalln("Seek example failed; ErrMessage: " + err.Error())
|
||||
}
|
||||
}
|
||||
fmt.Println("Assignment seek to beginning successfully")
|
||||
// ANCHOR_END: seek
|
||||
// ANCHOR: close
|
||||
// unsubscribe
|
||||
err = consumer.Unsubscribe()
|
||||
if err != nil {
|
||||
log.Fatal("failed to unsubscribe, err:", err)
|
||||
log.Fatal("Failed to unsubscribe consumer. ErrMessage: " + err.Error())
|
||||
}
|
||||
// close consumer
|
||||
err = consumer.Close()
|
||||
if err != nil {
|
||||
log.Fatal("failed to close consumer, err:", err)
|
||||
log.Fatal("Failed to close consumer. ErrMessage: " + err.Error())
|
||||
}
|
||||
// ANCHOR_END: close
|
||||
<-done
|
||||
|
@ -135,22 +116,22 @@ func main() {
|
|||
func initEnv(conn *sql.DB) {
|
||||
_, err := conn.Exec("CREATE DATABASE IF NOT EXISTS power")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create database, err:", err)
|
||||
log.Fatal("Failed to create database. ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = conn.Exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create stable, err:", err)
|
||||
log.Fatal("Failed to create stable. ErrMessage: " + err.Error())
|
||||
}
|
||||
_, err = conn.Exec("CREATE TOPIC IF NOT EXISTS topic_meters AS SELECT ts, current, voltage, phase, groupid, location FROM power.meters")
|
||||
if err != nil {
|
||||
log.Fatal("failed to create topic, err:", err)
|
||||
log.Fatal("Failed to create topic. ErrMessage: " + err.Error())
|
||||
}
|
||||
go func() {
|
||||
for i := 0; i < 10; i++ {
|
||||
time.Sleep(time.Second)
|
||||
_, err = conn.Exec("INSERT INTO power.d1001 USING power.meters TAGS (2, 'California.SanFrancisco') VALUES (NOW , 10.2, 219, 0.32)")
|
||||
if err != nil {
|
||||
log.Fatal("failed to insert data, err:", err)
|
||||
log.Fatal("Failed to insert data. ErrMessage: " + err.Error())
|
||||
}
|
||||
}
|
||||
done <- struct{}{}
|
||||
|
|
|
@ -16,6 +16,7 @@ async function createConnect() {
|
|||
}
|
||||
|
||||
async function test() {
|
||||
let dsn = 'ws://localhost:6041'
|
||||
let wsSql = null;
|
||||
let wsRows = null;
|
||||
let ttl = 0;
|
||||
|
@ -24,9 +25,10 @@ async function test() {
|
|||
await wsSql.schemalessInsert(influxdbData, taos.SchemalessProto.InfluxDBLineProtocol, taos.Precision.MILLI_SECONDS, ttl);
|
||||
await wsSql.schemalessInsert(telnetData, taos.SchemalessProto.OpenTSDBTelnetLineProtocol, taos.Precision.MILLI_SECONDS, ttl);
|
||||
await wsSql.schemalessInsert(jsonData, taos.SchemalessProto.OpenTSDBJsonFormatProtocol, taos.Precision.SECONDS, ttl);
|
||||
console.log("Inserted data with schemaless successfully.")
|
||||
}
|
||||
catch (err) {
|
||||
console.error("Failed to insert data with schemaless, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Failed to insert data with schemaless, url:"+ dsn +", ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
}
|
||||
finally {
|
||||
if (wsRows) {
|
||||
|
|
|
@ -1,34 +1,41 @@
|
|||
// ANCHOR: createConnect
|
||||
const taos = require("@tdengine/websocket");
|
||||
|
||||
let dsn = 'ws://localhost:6041';
|
||||
async function createConnect() {
|
||||
let dsn = 'ws://localhost:6041';
|
||||
let conf = new taos.WSConfig(dsn);
|
||||
conf.setUser('root');
|
||||
conf.setPwd('taosdata');
|
||||
conf.setDb('power');
|
||||
return await taos.sqlConnect(conf);
|
||||
|
||||
try {
|
||||
let conf = new taos.WSConfig(dsn);
|
||||
conf.setUser('root');
|
||||
conf.setPwd('taosdata');
|
||||
conf.setDb('power');
|
||||
conn = await taos.sqlConnect(conf);
|
||||
console.log("Connected to " + dsn + " successfully.");
|
||||
return conn;
|
||||
} catch (err) {
|
||||
console.log("Failed to connect to " + dns + "; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
throw err;
|
||||
}
|
||||
|
||||
}
|
||||
// ANCHOR_END: createConnect
|
||||
|
||||
// ANCHOR: create_db_and_table
|
||||
async function createDbAndTable(wsSql) {
|
||||
async function createDbAndTable() {
|
||||
let wsSql = null;
|
||||
try {
|
||||
wsSql = await createConnect();
|
||||
await wsSql.exec('CREATE DATABASE IF NOT EXISTS POWER ' +
|
||||
'KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;');
|
||||
|
||||
await wsSql.exec('USE power');
|
||||
|
||||
await wsSql.exec('CREATE STABLE IF NOT EXISTS meters ' +
|
||||
// create database
|
||||
await wsSql.exec('CREATE DATABASE IF NOT EXISTS power');
|
||||
console.log("Create database power successfully.");
|
||||
// create table
|
||||
await wsSql.exec('CREATE STABLE IF NOT EXISTS power.meters ' +
|
||||
'(_ts timestamp, current float, voltage int, phase float) ' +
|
||||
'TAGS (location binary(64), groupId int);');
|
||||
|
||||
taosResult = await wsSql.exec('describe meters');
|
||||
console.log(taosResult);
|
||||
console.log("Create stable power.meters successfully");
|
||||
} catch (err) {
|
||||
console.error("Failed to create db and table, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Failed to create db and table, url:" + dns + "; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
} finally {
|
||||
if (wsSql) {
|
||||
await wsSql.close();
|
||||
|
@ -39,8 +46,8 @@ async function createDbAndTable(wsSql) {
|
|||
// ANCHOR_END: create_db_and_table
|
||||
|
||||
// ANCHOR: insertData
|
||||
async function insertData(wsSql) {
|
||||
let wsSql = null;
|
||||
async function insertData() {
|
||||
let wsSql = null
|
||||
try {
|
||||
wsSql = await createConnect();
|
||||
let insertQuery = "INSERT INTO " +
|
||||
|
@ -53,9 +60,9 @@ async function insertData(wsSql) {
|
|||
"VALUES " +
|
||||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||
taosResult = await wsSql.exec(insertQuery);
|
||||
console.log(taosResult);
|
||||
console.log("Successfully inserted " + taosResult.getAffectRows() + " rows to power.meters.");
|
||||
} catch (err) {
|
||||
console.error("Failed to insert data to power.meters, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Failed to insert data to power.meters, url:" + dsn + "; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
} finally {
|
||||
if (wsSql) {
|
||||
await wsSql.close();
|
||||
|
@ -71,15 +78,13 @@ async function queryData() {
|
|||
try {
|
||||
wsSql = await createConnect();
|
||||
wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100');
|
||||
let meta = wsRows.getMeta();
|
||||
console.log("wsRow:meta:=>", meta);
|
||||
while (await wsRows.next()) {
|
||||
let result = wsRows.getData();
|
||||
console.log('queryRes.Scan().then=>', result);
|
||||
let row = wsRows.getData();
|
||||
console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
console.error("Failed to query data from power.meters," + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Failed to query data from power.meters, url:" + dsn + " ; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
}
|
||||
finally {
|
||||
if (wsRows) {
|
||||
|
@ -93,22 +98,20 @@ async function queryData() {
|
|||
// ANCHOR_END: queryData
|
||||
|
||||
// ANCHOR: sqlWithReqid
|
||||
async function sqlWithReqid(wsSql) {
|
||||
|
||||
async function sqlWithReqid() {
|
||||
let wsRows = null;
|
||||
let wsSql = null;
|
||||
let reqId = 1;
|
||||
try {
|
||||
wsSql = await createConnect();
|
||||
wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100', 1);
|
||||
let meta = wsRows.getMeta();
|
||||
console.log("wsRow:meta:=>", meta);
|
||||
wsRows = await wsSql.query('SELECT ts, current, location FROM power.meters limit 100', reqId);
|
||||
while (await wsRows.next()) {
|
||||
let result = wsRows.getData();
|
||||
console.log('queryRes.Scan().then=>', result);
|
||||
let row = wsRows.getData();
|
||||
console.log('ts: ' + row[0] + ', current: ' + row[1] + ', location: ' + row[2]);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
console.error("Failed to execute sql with reqId," + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Failed to execute sql with reqId: " + reqId + ", ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
}
|
||||
finally {
|
||||
if (wsRows) {
|
||||
|
|
|
@ -3,7 +3,8 @@ const taos = require("@tdengine/websocket");
|
|||
let db = 'power';
|
||||
let stable = 'meters';
|
||||
let numOfSubTable = 10;
|
||||
let numOfRow = 10;
|
||||
let numOfRow = 10;
|
||||
let dsn = 'ws://localhost:6041'
|
||||
function getRandomInt(min, max) {
|
||||
min = Math.ceil(min);
|
||||
max = Math.floor(max);
|
||||
|
@ -11,7 +12,7 @@ function getRandomInt(min, max) {
|
|||
}
|
||||
|
||||
async function prepare() {
|
||||
let dsn = 'ws://localhost:6041'
|
||||
|
||||
let conf = new taos.WSConfig(dsn);
|
||||
conf.setUser('root')
|
||||
conf.setPwd('taosdata')
|
||||
|
@ -54,11 +55,11 @@ async function prepare() {
|
|||
await stmt.bind(bindParams);
|
||||
await stmt.batch();
|
||||
await stmt.exec();
|
||||
console.log(`d_bind_${i} insert ` + stmt.getLastAffected() + " rows.");
|
||||
console.log("Successfully inserted " + stmt.getLastAffected() + " to power.meters.");
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
console.error("Failed to insert to table meters using stmt, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Failed to insert to table meters using stmt, url:" + dsn + "ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
}
|
||||
finally {
|
||||
if (stmt) {
|
||||
|
|
|
@ -1,23 +1,28 @@
|
|||
const taos = require("@tdengine/websocket");
|
||||
|
||||
// ANCHOR: create_consumer
|
||||
const db = 'power';
|
||||
const stable = 'meters';
|
||||
const topics = ['power_meters_topic'];
|
||||
|
||||
// ANCHOR: create_consumer
|
||||
const url = 'ws://localhost:6041';
|
||||
async function createConsumer() {
|
||||
|
||||
let groupId = "group1";
|
||||
let clientId = "1";
|
||||
let configMap = new Map([
|
||||
[taos.TMQConstants.GROUP_ID, "group1"],
|
||||
[taos.TMQConstants.CLIENT_ID, 'client1'],
|
||||
[taos.TMQConstants.GROUP_ID, groupId],
|
||||
[taos.TMQConstants.CLIENT_ID, clientId],
|
||||
[taos.TMQConstants.CONNECT_USER, "root"],
|
||||
[taos.TMQConstants.CONNECT_PASS, "taosdata"],
|
||||
[taos.TMQConstants.AUTO_OFFSET_RESET, "latest"],
|
||||
[taos.TMQConstants.WS_URL, 'ws://localhost:6041'],
|
||||
[taos.TMQConstants.WS_URL, url],
|
||||
[taos.TMQConstants.ENABLE_AUTO_COMMIT, 'true'],
|
||||
[taos.TMQConstants.AUTO_COMMIT_INTERVAL_MS, '1000']
|
||||
]);
|
||||
try {
|
||||
return await taos.tmqConnect(configMap);
|
||||
conn = await taos.tmqConnect(configMap);
|
||||
console.log(`Create consumer successfully, host: ${url}, groupId: ${groupId}, clientId: ${clientId}`)
|
||||
return conn;
|
||||
}catch (err) {
|
||||
console.log("Failed to create websocket consumer, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
throw err;
|
||||
|
@ -31,7 +36,7 @@ async function prepare() {
|
|||
conf.setUser('root');
|
||||
conf.setPwd('taosdata');
|
||||
conf.setDb('power');
|
||||
const createDB = `CREATE DATABASE IF NOT EXISTS POWER ${db} KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;`;
|
||||
const createDB = `CREATE DATABASE IF NOT EXISTS ${db}`;
|
||||
const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`;
|
||||
|
||||
let wsSql = await taos.sqlConnect(conf);
|
||||
|
@ -45,7 +50,7 @@ async function prepare() {
|
|||
for (let i = 0; i < 10; i++) {
|
||||
await wsSql.exec(`INSERT INTO d1001 USING ${stable} (location, groupId) TAGS ("California.SanFrancisco", 3) VALUES (NOW, ${10 + i}, ${200 + i}, ${0.32 + i})`);
|
||||
}
|
||||
wsSql.Close();
|
||||
wsSql.close();
|
||||
}
|
||||
|
||||
async function subscribe(consumer) {
|
||||
|
@ -55,12 +60,13 @@ async function subscribe(consumer) {
|
|||
for (let i = 0; i < 50; i++) {
|
||||
let res = await consumer.poll(100);
|
||||
for (let [key, value] of res) {
|
||||
console.log(key, value);
|
||||
console.log(`data: ${key} ${value}`);
|
||||
}
|
||||
consumer.commit();
|
||||
console.log("Commit offset manually successfully.");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to poll data; err.code, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Failed to poll data; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
throw err;
|
||||
}
|
||||
// ANCHOR_END: commit
|
||||
|
@ -74,6 +80,7 @@ async function test() {
|
|||
let consumer = await createConsumer()
|
||||
await subscribe(consumer)
|
||||
await consumer.unsubscribe();
|
||||
console.log("Consumer unsubscribed successfully.");
|
||||
}
|
||||
catch (err) {
|
||||
console.error("Failed to unsubscribe consume, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
|
|
|
@ -18,11 +18,11 @@ async function createConsumer() {
|
|||
]);
|
||||
try {
|
||||
return await taos.tmqConnect(configMap);
|
||||
}catch (err) {
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
throw err;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
// ANCHOR_END: create_consumer
|
||||
|
||||
|
@ -33,7 +33,7 @@ async function prepare() {
|
|||
conf.setDb('power');
|
||||
const createDB = `CREATE DATABASE IF NOT EXISTS POWER ${db} KEEP 3650 DURATION 10 BUFFER 16 WAL_LEVEL 1;`;
|
||||
const createStable = `CREATE STABLE IF NOT EXISTS ${db}.${stable} (ts timestamp, current float, voltage int, phase float) TAGS (location binary(64), groupId int);`;
|
||||
|
||||
|
||||
let wsSql = await taos.sqlConnect(conf);
|
||||
await wsSql.exec(createDB);
|
||||
await wsSql.exec(createStable);
|
||||
|
@ -55,11 +55,11 @@ async function subscribe(consumer) {
|
|||
for (let i = 0; i < 50; i++) {
|
||||
let res = await consumer.poll(100);
|
||||
for (let [key, value] of res) {
|
||||
console.log(key, value);
|
||||
console.log(`data: ${key} ${value}`);
|
||||
}
|
||||
}
|
||||
}catch (err) {
|
||||
console.error("Failed to poll data; err.code, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to poll data; ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
throw err;
|
||||
}
|
||||
|
||||
|
@ -76,22 +76,14 @@ async function test() {
|
|||
let res = new Map();
|
||||
while (res.size == 0) {
|
||||
res = await consumer.poll(100);
|
||||
}
|
||||
}
|
||||
|
||||
let assignment = await consumer.assignment();
|
||||
for (let i in assignment) {
|
||||
console.log("seek before:", assignment[i]);
|
||||
}
|
||||
|
||||
await consumer.seekToBeginning(assignment);
|
||||
assignment = await consumer.assignment();
|
||||
for (let i in assignment) {
|
||||
console.log("seek after:", assignment[i]);
|
||||
}
|
||||
await consumer.unsubscribe();
|
||||
console.log("Assignment seek to beginning successfully");
|
||||
}
|
||||
catch (err) {
|
||||
console.error("seek example failed, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
console.error("Seek example failed, ErrCode:" + err.code + "; ErrMessage: " + err.message);
|
||||
}
|
||||
finally {
|
||||
if (consumer) {
|
||||
|
|
|
@ -14,7 +14,7 @@ def create_connection():
|
|||
)
|
||||
print(f"Connected to {host}:{port} successfully.");
|
||||
except Exception as err:
|
||||
print(f"Failed to connect to {host}:{port} ; Err:{err}")
|
||||
print(f"Failed to connect to {host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -12,7 +12,7 @@ def create_connection():
|
|||
|
||||
print(f"Connected to {url} successfully.");
|
||||
except Exception as err:
|
||||
print(f"Failed to connect to {url} ; Err:{err}")
|
||||
print(f"Failed to connect to {url} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -14,7 +14,7 @@ def create_connection():
|
|||
)
|
||||
print(f"Connected to {host}:{port} successfully.");
|
||||
except Exception as err:
|
||||
print(f"Failed to connect to {host}:{port} ; Err:{err}")
|
||||
print(f"Failed to connect to {host}:{port} ; ErrMessage:{err}")
|
||||
|
||||
return conn
|
||||
# ANCHOR_END: connect
|
||||
|
|
|
@ -9,26 +9,18 @@ try:
|
|||
user="root",
|
||||
password="taosdata")
|
||||
|
||||
db = "power"
|
||||
# create database
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
||||
assert rowsAffected == 0
|
||||
|
||||
# change database. same as execute "USE db"
|
||||
conn.select_db(db)
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||
print(f"Create database power successfully, rowsAffected: {rowsAffected}");
|
||||
|
||||
# create super table
|
||||
rowsAffected = conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||
"CREATE TABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||
)
|
||||
assert rowsAffected == 0
|
||||
|
||||
# create table
|
||||
rowsAffected = conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupid, location) TAGS(0, 'Los Angles')")
|
||||
assert rowsAffected == 0
|
||||
print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}");
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
|
||||
print(f"Failed to create db and table, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -8,22 +8,18 @@ try:
|
|||
password="taosdata",
|
||||
timeout=30)
|
||||
|
||||
db = "power"
|
||||
# create database
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
||||
assert rowsAffected == 0
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||
print(f"Create database power successfully, rowsAffected: {rowsAffected}");
|
||||
|
||||
# create super table
|
||||
rowsAffected = conn.execute(
|
||||
f"CREATE TABLE IF NOT EXISTS `{db}`.`meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||
f"CREATE TABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||
)
|
||||
assert rowsAffected == 0
|
||||
# create table
|
||||
rowsAffected = conn.execute(f"CREATE TABLE IF NOT EXISTS `{db}`.`d0` USING `{db}`.`meters` (groupid, location) TAGS(0, 'Los Angles')")
|
||||
assert rowsAffected == 0
|
||||
print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}");
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to create db and table, url:{url} err:{err}")
|
||||
print(f"Failed to create db and table, url:{url} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -9,27 +9,18 @@ try:
|
|||
host=host,
|
||||
port=port)
|
||||
|
||||
db = "power"
|
||||
# create database
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
||||
assert rowsAffected == 0
|
||||
|
||||
# change database.
|
||||
rowsAffected = conn.execute(f"USE {db}")
|
||||
assert rowsAffected == 0
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||
print(f"Create database power successfully, rowsAffected: {rowsAffected}");
|
||||
|
||||
# create super table
|
||||
rowsAffected = conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||
"CREATE TABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
|
||||
)
|
||||
assert rowsAffected == 0
|
||||
|
||||
# create table
|
||||
rowsAffected = conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupid, location) TAGS(0, 'Los Angles')")
|
||||
assert rowsAffected == 0
|
||||
print(f"Create stable power.meters successfully, rowsAffected: {rowsAffected}");
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
|
||||
print(f"Failed to create db and table, db addrr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -1,12 +1,13 @@
|
|||
import taos
|
||||
|
||||
conn = None
|
||||
|
||||
host = "localhost"
|
||||
port = 6030
|
||||
try:
|
||||
conn = taos.connect(user="root",
|
||||
password="taosdata",
|
||||
host="localhost",
|
||||
port=6030)
|
||||
conn = taos.connect(host=host,
|
||||
port=port,
|
||||
user="root",
|
||||
password="taosdata")
|
||||
|
||||
sql = """
|
||||
INSERT INTO
|
||||
|
@ -17,10 +18,10 @@ try:
|
|||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||
"""
|
||||
affectedRows = conn.execute(sql)
|
||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
||||
print(f"Successfully inserted {affectedRows} rows to power.meters.")
|
||||
|
||||
except Exception as err:
|
||||
print(err)
|
||||
print(f"Failed to insert data to power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
import taosrest
|
||||
|
||||
conn = None
|
||||
|
||||
url="http://localhost:6041"
|
||||
try:
|
||||
conn = taosrest.connect(url="http://localhost:6041",
|
||||
conn = taosrest.connect(url=url,
|
||||
user="root",
|
||||
password="taosdata",
|
||||
timeout=30)
|
||||
|
@ -17,10 +17,10 @@ try:
|
|||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||
"""
|
||||
affectedRows = conn.execute(sql)
|
||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
||||
print(f"Successfully inserted {affectedRows} rows to power.meters.")
|
||||
|
||||
except Exception as err:
|
||||
print(err)
|
||||
print(f"Failed to insert data to power.meters, url:{url} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -1,12 +1,13 @@
|
|||
import taosws
|
||||
|
||||
conn = None
|
||||
|
||||
host="localhost"
|
||||
port=6041
|
||||
try:
|
||||
conn = taosws.connect(user="root",
|
||||
password="taosdata",
|
||||
host="localhost",
|
||||
port=6041)
|
||||
host=host,
|
||||
port=port)
|
||||
|
||||
sql = """
|
||||
INSERT INTO
|
||||
|
@ -17,10 +18,10 @@ try:
|
|||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||
"""
|
||||
affectedRows = conn.execute(sql)
|
||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
||||
print(f"Successfully inserted {affectedRows} rows to power.meters.")
|
||||
|
||||
except Exception as err:
|
||||
print(err)
|
||||
print(f"Failed to insert data to power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -1,26 +1,21 @@
|
|||
import taos
|
||||
|
||||
host="localhost"
|
||||
port=6030
|
||||
conn = None
|
||||
try:
|
||||
conn = taos.connect(host="localhost",
|
||||
port=6030,
|
||||
conn = taos.connect(host=host,
|
||||
port=port,
|
||||
user="root",
|
||||
password="taosdata")
|
||||
|
||||
result = conn.query("SELECT ts, current, location FROM power.meters limit 100")
|
||||
print(result)
|
||||
# Get fields from result
|
||||
fields = result.fields
|
||||
for field in fields:
|
||||
print(field)
|
||||
|
||||
# Get data from result as list of tuple
|
||||
data = result.fetch_all()
|
||||
for row in data:
|
||||
print(row)
|
||||
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to query data from power.meters, err:{err}")
|
||||
print(f"Failed to query data from power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
|
@ -1,15 +1,17 @@
|
|||
import taosrest
|
||||
|
||||
client = None
|
||||
|
||||
url="http://localhost:6041"
|
||||
try:
|
||||
client = taosrest.RestClient(url="http://localhost:6041",
|
||||
client = taosrest.RestClient(url=url,
|
||||
user="root",
|
||||
password="taosdata",
|
||||
timeout=30)
|
||||
|
||||
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", 1)
|
||||
print(result)
|
||||
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100")
|
||||
if result["data"]:
|
||||
for row in result["data"]:
|
||||
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to query data from power.meters, err:{err}")
|
||||
print(f"Failed to query data from power.meters, url:{url} ; ErrMessage:{err}")
|
||||
|
|
|
@ -1,22 +1,20 @@
|
|||
import taosws
|
||||
|
||||
conn = None
|
||||
|
||||
host="localhost"
|
||||
port=6041
|
||||
try:
|
||||
conn = taosws.connect(user="root",
|
||||
password="taosdata",
|
||||
host="localhost",
|
||||
port=6041)
|
||||
host=host,
|
||||
port=port)
|
||||
|
||||
result = conn.query("SELECT ts, current, location FROM power.meters limit 100")
|
||||
num_of_fields = result.field_count
|
||||
print(num_of_fields)
|
||||
|
||||
for row in result:
|
||||
print(row)
|
||||
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to query data from power.meters, err:{err}")
|
||||
print(f"Failed to query data from power.meters, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -1,25 +1,24 @@
|
|||
import taos
|
||||
|
||||
conn = None
|
||||
reqId = 3
|
||||
host="localhost"
|
||||
port=6030
|
||||
try:
|
||||
conn = taos.connect(host="localhost",
|
||||
port=6030,
|
||||
conn = taos.connect(host=host,
|
||||
port=port,
|
||||
user="root",
|
||||
password="taosdata")
|
||||
|
||||
result = conn.query("SELECT ts, current, location FROM power.meters limit 100", 1)
|
||||
# Get fields from result
|
||||
fields = result.fields
|
||||
for field in fields:
|
||||
print(field)
|
||||
|
||||
result = conn.query("SELECT ts, current, location FROM power.meters limit 100", reqId)
|
||||
# Get data from result as list of tuple
|
||||
data = result.fetch_all()
|
||||
for row in data:
|
||||
print(row)
|
||||
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to execute sql with reqId, err:{err}")
|
||||
print(f"Failed to execute sql with reqId:{reqId}, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
conn.close()
|
||||
|
|
|
@ -1,15 +1,18 @@
|
|||
import taosrest
|
||||
|
||||
client = None
|
||||
|
||||
url="http://localhost:6041"
|
||||
reqId = 3
|
||||
try:
|
||||
client = taosrest.RestClient(url="http://localhost:6041",
|
||||
client = taosrest.RestClient(url=url,
|
||||
user="root",
|
||||
password="taosdata",
|
||||
timeout=30)
|
||||
|
||||
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", 1)
|
||||
print(result)
|
||||
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", reqId)
|
||||
if result["data"]:
|
||||
for row in result["data"]:
|
||||
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to execute sql with reqId, err:{err}")
|
||||
print(f"Failed to execute sql with reqId:{reqId}, url:{url} ; ErrMessage:{err}")
|
||||
|
|
|
@ -1,22 +1,24 @@
|
|||
import taosws
|
||||
|
||||
conn = None
|
||||
|
||||
reqId = 3
|
||||
host="localhost"
|
||||
port=6041
|
||||
try:
|
||||
conn = taosws.connect(
|
||||
user="root",
|
||||
password="taosdata",
|
||||
host="localhost",
|
||||
port=6041,
|
||||
host=host,
|
||||
port=port,
|
||||
)
|
||||
|
||||
result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=1)
|
||||
|
||||
result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=3)
|
||||
# Get data from result as list of tuple
|
||||
for row in result:
|
||||
print(row)
|
||||
print(f"ts: {row[0]}, current: {row[1]}, location: {row[2]}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to execute sql with reqId, err:{err}")
|
||||
print(f"Failed to execute sql with reqId:{reqId}, db addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
conn.close()
|
||||
|
|
|
@ -9,13 +9,14 @@ telnetDemo = ["metric_telnet 1707095283260 4 host=host0 interface=eth0"]
|
|||
jsonDemo = [
|
||||
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
|
||||
]
|
||||
|
||||
host = "localhost"
|
||||
port = 6030
|
||||
try:
|
||||
conn = taos.connect(
|
||||
host="localhost",
|
||||
user="root",
|
||||
password="taosdata",
|
||||
port=6030
|
||||
host=host,
|
||||
port=port
|
||||
)
|
||||
|
||||
conn.execute("CREATE DATABASE IF NOT EXISTS power")
|
||||
|
@ -31,8 +32,9 @@ try:
|
|||
conn.schemaless_insert(
|
||||
jsonDemo, taos.SmlProtocol.JSON_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS
|
||||
)
|
||||
print("Inserted data with schemaless successfully.");
|
||||
except Exception as err:
|
||||
print(f"Failed to insert data with schemaless, err:{err}")
|
||||
print(f"Failed to insert data with schemaless, addr: {host}:{port} ErrMessage:{err}")
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
import taosws
|
||||
|
||||
db = "power"
|
||||
def prepare():
|
||||
conn = None
|
||||
try:
|
||||
|
@ -10,11 +9,12 @@ def prepare():
|
|||
port=6041)
|
||||
|
||||
# create database
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
|
||||
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS power")
|
||||
assert rowsAffected == 0
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to create db and table, err:{err}")
|
||||
raise err
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
@ -32,13 +32,14 @@ def schemaless_insert():
|
|||
jsonDemo = [
|
||||
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
|
||||
]
|
||||
|
||||
host = "localhost"
|
||||
port = 6041
|
||||
try:
|
||||
conn = taosws.connect(user="root",
|
||||
password="taosdata",
|
||||
host="localhost",
|
||||
port=6041,
|
||||
database=db)
|
||||
host=host,
|
||||
port=port,
|
||||
database='power')
|
||||
|
||||
conn.schemaless_insert(
|
||||
lines = lineDemo,
|
||||
|
@ -63,10 +64,18 @@ def schemaless_insert():
|
|||
ttl=1,
|
||||
req_id=3,
|
||||
)
|
||||
|
||||
print("Inserted data with schemaless successfully.");
|
||||
except Exception as err:
|
||||
print(f"Failed to insert data with schemaless, err:{err}")
|
||||
|
||||
print(f"Failed to insert data with schemaless, addr: {host}:{port} ErrMessage:{err}")
|
||||
raise err
|
||||
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
prepare()
|
||||
schemaless_insert
|
||||
except Exception as err:
|
||||
print(f"Failed to insert data with schemaless, err:{err}")
|
|
@ -7,13 +7,14 @@ numOfRow = 10
|
|||
|
||||
conn = None
|
||||
stmt = None
|
||||
|
||||
host="localhost",
|
||||
port=6030,
|
||||
try:
|
||||
conn = taos.connect(
|
||||
host="localhost",
|
||||
user="root",
|
||||
password="taosdata",
|
||||
port=6030,
|
||||
host=host,
|
||||
port=port,
|
||||
)
|
||||
|
||||
conn.execute("CREATE DATABASE IF NOT EXISTS power")
|
||||
|
@ -52,10 +53,10 @@ try:
|
|||
params[3].float(phases)
|
||||
stmt.bind_param_batch(params)
|
||||
stmt.execute()
|
||||
print(f"stmt insert successfully.")
|
||||
print(f"Successfully inserted to power.meters.")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to insert to table meters using stmt, error: {err}")
|
||||
print(f"Failed to insert to table meters using stmt, addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if stmt:
|
||||
stmt.close()
|
||||
|
|
|
@ -8,6 +8,8 @@ numOfRow = 10
|
|||
|
||||
conn = None
|
||||
stmt = None
|
||||
host="localhost"
|
||||
port=6041
|
||||
try:
|
||||
conn = taosws.connect(user="root",
|
||||
password="taosdata",
|
||||
|
@ -56,10 +58,10 @@ try:
|
|||
stmt.add_batch()
|
||||
stmt.execute()
|
||||
|
||||
print(f"stmt insert successfully.")
|
||||
print(f"Successfully inserted to power.meters.")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to insert to table meters using stmt, error: {err}")
|
||||
print(f"Failed to insert to table meters using stmt, addr:{host}:{port} ; ErrMessage:{err}")
|
||||
finally:
|
||||
if stmt:
|
||||
stmt.close()
|
||||
|
|
|
@ -37,9 +37,9 @@ def prepareMeta():
|
|||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||
"""
|
||||
affectedRows = conn.execute(sql)
|
||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
||||
print(f"Inserted into {affectedRows} rows to power.meters successfully.")
|
||||
except Exception as err:
|
||||
print(f"prepare meta err:{err}")
|
||||
print(f"Prepare insert data error, ErrMessage:{err}")
|
||||
raise err
|
||||
finally:
|
||||
if conn:
|
||||
|
@ -49,23 +49,28 @@ def prepareMeta():
|
|||
from taos.tmq import Consumer
|
||||
|
||||
def create_consumer():
|
||||
host = "localhost"
|
||||
port = 6030
|
||||
groupId = "group1"
|
||||
clientId = "1"
|
||||
try:
|
||||
consumer = Consumer(
|
||||
{
|
||||
"group.id": "group1",
|
||||
"client.id": "1",
|
||||
"group.id": groupId,
|
||||
"client.id": clientId,
|
||||
"td.connect.user": "root",
|
||||
"td.connect.pass": "taosdata",
|
||||
"enable.auto.commit": "true",
|
||||
"auto.commit.interval.ms": "1000",
|
||||
"auto.offset.reset": "latest",
|
||||
"td.connect.ip": "localhost",
|
||||
"td.connect.port": "6030",
|
||||
"td.connect.ip": host,
|
||||
"td.connect.port": port,
|
||||
}
|
||||
)
|
||||
print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}");
|
||||
return consumer
|
||||
except Exception as err:
|
||||
print(f"Failed to poll data, err:{err}")
|
||||
print(f"Failed to create native consumer, host: {host}:{port} ; ErrMessage:{err}");
|
||||
raise err
|
||||
# ANCHOR_END: create_consumer
|
||||
|
||||
|
@ -75,22 +80,23 @@ def subscribe(consumer):
|
|||
try:
|
||||
# subscribe to the topics
|
||||
consumer.subscribe(["topic_meters"])
|
||||
print("subscribe topics successfully")
|
||||
print("Subscribe topics successfully")
|
||||
for i in range(50):
|
||||
records = consumer.poll(1)
|
||||
if records:
|
||||
err = records.error()
|
||||
if err is not None:
|
||||
print(f"poll data error, {err}")
|
||||
print(f"Poll data error, {err}")
|
||||
raise err
|
||||
|
||||
val = records.value()
|
||||
if val:
|
||||
for block in val:
|
||||
print(block.fetchall())
|
||||
data = block.fetchall()
|
||||
print(f"data: {data}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to poll data, err:{err}")
|
||||
print(f"Failed to poll data, ErrMessage:{err}")
|
||||
raise err
|
||||
|
||||
|
||||
|
@ -104,7 +110,7 @@ def commit_offset(consumer):
|
|||
if records:
|
||||
err = records.error()
|
||||
if err is not None:
|
||||
print(f"poll data error, {err}")
|
||||
print(f"Poll data error, {err}")
|
||||
raise err
|
||||
|
||||
val = records.value()
|
||||
|
@ -114,9 +120,10 @@ def commit_offset(consumer):
|
|||
|
||||
# after processing the data, commit the offset manually
|
||||
consumer.commit(records)
|
||||
print("Commit offset manually successfully.");
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to poll data, err:{err}")
|
||||
print(f"Failed to poll data, ErrMessage:{err}")
|
||||
raise err
|
||||
# ANCHOR_END: commit_offset
|
||||
|
||||
|
@ -127,25 +134,25 @@ def seek_offset(consumer):
|
|||
assignments = consumer.assignment()
|
||||
if assignments:
|
||||
for partition in assignments:
|
||||
print(f"first data polled: {partition.offset}")
|
||||
partition.offset = 0
|
||||
consumer.seek(partition)
|
||||
print(f"assignment seek to beginning successfully");
|
||||
print(f"Assignment seek to beginning successfully");
|
||||
except Exception as err:
|
||||
print(f"seek example failed; err:{err}")
|
||||
print(f"Seek example failed; ErrMessage:{err}")
|
||||
raise err
|
||||
# ANCHOR_END: assignment
|
||||
|
||||
|
||||
# ANCHOR: unsubscribe
|
||||
def unsubscribe(consumer):
|
||||
# ANCHOR: unsubscribe
|
||||
try:
|
||||
consumer.unsubscribe()
|
||||
print("Consumer unsubscribed successfully.");
|
||||
except Exception as err:
|
||||
print(f"Failed to unsubscribe consumer. err:{err}")
|
||||
|
||||
|
||||
# ANCHOR_END: unsubscribe
|
||||
print(f"Failed to unsubscribe consumer. ErrMessage:{err}")
|
||||
finally:
|
||||
if consumer:
|
||||
consumer.close()
|
||||
# ANCHOR_END: unsubscribe
|
||||
|
||||
if __name__ == "__main__":
|
||||
consumer = None
|
||||
|
@ -155,9 +162,10 @@ if __name__ == "__main__":
|
|||
subscribe(consumer)
|
||||
seek_offset(consumer)
|
||||
commit_offset(consumer)
|
||||
unsubscribe(consumer)
|
||||
consumer.unsubscribe()
|
||||
print("Consumer unsubscribed successfully.");
|
||||
except Exception as err:
|
||||
print(f"Failed to stmt consumer. err:{err}")
|
||||
print(f"Failed to stmt consumer. ErrMessage:{err}")
|
||||
finally:
|
||||
if consumer:
|
||||
consumer.close()
|
||||
consumer.unsubscribe()
|
||||
|
||||
|
|
|
@ -48,10 +48,10 @@ def prepareMeta():
|
|||
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
|
||||
"""
|
||||
affectedRows = conn.execute(sql)
|
||||
print(f"inserted into {affectedRows} rows to power.meters successfully.")
|
||||
print(f"Inserted into {affectedRows} rows to power.meters successfully.")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to prepareMeta {err}")
|
||||
print(f"Failed to prepareMeta ErrMessage:{err}")
|
||||
raise err
|
||||
finally:
|
||||
if conn:
|
||||
|
@ -60,20 +60,25 @@ def prepareMeta():
|
|||
|
||||
# ANCHOR: create_consumer
|
||||
def create_consumer():
|
||||
host = "localhost"
|
||||
port = 6041
|
||||
groupId = "group1"
|
||||
clientId = "1"
|
||||
try:
|
||||
consumer = taosws.Consumer(conf={
|
||||
"td.connect.websocket.scheme": "ws",
|
||||
"group.id": "group1",
|
||||
"client.id": "1",
|
||||
"group.id": groupId,
|
||||
"client.id": clientId,
|
||||
"auto.offset.reset": "latest",
|
||||
"td.connect.ip": "localhost",
|
||||
"td.connect.port": "6041",
|
||||
"td.connect.ip": host,
|
||||
"td.connect.port": port,
|
||||
"enable.auto.commit": "true",
|
||||
"auto.commit.interval.ms": "1000",
|
||||
})
|
||||
print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}");
|
||||
return consumer;
|
||||
except Exception as err:
|
||||
print(f"Failed to create websocket consumer, err:{err}");
|
||||
print(f"Failed to create websocket consumer, host: {host}:{port} ; ErrMessage:{err}");
|
||||
raise err
|
||||
|
||||
|
||||
|
@ -90,10 +95,10 @@ def seek_offset(consumer):
|
|||
print(
|
||||
f"vg_id: {assign.vg_id()}, offset: {assign.offset()}, begin: {assign.begin()}, end: {assign.end()}")
|
||||
consumer.seek(topic, assign.vg_id(), assign.begin())
|
||||
print("assignment seek to beginning successfully");
|
||||
print("Assignment seek to beginning successfully");
|
||||
|
||||
except Exception as err:
|
||||
print(f"seek example failed; err:{err}")
|
||||
print(f"Seek example failed; ErrMessage:{err}")
|
||||
raise err
|
||||
# ANCHOR_END: assignment
|
||||
|
||||
|
@ -102,16 +107,16 @@ def seek_offset(consumer):
|
|||
def subscribe(consumer):
|
||||
try:
|
||||
consumer.subscribe([topic])
|
||||
print("subscribe topics successfully")
|
||||
print("Subscribe topics successfully")
|
||||
for i in range(50):
|
||||
records = consumer.poll(timeout=1.0)
|
||||
if records:
|
||||
for block in records:
|
||||
for row in block:
|
||||
print(row)
|
||||
print(f"data: {row}")
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to poll data, err:{err}")
|
||||
print(f"Failed to poll data, ErrMessage:{err}")
|
||||
raise err
|
||||
|
||||
|
||||
|
@ -125,25 +130,30 @@ def commit_offset(consumer):
|
|||
if records:
|
||||
for block in records:
|
||||
for row in block:
|
||||
print(row)
|
||||
print(f"data: {row}")
|
||||
|
||||
# after processing the data, commit the offset manually
|
||||
consumer.commit(records)
|
||||
print("Commit offset manually successfully.");
|
||||
|
||||
except Exception as err:
|
||||
print(f"Failed to poll data, err:{err}")
|
||||
print(f"Failed to poll data, ErrMessage:{err}")
|
||||
raise err
|
||||
|
||||
|
||||
# ANCHOR_END: commit_offset
|
||||
#
|
||||
# ANCHOR: unsubscribe
|
||||
|
||||
def unsubscribe(consumer):
|
||||
# ANCHOR: unsubscribe
|
||||
try:
|
||||
consumer.unsubscribe()
|
||||
print("Consumer unsubscribed successfully.");
|
||||
except Exception as err:
|
||||
print("Failed to unsubscribe consumer. err:{err}")
|
||||
|
||||
print(f"Failed to unsubscribe consumer. ErrMessage:{err}")
|
||||
finally:
|
||||
if consumer:
|
||||
consumer.close()
|
||||
|
||||
# ANCHOR_END: unsubscribe
|
||||
|
||||
|
@ -154,10 +164,8 @@ if __name__ == "__main__":
|
|||
consumer = create_consumer()
|
||||
subscribe(consumer)
|
||||
seek_offset(consumer)
|
||||
commit_offset(consumer)
|
||||
unsubscribe(consumer)
|
||||
commit_offset(consumer)
|
||||
except Exception as err:
|
||||
print(f"Failed to stmt consumer. err:{err}")
|
||||
print(f"Failed to stmt consumer. ErrorMessage:{err}")
|
||||
finally:
|
||||
if consumer:
|
||||
consumer.close()
|
||||
unsubscribe(consumer);
|
|
@ -1,9 +1,17 @@
|
|||
use taos::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Error> {
|
||||
#[allow(unused_variables)]
|
||||
let taos = TaosBuilder::from_dsn("taos://localhost:6030")?.build()?;
|
||||
println!("Connected to localhost with native connection successfully.");
|
||||
Ok(())
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let dsn = "taos://localhost:6030".to_string();
|
||||
|
||||
match TaosBuilder::from_dsn(&dsn)?.build().await {
|
||||
Ok(_taos) => {
|
||||
println!("Connected to {} successfully.", dsn);
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to connect to {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
use taos::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let url = "taos://localhost:6030";
|
||||
|
||||
// ANCHOR: create_db_and_table
|
||||
let taos = TaosBuilder::from_dsn(url)?.build().await?;
|
||||
|
||||
// create database and use it
|
||||
match taos.exec_many([
|
||||
"CREATE DATABASE IF NOT EXISTS power",
|
||||
]).await {
|
||||
Ok(afffected_rows) => println!("Create database power successfully, rowsAffected: {}", afffected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to create database power; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// create super table
|
||||
match taos.exec_many([
|
||||
"CREATE STABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
|
||||
TAGS (`groupid` INT, `location` BINARY(24))",
|
||||
]).await {
|
||||
Ok(afffected_rows) => println!("Create stable power.meters successfully, rowsAffected: {}", afffected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to create stable power.meters; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
// ANCHOR_END: create_db_and_table
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
use taos::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let dsn = "taos://localhost:6030";
|
||||
let builder = TaosBuilder::from_dsn(dsn)?;
|
||||
|
||||
let taos = builder.build().await?;
|
||||
|
||||
|
||||
// ANCHOR: insert_data
|
||||
match taos.exec(r#"INSERT INTO
|
||||
power.d1001 USING power.meters TAGS(2,'California.SanFrancisco')
|
||||
VALUES
|
||||
(NOW + 1a, 10.30000, 219, 0.31000)
|
||||
(NOW + 2a, 12.60000, 218, 0.33000)
|
||||
(NOW + 3a, 12.30000, 221, 0.31000)
|
||||
power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco')
|
||||
VALUES
|
||||
(NOW + 1a, 10.30000, 218, 0.25000) "#).await{
|
||||
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data to power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// ANCHOR_END: insert_data
|
||||
|
||||
Ok(())
|
||||
}
|
|
@ -9,58 +9,33 @@ async fn main() -> anyhow::Result<()> {
|
|||
|
||||
let taos = builder.build().await?;
|
||||
|
||||
// ANCHOR: create_db_and_table
|
||||
let db = "power";
|
||||
// create database
|
||||
taos.exec_many([
|
||||
format!("CREATE DATABASE IF NOT EXISTS `{db}`"),
|
||||
format!("USE `{db}`"),
|
||||
])
|
||||
.await?;
|
||||
println!("Create database power successfully.");
|
||||
|
||||
// create super table
|
||||
taos.exec_many([
|
||||
"CREATE STABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
|
||||
TAGS (`groupid` INT, `location` BINARY(24))",
|
||||
]).await?;
|
||||
println!("Create stable meters successfully.");
|
||||
|
||||
// ANCHOR_END: create_db_and_table
|
||||
|
||||
// ANCHOR: insert_data
|
||||
let inserted = taos.exec(r#"INSERT INTO
|
||||
power.d1001 USING power.meters TAGS(2,'California.SanFrancisco')
|
||||
VALUES
|
||||
(NOW + 1a, 10.30000, 219, 0.31000)
|
||||
(NOW + 2a, 12.60000, 218, 0.33000)
|
||||
(NOW + 3a, 12.30000, 221, 0.31000)
|
||||
power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco')
|
||||
VALUES
|
||||
(NOW + 1a, 10.30000, 218, 0.25000) "#).await?;
|
||||
|
||||
println!("inserted: {} rows to power.meters successfully.", inserted);
|
||||
// ANCHOR_END: insert_data
|
||||
|
||||
// ANCHOR: query_data
|
||||
// query data, make sure the database and table are created before
|
||||
let mut result = taos.query("SELECT ts, current, location FROM power.meters limit 100").await?;
|
||||
|
||||
for field in result.fields() {
|
||||
println!("got field: {}", field.name());
|
||||
}
|
||||
|
||||
let mut rows = result.rows();
|
||||
let mut nrows = 0;
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
for (col, (name, value)) in row.enumerate() {
|
||||
println!(
|
||||
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||
nrows, col, name, value
|
||||
);
|
||||
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await{
|
||||
Ok(mut result) => {
|
||||
for field in result.fields() {
|
||||
println!("got field: {}", field.name());
|
||||
}
|
||||
|
||||
let mut rows = result.rows();
|
||||
let mut nrows = 0;
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
for (col, (name, value)) in row.enumerate() {
|
||||
println!(
|
||||
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||
nrows, col, name, value
|
||||
);
|
||||
}
|
||||
nrows += 1;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to query data from power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
nrows += 1;
|
||||
}
|
||||
|
||||
|
||||
// ANCHOR_END: query_data
|
||||
|
||||
// ANCHOR: query_data_2
|
||||
|
@ -72,30 +47,56 @@ async fn main() -> anyhow::Result<()> {
|
|||
ts: DateTime<Local>,
|
||||
// float to f32
|
||||
current: Option<f32>,
|
||||
// int to i32
|
||||
voltage: Option<i32>,
|
||||
phase: Option<f32>,
|
||||
groupid: i32,
|
||||
// binary/varchar to String
|
||||
location: String,
|
||||
}
|
||||
|
||||
let records: Vec<Record> = taos
|
||||
.query("select ts, current, voltage, phase, groupid, location from power.meters limit 100")
|
||||
.await?
|
||||
.deserialize()
|
||||
.try_collect()
|
||||
.await?;
|
||||
|
||||
dbg!(records);
|
||||
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await {
|
||||
Ok(mut query) => {
|
||||
match query.deserialize::<Record>().try_collect::<Vec<_>>().await {
|
||||
Ok(records) => {
|
||||
dbg!(records);
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to deserialize query results; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to query data from power.meters, url: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: query_data_2
|
||||
|
||||
// ANCHOR: query_with_req_id
|
||||
let result = taos.query_with_req_id("SELECT ts, current, location FROM power.meters limit 1", 1).await?;
|
||||
for field in result.fields() {
|
||||
println!("got field: {}", field.name());
|
||||
|
||||
let req_id :u64 = 3;
|
||||
match taos.query_with_req_id("SELECT ts, current, location FROM power.meters limit 1", req_id).await{
|
||||
Ok(mut result) => {
|
||||
for field in result.fields() {
|
||||
println!("got field: {}", field.name());
|
||||
}
|
||||
|
||||
let mut rows = result.rows();
|
||||
let mut nrows = 0;
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
for (col, (name, value)) in row.enumerate() {
|
||||
println!(
|
||||
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||
nrows, col, name, value
|
||||
);
|
||||
}
|
||||
nrows += 1;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to execute sql with reqId: {}, dsn: {}; ErrMessage: {}", req_id, dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
println!("query with reqId successfully");
|
||||
|
||||
// ANCHOR_END: query_with_req_id
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -11,7 +11,8 @@ use taos::taos_query;
|
|||
async fn main() -> anyhow::Result<()> {
|
||||
std::env::set_var("RUST_LOG", "taos=debug");
|
||||
pretty_env_logger::init();
|
||||
let dsn = "taos://localhost:6030".to_string();
|
||||
let host = "localhost";
|
||||
let dsn = format!("taos://{}:6030", host);
|
||||
log::debug!("dsn: {:?}", &dsn);
|
||||
|
||||
let client = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||
|
@ -39,7 +40,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
.ttl(1000)
|
||||
.req_id(100u64)
|
||||
.build()?;
|
||||
assert_eq!(client.put(&sml_data).await?, ());
|
||||
match client.put(&sml_data).await{
|
||||
Ok(_) => {},
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// SchemalessProtocol::Telnet
|
||||
let data = [
|
||||
|
@ -55,7 +62,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
.ttl(1000)
|
||||
.req_id(200u64)
|
||||
.build()?;
|
||||
assert_eq!(client.put(&sml_data).await?, ());
|
||||
match client.put(&sml_data).await{
|
||||
Ok(_) => {},
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// SchemalessProtocol::Json
|
||||
let data = [
|
||||
|
@ -80,7 +93,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
.ttl(1000)
|
||||
.req_id(300u64)
|
||||
.build()?;
|
||||
assert_eq!(client.put(&sml_data).await?, ());
|
||||
match client.put(&sml_data).await{
|
||||
Ok(_) => {},
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
println!("Inserted data with schemaless successfully.");
|
||||
Ok(())
|
||||
|
|
|
@ -2,12 +2,13 @@ use taos::*;
|
|||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let taos = TaosBuilder::from_dsn("taos://")?.build().await?;
|
||||
let dsn = "taos://localhost:6030";
|
||||
let taos = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||
|
||||
taos.exec("DROP DATABASE IF EXISTS power").await?;
|
||||
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?;
|
||||
taos.exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))").await?;
|
||||
|
||||
let mut stmt = Stmt::init(&taos).await?;
|
||||
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)").await?;
|
||||
|
@ -15,8 +16,8 @@ async fn main() -> anyhow::Result<()> {
|
|||
const NUM_TABLES: usize = 10;
|
||||
const NUM_ROWS: usize = 10;
|
||||
for i in 0..NUM_TABLES {
|
||||
let table_name = format!("d{}", i);
|
||||
let tags = vec![Value::VarChar("California.SanFransico".into()), Value::Int(2)];
|
||||
let table_name = format!("d_bind_{}", i);
|
||||
let tags = vec![Value::Int(i as i32), Value::VarChar(format!("location_{}", i).into())];
|
||||
|
||||
// set table name and tags for the prepared statement.
|
||||
stmt.set_tbname_tags(&table_name, &tags).await?;
|
||||
|
@ -35,9 +36,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
}
|
||||
|
||||
// execute.
|
||||
let rows = stmt.execute().await?;
|
||||
assert_eq!(rows, NUM_TABLES * NUM_ROWS);
|
||||
match stmt.execute().await{
|
||||
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert to table meters using stmt, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
println!("execute stmt insert successfully");
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -12,7 +12,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
use taos_query::prelude::*;
|
||||
// ANCHOR: create_consumer_dsn
|
||||
let dsn = "taos://localhost:6030".to_string();
|
||||
log::info!("dsn: {}", dsn);
|
||||
println!("dsn: {}", dsn);
|
||||
let mut dsn = Dsn::from_str(&dsn)?;
|
||||
// ANCHOR_END: create_consumer_dsn
|
||||
|
||||
|
@ -37,20 +37,36 @@ async fn main() -> anyhow::Result<()> {
|
|||
// ANCHOR_END: create_topic
|
||||
|
||||
// ANCHOR: create_consumer_ac
|
||||
let group_id = "group1".to_string();
|
||||
let client_id = "client1".to_string();
|
||||
dsn.params.insert("auto.offset.reset".to_string(), "latest".to_string());
|
||||
dsn.params.insert("msg.with.table.name".to_string(), "true".to_string());
|
||||
dsn.params.insert("enable.auto.commit".to_string(), "true".to_string());
|
||||
dsn.params.insert("auto.commit.interval.ms".to_string(), "1000".to_string());
|
||||
dsn.params.insert("group.id".to_string(), "group1".to_string());
|
||||
dsn.params.insert("client.id".to_string(), "client1".to_string());
|
||||
dsn.params.insert("group.id".to_string(), group_id.clone());
|
||||
dsn.params.insert("client.id".to_string(), client_id.clone());
|
||||
|
||||
let builder = TmqBuilder::from_dsn(&dsn)?;
|
||||
let mut consumer = builder.build().await?;
|
||||
let mut consumer = match builder.build().await{
|
||||
Ok(consumer) => {
|
||||
println!("Create consumer successfully, dsn: {}, groupId: {}, clientId: {}.", dsn, group_id, client_id);
|
||||
consumer
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to create consumer, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
};
|
||||
// ANCHOR_END: create_consumer_ac
|
||||
|
||||
// ANCHOR: subscribe
|
||||
consumer.subscribe(["topic_meters"]).await?;
|
||||
// ANCHOR_END: subscribe
|
||||
// ANCHOR: consume
|
||||
match consumer.subscribe(["topic_meters"]).await{
|
||||
Ok(_) => println!("Subscribe topics successfully."),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to subscribe topic_meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
|
@ -67,8 +83,6 @@ async fn main() -> anyhow::Result<()> {
|
|||
location: String,
|
||||
}
|
||||
|
||||
// ANCHOR: consume
|
||||
|
||||
consumer
|
||||
.stream()
|
||||
.try_for_each(|(offset, message)| async move {
|
||||
|
@ -85,7 +99,10 @@ async fn main() -> anyhow::Result<()> {
|
|||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
.await.map_err(|e| {
|
||||
eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e);
|
||||
e
|
||||
})?;
|
||||
|
||||
// ANCHOR_END: consume
|
||||
|
||||
|
@ -105,16 +122,25 @@ async fn main() -> anyhow::Result<()> {
|
|||
}
|
||||
}
|
||||
// commit offset manually when you have processed the message.
|
||||
consumer.commit(offset).await?;
|
||||
match consumer.commit(offset).await{
|
||||
Ok(_) => println!("Commit offset manually successfully."),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to commit offset manually, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
.await.map_err(|e| {
|
||||
eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e);
|
||||
e
|
||||
})?;
|
||||
// ANCHOR_END: consumer_commit_manually
|
||||
|
||||
// ANCHOR: assignments
|
||||
|
||||
// ANCHOR: seek_offset
|
||||
let assignments = consumer.assignments().await.unwrap();
|
||||
log::info!("assignments: {:?}", assignments);
|
||||
// ANCHOR_END: assignments
|
||||
println!("Now assignments: {:?}", assignments);
|
||||
|
||||
// seek offset
|
||||
for topic_vec_assignment in assignments {
|
||||
|
@ -125,7 +151,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
let current = assignment.current_offset();
|
||||
let begin = assignment.begin();
|
||||
let end = assignment.end();
|
||||
log::debug!(
|
||||
println!(
|
||||
"topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}",
|
||||
topic,
|
||||
vgroup_id,
|
||||
|
@ -133,26 +159,28 @@ async fn main() -> anyhow::Result<()> {
|
|||
begin,
|
||||
end
|
||||
);
|
||||
// ANCHOR: seek_offset
|
||||
let res = consumer.offset_seek(topic, vgroup_id, end).await;
|
||||
if res.is_err() {
|
||||
log::error!("seek offset error: {:?}", res);
|
||||
let a = consumer.assignments().await.unwrap();
|
||||
log::error!("assignments: {:?}", a);
|
||||
|
||||
match consumer.offset_seek(topic, vgroup_id, begin).await{
|
||||
Ok(_) => (),
|
||||
Err(err) => {
|
||||
eprintln!("Seek example failed; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: seek_offset
|
||||
}
|
||||
|
||||
let topic_assignment = consumer.topic_assignment(topic).await;
|
||||
log::debug!("topic assignment: {:?}", topic_assignment);
|
||||
println!("Topic assignment: {:?}", topic_assignment);
|
||||
}
|
||||
|
||||
println!("Assignment seek to beginning successfully.");
|
||||
// after seek offset
|
||||
let assignments = consumer.assignments().await.unwrap();
|
||||
log::info!("after seek offset assignments: {:?}", assignments);
|
||||
println!("After seek offset assignments: {:?}", assignments);
|
||||
// ANCHOR_END: seek_offset
|
||||
|
||||
// ANCHOR: unsubscribe
|
||||
consumer.unsubscribe().await;
|
||||
println!("Consumer unsubscribed successfully.");
|
||||
// ANCHOR_END: unsubscribe
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
|
|
|
@ -1,9 +1,17 @@
|
|||
use taos::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Error> {
|
||||
#[allow(unused_variables)]
|
||||
let taos = TaosBuilder::from_dsn("taos+ws://localhost:6041")?.build()?;
|
||||
println!("Connected to localhost with websocket connection successfully.");
|
||||
Ok(())
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let dsn = "ws://localhost:6041".to_string();
|
||||
|
||||
match TaosBuilder::from_dsn(&dsn)?.build().await {
|
||||
Ok(_taos) => {
|
||||
println!("Connected to {} successfully.", dsn);
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to connect to {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,35 @@
|
|||
use taos::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let url = "ws://localhost:6041";
|
||||
|
||||
// ANCHOR: create_db_and_table
|
||||
let taos = TaosBuilder::from_dsn(url)?.build().await?;
|
||||
|
||||
// create database and use it
|
||||
match taos.exec_many([
|
||||
"CREATE DATABASE IF NOT EXISTS power",
|
||||
]).await {
|
||||
Ok(afffected_rows) => println!("Create database power successfully, rowsAffected: {}", afffected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to create database power; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// create super table
|
||||
match taos.exec_many([
|
||||
"CREATE STABLE IF NOT EXISTS power.meters (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) \
|
||||
TAGS (`groupid` INT, `location` BINARY(24))",
|
||||
]).await {
|
||||
Ok(afffected_rows) => println!("Create stable power.meters successfully, rowsAffected: {}", afffected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to create stable power.meters; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
// ANCHOR_END: create_db_and_table
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
use taos::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let dsn = "ws://localhost:6041";
|
||||
let builder = TaosBuilder::from_dsn(dsn)?;
|
||||
|
||||
let taos = builder.build().await?;
|
||||
|
||||
|
||||
// ANCHOR: insert_data
|
||||
match taos.exec(r#"INSERT INTO
|
||||
power.d1001 USING power.meters TAGS(2,'California.SanFrancisco')
|
||||
VALUES
|
||||
(NOW + 1a, 10.30000, 219, 0.31000)
|
||||
(NOW + 2a, 12.60000, 218, 0.33000)
|
||||
(NOW + 3a, 12.30000, 221, 0.31000)
|
||||
power.d1002 USING power.meters TAGS(3, 'California.SanFrancisco')
|
||||
VALUES
|
||||
(NOW + 1a, 10.30000, 218, 0.25000) "#).await{
|
||||
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data to power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// ANCHOR_END: insert_data
|
||||
|
||||
Ok(())
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
use taos::*;
|
||||
use chrono::Local;
|
||||
use chrono::DateTime;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let dsn = "ws://localhost:6041";
|
||||
let builder = TaosBuilder::from_dsn(dsn)?;
|
||||
|
||||
let taos = builder.build().await?;
|
||||
|
||||
// ANCHOR: query_data
|
||||
// query data, make sure the database and table are created before
|
||||
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await{
|
||||
Ok(mut result) => {
|
||||
for field in result.fields() {
|
||||
println!("got field: {}", field.name());
|
||||
}
|
||||
|
||||
let mut rows = result.rows();
|
||||
let mut nrows = 0;
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
for (col, (name, value)) in row.enumerate() {
|
||||
println!(
|
||||
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||
nrows, col, name, value
|
||||
);
|
||||
}
|
||||
nrows += 1;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to query data from power.meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ANCHOR_END: query_data
|
||||
|
||||
// ANCHOR: query_data_2
|
||||
// query data, make sure the database and table are created before
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct Record {
|
||||
// deserialize timestamp to chrono::DateTime<Local>
|
||||
ts: DateTime<Local>,
|
||||
// float to f32
|
||||
current: Option<f32>,
|
||||
// binary/varchar to String
|
||||
location: String,
|
||||
}
|
||||
|
||||
match taos.query("SELECT ts, current, location FROM power.meters limit 100").await {
|
||||
Ok(mut query) => {
|
||||
match query.deserialize::<Record>().try_collect::<Vec<_>>().await {
|
||||
Ok(records) => {
|
||||
dbg!(records);
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to deserialize query results; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to query data from power.meters, url: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: query_data_2
|
||||
|
||||
// ANCHOR: query_with_req_id
|
||||
|
||||
let req_id :u64 = 3;
|
||||
match taos.query_with_req_id("SELECT ts, current, location FROM power.meters limit 1", req_id).await{
|
||||
Ok(mut result) => {
|
||||
for field in result.fields() {
|
||||
println!("got field: {}", field.name());
|
||||
}
|
||||
|
||||
let mut rows = result.rows();
|
||||
let mut nrows = 0;
|
||||
while let Some(row) = rows.try_next().await? {
|
||||
for (col, (name, value)) in row.enumerate() {
|
||||
println!(
|
||||
"[{}] got value in col {} (named `{:>8}`): {}",
|
||||
nrows, col, name, value
|
||||
);
|
||||
}
|
||||
nrows += 1;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to execute sql with reqId: {}, dsn: {}; ErrMessage: {}", req_id, dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// ANCHOR_END: query_with_req_id
|
||||
Ok(())
|
||||
}
|
|
@ -11,7 +11,8 @@ use taos::taos_query;
|
|||
async fn main() -> anyhow::Result<()> {
|
||||
std::env::set_var("RUST_LOG", "taos=debug");
|
||||
pretty_env_logger::init();
|
||||
let dsn = "http://localhost:6041/power".to_string();
|
||||
let host = "localhost";
|
||||
let dsn = format!("ws://{}:6041/power", host);
|
||||
log::debug!("dsn: {:?}", &dsn);
|
||||
|
||||
let client = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||
|
@ -30,7 +31,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
.ttl(1000)
|
||||
.req_id(100u64)
|
||||
.build()?;
|
||||
assert_eq!(client.put(&sml_data).await?, ());
|
||||
match client.put(&sml_data).await{
|
||||
Ok(_) => {},
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// SchemalessProtocol::Telnet
|
||||
let data = [
|
||||
|
@ -46,7 +53,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
.ttl(1000)
|
||||
.req_id(200u64)
|
||||
.build()?;
|
||||
assert_eq!(client.put(&sml_data).await?, ());
|
||||
match client.put(&sml_data).await{
|
||||
Ok(_) => {},
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
// SchemalessProtocol::Json
|
||||
let data = [
|
||||
|
@ -71,7 +84,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
.ttl(1000)
|
||||
.req_id(300u64)
|
||||
.build()?;
|
||||
assert_eq!(client.put(&sml_data).await?, ());
|
||||
match client.put(&sml_data).await{
|
||||
Ok(_) => {},
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert data with schemaless, host: {}; ErrMessage: {}", host, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
println!("Inserted data with schemaless successfully.");
|
||||
Ok(())
|
||||
|
|
|
@ -2,12 +2,13 @@ use taos::*;
|
|||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let taos = TaosBuilder::from_dsn("ws://")?.build().await?;
|
||||
let dsn = "ws://";
|
||||
let taos = TaosBuilder::from_dsn(dsn)?.build().await?;
|
||||
|
||||
taos.exec("DROP DATABASE IF EXISTS power").await?;
|
||||
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?;
|
||||
taos.exec("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))").await?;
|
||||
|
||||
let mut stmt = Stmt::init(&taos).await?;
|
||||
stmt.prepare("INSERT INTO ? USING meters TAGS(?, ?) VALUES(?, ?, ?, ?)").await?;
|
||||
|
@ -15,8 +16,8 @@ async fn main() -> anyhow::Result<()> {
|
|||
const NUM_TABLES: usize = 10;
|
||||
const NUM_ROWS: usize = 10;
|
||||
for i in 0..NUM_TABLES {
|
||||
let table_name = format!("d{}", i);
|
||||
let tags = vec![Value::VarChar("California.SanFransico".into()), Value::Int(2)];
|
||||
let table_name = format!("d_bind_{}", i);
|
||||
let tags = vec![Value::Int(i as i32), Value::VarChar(format!("location_{}", i).into())];
|
||||
|
||||
// set table name and tags for the prepared statement.
|
||||
stmt.set_tbname_tags(&table_name, &tags).await?;
|
||||
|
@ -35,9 +36,13 @@ async fn main() -> anyhow::Result<()> {
|
|||
}
|
||||
|
||||
// execute.
|
||||
let rows = stmt.execute().await?;
|
||||
assert_eq!(rows, NUM_TABLES * NUM_ROWS);
|
||||
|
||||
println!("execute stmt insert successfully");
|
||||
match stmt.execute().await{
|
||||
Ok(affected_rows) => println!("Successfully inserted {} rows to power.meters.", affected_rows),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to insert to table meters using stmt, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -12,7 +12,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
use taos_query::prelude::*;
|
||||
// ANCHOR: create_consumer_dsn
|
||||
let dsn = "ws://localhost:6041".to_string();
|
||||
log::info!("dsn: {}", dsn);
|
||||
println!("dsn: {}", dsn);
|
||||
let mut dsn = Dsn::from_str(&dsn)?;
|
||||
// ANCHOR_END: create_consumer_dsn
|
||||
|
||||
|
@ -37,20 +37,36 @@ async fn main() -> anyhow::Result<()> {
|
|||
// ANCHOR_END: create_topic
|
||||
|
||||
// ANCHOR: create_consumer_ac
|
||||
let group_id = "group1".to_string();
|
||||
let client_id = "client1".to_string();
|
||||
dsn.params.insert("auto.offset.reset".to_string(), "latest".to_string());
|
||||
dsn.params.insert("msg.with.table.name".to_string(), "true".to_string());
|
||||
dsn.params.insert("enable.auto.commit".to_string(), "true".to_string());
|
||||
dsn.params.insert("auto.commit.interval.ms".to_string(), "1000".to_string());
|
||||
dsn.params.insert("group.id".to_string(), "group1".to_string());
|
||||
dsn.params.insert("client.id".to_string(), "client1".to_string());
|
||||
dsn.params.insert("group.id".to_string(), group_id.clone());
|
||||
dsn.params.insert("client.id".to_string(), client_id.clone());
|
||||
|
||||
let builder = TmqBuilder::from_dsn(&dsn)?;
|
||||
let mut consumer = builder.build().await?;
|
||||
let mut consumer = match builder.build().await{
|
||||
Ok(consumer) => {
|
||||
println!("Create consumer successfully, dsn: {}, groupId: {}, clientId: {}.", dsn, group_id, client_id);
|
||||
consumer
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Failed to create consumer, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
};
|
||||
// ANCHOR_END: create_consumer_ac
|
||||
|
||||
// ANCHOR: subscribe
|
||||
consumer.subscribe(["topic_meters"]).await?;
|
||||
// ANCHOR_END: subscribe
|
||||
// ANCHOR: consume
|
||||
match consumer.subscribe(["topic_meters"]).await{
|
||||
Ok(_) => println!("Subscribe topics successfully."),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to subscribe topic_meters, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
|
@ -67,8 +83,6 @@ async fn main() -> anyhow::Result<()> {
|
|||
location: String,
|
||||
}
|
||||
|
||||
// ANCHOR: consume
|
||||
|
||||
consumer
|
||||
.stream()
|
||||
.try_for_each(|(offset, message)| async move {
|
||||
|
@ -85,7 +99,10 @@ async fn main() -> anyhow::Result<()> {
|
|||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
.await.map_err(|e| {
|
||||
eprintln!("Failed to poll data; ErrMessage: {:?}", e);
|
||||
e
|
||||
})?;
|
||||
|
||||
// ANCHOR_END: consume
|
||||
|
||||
|
@ -105,16 +122,25 @@ async fn main() -> anyhow::Result<()> {
|
|||
}
|
||||
}
|
||||
// commit offset manually when you have processed the message.
|
||||
consumer.commit(offset).await?;
|
||||
match consumer.commit(offset).await{
|
||||
Ok(_) => println!("Commit offset manually successfully."),
|
||||
Err(err) => {
|
||||
eprintln!("Failed to commit offset manually, dsn: {}; ErrMessage: {}", dsn, err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
.await.map_err(|e| {
|
||||
eprintln!("Failed to execute consumer functions. ErrMessage: {:?}", e);
|
||||
e
|
||||
})?;
|
||||
// ANCHOR_END: consumer_commit_manually
|
||||
|
||||
// ANCHOR: assignments
|
||||
|
||||
// ANCHOR: seek_offset
|
||||
let assignments = consumer.assignments().await.unwrap();
|
||||
log::info!("assignments: {:?}", assignments);
|
||||
// ANCHOR_END: assignments
|
||||
println!("assignments: {:?}", assignments);
|
||||
|
||||
// seek offset
|
||||
for topic_vec_assignment in assignments {
|
||||
|
@ -125,7 +151,7 @@ async fn main() -> anyhow::Result<()> {
|
|||
let current = assignment.current_offset();
|
||||
let begin = assignment.begin();
|
||||
let end = assignment.end();
|
||||
log::debug!(
|
||||
println!(
|
||||
"topic: {}, vgroup_id: {}, current offset: {} begin {}, end: {}",
|
||||
topic,
|
||||
vgroup_id,
|
||||
|
@ -133,26 +159,28 @@ async fn main() -> anyhow::Result<()> {
|
|||
begin,
|
||||
end
|
||||
);
|
||||
// ANCHOR: seek_offset
|
||||
let res = consumer.offset_seek(topic, vgroup_id, end).await;
|
||||
if res.is_err() {
|
||||
log::error!("seek offset error: {:?}", res);
|
||||
let a = consumer.assignments().await.unwrap();
|
||||
log::error!("assignments: {:?}", a);
|
||||
|
||||
match consumer.offset_seek(topic, vgroup_id, begin).await{
|
||||
Ok(_) => (),
|
||||
Err(err) => {
|
||||
eprintln!("seek example failed; ErrMessage: {}", err);
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: seek_offset
|
||||
}
|
||||
|
||||
let topic_assignment = consumer.topic_assignment(topic).await;
|
||||
log::debug!("topic assignment: {:?}", topic_assignment);
|
||||
println!("topic assignment: {:?}", topic_assignment);
|
||||
}
|
||||
|
||||
println!("Assignment seek to beginning successfully.");
|
||||
// after seek offset
|
||||
let assignments = consumer.assignments().await.unwrap();
|
||||
log::info!("after seek offset assignments: {:?}", assignments);
|
||||
println!("After seek offset assignments: {:?}", assignments);
|
||||
// ANCHOR_END: seek_offset
|
||||
|
||||
// ANCHOR: unsubscribe
|
||||
consumer.unsubscribe().await;
|
||||
println!("Consumer unsubscribed successfully.");
|
||||
// ANCHOR_END: unsubscribe
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
|
|
|
@ -53,7 +53,7 @@ REST API:直接调用 `taosadapter` 提供的 REST API 接口,进行数据
|
|||
<TabItem label="Rust" value="rust">
|
||||
|
||||
```rust
|
||||
{{#include docs/examples/rust/nativeexample/examples/query.rs:create_db_and_table}}
|
||||
{{#include docs/examples/rust/nativeexample/examples/createdb.rs:create_db_and_table}}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
|
@ -129,7 +129,7 @@ NOW 为系统内部函数,默认为客户端所在计算机当前时间。 NOW
|
|||
<TabItem label="Rust" value="rust">
|
||||
|
||||
```rust
|
||||
{{#include docs/examples/rust/nativeexample/examples/query.rs:insert_data}}
|
||||
{{#include docs/examples/rust/nativeexample/examples/insert.rs:insert_data}}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
|
|
|
@ -37,13 +37,15 @@ public class ConsumerLoopFull {
|
|||
config.setProperty("value.deserializer.encoding", "UTF-8");
|
||||
|
||||
try {
|
||||
return new TaosConsumer<>(config);
|
||||
TaosConsumer<ResultBean> consumer= new TaosConsumer<>(config);
|
||||
System.out.println("Create consumer successfully, host: " + config.getProperty("bootstrap.servers") + ", groupId: " + config.getProperty("group.id") + ", clientId: " + config.getProperty("client.id"));
|
||||
return consumer;
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to create native consumer, host: " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to create consumer", ex);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers")
|
||||
System.out.println("Failed to create native consumer, host: " + config.getProperty("bootstrap.servers")
|
||||
+ "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to create consumer", ex);
|
||||
}
|
||||
|
@ -57,7 +59,7 @@ public class ConsumerLoopFull {
|
|||
|
||||
// subscribe to the topics
|
||||
consumer.subscribe(topics);
|
||||
System.out.println("subscribe topics successfully");
|
||||
System.out.println("Subscribe topics successfully.");
|
||||
for (int i = 0; i < 50; i++) {
|
||||
// poll data
|
||||
ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
|
||||
|
@ -70,10 +72,10 @@ public class ConsumerLoopFull {
|
|||
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to poll data; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to poll data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to poll data", ex);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Failed to poll data; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to poll data, ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to poll data", ex);
|
||||
}
|
||||
// ANCHOR_END: poll_data_code_piece
|
||||
|
@ -86,9 +88,9 @@ public class ConsumerLoopFull {
|
|||
|
||||
// subscribe to the topics
|
||||
consumer.subscribe(topics);
|
||||
System.out.println("subscribe topics successfully");
|
||||
System.out.println("Subscribe topics successfully.");
|
||||
Set<TopicPartition> assignment = consumer.assignment();
|
||||
System.out.println("now assignment: " + JSON.toJSONString(assignment));
|
||||
System.out.println("Now assignment: " + JSON.toJSONString(assignment));
|
||||
|
||||
ConsumerRecords<ResultBean> records = ConsumerRecords.emptyRecord();
|
||||
// make sure we have got some data
|
||||
|
@ -97,14 +99,13 @@ public class ConsumerLoopFull {
|
|||
}
|
||||
|
||||
consumer.seekToBeginning(assignment);
|
||||
System.out.println("assignment seek to beginning successfully");
|
||||
System.out.println("beginning assignment: " + JSON.toJSONString(assignment));
|
||||
System.out.println("Assignment seek to beginning successfully.");
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("seek example failed", ex);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("seek example failed; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Seek example failed; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("seek example failed", ex);
|
||||
}
|
||||
// ANCHOR_END: consumer_seek
|
||||
|
@ -127,6 +128,7 @@ public class ConsumerLoopFull {
|
|||
if (!records.isEmpty()) {
|
||||
// after processing the data, commit the offset manually
|
||||
consumer.commitSync();
|
||||
System.out.println("Commit offset manually successfully.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
|
@ -147,6 +149,7 @@ public class ConsumerLoopFull {
|
|||
try {
|
||||
// unsubscribe the consumer
|
||||
consumer.unsubscribe();
|
||||
System.out.println("Consumer unsubscribed successfully.");
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
|
@ -158,6 +161,7 @@ public class ConsumerLoopFull {
|
|||
finally {
|
||||
// close the consumer
|
||||
consumer.close();
|
||||
System.out.println("Consumer closed successfully.");
|
||||
}
|
||||
// ANCHOR_END: unsubscribe_data_code_piece
|
||||
}
|
||||
|
@ -313,22 +317,22 @@ public class ConsumerLoopFull {
|
|||
System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
System.out.println("pollDataExample executed successfully");
|
||||
System.out.println("pollDataExample executed successfully.");
|
||||
});
|
||||
|
||||
try {
|
||||
TaosConsumer<ResultBean> consumer = getConsumer();
|
||||
|
||||
pollExample(consumer);
|
||||
System.out.println("pollExample executed successfully");
|
||||
System.out.println("pollExample executed successfully.");
|
||||
consumer.unsubscribe();
|
||||
|
||||
seekExample(consumer);
|
||||
System.out.println("seekExample executed successfully");
|
||||
System.out.println("seekExample executed successfully.");
|
||||
consumer.unsubscribe();
|
||||
|
||||
commitExample(consumer);
|
||||
System.out.println("commitExample executed successfully");
|
||||
System.out.println("commitExample executed successfully.");
|
||||
consumer.unsubscribe();
|
||||
|
||||
unsubscribeExample(consumer);
|
||||
|
|
|
@ -30,17 +30,11 @@ public class JdbcCreatDBDemo {
|
|||
// create database
|
||||
int rowsAffected = stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS power");
|
||||
// you can check rowsAffected here
|
||||
assert rowsAffected == 0;
|
||||
|
||||
// use database
|
||||
rowsAffected = stmt.executeUpdate("USE power");
|
||||
// you can check rowsAffected here
|
||||
assert rowsAffected == 0;
|
||||
|
||||
System.out.println("Create database power successfully, rowsAffected: " + rowsAffected);
|
||||
// create table
|
||||
rowsAffected = stmt.executeUpdate("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||
rowsAffected = stmt.executeUpdate("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||
// you can check rowsAffected here
|
||||
assert rowsAffected == 0;
|
||||
System.out.println("Create stable power.meters successfully, rowsAffected: " + rowsAffected);
|
||||
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
|
|
|
@ -39,7 +39,7 @@ public class JdbcInsertDataDemo {
|
|||
"(NOW + 1a, 10.30000, 218, 0.25000) ";
|
||||
int affectedRows = stmt.executeUpdate(insertQuery);
|
||||
// you can check affectedRows here
|
||||
System.out.println("inserted into " + affectedRows + " rows to power.meters successfully.");
|
||||
System.out.println("Successfully inserted " + affectedRows + " rows to power.meters.");
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to insert data to power.meters, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
|
|
|
@ -25,22 +25,32 @@ public class JdbcReqIdDemo {
|
|||
System.out.println("get connection starting...");
|
||||
|
||||
// ANCHOR: with_reqid
|
||||
long reqId = 3L;
|
||||
try (Connection connection = DriverManager.getConnection(jdbcUrl, properties);
|
||||
// Create a statement that allows specifying a request ID
|
||||
AbstractStatement aStmt = (AbstractStatement) connection.createStatement()) {
|
||||
|
||||
try (ResultSet rs = aStmt.executeQuery("SELECT ts, current, location FROM power.meters limit 1", 3L)) {
|
||||
while (rs.next()) {
|
||||
Timestamp timestamp = rs.getTimestamp(1);
|
||||
System.out.println("timestamp = " + timestamp);
|
||||
try (ResultSet resultSet = aStmt.executeQuery("SELECT ts, current, location FROM power.meters limit 1", reqId)) {
|
||||
Timestamp ts;
|
||||
float current;
|
||||
String location;
|
||||
while (resultSet.next()) {
|
||||
ts = resultSet.getTimestamp(1);
|
||||
current = resultSet.getFloat(2);
|
||||
// we recommend using the column name to get the value
|
||||
location = resultSet.getString("location");
|
||||
|
||||
// you can check data here
|
||||
System.out.printf("ts: %s, current: %f, location: %s %n", ts, current, location);
|
||||
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to execute sql with reqId, url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to execute sql with reqId: " + reqId + ", url:" + jdbcUrl + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
throw ex;
|
||||
} catch (Exception ex){
|
||||
System.out.println("Failed to execute sql with reqId, url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to execute sql with reqId: " + reqId + ", url:" + jdbcUrl + "; ErrMessage: " + ex.getMessage());
|
||||
throw ex;
|
||||
}
|
||||
// ANCHOR_END: with_reqid
|
||||
|
|
|
@ -24,7 +24,7 @@ public class ParameterBindingBasicDemo {
|
|||
|
||||
init(conn);
|
||||
|
||||
String sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)";
|
||||
String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)";
|
||||
|
||||
try (TSDBPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSDBPreparedStatement.class)) {
|
||||
|
||||
|
@ -65,6 +65,8 @@ public class ParameterBindingBasicDemo {
|
|||
}
|
||||
// execute column
|
||||
pstmt.columnDataExecuteBatch();
|
||||
// you can check exeResult here
|
||||
System.out.println("Successfully inserted " + (numOfSubTable * numOfRow) + " rows to power.meters.");
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
|
|
|
@ -21,7 +21,7 @@ public class WSParameterBindingBasicDemo {
|
|||
try (Connection conn = DriverManager.getConnection(jdbcUrl, "root", "taosdata")) {
|
||||
init(conn);
|
||||
|
||||
String sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)";
|
||||
String sql = "INSERT INTO ? USING power.meters TAGS(?,?) VALUES (?,?,?,?)";
|
||||
|
||||
try (TSWSPreparedStatement pstmt = conn.prepareStatement(sql).unwrap(TSWSPreparedStatement.class)) {
|
||||
|
||||
|
@ -44,7 +44,7 @@ public class WSParameterBindingBasicDemo {
|
|||
}
|
||||
int [] exeResult = pstmt.executeBatch();
|
||||
// you can check exeResult here
|
||||
System.out.println("insert " + exeResult.length + " rows.");
|
||||
System.out.println("Successfully inserted " + exeResult.length + " rows to power.meters.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
|
@ -61,7 +61,7 @@ public class WSParameterBindingBasicDemo {
|
|||
try (Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("CREATE DATABASE IF NOT EXISTS power");
|
||||
stmt.execute("USE power");
|
||||
stmt.execute("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||
stmt.execute("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,6 +10,7 @@ import java.util.*;
|
|||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
// ANCHOR: consumer_demo
|
||||
public class WsConsumerLoopFull {
|
||||
|
@ -34,13 +35,15 @@ public class WsConsumerLoopFull {
|
|||
config.setProperty("value.deserializer.encoding", "UTF-8");
|
||||
|
||||
try {
|
||||
return new TaosConsumer<>(config);
|
||||
TaosConsumer<ResultBean> consumer= new TaosConsumer<>(config);
|
||||
System.out.println("Create consumer successfully, host: " + config.getProperty("bootstrap.servers") + ", groupId: " + config.getProperty("group.id") + ", clientId: " + config.getProperty("client.id"));
|
||||
return consumer;
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to create websocket consumer, host: " + config.getProperty("bootstrap.servers") + "; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to create consumer", ex);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Failed to create websocket consumer, host : " + config.getProperty("bootstrap.servers")
|
||||
System.out.println("Failed to create websocket consumer, host: " + config.getProperty("bootstrap.servers")
|
||||
+ "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to create consumer", ex);
|
||||
}
|
||||
|
@ -54,7 +57,7 @@ public class WsConsumerLoopFull {
|
|||
|
||||
// subscribe to the topics
|
||||
consumer.subscribe(topics);
|
||||
System.out.println("subscribe topics successfully");
|
||||
System.out.println("Subscribe topics successfully.");
|
||||
for (int i = 0; i < 50; i++) {
|
||||
// poll data
|
||||
ConsumerRecords<ResultBean> records = consumer.poll(Duration.ofMillis(100));
|
||||
|
@ -67,10 +70,10 @@ public class WsConsumerLoopFull {
|
|||
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to poll data; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to poll data, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to poll data", ex);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Failed to poll data; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Failed to poll data, ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("Failed to poll data", ex);
|
||||
}
|
||||
// ANCHOR_END: poll_data_code_piece
|
||||
|
@ -83,9 +86,9 @@ public class WsConsumerLoopFull {
|
|||
|
||||
// subscribe to the topics
|
||||
consumer.subscribe(topics);
|
||||
System.out.println("subscribe topics successfully");
|
||||
System.out.println("Subscribe topics successfully.");
|
||||
Set<TopicPartition> assignment = consumer.assignment();
|
||||
System.out.println("now assignment: " + JSON.toJSONString(assignment));
|
||||
System.out.println("Now assignment: " + JSON.toJSONString(assignment));
|
||||
|
||||
ConsumerRecords<ResultBean> records = ConsumerRecords.emptyRecord();
|
||||
// make sure we have got some data
|
||||
|
@ -94,14 +97,13 @@ public class WsConsumerLoopFull {
|
|||
}
|
||||
|
||||
consumer.seekToBeginning(assignment);
|
||||
System.out.println("assignment seek to beginning successfully");
|
||||
System.out.println("beginning assignment: " + JSON.toJSONString(assignment));
|
||||
System.out.println("Assignment seek to beginning successfully.");
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Seek example failed; ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("seek example failed", ex);
|
||||
} catch (Exception ex) {
|
||||
System.out.println("seek example failed; ErrMessage: " + ex.getMessage());
|
||||
System.out.println("Seek example failed; ErrMessage: " + ex.getMessage());
|
||||
throw new SQLException("seek example failed", ex);
|
||||
}
|
||||
// ANCHOR_END: consumer_seek
|
||||
|
@ -124,6 +126,7 @@ public class WsConsumerLoopFull {
|
|||
if (!records.isEmpty()) {
|
||||
// after processing the data, commit the offset manually
|
||||
consumer.commitSync();
|
||||
System.out.println("Commit offset manually successfully.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
|
@ -144,6 +147,7 @@ public class WsConsumerLoopFull {
|
|||
try {
|
||||
// unsubscribe the consumer
|
||||
consumer.unsubscribe();
|
||||
System.out.println("Consumer unsubscribed successfully.");
|
||||
} catch (SQLException ex) {
|
||||
// handle any errors, please refer to the JDBC specifications for detailed exceptions info
|
||||
System.out.println("Failed to unsubscribe consumer. ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
|
@ -155,6 +159,7 @@ public class WsConsumerLoopFull {
|
|||
finally {
|
||||
// close the consumer
|
||||
consumer.close();
|
||||
System.out.println("Consumer closed successfully.");
|
||||
}
|
||||
// ANCHOR_END: unsubscribe_data_code_piece
|
||||
}
|
||||
|
@ -310,26 +315,26 @@ public class WsConsumerLoopFull {
|
|||
System.out.println("Failed to prepare data, ErrMessage: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
System.out.println("pollDataExample executed successfully");
|
||||
System.out.println("pollDataExample executed successfully.");
|
||||
});
|
||||
|
||||
try {
|
||||
TaosConsumer<ResultBean> consumer = getConsumer();
|
||||
|
||||
pollExample(consumer);
|
||||
System.out.println("pollExample executed successfully");
|
||||
System.out.println("pollExample executed successfully.");
|
||||
consumer.unsubscribe();
|
||||
|
||||
seekExample(consumer);
|
||||
System.out.println("seekExample executed successfully");
|
||||
System.out.println("seekExample executed successfully.");
|
||||
consumer.unsubscribe();
|
||||
|
||||
commitExample(consumer);
|
||||
System.out.println("commitExample executed successfully");
|
||||
System.out.println("commitExample executed successfully.");
|
||||
consumer.unsubscribe();
|
||||
|
||||
unsubscribeExample(consumer);
|
||||
System.out.println("unsubscribeExample executed successfully");
|
||||
System.out.println("unsubscribeExample executed successfully.");
|
||||
|
||||
} catch (SQLException ex) {
|
||||
System.out.println("Failed to poll data from topic_meters, ErrCode:" + ex.getErrorCode() + "; ErrMessage: " + ex.getMessage());
|
||||
|
|
|
@ -2,6 +2,21 @@
|
|||
|
||||
set -e
|
||||
|
||||
check_transactions() {
|
||||
for i in {1..30}
|
||||
do
|
||||
output=$(taos -s "show transactions;")
|
||||
if [[ $output == *"Query OK, 0 row(s)"* ]]; then
|
||||
echo "Success: No transactions are in progress."
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo "Error: Transactions are still in progress after 30 attempts."
|
||||
return 1
|
||||
}
|
||||
|
||||
taosd >>/dev/null 2>&1 &
|
||||
taosadapter >>/dev/null 2>&1 &
|
||||
sleep 1
|
||||
|
@ -19,60 +34,61 @@ taos -s "drop database if exists power"
|
|||
go run ./sqlquery/main.go
|
||||
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./queryreqid/main.go
|
||||
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./stmt/native/main.go
|
||||
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./stmt/ws/main.go
|
||||
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
sleep 3
|
||||
go run ./schemaless/native/main.go
|
||||
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./schemaless/ws/main.go
|
||||
|
||||
taos -s "drop topic if exists topic_meters"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./tmq/native/main.go
|
||||
|
||||
taos -s "drop topic if exists topic_meters"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./tmq/ws/main.go
|
||||
|
||||
|
||||
taos -s "drop database if exists test"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./insert/json/main.go
|
||||
taos -s "drop database if exists test"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./insert/line/main.go
|
||||
taos -s "drop topic if exists topic_meters"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./insert/sql/main.go
|
||||
taos -s "drop database if exists power"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./insert/stmt/main.go
|
||||
taos -s "drop database if exists test"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./insert/telnet/main.go
|
||||
|
||||
go run ./query/sync/main.go
|
||||
|
||||
taos -s "drop topic if exists example_tmq_topic"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
taos -s "drop database if exists example_tmq"
|
||||
sleep 1
|
||||
check_transactions || exit 1
|
||||
go run ./sub/main.go
|
||||
|
|
Loading…
Reference in New Issue