示例#1
0
func TestSelect(t *testing.T) {
	skipIfConnectionIsNil(t)

	cursor, e := ctx.NewQuery().From(tableName).Where(dbox.Eq("Age", "34")).Cursor(nil)
	if e != nil {
		t.Fatalf("Cursor error: " + e.Error())
	}
	defer cursor.Close()

	// if cursor.Count() == 0 {
	// 	t.Fatalf("No record found")
	// }

	var datas []toolkit.M
	e = cursor.Fetch(&datas, 2, false)
	if e != nil {
		t.Fatalf("Fetch error: %s", e.Error())
	}
	// if len(datas) != cursor.Count() {
	// 	t.Fatalf("Expect %d records got %d\n%s\n", cursor.Count(), len(datas), toolkit.JsonString(datas))
	// }
	toolkit.Printf("Total Record : %d\n", cursor.Count())
	toolkit.Printf("Record found: %d\nData:\n%s\n", len(datas), toolkit.JsonString(datas))

	// toolkit.Printf("Record found: %d\nData:\n%s\n", len(datas),
	// 	func() string {
	// 		var ret []string
	// 		for _, v := range datas {
	// 			ret = append(ret, v.GetString("_id"))
	// 		}
	// 		return strings.Join(ret, ",")
	// 	}())
}
示例#2
0
func (m *MigrateData) DoMasterUnit() error {
	tStart := time.Now()
	tk.Println("Starting MasterUnit..")
	mod := new(MasterUnit)

	c, e := m.BaseController.MongoCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)

	if e != nil {
		return e
	}

	defer c.Close()

	result := []tk.M{}
	e = c.Fetch(&result, 0, false)
	for _, val := range result {
		val.Set("Unit", val.Get("_id").(string))
		_, e := m.InsertOut(val, new(MasterUnit))
		if e != nil {
			tk.Printf("\n----------- ERROR -------------- \n %v \n\n %#v \n-------------------------  \n", e.Error(), val)
			return e
		}

	}

	cr, e := m.BaseController.SqlCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)
	ctn := cr.Count()
	cr.Close()

	tk.Printf("Completed Success in %v | %v data(s)\n", time.Since(tStart), ctn)
	return nil
}
示例#3
0
func TestTakeSkip(t *testing.T) {
	t.Skip()
	c, e := prepareConnection()
	if e != nil {
		t.Errorf("Unable to connect %s \n", e.Error())
	}
	defer c.Close()

	csr, e := c.NewQuery().
		Select("id", "productname").
		From(tableProducts).
		Take(5).
		Skip(10).
		Cursor(nil)
	if e != nil {
		t.Errorf("Cursor pre error: %s \n", e.Error())
		return
	}
	if csr == nil {
		t.Errorf("Cursor not initialized")
		return
	}
	defer csr.Close()

	rets := []toolkit.M{}
	e = csr.Fetch(&rets, 0, false)
	if e != nil {
		t.Errorf("Unable to fetch: %s \n", e.Error())
	} else {
		toolkit.Printf("Fetch OK. Result: %v \n", toolkit.JsonString(rets))
		toolkit.Printf("Total Record OK. Result: %v \n", toolkit.SliceLen(rets))

	}
}
示例#4
0
func TestSelect(t *testing.T) {
	t.Skip()
	c, e := prepareConnection()

	if e != nil {
		t.Errorf("Unable to connect %s \n", e.Error())
	}
	defer c.Close()

	// csr, e := c.NewQuery().Select().From("tes").Where(dbox.Eq("id", "3")).Cursor(nil)
	csr, e := c.NewQuery().
		// Select("empno", "ename", "hiredate").
		From(tableCustomers).Cursor(nil)

	if e != nil {
		t.Errorf("Cursor pre error: %s \n", e.Error())
		return
	}
	if csr == nil {
		t.Errorf("Cursor not initialized")
		return
	}
	defer csr.Close()

	rets := []toolkit.M{}
	e = csr.Fetch(&rets, 0, false)
	if e != nil {
		t.Errorf("Unable to fetch N: %s \n", e.Error())
	} else {
		toolkit.Printf("Fetch N OK. Result: %v \n", toolkit.JsonString(rets))
		toolkit.Printf("Total Fetch OK : %v \n", toolkit.SliceLen(rets))
	}
}
示例#5
0
func (b *BaseController) InsertBulk(result []tk.M, m orm.IModel, wg *sync.WaitGroup) {
	var datas []orm.IModel
	for _, i := range result {
		valueType := reflect.TypeOf(m).Elem()
		for f := 0; f < valueType.NumField(); f++ {
			field := valueType.Field(f)
			bsonField := field.Tag.Get("bson")
			jsonField := field.Tag.Get("json")

			if jsonField != bsonField && field.Name != "RWMutex" && field.Name != "ModelBase" {
				i.Set(field.Name, GetMgoValue(i, bsonField))
			}
			switch field.Type.Name() {
			case "string":
				if GetMgoValue(i, bsonField) == nil {
					i.Set(field.Name, "")
				}
				break
			case "Time":
				if GetMgoValue(i, bsonField) == nil {
					i.Set(field.Name, time.Time{})
				} else {
					i.Set(field.Name, GetMgoValue(i, bsonField).(time.Time).UTC())
				}
				break
			default:
				break
			}

		}

		newPointer := getNewPointer(m)
		e := tk.Serde(i, newPointer, "json")
		datas = append(datas, newPointer)

		if e != nil {
			tk.Printf("\n----------- ERROR -------------- \n %v \n\n %#v \n\n %#v \n-------------------------  \n", e.Error(), i, newPointer)
			wg.Done()
		}

	}

	if nil != datas {
		muinsert.Lock()
		for {
			e := b.Ctx.InsertBulk(datas)
			if e == nil {
				ctn := len(result)
				idx += ctn
				tk.Printf("saved: %v data(s)\n", idx)
				break
			} else {
				b.Ctx.Connection.Connect()
			}
		}
		muinsert.Unlock()
	}

	wg.Done()
}
示例#6
0
func TestGetObj(t *testing.T) {
	c, e := prepareConnection()
	if e != nil {
		t.Errorf("Unable to connect %s \n", e.Error())
		return
	}
	defer c.Close()
	//ObjTypeTable, ObjTypeView, ObjTypeProcedure, ObjTypeAll
	toolkit.Printf("List Table : %v\n", c.ObjectNames(dbox.ObjTypeTable))
	toolkit.Printf("List Procedure : %v\n", c.ObjectNames(dbox.ObjTypeProcedure))
	toolkit.Printf("List All Object : %v\n", c.ObjectNames(""))
}
示例#7
0
func (m *MigrateData) DoPowerPlantOutages() error {
	tStart := time.Now()
	tk.Println("Starting DoPowerPlantOutages..")
	mod := new(PowerPlantOutages)

	c, e := m.BaseController.MongoCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)

	if e != nil {
		return e
	}

	defer c.Close()

	result := []tk.M{}
	e = c.Fetch(&result, 0, false)

	for _, val := range result {
		details := val.Get("Details").(interface{}).([]interface{})
		val.Set("Details", nil)

		_, e := m.InsertOut(val, new(PowerPlantOutages))
		if e != nil {
			tk.Printf("\n----------- ERROR -------------- \n %v \n\n %#v \n-------------------------  \n", e.Error(), val)
			return e
		}
		id := val.GetString("_id")
		tk.Printf("%#v \n\n", id)

		for _, detail := range details {
			det := detail.(tk.M)
			det.Set("POId", id)
			tk.Println(det)
			_, e = m.InsertOut(det, new(PowerPlantOutagesDetails))
			if e != nil {
				tk.Printf("\n----------- ERROR -------------- \n %v \n\n %#v \n-------------------------  \n", e.Error(), det)
				return e
			}
		}
	}

	cr, e := m.BaseController.SqlCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)
	ctn := cr.Count()
	cr.Close()

	tk.Printf("Completed Success in %v | %v data(s)\n", time.Since(tStart), ctn)
	return nil

}
示例#8
0
func TestSelectAggregate(t *testing.T) {
	t.Skip()
	c, e := prepareConnection()
	if e != nil {
		t.Errorf("Unable to connect %s \n", e.Error())
	}
	defer c.Close()

	csr, e := c.NewQuery().
		Select("productname").
		Aggr(dbox.AggrSum, "price", "Total Price").
		Aggr(dbox.AggrAvr, "price", "Avg").
		From(tableProducts).
		Group("productname").
		Cursor(nil)
	if e != nil {
		t.Errorf("Cursor pre error: %s \n", e.Error())
		return
	}
	if csr == nil {
		t.Errorf("Cursor not initialized")
		return
	}
	defer csr.Close()

	rets := []toolkit.M{}
	e = csr.Fetch(&rets, 0, false)
	if e != nil {
		t.Errorf("Unable to fetch: %s \n", e.Error())
	} else {
		toolkit.Printf("Fetch OK. Result: %v \n", toolkit.JsonString(rets))

	}
}
示例#9
0
func TestSelectFilter(t *testing.T) {
	t.Skip()
	c, e := prepareConnection()
	if e != nil {
		t.Errorf("Unable to connect %s \n", e.Error())
		return
	}
	defer c.Close()

	csr, e := c.NewQuery().
		Select("empno", "ename", "mgr", "hiredate").
		Where(dbox.Or(dbox.Eq("empno", 7521), dbox.Eq("ename", "ADAMS"))).
		From(tableName).Cursor(nil)
	if e != nil {
		t.Errorf("Cursor pre error: %s \n", e.Error())
		return
	}
	if csr == nil {
		t.Errorf("Cursor not initialized")
		return
	}
	defer csr.Close()

	rets := /*[]customers{}*/ []toolkit.M{}
	e = csr.Fetch(&rets, 0, false)
	if e != nil {
		t.Errorf("Unable to fetch: %s \n", e.Error())
	} else {
		toolkit.Printf("Filter OK. Result: %v \n", toolkit.JsonString(rets))
	}
}
示例#10
0
func TestOdbc(t *testing.T) {
	conn, e := odbc.Connect("DSN=mysql-dsn;UID=root;PWD=root")
	if e != nil {
		toolkit.Println("Conn Error found: ", e.Error())
	}
	toolkit.Println(conn)
	query := "SELECT id, name FROM dummy"
	stmt, e := conn.Prepare(query)
	if e != nil {
		toolkit.Println("STMT Error found: ", e.Error())
	}
	// toolkit.Println(conn, stmt)
	e = stmt.Execute()
	if e != nil {
		toolkit.Println("Execute Error found: ", e.Error())
	}

	rows, e := stmt.FetchAll()
	if e != nil {
		toolkit.Println("FetchAll Error found: ", e.Error())
	}
	// toolkit.Println(toolkit.JsonString(rows))
	for _, row := range rows {
		toolkit.Printf("%v\n", row.Data)
	}

	stmt.Close()
	conn.Close()
}
示例#11
0
文件: z0_test.go 项目: eaciit/sebar
func TestStorageWrite(t *testing.T) {
	skipIfClientNil(t)
	es := []string{}

	toolkit.Printf("Writing Data:\n")
	for i := 0; i < 200; i++ {
		dataku := toolkit.RandInt(1000)
		totalInt += dataku
		//toolkit.Printf("%d ", dataku)

		in := toolkit.M{}.Set("key", fmt.Sprintf("public.dataku.%d", i)).Set("data", toolkit.ToBytes(dataku, ""))
		writeResult := client.Call("set", in)
		if writeResult.Status != toolkit.Status_OK {
			es = append(es, toolkit.Sprintf("Fail to write data %d : %d => %s", i, dataku, writeResult.Message))
		}
	}

	if len(es) > 0 {
		errorTxt := ""
		if len(es) <= 10 {
			errorTxt = strings.Join(es, "\n")
		} else {
			errorTxt = strings.Join(es[:10], "\n") + "\n... And others ..."
		}
		t.Errorf("Write data fail.\n%s", errorTxt)
	}
}
示例#12
0
func TestFreeQuery(t *testing.T) {
	t.Skip()
	c, e := prepareConnection()
	if e != nil {
		t.Errorf("Unable to connect %s \n", e.Error())
	}
	defer c.Close()

	csr, e := c.NewQuery().
		Command("freequery", toolkit.M{}.
			Set("syntax", "select name from tes where name like 'r%'")).
		Cursor(nil)

	if csr == nil {
		t.Errorf("Cursor not initialized", e.Error())
		return
	}
	defer csr.Close()

	results := make([]map[string]interface{}, 0)
	err := csr.Fetch(&results, 0, false)
	if err != nil {
		t.Errorf("Unable to fetch: %s \n", err.Error())
	} else {
		toolkit.Println("======================")
		toolkit.Println("TEST FREE QUERY")
		toolkit.Println("======================")
		toolkit.Println("Fetch N OK. Result: ")
		for _, val := range results {
			toolkit.Printf("%v \n",
				toolkit.JsonString(val))
		}
	}
}
示例#13
0
func TestSelect(t *testing.T) {
	// t.Skip()
	skipIfConnectionIsNil(t)

	cursor, e := ctx.NewQuery().
		Select("id", "nama", "amount").
		From(tableName).
		Cursor(nil)
	if e != nil {
		t.Fatalf("Cursor error: " + e.Error())
	}
	defer cursor.Close()

	var results []toolkit.M
	e = cursor.Fetch(&results, 0, false)

	if e != nil {
		t.Errorf("Unable to fetch: %s \n", e.Error())
	} else {
		toolkit.Println("======================")
		toolkit.Println(operation)
		toolkit.Println("======================")
		toolkit.Println(sintaks)
		toolkit.Println("Number of rows", cursor.Count())
		toolkit.Println("Fetch OK. Result:")
		for _, val := range results {
			toolkit.Printf("%v \n",
				toolkit.JsonString(val))
		}
	}
}
示例#14
0
func (m *MigrateData) DoGenerateTempMstPlant() error {
	tStart := time.Now()
	tk.Println("Starting DoGenerateTempMstPlant..")
	mod := new(TempMstPlant)

	c, e := m.BaseController.MongoCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)

	if e != nil {
		return e
	}

	defer c.Close()

	result := []tk.M{}
	e = c.Fetch(&result, 0, false)

	_ = tStart
	for _, val := range result {
		for {
			_, e := m.InsertOut(val, new(TempMstPlant))
			if e == nil {
				break
			} else {
				m.SqlCtx.Connection.Connect()
			}
		}
	}

	cr, e := m.BaseController.SqlCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)
	ctn := cr.Count()
	cr.Close()

	tk.Printf("Completed Success in %v | %v data(s)\n", time.Since(tStart), ctn)
	return nil
}
示例#15
0
func TestFrom(t *testing.T) {
	for i := 0; i < sampleCount; i++ {
		obj := Obj{}
		obj.F = toolkit.ToFloat64(toolkit.RandInt(1000), 2, toolkit.RoundingAuto)
		obj.I = toolkit.RandInt(1000) + 5
		objs = append(objs, obj)

		if i == 0 {
			min = obj.I
			max = obj.I
			sum = obj.I
			avg = toolkit.ToFloat64(obj.I, 4, toolkit.RoundingAuto)
		} else {
			sum += obj.I
			avg = toolkit.ToFloat64(sum, 4, toolkit.RoundingAuto) /
				toolkit.ToFloat64(i+1, 4, toolkit.RoundingAuto)
			if min > obj.I {
				min = obj.I
			}
			if max < obj.I {
				max = obj.I
			}
		}
	}

	c = crowd.From(&objs)
	check(t, c.Error, "")
	toolkit.Printf("Data len: %d, max: %d, min: %d, sum: %d, avg: %5.4f\n", c.Len(), max, min, sum, avg)
}
示例#16
0
func TestSelectLimit(t *testing.T) {
	t.Skip("Skip : Comment this line to do test")
	skipIfConnectionIsNil(t)

	cursor, e := ctx.NewQuery().
		Select("EmployeeId", "FirstName").
		Skip(0).Take(3).
		From(tableName).
		Cursor(nil)

	if e != nil {
		t.Fatalf("Cursor error: " + e.Error())
	}

	datas := make([]toolkit.M, 0, 0)
	e = cursor.Fetch(&datas, 0, false)
	if e != nil {
		t.Fatalf("Fetch error: %s", e.Error())
	}

	toolkit.Printf("Total Record : %d\n", cursor.Count())
	toolkit.Printf("Record found: %d\nData:\n%s\n", len(datas), toolkit.JsonString(datas))

	cursor.Close()

	//==================
	cursor, e = ctx.NewQuery().
		Select("EmployeeId").
		Skip(3).Take(5).
		From(tableName).
		Cursor(nil)

	if e != nil {
		t.Fatalf("Cursor error: " + e.Error())
	}

	datas = make([]toolkit.M, 0, 0)
	e = cursor.Fetch(&datas, 0, false)
	if e != nil {
		t.Fatalf("Fetch error: %s", e.Error())
	}

	toolkit.Printf("Total Record : %d\n", cursor.Count())
	toolkit.Printf("Record found: %d\nData:\n%s\n", len(datas), toolkit.JsonString(datas))

	cursor.Close()
}
示例#17
0
func TestSelect(t *testing.T) {
	t.Skip("Skip : Comment this line to do test")
	skipIfConnectionIsNil(t)

	cursor, e := ctx.NewQuery().From(tableName).Where(dbox.Eq("Age", 34)).Cursor(nil)
	if e != nil {
		t.Fatalf("Cursor error: " + e.Error())
	}
	defer cursor.Close()

	var datas []toolkit.M
	e = cursor.Fetch(&datas, 2, false)
	if e != nil {
		t.Fatalf("Fetch error: %s", e.Error())
	}

	toolkit.Printf("Total Record : %d\n", cursor.Count())
	toolkit.Printf("Record found: %d\nData:\n%s\n", len(datas), toolkit.JsonString(datas))
}
示例#18
0
func (b *BaseController) Insert(result []tk.M, m orm.IModel, wg *sync.WaitGroup) {
	// muinsert := &sync.Mutex{}
	for _, i := range result {
		valueType := reflect.TypeOf(m).Elem()
		for f := 0; f < valueType.NumField(); f++ {
			field := valueType.Field(f)
			bsonField := field.Tag.Get("bson")
			jsonField := field.Tag.Get("json")

			if jsonField != bsonField && field.Name != "RWMutex" && field.Name != "ModelBase" {
				i.Set(field.Name, GetMgoValue(i, bsonField))
			}
			switch field.Type.Name() {
			case "string":
				if GetMgoValue(i, bsonField) == nil {
					i.Set(field.Name, "")
				}
				break
			case "Time":
				if GetMgoValue(i, bsonField) == nil {
					i.Set(field.Name, time.Time{})
				} else {
					i.Set(field.Name, GetMgoValue(i, bsonField).(time.Time).UTC())
				}
				break
			default:
				break
			}

		}

		newPointer := getNewPointer(m)
		e := tk.Serde(i, newPointer, "json")
		var newId int64
		for index := 0; index < retry; index++ {
			muinsert.Lock()
			newId, e = b.Ctx.InsertOut(newPointer)
			_ = newId
			muinsert.Unlock()
			if e == nil {
				wg.Done()
				break
			} else {
				b.Ctx.Connection.Connect()
			}
		}

		if e != nil {
			tk.Printf("\n----------- ERROR -------------- \n %v \n\n %#v \n\n %#v \n-------------------------  \n", e.Error(), i, newPointer)
			wg.Done()
		}

	}
	wg.Done()
}
示例#19
0
func TestViewAllTables(t *testing.T) {
	t.Skip()
	skipIfConnectionIsNil(t)

	csr := ctx.ObjectNames(dbox.ObjTypeTable)

	toolkit.Println("list of table : ")
	for i := 0; i < len(csr); i++ {
		toolkit.Printf("%v \n", toolkit.JsonString(csr[i]))
	}
}
示例#20
0
func TestViewProcedureName(t *testing.T) {
	t.Skip()
	skipIfConnectionIsNil(t)

	proc := ctx.ObjectNames(dbox.ObjTypeProcedure)

	toolkit.Println("list of procedure : ")
	for i := 0; i < len(proc); i++ {
		toolkit.Printf("%v \n", toolkit.JsonString(proc[i]))
	}

}
示例#21
0
func TestAllObj(t *testing.T) {
	t.Skip()
	skipIfConnectionIsNil(t)

	all := ctx.ObjectNames(dbox.ObjTypeAll)

	toolkit.Println("list of all objects : ")
	for i := 0; i < len(all); i++ {
		toolkit.Printf("%v \n", toolkit.JsonString(all[i]))
	}

}
示例#22
0
func TestViewName(t *testing.T) {
	t.Skip()
	skipIfConnectionIsNil(t)

	view := ctx.ObjectNames(dbox.ObjTypeView)

	toolkit.Println("list of view : ")
	for i := 0; i < len(view); i++ {
		toolkit.Printf("%v \n", toolkit.JsonString(view[i]))
	}

}
示例#23
0
func (m *MigrateData) DoGenerateDataBrowserFields() error {
	tStart := time.Now()
	tk.Println("Starting DoGenerateDataBrowserFields..")
	mod := new(DataBrowserFields)

	c, e := m.BaseController.MongoCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)

	if e != nil {
		return e
	}

	defer c.Close()

	result := []tk.M{}
	e = c.Fetch(&result, 0, false)

	for _, val := range result {
		selectedFields := val.Get("Fields")
		if nil != selectedFields {
			fields := selectedFields.(interface{}).([]interface{})
			for _, field := range fields {
				for {
					v := reflect.ValueOf(field)
					x := v.Interface()
					details := x.(tk.M)

					newVal := tk.M{}
					newVal.Set("FieldsReference", val.Get("_id"))
					newVal.Set("Alias", details["alias"])
					newVal.Set("Field", details["field"])
					newVal.Set("Type", details["tipe"])

					_, e := m.InsertOut(newVal, new(DataBrowserFields))
					if e == nil {
						break
					} else {
						tk.Println(e.Error())
						m.SqlCtx.Connection.Connect()
					}
				}
			}
		}
	}

	cr, e := m.BaseController.SqlCtx.Connection.NewQuery().From(mod.TableName()).Cursor(nil)
	ctn := cr.Count()
	cr.Close()

	tk.Printf("Completed Success in %v | %v data(s)\n", time.Since(tStart), ctn)
	return nil
}
示例#24
0
func TestSelect(t *testing.T) {
	// t.Skip()
	c, e := prepareConnection()
	if e != nil {
		t.Errorf("Unable to connect %s \n", e.Error())
	}
	defer c.Close()

	csr, e := c.NewQuery().
		From("customers").
		Select("datenow", "currency"). //tested and not working with 2 field
		// Order("unitsinstock"). //tested and not working
		// Skip(10). //tested and not working

		// Where(dbox.And(dbox.Gte("unitsinstock", 15), dbox.Eq("productname", "Chai"))).

		// Where(dbox.And(dbox.Gte("unitsinstock", "@stock"), dbox.Eq("productname", "@name"))).
		// Cursor(toolkit.M{}.Set("@stock", 15).Set("@name", "Chai"))
		// Take(10).
		Cursor(nil)
	if e != nil {
		t.Errorf("Cursor pre error: %s \n", e.Error())
		return
	}
	if csr == nil {
		t.Errorf("Cursor not initialized")
		return
	}
	defer csr.Close()

	result := make([]map[string]interface{}, 0) //[]toolkit.M{}
	e = csr.Fetch(&result, 0, false)
	if e != nil {
		t.Errorf("Unable to fetch all: %s \n", e.Error())
	} else {
		toolkit.Printf("Fetch all OK. Result: %v \n", toolkit.JsonString(result))
	}

	e = csr.ResetFetch()
	if e != nil {
		t.Errorf("Unable to reset fetch: %s \n", e.Error())
	}

	/*ds, e = csr.Fetch(nil, 3, false)
	if e != nil {
		t.Errorf("Unable to fetch N: %s \n", e.Error())
	} else {
		fmt.Printf("Fetch N OK. Result: %v \n",
			ds.Data)
	}*/
}
示例#25
0
func TestLoadApp(t *testing.T) {
	//t.Skip()
	apps := []colonycore.Application{}
	c, e := colonycore.Find(new(colonycore.Application), dbox.Lte("_id", "appn4"))
	if e != nil {
		t.Errorf("Load appn fail:" + e.Error())
		return
	}
	e = c.Fetch(&apps, 0, false)
	if e != nil {
		t.Error("Fetching appn fail:" + e.Error())
	}
	toolkit.Printf("Applications: %s\n", toolkit.JsonString(apps))
}
示例#26
0
func TestSelect(t *testing.T) {
	// t.Skip()
	skipIfConnectionIsNil(t)

	cursor, e := ctx.NewQuery().
		Select("id", "nama", "amount").
		From(tableName).
		Where(dbox.And(dbox.Gt("amount", 150), dbox.Eq("nama", "buku"))).
		// Where(dbox.Contains("nama", "tem", "pe")).
		// Order("nama").
		// Skip(2).
		// Take(1).
		Cursor(nil)
	// Where(dbox.And(dbox.Gt("price", "@price"), dbox.Eq("status", "@status"))).
	// Cursor(toolkit.M{}.Set("@price", 100000).Set("@status", "available"))
	// Where(dbox.And(dbox.Or(dbox.Eq("nama", "@name1"), dbox.Eq("nama", "@name2"),
	// dbox.Eq("nama", "@name3")), dbox.Lt("quantity", "@quantity"))).
	// Cursor(toolkit.M{}.Set("@name1", "buku").Set("@name2", "tas").
	// Set("@name3", "dompet").Set("@quantity", 4))
	if e != nil {
		t.Fatalf("Cursor error: " + e.Error())
	}
	defer cursor.Close()

	var results []toolkit.M
	e = cursor.Fetch(&results, 0, false)

	operation = "Test Select Filter"
	sintaks = `
		ctx.NewQuery().
		Select("id", "nama", "amount").
		From(tableName).
		Where(dbox.And(dbox.Gt("amount", 150000), 
			dbox.Eq("nama", "buku"))).
		Cursor(nil)`

	if e != nil {
		t.Errorf("Unable to fetch: %s \n", e.Error())
	} else {
		toolkit.Println("======================")
		toolkit.Println(operation)
		toolkit.Println("======================")
		toolkit.Println(sintaks)
		toolkit.Println("Fetch OK. Result:")
		for _, val := range results {
			toolkit.Printf("%v \n",
				toolkit.JsonString(val))
		}
	}
}
示例#27
0
func TestFind(t *testing.T) {
	ms := []toolkit.M{}
	for i := 1; i <= 10; i++ {
		m := toolkit.M{}
		m.Set("_id", i)
		m.Set("random", toolkit.RandInt(100))
		ms = append(ms, m)
	}
	toolkit.Printf("Original Value\n%s\n", toolkit.JsonString(ms))

	indexes := dbox.Find(ms, []*dbox.Filter{
		//dbox.Or(dbox.Lt("random", 20), dbox.And(dbox.Gte("random", 60), dbox.Lte("random", 70)))})
		dbox.And(dbox.Gte("random", 30), dbox.Lte("random", 80))})

	records := []toolkit.M{}
	for _, v := range indexes {
		records = append(records, ms[v])
	}
	for _, r := range records {
		toolkit.Printf("Record: %s \n", toolkit.JsonString(r))
	}
	toolkit.Printf("Find %d records of %d records\n", len(indexes), len(ms))
}
示例#28
0
func TestSelectAggregate(t *testing.T) {
	t.Skip()
	skipIfConnectionIsNil(t)

	csr, e := ctx.NewQuery().
		Select("nama").
		// Aggr(dbox.AggrSum, 1, "Total Item").
		Aggr(dbox.AggrMax, "amount", "Max Amount").
		Aggr(dbox.AggrSum, "amount", "Total Amount").
		// Aggr(dbox.AggrAvr, "amount", "Average Amount").
		From(tableName).
		Group("nama").
		Order("-nama").
		Cursor(nil)
	if e != nil {
		t.Errorf("Cursor pre error: %s \n", e.Error())
		return
	}
	if csr == nil {
		t.Errorf("Cursor not initialized")
		return
	}
	defer csr.Close()

	results := make([]map[string]interface{}, 0)

	err := csr.Fetch(&results, 0, false)
	sintaks = `
		ctx.NewQuery().
		Select("nama").
		Aggr(dbox.AggrMax, "amount", "Max Amount").
		Aggr(dbox.AggrSum, "amount", "Total Amount").
		From(tableName).
		Group("nama").
		Order("-nama").
		Cursor(nil)`
	if err != nil {
		t.Errorf("Unable to fetch: %s \n", err.Error())
	} else {
		toolkit.Println("======================")
		toolkit.Println("QUERY AGGREGATION")
		toolkit.Println("======================")
		toolkit.Println("Fetch N OK. Result:")
		for _, val := range results {
			toolkit.Printf("%v \n",
				toolkit.JsonString(val))
		}
	}
}
示例#29
0
// 	if e != nil {
// 		t.Errorf("Unable to fetch: %s \n", e.Error())
// 	} else {
// 		toolkit.Println("======================")
// 		toolkit.Println(operation)
// 		toolkit.Println("======================")
// 		toolkit.Println(sintaks)
// 		toolkit.Println("Fetch OK. Result:")
// 		for _, val := range results {
// 			toolkit.Printf("%v \n",
// 				toolkit.JsonString(val))
// 		}
// 	}
// }
func TestSelectFilter(t *testing.T) {
	// t.Skip()
	skipIfConnectionIsNil(t)

	cursor, e := ctx.NewQuery().
		Select("_id", "nama", "amount").
		From(tableName).
		Where(dbox.And(dbox.Gt("amount", 150), dbox.Eq("nama", "buku"))).
		Cursor(nil)

	operation = "TestSelectFilter"
	sintaks = `
		ctx.NewQuery().
		Select("_id", "nama", "amount").
		From(tableName).
		Where(dbox.And(dbox.Gt("amount", 150000), 
			dbox.Eq("nama", "buku"))).
		Cursor(nil)`

	if e != nil {
		t.Fatalf("Cursor error: " + e.Error())
	}
	defer cursor.Close()

	if cursor.Count() == 0 {
		t.Fatalf("No record found")
	}

	var results []toolkit.M
	e = cursor.Fetch(&results, 0, false)

	if e != nil {
		t.Errorf("Unable to fetch: %s \n", e.Error())
	} else {
		toolkit.Println("======================")
		toolkit.Println(operation)
		toolkit.Println("======================")
		toolkit.Println(sintaks)
		toolkit.Println("Fetch OK. Result:")
		for _, val := range results {
			toolkit.Printf("%v \n",
				toolkit.JsonString(val))
		}
	}
}
示例#30
0
func TestCursor(t *testing.T) {
	skipIfConnectionIsNil(t)
	cursor, e := ctx.NewQuery().From(tableName).
		Where(dbox.Lte("enable", false)).
		Cursor(nil)
	if e != nil {
		t.Errorf("Unable to generate cursor. %s", e.Error())
	}
	defer cursor.Close()

	results := make([]toolkit.M, 0)
	e = cursor.Fetch(&results, 0, false)
	if e != nil {
		t.Errorf("Unable to iterate cursor %s", e.Error())
	} else {
		toolkit.Printf("Result:\n%s\n", toolkit.JsonString(results))
	}
}