Beispiel #1
0
func finUpdateObj(jsonData []toolkit.M, replaceData toolkit.M, isType string) []toolkit.M {
	var (
		mapVal []toolkit.M
	)

	if isType == "update" {
		iReplaceData := toolkit.Id(replaceData)
		//reflectIs := reflect.ValueOf(iReplaceData).Kind()
		//dataUptId := ToString(reflectIs, iReplaceData)
		dataUptId := toolkit.ToString(iReplaceData)

		for _, v := range jsonData {
			iSubV := toolkit.Id(v)
			//reflectIs := reflect.ValueOf(iSubV).Kind()
			subvIdString := toolkit.ToString(iSubV)
			if strings.ToLower(subvIdString) == strings.ToLower(dataUptId) {
				for key, _ := range v {
					delete(v, key)
				}

			}

			var newData = make(map[string]interface{})
			for i, dataUpt := range replaceData {
				newData[i] = dataUpt
			}
			for i, newSubV := range v {
				newData[i] = newSubV
			}
			mapVal = append(mapVal, newData)
		}
		return mapVal
	} else if isType == "insert" {
		val := append(jsonData, replaceData)
		return val
	}
	return nil

}
Beispiel #2
0
func (m *ModelBase) RecordID() interface{} {
	if m.model == nil {
		return nil
	}
	return tk.Id(m.model)
}
Beispiel #3
0
func (q *Query) Exec(parm toolkit.M) error {
	var e error
	if parm == nil {
		parm = toolkit.M{}
	}
	/*
		if q.Parts == nil {
			return errorlib.Error(packageName, modQuery,
				"Cursor", fmt.Sprintf("No Query Parts"))
		}
	*/

	dbname := q.Connection().Info().Database
	tablename := ""

	if parm == nil {
		parm = toolkit.M{}
	}
	data := parm.Get("data", nil)

	/*
		parts will return E - map{interface{}}interface{}
		where each interface{} returned is slice of interfaces --> []interface{}
	*/
	parts := crowd.From(q.Parts()).Group(func(x interface{}) interface{} {
		qp := x.(*dbox.QueryPart)
		return qp.PartType
	}, nil).Data

	fromParts, hasFrom := parts[dbox.QueryPartFrom]
	if !hasFrom {
		return errorlib.Error(packageName, modQuery, "Exec", "Invalid table name")
	}
	tablename = fromParts.([]interface{})[0].(*dbox.QueryPart).Value.(string)

	var where interface{}
	commandType := ""
	multi := false

	_, hasDelete := parts[dbox.QueryPartDelete]
	_, hasInsert := parts[dbox.QueryPartInsert]
	_, hasUpdate := parts[dbox.QueryPartUpdate]
	_, hasSave := parts[dbox.QueryPartSave]

	if hasDelete {
		commandType = dbox.QueryPartDelete
	} else if hasInsert {
		commandType = dbox.QueryPartInsert
	} else if hasUpdate {
		commandType = dbox.QueryPartUpdate
	} else if hasSave {
		commandType = dbox.QueryPartSave
	}

	whereParts, hasWhere := parts[dbox.QueryPartWhere]
	if hasWhere {
		fb := q.Connection().Fb()
		for _, p := range whereParts.([]interface{}) {
			fs := p.(*dbox.QueryPart).Value.([]*dbox.Filter)
			for _, f := range fs {
				fb.AddFilter(f)
			}
		}
		where, e = fb.Build()
		if e != nil {
			return errorlib.Error(packageName, modQuery, "Exec",
				e.Error())
		} else {
			//fmt.Printf("Where: %s\n", toolkit.JsonString(where))
		}
	}

	if data == nil {
		multi = true
	} else {
		if where == nil {
			id := toolkit.Id(data)
			if id != nil {
				where = (toolkit.M{}).Set("_id", id)
			}
		} else {
			multi = true
		}
	}

	session := q.Session()

	multiExec := q.Config("multiexec", false).(bool)
	if !multiExec && !q.usePooling && session != nil {
		defer session.Close()
	}
	mgoColl := session.DB(dbname).C(tablename)
	if commandType == dbox.QueryPartInsert {
		e = mgoColl.Insert(data)
	} else if commandType == dbox.QueryPartUpdate {
		if multi {
			dataM, e := toolkit.ToM(data)
			if e != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}
			if len(dataM) == 0 {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, "Update data points is empty")
			}
			updatedData := toolkit.M{}.Set("$set", dataM)
			_, e = mgoColl.UpdateAll(where, updatedData)
		} else {
			e = mgoColl.Update(where, data)
			if e != nil {
				e = fmt.Errorf("%s [%v]", e.Error(), where)
			}
		}
	} else if commandType == dbox.QueryPartDelete {
		if multi {
			_, e = mgoColl.RemoveAll(where)
		} else {
			e = mgoColl.Remove(where)
			if e != nil {
				e = fmt.Errorf("%s [%v]", e.Error(), where)
			}
		}
	} else if commandType == dbox.QueryPartSave {
		_, e = mgoColl.Upsert(where, data)
	}
	if e != nil {
		return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
	}
	return nil
}
Beispiel #4
0
func (q *Query) Exec(in toolkit.M) error {
	setting, e := q.prepare(in)
	commandType := setting["commandtype"].(string)
	//toolkit.Printf("Command type: %s\n", commandType)
	if e != nil {
		return err.Error(packageName, modQuery, "Exec: "+commandType, e.Error())
	}

	if setting.GetString("commandtype") == dbox.QueryPartSelect {
		return err.Error(packageName, modQuery, "Exec: "+commandType, "Exec is not working with select command, please use .Cursor instead")
	}

	q.Lock()
	defer q.Unlock()

	var dataM toolkit.M
	var dataMs []toolkit.M

	hasData := in.Has("data")
	dataIsSlice := false
	data := in.Get("data")
	if toolkit.IsSlice(data) {
		dataIsSlice = true
		e = toolkit.Unjson(toolkit.Jsonify(data), dataMs)
		if e != nil {
			return err.Error(packageName, modQuery, "Exec: "+commandType, "Data encoding error: "+e.Error())
		}
	} else {
		dataM, e = toolkit.ToM(data)
		dataMs = append(dataMs, dataM)
		if e != nil {
			return err.Error(packageName, modQuery, "Exec: "+commandType, "Data encoding error: "+e.Error())
		}
	}

	hasWhere := setting.Has("where")
	where := setting.Get("where", []*dbox.Filter{}).([]*dbox.Filter)
	if hasWhere && len(where) == 0 {
		inWhere := in.Get("where")
		if inWhere == nil {
			hasWhere = false
			where = nil
		} else {
			if !toolkit.IsSlice(inWhere) {
				where = append(where, inWhere.(*dbox.Filter))
			} else {
				where = inWhere.([]*dbox.Filter)
			}
		}
	}

	if hasData && hasWhere == false && toolkit.HasMember([]interface{}{dbox.QueryPartInsert, dbox.QueryPartDelete,
		dbox.QueryPartUpdate, dbox.QueryPartSave}, commandType) {
		hasWhere = true
		//toolkit.Println("check where")
		if toolkit.IsSlice(data) {
			ids := []interface{}{}
			idField := ""
			if idField == "" {
				return err.Error(packageName, modQuery, "Exec: "+commandType, "Data send is a slice, but its element has no ID")
			}
			dataCount := toolkit.SliceLen(data)
			for i := 0; i < dataCount; i++ {
				dataI := toolkit.SliceItem(data, i)
				if i == 0 {
					idField = toolkit.IdField(dataI)
				}
				ids = append(ids, toolkit.Id(dataI))
			}
			where = []*dbox.Filter{dbox.In(idField, ids)}
		} else {
			idfield := "_id"
			id := toolkit.Id(data)
			if !toolkit.IsNilOrEmpty(id) {
				where = []*dbox.Filter{dbox.Eq(idfield, id)}
			} else {
				where = nil
				hasWhere = false
			}
		}
	}
	/*
		toolkit.Printf("CommandType: %s HasData: %v HasWhere: %v Where: %s\n",
			commandType, hasData, hasWhere, toolkit.JsonString(where))
	*/
	e = q.openFile(commandType)
	//toolkit.Printf(commandType+" Open File, found record: %d\nData:%s\n", len(q.data), toolkit.JsonString(q.data))
	if e != nil {
		return err.Error(packageName, modQuery, "Exec: "+commandType, e.Error())
	}

	var indexes []interface{}
	if hasWhere && commandType != dbox.QueryPartInsert {
		whereIndex := dbox.Find(q.data, where)
		indexes = toolkit.ToInterfaceArray(&whereIndex)
		//toolkit.Printf("Where Index: %s Index:%s\n", toolkit.JsonString(whereIndex), toolkit.JsonString(indexes))
	}
	if commandType == dbox.QueryPartInsert {
		if !hasData {
			return err.Error(packageName, modQuery, "Exec: "+commandType, "Data is empty")
		}
		if !dataIsSlice {
			dataMs = []toolkit.M{dataM}
		}

		//-- validate
		for _, datam := range dataMs {
			idField, idValue := toolkit.IdInfo(datam)
			toolkit.Serde(dbox.Find(q.data, []*dbox.Filter{dbox.Eq(idField, idValue)}), &indexes, "")
			if len(indexes) > 0 {
				return err.Error(packageName, modQuery, "Exec: "+commandType, toolkit.Sprintf("Data %v already exist", idValue))
			}
		}

		//-- insert the data
		q.data = append(q.data, dataMs...)
	} else if commandType == dbox.QueryPartUpdate {

		//-- valida
		if !hasData {
			return err.Error(packageName, modQuery, "Exec: "+commandType, "Data is empty")
		}

		var dataUpdate toolkit.M
		var updateDataIndex int

		// if it is a slice then we need to update each data passed on its slice
		isDataSlice := toolkit.IsSlice(data)
		if isDataSlice == false {
			isDataSlice = false
			e = toolkit.Serde(data, &dataUpdate, "")
			if e != nil {
				return err.Error(packageName, modQuery, "Exec: "+commandType, "Serde data fail"+e.Error())
			}
		}

		var idField string
		//toolkit.Printf("Indexes: %s\n", toolkit.JsonString(indexes))

		for i, v := range q.data {
			// update only data that match given inde
			if toolkit.HasMember(indexes, i) || !hasWhere {
				if idField == "" {
					idField = toolkit.IdField(v)
					if idField == "" {
						return err.Error(packageName, modQuery, "Exec: "+commandType, "No ID")
					}
				}

				// If dataslice is sent, iterate f
				if isDataSlice {
					e = toolkit.Serde(toolkit.SliceItem(data, updateDataIndex), &dataUpdate, "")
					if e != nil {
						return err.Error(packageName, modQuery, "Exec: "+commandType, "Serde data fail "+e.Error())
					}
					updateDataIndex++
				}
				dataOrigin := q.data[i]
				toolkit.CopyM(&dataUpdate, &dataOrigin, false, []string{"_id"})
				toolkit.Serde(dataOrigin, &v, "")
				q.data[i] = v
			}
		}
	} else if commandType == dbox.QueryPartDelete {
		if hasWhere && len(where) > 0 {
			indexes := dbox.Find(q.data, where)
			if len(indexes) > 0 {
				newdata := []toolkit.M{}
				for index, v := range q.data {
					partOfIndex := toolkit.HasMember(indexes, index)
					if partOfIndex == false {
						newdata = append(newdata, v)
					}
					//toolkit.Println("i:", indexes, ", index:", index, ", p.ofIndex: ", partOfIndex, ", data: ", toolkit.JsonString(newdata))
				}
				q.data = newdata
			}
		} else {
			q.data = []toolkit.M{}
		}
		//toolkit.Printf("Data now: %s\n", toolkit.JsonString(q.data))
	} else if commandType == dbox.QueryPartSave {
		if !hasData {
			return err.Error(packageName, modQuery, "Exec: "+commandType, "Data is empty")
		}

		var dataMs []toolkit.M
		var dataM toolkit.M
		if !toolkit.IsSlice(data) {
			e = toolkit.Serde(&data, &dataM, "json")
			if e != nil {
				return err.Error(packageName, modQuery, "Exec: "+commandType+" Serde data fail", e.Error())
			}
			dataMs = append(dataMs, dataM)
		} else {
			e = toolkit.Serde(&data, &dataMs, "json")
			if e != nil {
				return err.Error(packageName, modQuery, "Exec: "+commandType+" Serde data fail", e.Error())
			}
		}
		//toolkit.Printf("Saving: %s\n", toolkit.JsonString(dataMs))

		for _, v := range dataMs {
			idField, idValue := toolkit.IdInfo(v)
			indexes := dbox.Find(q.data, []*dbox.Filter{dbox.Eq(idField, idValue)})
			if len(indexes) == 0 {
				q.data = append(q.data, v)
			} else {
				dataOrigin := q.data[indexes[0]]
				//toolkit.Printf("Copy data %s to %s\n", toolkit.JsonString(v), toolkit.JsonString(dataOrigin))
				toolkit.CopyM(&v, &dataOrigin, false, []string{idField})
				q.data[indexes[0]] = dataOrigin
			}
		}
	}
	e = q.writeFile()
	if e != nil {
		return err.Error(packageName, modQuery, "Exec: "+commandType+" Write fail", e.Error())
	}
	return nil
}
Beispiel #5
0
func (q *Query) Exec(parm toolkit.M) error {
	var e error
	if parm == nil {
		parm = toolkit.M{}
	}
	// fmt.Println("Parameter Exec : ", parm)

	dbname := q.Connection().Info().Database
	tablename := ""

	if parm == nil {
		parm = toolkit.M{}
	}
	data := parm.Get("data", nil)

	// fmt.Println("Hasil ekstraksi Param : ", data)

	//========================EXTRACT FIELD, DATA AND FORMAT DATE=============================

	var attributes string
	var values string
	var setUpdate string

	if data != nil {

		var reflectValue = reflect.ValueOf(data)
		if reflectValue.Kind() == reflect.Ptr {
			reflectValue = reflectValue.Elem()
		}
		var reflectType = reflectValue.Type()

		for i := 0; i < reflectValue.NumField(); i++ {
			namaField := reflectType.Field(i).Name
			dataValues := reflectValue.Field(i).Interface()
			stringValues := StringValue(dataValues, q.GetDriverDB())
			if i == 0 {
				attributes = "(" + namaField
				values = "(" + stringValues
				setUpdate = namaField + " = " + stringValues
			} else {
				attributes += " , " + namaField
				values += " , " + stringValues
				setUpdate += " , " + namaField + " = " + stringValues
			}
		}
		attributes += ")"
		values += ")"
	}

	//=================================END OF EXTRACTION=======================================

	temp := ""
	parts := crowd.From(q.Parts()).Group(func(x interface{}) interface{} {
		qp := x.(*dbox.QueryPart)
		temp = toolkit.JsonString(qp)
		return qp.PartType
	}, nil).Data

	fromParts, hasFrom := parts[dbox.QueryPartFrom]
	if !hasFrom {

		return errorlib.Error(packageName, "Query", modQuery, "Invalid table name")
	}
	tablename = fromParts.([]interface{})[0].(*dbox.QueryPart).Value.(string)

	var where interface{}
	whereParts, hasWhere := parts[dbox.QueryPartWhere]
	if hasWhere {
		fb := q.Connection().Fb()
		for _, p := range whereParts.([]interface{}) {
			fs := p.(*dbox.QueryPart).Value.([]*dbox.Filter)
			for _, f := range fs {
				fb.AddFilter(f)
			}
		}
		where, e = fb.Build()
		if e != nil {

		} else {

		}

	}
	commandType := ""
	multi := false

	_, hasDelete := parts[dbox.QueryPartDelete]
	_, hasInsert := parts[dbox.QueryPartInsert]
	_, hasUpdate := parts[dbox.QueryPartUpdate]
	_, hasSave := parts[dbox.QueryPartSave]

	if hasDelete {
		commandType = dbox.QueryPartDelete
	} else if hasInsert {
		commandType = dbox.QueryPartInsert
	} else if hasUpdate {
		commandType = dbox.QueryPartUpdate
	} else if hasSave {
		commandType = dbox.QueryPartSave
	}

	if data == nil {
		//---
		multi = true
	} else {
		if where == nil {
			id := toolkit.Id(data)
			if id != nil {
				where = (toolkit.M{}).Set("_id", id)
			}
		} else {
			multi = true
		}
	}
	session := q.Session()

	if dbname != "" && tablename != "" && multi == true {

	}
	if commandType == dbox.QueryPartInsert {

	} else if commandType == dbox.QueryPartUpdate {
		statement := "UPDATE " + tablename + " SET " + setUpdate + " WHERE " + cast.ToString(where)
		fmt.Println("Update Statement : ", statement)
		_, e = session.Exec(statement)
		if e != nil {
			fmt.Println(e.Error())
		}

	} else if commandType == dbox.QueryPartDelete {
		if where == nil {
			statement := "DELETE FROM " + tablename
			fmt.Println(statement)
			_, e = session.Exec(statement)
			if e != nil {
				fmt.Println(e.Error())
			}
		} else {
			statement := "DELETE FROM " + tablename + " where " + cast.ToString(where)
			fmt.Println(statement)
			_, e = session.Exec(statement)
			if e != nil {
				fmt.Println(e.Error())
			}
		}

	} else if commandType == dbox.QueryPartSave {

		statement := "INSERT INTO " + tablename + " " + attributes + " VALUES " + values
		fmt.Println("Insert Statement : ", statement)
		_, e = session.Exec(statement)
		if e != nil {
			fmt.Println(e.Error())
		}
	}
	if e != nil {
		return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
	}
	return nil
}
Beispiel #6
0
func (q *Query) HasPartExec() error {
	var jsonString []byte
	var err error
	if q.hasNewSave {
		var newData []toolkit.M //interface{}
		for _, v := range q.sliceData {
			if len(v) != 0 {
				newData = append(newData, v)
			}
		}
		q.sliceData = newData

		jsonString, err = json.MarshalIndent(q.sliceData, "", "  ")
		if err != nil {
			return errorlib.Error(packageName, modQuery+".Exec", "Has part exec Marshal JSON", err.Error())
		}
	} else if q.hasSave {
		var newData []toolkit.M //interface{}
		for _, v := range q.sliceData {
			if len(v) != 0 {
				newData = append(newData, v)
			}
		}

		lastJson := q.Connection().(*Connection).getJsonToMap
		var dataAfterUnset []toolkit.M
		for _, v := range lastJson {
			id := toolkit.Id(v)
			sId := ToString(reflect.ValueOf(id).Kind(), id)

			for _, vSlice := range newData {
				idLast := toolkit.Id(vSlice)
				sIdLast := ToString(reflect.ValueOf(idLast).Kind(), idLast)

				if strings.ToLower(sId) == strings.ToLower(sIdLast) {
					for k, _ := range v {
						v.Unset(k)
					}
				}
			}
			if len(v) != 0 {
				dataAfterUnset = append(dataAfterUnset, v)
			}

		}

		var allJsonData []toolkit.M
		allJsonData = append(dataAfterUnset, newData...)

		jsonString, err = json.MarshalIndent(allJsonData, "", "  ")
		if err != nil {
			return errorlib.Error(packageName, modQuery+".Exec", "Has part exec Marshal JSON", err.Error())
		}
	}

	err = ioutil.WriteFile(q.Connection().(*Connection).filePath, jsonString, 0666)
	if err != nil {
		return errorlib.Error(packageName, modQuery+".Exec", "Write file", err.Error())
	}
	return nil
}
Beispiel #7
0
func finUpdateObj(jsonData []toolkit.M, replaceData toolkit.M, isType string) []toolkit.M {
	var (
		remMap toolkit.M
		mapVal []toolkit.M
	)

	if isType == "update" {
		iReplaceData := toolkit.Id(replaceData)
		reflectIs := reflect.ValueOf(iReplaceData).Kind()
		dataUptId := fmt.Sprintf("%s", ToString(reflectIs, iReplaceData))

		for _, v := range jsonData {
			iSubV := toolkit.Id(v)
			reflectIs := reflect.ValueOf(iSubV).Kind()
			subvIdString := fmt.Sprintf("%s", ToString(reflectIs, iSubV))
			if strings.ToLower(subvIdString) == strings.ToLower(dataUptId) {
				for key, _ := range v {
					delete(v, key)
				}

			}

			// if len(v) != 0 {
			var newData = make(map[string]interface{})
			for i, dataUpt := range replaceData {
				newData[i] = dataUpt
			}
			for i, newSubV := range v {
				newData[i] = newSubV
			}
			mapVal = append(mapVal, newData)
			// }
		}

		// mapVal = append(mapVal, replaceData)

		return mapVal
	} else if isType == "insert" {
		val := append(jsonData, replaceData)
		return val
	} else if isType == "deleteMulti" {
		for _, v := range jsonData {
			for _, subV := range v {
				reflectIs := reflect.ValueOf(subV).Kind()
				subvIdString := fmt.Sprintf("%s", ToString(reflectIs, subV))

				for _, dataUpt := range replaceData {
					reflectIs := reflect.ValueOf(dataUpt).Kind()
					dataUptId := fmt.Sprintf("%s", ToString(reflectIs, dataUpt))

					if strings.ToLower(dataUptId) == strings.ToLower(subvIdString) {
						remMap = v
						break
					}
				}

				for key, remVal := range remMap {
					delete(v, key)

					if reflect.ValueOf(subV).Kind() == reflect.String && reflect.ValueOf(remVal).Kind() == reflect.String {
						if strings.ToLower(remVal.(string)) == strings.ToLower(subV.(string)) {
							break
						}
					}
				}
			}

			if len(v) != 0 {
				var newData = make(map[string]interface{})
				for i, newSubV := range v {
					newData[i] = newSubV
				}
				mapVal = append(mapVal, newData)
			} /*else {
				var emptySlice toolkit.M
				mapVal = append(mapVal, emptySlice)
			}*/

		}
		return mapVal
	}
	return nil

}
Beispiel #8
0
func (q *Query) Exec(parm toolkit.M) error {
	var e error

	if parm == nil {
		parm = toolkit.M{}
	}

	data := parm.Get("data", nil)
	filePath := q.Connection().(*Connection).filePath
	/*
		p arts will return E - map{interface{}}interface{}
		where each interface{} returned is slice of interfaces --> []interface{}
	*/
	parts := crowd.From(q.Parts()).Group(func(x interface{}) interface{} {
		qp := x.(*dbox.QueryPart)
		/*
			fmt.Printf("[%s] QP = %s \n",
				toolkit.Id(data),
				toolkit.JsonString(qp))
		*/
		return qp.PartType
	}, nil).Data

	var where interface{}
	commandType := ""
	multi := false

	_, hasDelete := parts[dbox.QueryPartDelete]
	_, hasInsert := parts[dbox.QueryPartInsert]
	_, hasUpdate := parts[dbox.QueryPartUpdate]
	_, hasSave := parts[dbox.QueryPartSave]

	if hasDelete {
		commandType = dbox.QueryPartDelete
	} else if hasInsert {
		commandType = dbox.QueryPartInsert
	} else if hasUpdate {
		commandType = dbox.QueryPartUpdate
	} else if hasSave {
		commandType = dbox.QueryPartSave
	}
	//fmt.Printf("Data:\n%v\n", toolkit.JsonString(data))

	if data == nil {
		//---
		multi = true

		//
		whereParts, hasWhere := parts[dbox.QueryPartWhere]
		if hasWhere {

			fb := q.Connection().Fb()
			for _, p := range whereParts.([]interface{}) {
				fs := p.(*dbox.QueryPart).Value.([]*dbox.Filter)
				for _, f := range fs {
					fb.AddFilter(f)
				}
			}
			where, e = fb.Build()
			if e != nil {
				return errorlib.Error(packageName, modQuery, "Cursor",
					e.Error())
			} else {
				//fmt.Printf("Where: %s", toolkit.JsonString(where))
			}
		}
	} else {
		if where == nil {
			id := toolkit.Id(data)
			if id != nil {
				where = (toolkit.M{}).Set("id", id)
			}
		} else {
			multi = true
		}
	}

	if commandType == dbox.QueryPartInsert {

		var jsonUpdatedValue []byte
		if reflect.ValueOf(data).Kind() == reflect.Slice {
			readF, _ := ioutil.ReadFile(filePath)

			var dataMap []toolkit.M
			e := json.Unmarshal(readF, &dataMap)
			if e != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}

			j, err := json.Marshal(data)
			if err != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}

			var jToMap []toolkit.M
			e = json.Unmarshal(j, &jToMap)

			var sliceData []toolkit.M
			for _, v := range jToMap {
				id := toolkit.Id(v)
				if id == nil {
					return errorlib.Error(packageName, modCursor+".Exec", commandType, "Unable to find ID when insert slice data")
				}
				sliceData = finUpdateObj(dataMap, v, "insert")
			}

			jsonUpdatedValue, err = json.MarshalIndent(sliceData, "", "  ")
			if err != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}
		} else {
			readF, e := ioutil.ReadFile(filePath)
			if e != nil {
				return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
			}

			var dataMap []toolkit.M
			e = json.Unmarshal(readF, &dataMap)
			if e != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}
			dataToMap, e := toolkit.ToM(data)
			if e != nil {
				return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
			}

			id := toolkit.Id(dataToMap)
			if id == nil {
				return errorlib.Error(packageName, modCursor+".Exec", commandType, "Unable to find ID when insert struct data")
			}
			idToS := ToString(reflect.ValueOf(id).Kind(), id)

			for _, vDataMap := range dataMap {
				idDataMap := toolkit.Id(vDataMap)
				idToSMap := ToString(reflect.ValueOf(idDataMap).Kind(), idDataMap)
				if id == nil {
					return errorlib.Error(packageName, modCursor+".Exec", commandType, "Unable to find ID when insert struct data")
				}

				if strings.ToLower(idToS) == strings.ToLower(idToSMap) {
					return errorlib.Error(packageName, modCursor+".Exec", commandType, "ID "+idToSMap+" already exist, unable insert data ")
				}
			}

			updatedValue := finUpdateObj(dataMap, dataToMap, "insert")
			jsonUpdatedValue, e = json.MarshalIndent(updatedValue, "", "  ")
			if e != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}
		}

		q.Connection().(*Connection).WriteSession()
		i, e := q.Connection().(*Connection).openFile.Write(jsonUpdatedValue) //t.WriteString(string(j))
		if i == 0 || e != nil {
			return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
		}

		err := q.Connection().(*Connection).CloseWriteSession()
		if err != nil {
			return errorlib.Error(packageName, modQuery+".Exec", commandType, err.Error())
		}
	} else if commandType == dbox.QueryPartUpdate {
		if multi {
			// 		_, e = mgoColl.UpdateAll(where, data)
		} else {
			readF, e := ioutil.ReadFile(filePath)
			if e != nil {
				return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
			}

			var dataMap []toolkit.M
			e = json.Unmarshal(readF, &dataMap)
			if e != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}
			a, e := toolkit.ToM(data)
			if e != nil {
				return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
			}

			id := toolkit.Id(a)
			if id == nil {
				return errorlib.Error(packageName, modCursor+".Exec", commandType, "Unable to find ID when update data")
			}

			updatedValue := finUpdateObj(dataMap, a, "update")

			jsonUpdatedValue, err := json.MarshalIndent(updatedValue, "", "  ")
			if err != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}

			err = q.Connection().(*Connection).WriteSession()
			if err != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, err.Error())
			}

			i, e := q.Connection().(*Connection).openFile.Write(jsonUpdatedValue) //t.WriteString(string(j))
			if i == 0 || e != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
			}

			err = q.Connection().(*Connection).CloseWriteSession()
			if err != nil {
				return errorlib.Error(packageName, modQuery+".Exec", commandType, err.Error())
			}
		}
	} else if commandType == dbox.QueryPartDelete {
		if multi {
			if where != nil {
				readF, e := ioutil.ReadFile(filePath)
				if e != nil {
					return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
				}

				var dataMap []toolkit.M
				e = json.Unmarshal(readF, &dataMap)
				if e != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}
				a, e := toolkit.ToM(where)
				if e != nil {
					return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
				}

				id := toolkit.Id(a)
				if id == nil {
					return errorlib.Error(packageName, modCursor+".Exec", commandType, "Unable to find ID when delete data")
				}

				updatedValue := finUpdateObj(dataMap, a, "deleteMulti")

				jsonUpdatedValue, err := json.MarshalIndent(updatedValue, "", "  ")
				if err != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}

				err = q.Connection().(*Connection).WriteSession()
				if err != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, err.Error())
				}

				if string(jsonUpdatedValue) == "null" {
					ioutil.WriteFile(q.Connection().(*Connection).filePath, []byte("[\n]"), 0666)
				} else {
					i, e := q.Connection().(*Connection).openFile.Write(jsonUpdatedValue) //t.WriteString(string(j))
					if i == 0 || e != nil {
						return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
					}

					err = q.Connection().(*Connection).CloseWriteSession()
					if err != nil {
						return errorlib.Error(packageName, modQuery+".Exec", commandType, err.Error())
					}
				}
			} else {
				e := os.Remove(filePath)
				if e != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}

				_, err := os.Stat(filePath)
				if os.IsNotExist(err) {
					cf, e := os.Create(filePath)
					if e != nil {
						return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
					}
					cf.Close()
				}
				ioutil.WriteFile(q.Connection().(*Connection).filePath, []byte("[\n]"), 0666)
			}
		} else {

		}
	} else if commandType == dbox.QueryPartSave {
		/*dataType := reflect.ValueOf(data).Kind()
		//fmt.Printf("DataType: %s\nData:\n%v\n", dataType.String(), toolkit.JsonString(data))
		if reflect.Slice == dataType {
			if q.Connection().(*Connection).openFile == nil {
				q.Connection().(*Connection).OpenSession()
			}

			if q.Connection().(*Connection).isNewSave {
				j, err := json.MarshalIndent(data, "", "  ")
				if err != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}

				i, e := q.Connection().(*Connection).openFile.Write(j) //t.WriteString(string(j))
				if i == 0 || e != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}
			} else {
				readF, e := ioutil.ReadFile(filePath)
				if e != nil {
					return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
				}

				var dataMap, newData []map[string]interface{}
				if e := json.Unmarshal(readF, &dataMap); e != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}

				v := toolkit.JsonString(data)
				if e = json.Unmarshal([]byte(v), &newData); e != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}

				mergeData := append(dataMap, newData...)

				jsonUpdatedValue, err := json.MarshalIndent(mergeData, "", "  ")
				if err != nil {
					return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
				}

				e = ioutil.WriteFile(filePath, jsonUpdatedValue, 0666)
				if e != nil {
					return errorlib.Error(packageName, modQuery+".Exec", "Write file", e.Error())
				}
			}
		} else {*/
		if q.Connection().(*Connection).openFile == nil {
			q.Connection().(*Connection).OpenSession()
		}
		q.dataType = "struct"
		dataMap, e := toolkit.ToM(data)
		if e != nil {
			return errorlib.Error(packageName, modCursor+".Exec", commandType, e.Error())
		}

		id := toolkit.Id(dataMap)
		if id == nil {
			return errorlib.Error(packageName, modCursor+".Exec", commandType, "Unable to find ID")
		}

		idString := ToString(reflect.ValueOf(id).Kind(), id)

		if q.Connection().(*Connection).sData == "" {
			q.Connection().(*Connection).sData = idString
		} else if q.Connection().(*Connection).sData == idString {
			q.Connection().(*Connection).sData = idString
			updatedValue := finUpdateObj(q.sliceData, dataMap, "update")
			q.sliceData = updatedValue
		} else {
			q.Connection().(*Connection).sData = idString
			_ = finUpdateObj(q.sliceData, dataMap, "update")
			q.sliceData = append(q.sliceData, dataMap)
		}

		if len(q.sliceData) == 0 {
			q.sliceData = append(q.sliceData, dataMap)
		}

		if q.Connection().(*Connection).isNewSave {
			q.hasNewSave = hasSave
		} else {
			q.hasSave = hasSave
		}
		/*}*/
	}

	if e != nil {
		return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
	}

	return nil
}
Beispiel #9
0
func (q *Query) Exec(parm toolkit.M) error {
	var (
		e                    error
		updatedValue, dataMs []toolkit.M
		dataM                toolkit.M
	)

	filters, e := q.Filters(parm)
	if e != nil {
		return errorlib.Error(packageName, modQuery, "Exec", e.Error())
	}

	if parm == nil {
		parm = toolkit.M{}
	}

	data := parm.Get("data", nil)
	filePath := q.Connection().(*Connection).filePath
	commandType := filters.Get("cmdType").(string)
	hasWhere := filters.Has("where")
	hasCmdType := toolkit.M{}
	hasData := parm.Has("data")
	getWhere := filters.Get("where", []*dbox.Filter{}).([]*dbox.Filter)
	dataIsSlice := toolkit.IsSlice(data)
	if dataIsSlice {
		e = toolkit.Unjson(toolkit.Jsonify(data), &dataMs)
		if e != nil {
			return errorlib.Error(packageName, modQuery, "Exec: "+commandType, "Data encoding error: "+e.Error())
		}
		for _, v := range dataMs {
			id := toolkit.Id(v)
			idF := toolkit.IdField(v)

			if toolkit.IsNilOrEmpty(id) {
				return errorlib.Error(packageName, modCursor+".Exec", commandType, "Unable to find ID in slice data")
			} else {
				getWhere = []*dbox.Filter{dbox.Eq(idF, id)}
			}
		}
	} else {
		dataM, e = toolkit.ToM(data)
		if e != nil {
			return errorlib.Error(packageName, modQuery, "Exec: "+commandType, "Unable to Map, error: "+e.Error())
		}

		id := toolkit.Id(dataM)
		if !toolkit.IsNilOrEmpty(id) {
			getWhere = []*dbox.Filter{dbox.Eq(toolkit.IdField(dataM), id)}
		}
	}

	var dataMaps []toolkit.M
	q.ReadFile(&dataMaps, filePath)

	if commandType == dbox.QueryPartInsert {
		hasCmdType.Set("hasInsert", true)

		if !hasData {
			return errorlib.Error(packageName, modCursor+".Exec", commandType, "Sorry data not found!, unable to insert data")
		}

		result := dbox.Find(dataMaps, getWhere)
		if len(result) > 0 {
			return errorlib.Error(packageName, modCursor+".Exec", commandType, "ID already exist, unable insert data ")
		}

		if dataIsSlice {
			var sliceData []toolkit.M
			for _, v := range dataMs {
				sliceData = finUpdateObj(dataMaps, v, "insert")
			}
			updatedValue = sliceData
		} else {
			updatedValue = finUpdateObj(dataMaps, dataM, "insert")
		}
	} else if commandType == dbox.QueryPartUpdate {
		hasCmdType.Set("hasUpdate", true)

		if !hasData {
			return errorlib.Error(packageName, modCursor+".Exec", commandType, "Sorry data not found!, unable to update data")
		}

		if hasWhere {
			var indexes []interface{}
			whereIndex := dbox.Find(dataMaps, getWhere)
			indexes = toolkit.ToInterfaceArray(&whereIndex)
			// toolkit.Printf("whereIndex>%v indexes%v\n", whereIndex, indexes)

			var dataUpdate toolkit.M
			var updateDataIndex int
			isDataSlice := toolkit.IsSlice(data)
			if isDataSlice == false {
				isDataSlice = false
				data, e = toolkit.ToM(data)
				if e != nil {
					return errorlib.Error(packageName, modQuery, "Exec: "+commandType, "Serde data fail"+e.Error())
				}

				e = toolkit.Serde(data, &dataUpdate, "")
				if e != nil {
					return errorlib.Error(packageName, modQuery, "Exec: "+commandType, "Serde data fail"+e.Error())
				}
			}

			for i, v := range dataMaps {
				if toolkit.HasMember(indexes, i) || !hasWhere {
					if isDataSlice {
						e = toolkit.Serde(toolkit.SliceItem(data, updateDataIndex), &dataUpdate, "")
						if e != nil {
							return errorlib.Error(packageName, modQuery, "Exec: "+commandType, "Serde data fail"+e.Error())
						}
						updateDataIndex++
					}

					dataOrigin := dataMaps[i]
					toolkit.CopyM(&dataUpdate, &dataOrigin, false, []string{"_id"})
					toolkit.Serde(dataOrigin, &v, "")
					dataMaps[i] = v
				}
			}
			updatedValue = dataMaps
		} else {
			updatedValue = finUpdateObj(dataMaps, dataM, "update")
		}
	} else if commandType == dbox.QueryPartDelete {
		hasCmdType.Set("hasDelete", true)
		// if multi {
		if hasWhere {
			result := dbox.Find(dataMaps, getWhere)
			if len(result) > 0 {
				for i, v := range dataMaps {
					if toolkit.HasMember(result, i) == false {
						updatedValue = append(updatedValue, v)
					}
				}
			}
		} else {
			updatedValue = []toolkit.M{}
		}
	} else if commandType == dbox.QueryPartSave {
		hasCmdType.Set("hasSave", true)
		if !hasData {
			return errorlib.Error(packageName, modCursor+".Exec", commandType, "Sorry data not found!, unable to update data")
		}

		q.dataType = "save"
		q.whereData = append(q.whereData, getWhere...)
		q.sliceData = append(q.sliceData, dataM)
	}

	if hasCmdType.Has("hasInsert") || hasCmdType.Has("hasUpdate") || hasCmdType.Has("hasDelete") {
		e = q.WriteFile(updatedValue)
		if e != nil {
			return errorlib.Error(packageName, modQuery+".Exec", commandType, e.Error())
		}
	}

	return nil
}
Beispiel #10
0
func (q *Query) Exec(in toolkit.M) error {
	setting, e := q.prepare(in)
	commandType := setting["commandtype"].(string)
	if e != nil {
		return err.Error(packageName, modQuery, "Exec: "+commandType, e.Error())
	}

	if setting.GetString("commandtype") == dbox.QueryPartSelect {
		return err.Error(packageName, modQuery, "Exec: "+commandType, "Exec is not working with select command, please use .Cursor instead")
	}

	q.Lock()
	defer q.Unlock()

	var dataM toolkit.M
	var dataMs []toolkit.M

	hasData := in.Has("data")
	dataIsSlice := false
	data := in.Get("data")
	if toolkit.IsSlice(data) {
		dataIsSlice = true
		e = toolkit.Unjson(toolkit.Jsonify(data), dataMs)
		if e != nil {
			return err.Error(packageName, modQuery, "Exec: "+commandType, "Data encoding error: "+e.Error())
		}
	} else {
		dataM, e = toolkit.ToM(data)
		dataMs = append(dataMs, dataM)
		if e != nil {
			return err.Error(packageName, modQuery, "Exec: "+commandType, "Data encoding error: "+e.Error())
		}
	}

	hasWhere := in.Has("where")
	where := in.Get("where", []*dbox.Filter{}).([]*dbox.Filter)

	if hasData && hasWhere == false && toolkit.HasMember([]interface{}{dbox.QueryPartInsert, dbox.QueryPartUpdate, dbox.QueryPartSave}, commandType) {
		hasWhere = true
		if toolkit.IsSlice(data) {
			ids := []interface{}{}
			idField := ""
			if idField == "" {
				return err.Error(packageName, modQuery, "Exec:"+commandType, "Data send is a slice, but its element has no ID")
			}
			dataCount := toolkit.SliceLen(data)
			for i := 0; i < dataCount; i++ {
				dataI := toolkit.SliceItem(data, i)
				if i == 0 {
					idField = toolkit.IdField(dataI)
				}
				ids = append(ids, toolkit.Id(dataI))
			}
			where = []*dbox.Filter{dbox.In(idField, ids)}
		} else {
			id := toolkit.Id(data)
			if toolkit.IsNilOrEmpty(id) {
				where = []*dbox.Filter{dbox.Eq(toolkit.IdField(id), id)}
			} else {
				where = nil
				hasWhere = false
			}
		}
	}

	q.openFile()
	if commandType == dbox.QueryPartInsert {
		if !hasData {
			return err.Error(packageName, modQuery, "Exec:"+commandType, "Data is empty")
		}
		if dataIsSlice {
			q.data = append(q.data, dataMs...)
		} else {
			q.data = append(q.data, dataM)
		}
	} else if commandType == dbox.QueryPartUpdate {
		if !hasData {
			return err.Error(packageName, modQuery, "Exec:"+commandType, "Data is empty")
		}

		var indexes []interface{}
		if hasWhere {
			toolkit.Serde(dbox.Find(q.data, where), &indexes, "")
		}

		var dataUpdate toolkit.M
		var updateDataIndex int

		isDataSlice := toolkit.IsSlice(data)
		if isDataSlice == false {
			isDataSlice = false
			e = toolkit.Serde(data, &dataUpdate, "")
			if e != nil {
				return err.Error(packageName, modQuery, "Exec:"+commandType, "Unable to serialize data. "+e.Error())
			}
		}
		var idField string
		for i, v := range q.data {
			if toolkit.HasMember(indexes, i) || len(indexes) == 0 {
				if idField == "" {
					idField = toolkit.IdField(v)
					if idField == "" {
						return err.Error(packageName, modQuery, "Exec:"+commandType, "No ID")
					}
				}

				var dataOrigin toolkit.M
				e = toolkit.Serde(v, &dataOrigin, "")
				if e != nil {
					return err.Error(packageName, modQuery, "Exec:"+commandType, "Unable to serialize data origin. "+e.Error())
				}
				if isDataSlice {
					e = toolkit.Serde(toolkit.SliceItem(data, updateDataIndex), &dataUpdate, "")
					if e != nil {
						return err.Error(packageName, modQuery, "Exec:"+commandType, "Unable to serialize data. "+e.Error())
					}
					updateDataIndex++
				}
				for fieldName, fieldValue := range dataUpdate {
					if fieldName != idField {
						if dataOrigin.Has(fieldName) {
							dataOrigin.Set(fieldName, fieldValue)
						}

					}
				}
				toolkit.Serde(dataOrigin, &v, "")
				q.data[i] = v
			}
		}
	} else if commandType == dbox.QueryPartDelete {
		if hasWhere {
			var indexes []interface{}
			toolkit.Serde(dbox.Find(q.data, where), &indexes, "")
			if len(indexes) > 0 {
				newdata := []toolkit.M{}
				for index, v := range q.data {
					if toolkit.HasMember(indexes, index) == false {
						newdata = append(newdata, v)
					}
				}
				q.data = newdata
			}
		} else {
			q.data = []toolkit.M{}
		}
	} else if commandType == dbox.QueryPartSave {
		if !hasData {
			return err.Error(packageName, modQuery, "Exec:"+commandType, "Data is empty")
		}
	}
	q.writeFile()
	return nil
}