示例#1
0
文件: pq.go 项目: dvarrazzo/pger
func connect(conninfo string) (*PgConn, error) {
	cs := C.CString(conninfo)
	defer C.free(unsafe.Pointer(cs))
	conn := C.PQconnectdb(cs)
	if C.PQstatus(conn) != C.CONNECTION_OK {
		cerr := C.PQerrorMessage(conn)
		err := fmt.Errorf("connection failed: %s", C.GoString(cerr))
		C.PQfinish(conn)
		return nil, err
	}

	// TODO: support other encodings?
	pname := C.CString("client_encoding")
	defer C.free(unsafe.Pointer(pname))
	cenc := C.PQparameterStatus(conn, pname)
	if cenc == nil {
		err := errors.New("connection failed: no client encoding")
		C.PQfinish(conn)
		return nil, err
	}
	if enc := C.GoString(cenc); enc != "UTF8" {
		err := fmt.Errorf(
			"connection failed: client encoding not supported: %s", enc)
		C.PQfinish(conn)
		return nil, err
	}

	// one-line error message
	C.PQsetErrorVerbosity(conn, C.PQERRORS_TERSE)

	return &PgConn{conn: conn, conninfo: conninfo}, nil
}
示例#2
0
// dsn is passed directly to PQconnectdb
func (d *libpqDriver) Open(dsn string) (driver.Conn, error) {
	if C.PQisthreadsafe() != 1 {
		return nil, ErrThreadSafety
	}

	params := C.CString(dsn)
	defer C.free(unsafe.Pointer(params))

	db := C.PQconnectdb(params)
	if C.PQstatus(db) != C.CONNECTION_OK {
		defer C.PQfinish(db)
		return nil, errors.New("libpq: connection error " + C.GoString(C.PQerrorMessage(db)))
	}

	oids, err := d.getOids(db, dsn)
	if err != nil {
		defer C.PQfinish(db)
		return nil, ErrFetchingOids
	}

	return &libpqConn{
		db:        db,
		oids:      oids,
		stmtCache: make(map[string]driver.Stmt),
		stmtNum:   0,
	}, nil
}
示例#3
0
func connError(db *C.PGconn) error {
	return errors.New("conn error:" + C.GoString(C.PQerrorMessage(db)))
}