#
#	action sequence for object action setQueryAttribute
#
# log start
qexpression 
	copycvars(this,"action,objtype,attribute,key,value");
	logger.debug("setQueryAttribute: action: "+this.action+", query: "+this.key+", attribute: "+this.attribute+", value: "+this.value)

#
# determine if the attribute is already defined in CCRW
#
sql 			select * from CCRW where RWTYP='DQUERYPARAM' and RWPARENT=::key:: and RWNAME=::attribute::
named_params	key,attribute
result_varname	qares

if 		(this.qares.getRowCount()>0)
goto	updateccrw

#
# determine if the query has a dquerymfile
#
sql				select MFILEID,MFILEPATH from CCMFILES where ((MFILETYPE='gentext') or (MFILETYPE='dquerymfile')) and MFILEID=CONCAT('dquerymfile_',::key::)
named_params	key
result_varname	mfres

#
# if query has a dquerymfile, add the attribute there, otherwise add in CCRW
#
if (this.mfres.getRowCount()>0)
goto checkmfile

#
# attribute is not yet present, neither in CCRW nor in an DQUERYMFILE, add attribute to CCRW
#
sql INSERT INTO CCRW(RWTYP,RWPARENT,RWNAME,RWVALUE) VALUES('DQUERYPARAM',::key::,::attribute::,::value::)
named_params key,attribute,value

#
# write to CCRW complete
#
goto done

#
# attribute already present in CCRW, update it
#
updateccrw:
sql				update CCRW set RWVALUE=::value:: where RWTYP='DQUERYPARAM' and RWPARENT=::key:: and RWNAME=::attribute::
named_params	key,attribute,value

#
# update in CCRW complete
#
goto	done

#
# check if attribute contained in DQUERYMFILE
#
checkmfile:
qexpression
	proc: {
		this.mfctx = {};
		objcomp.compileMfile(this.mfres.getRowObject(0).MFILEID,
			this.mfctx;
			{	default_section: 'query'	},
			function(err,res) {
				if (err) {
					this.errcoll.collect(err,"Error in setQueryAttribute, compiling DQUERYMFILE ID="+this.mfres.getRowObject(0).MFILEID,res);
					break proc;
				}
				if (this.mfctx.query.hasOwnProperty(this.attribute)) {
					this.mfileHasAttribute = true;
				}
			}
		);
	}

#
#	determine to add new attribute or update existing attribute
#
unless	(this.mfileHasAttribute)
goto	addtomfile

#
#	as a temporary step, simple add the new value of the attribute to the end of the dquerymfile
#	TODO: implement better way to update the definitionof the attribute inside the MFILE
#
updateinmfile:
goto	addtomfile
	

#
# add attribute to dquerymfile
#
addtomfile:
qexpression
	this.mfpath = this.mfres.getRowObject(0).MFILEPATH;
	this.fd = fs.openSync(this.mfpath,"a");
	fs.writeSync(this.fd,
				"\n[query]\n" +
				"@"+this.attribute+"\n    "+this.value);
	fs.closeSync(this.fd);
	
#
#
#
done:
qexpression this.query.chain_query = {dataname: "queryinfo", queryname: this.key};
