You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

107 lines
2.8 KiB

package sqlx_test
import (
"context"
"fmt"
"git.diulo.com/mogfee/kit/mysql/sqlx"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/jaeger"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"io"
"testing"
"time"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
)
var datasource = "root:123456@tcp(127.0.0.1:3306)/test_gozero"
var driverName = "mysql"
func TestNewSqlConn(t *testing.T) {
sqlConn := sqlx.NewSqlConn(driverName, datasource)
//result, err := sqlConn.Exec("insert into user(name) value ('aa')")
//if err != nil {
// t.Error(err)
//}
//fmt.Println(result.LastInsertId())
//var id int
//if err := sqlConn.QueryRow(&id, "select name from user where id=?", 1); err != nil {
// t.Error(err)
//}
//fmt.Println(id)
//return
type row struct {
Id int64 `db:"id"`
Name string `db:"name"`
Email string `db:"email"`
}
//data := row{}
//if err := sqlConn.QueryRow(&data, "select id,name,email from user"); err != nil {
// t.Error(err)
//}
//list := make([]*row, 0)
//if err := sqlConn.QueryRows(&list, "select id,name,email from user limit 2"); err != nil {
// t.Error(err)
//}
//fmt.Printf("%+v\n", list)
//exp, err := newExporter(os.Stdout)
//if err != nil {
// panic(err)
//}
r, _ := resource.Merge(resource.Default(), resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName("fib"),
semconv.ServiceVersion("v0.1.0"),
attribute.String("environment", "demo"),
))
exp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint("http://127.0.0.1:14268/api/traces")))
if err != nil {
panic(err)
}
tp := trace.NewTracerProvider(trace.WithBatcher(exp), trace.WithResource(r))
defer func() {
if err = tp.Shutdown(context.Background()); err != nil {
panic(err)
}
}()
otel.SetTracerProvider(tp)
ctx := context.Background()
newCtx, span := otel.Tracer("sql_client").Start(ctx, "Run")
err = sqlConn.Transact(func(session sqlx.Session) error {
data := row{}
err := session.QueryRowCtx(newCtx, &data, "select * from user where id=?", 1)
if err != nil {
return err
}
fmt.Println(data.Name)
res, err := session.ExecCtx(newCtx, "update user set name=? where id=?", time.Now().Unix(), 1)
if err != nil {
return err
}
fmt.Println(res.RowsAffected())
fmt.Println(res.LastInsertId())
return nil
})
if err != nil {
t.Error(err)
}
span.End()
time.Sleep(time.Second)
}
// newExporter returns a console exporter.
func newExporter(w io.Writer) (trace.SpanExporter, error) {
return stdouttrace.New(
stdouttrace.WithWriter(w),
// Use human-readable output.
stdouttrace.WithPrettyPrint(),
// Do not print timestamps for the demo.
stdouttrace.WithoutTimestamps(),
)
}