taosSqlCgo.go 2.4 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/*
 * 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

/*
#cgo CFLAGS : -I/usr/local/include/taos/
#cgo LDFLAGS: -L/usr/local/lib/taos -ltaos
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <taos.h>
*/
import "C"

import (
	"errors"
	"unsafe"
)

func (mc *taosConn) taosConnect(ip, user, pass, db string, port int) (taos unsafe.Pointer, err error){
	cuser := C.CString(user)
	cpass := C.CString(pass)
	cip   := C.CString(ip) // TODO: Addr : x.x.x.x:port, must process to ip and port format
	cdb   := C.CString("")
	port   = 0
	defer C.free(unsafe.Pointer(cip))
	defer C.free(unsafe.Pointer(cuser))
	defer C.free(unsafe.Pointer(cpass))
	defer C.free(unsafe.Pointer(cdb))

	taosObj := C.taos_connect(cip, cuser, cpass, cdb, (C.int)(port))
    if taosObj == nil {
        return nil, errors.New("taos_connect() fail!")
    }

    return (unsafe.Pointer)(taosObj), nil
} 

func (mc *taosConn) taosQuery(sqlstr string) (int, error) {
	taosLog.Printf("taosQuery() input sql:%s\n", sqlstr)

    csqlstr   := C.CString(sqlstr)
	defer C.free(unsafe.Pointer(csqlstr))
    code := int(C.taos_query(mc.taos, csqlstr))

    if 0 != code {
    	mc.taos_error()
    	errStr := C.GoString(C.taos_errstr(mc.taos))
    	taosLog.Println("taos_query() failed:", errStr)
	    return 0, errors.New(errStr)
    }

    // 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
    }

    return num_fields, nil
}

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

func (mc *taosConn) taos_error() {
    // free local resouce: allocated memory/metric-meta refcnt
    //var pRes unsafe.Pointer
    pRes := C.taos_use_result(mc.taos)
    C.taos_free_result(pRes)
}