#
#	action sequence for object action addQueryAttribute
#
# log start
qexpression 
	copycvars(this,"action,objtype,attribute,key,value");
	logger.debug("setQueryAttribute: 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	alreadyccrw

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

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

#
# attribute is not yet present in CCRW and query does not have a 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, refuse to add it
#
alreadyccrw:
qexpression		this.errcoll.collect(null,"Attribute "+this.attribute+" already defined in CCRW for query "+this.key,this.qares);

#
# terminate flow
#
goto done

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

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

#
# attribute already defined in MFILE, refuse to process further
#
qexpression
	this.errcoll.collect(null,"Attribute "+this.attribute+" already defined in query definition managed file "+
									this.definition_mfileid+" for query "+this.key,this.mfctx.query);

#
# terminate flow
#
goto done
	

#
# add attribute to dquerymfile (append to end of file)
#
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};
