taosSqlCgo.go 2.3 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package taosSql

/*
P
plum-lihui 已提交
18 19
#cgo CFLAGS : -I/usr/include
#cgo LDFLAGS: -L/usr/lib -ltaos
H
hzcheng 已提交
20 21 22 23 24 25 26 27 28 29 30 31
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <taos.h>
*/
import "C"

import (
	"errors"
	"unsafe"
)

32
func (mc *taosConn) taosConnect(ip, user, pass, db string, port int) (taos unsafe.Pointer, err error) {
H
hzcheng 已提交
33 34
	cuser := C.CString(user)
	cpass := C.CString(pass)
35 36
	cip := C.CString(ip)
	cdb := C.CString(db)
H
hzcheng 已提交
37 38 39 40 41
	defer C.free(unsafe.Pointer(cip))
	defer C.free(unsafe.Pointer(cuser))
	defer C.free(unsafe.Pointer(cpass))
	defer C.free(unsafe.Pointer(cdb))

42
	taosObj := C.taos_connect(cip, cuser, cpass, cdb, (C.ushort)(port))
43 44 45
	if taosObj == nil {
		return nil, errors.New("taos_connect() fail!")
	}
H
hzcheng 已提交
46

47 48
	return (unsafe.Pointer)(taosObj), nil
}
H
hzcheng 已提交
49 50

func (mc *taosConn) taosQuery(sqlstr string) (int, error) {
51
	//taosLog.Printf("taosQuery() input sql:%s\n", sqlstr)
H
hzcheng 已提交
52

53
	csqlstr := C.CString(sqlstr)
H
hzcheng 已提交
54
	defer C.free(unsafe.Pointer(csqlstr))
55
	code := int(C.taos_query(mc.taos, csqlstr))
H
hzcheng 已提交
56

57 58 59 60 61 62 63
	if 0 != code {
		mc.taos_error()
		errStr := C.GoString(C.taos_errstr(mc.taos))
		taosLog.Println("taos_query() failed:", errStr)
		taosLog.Printf("taosQuery() input sql:%s\n", sqlstr)
		return 0, errors.New(errStr)
	}
H
hzcheng 已提交
64

65 66 67 68 69 70
	// read result and save into mc struct
	num_fields := int(C.taos_field_count(mc.taos))
	if 0 == num_fields { // there are no select and show kinds of commands
		mc.affectedRows = int(C.taos_affected_rows(mc.taos))
		mc.insertId = 0
	}
H
hzcheng 已提交
71

72
	return num_fields, nil
H
hzcheng 已提交
73 74 75 76 77 78 79
}

func (mc *taosConn) taos_close() {
	C.taos_close(mc.taos)
}

func (mc *taosConn) taos_error() {
80 81 82 83
	// free local resouce: allocated memory/metric-meta refcnt
	//var pRes unsafe.Pointer
	pRes := C.taos_use_result(mc.taos)
	C.taos_free_result(pRes)
H
hzcheng 已提交
84
}