#
#		ITSV GmbH
#	CCDB - Command and Control Database
#
#	FILE:				deleteQueryAttribute_objaction.txt
#	DESCRIPTION:		Object Action steps sequence for object action "DELETE" on object class "query"
#						this file must be registered as managed file ID=objact_deleteQueryAttribute
#						to be executed when choosing object action "DELETE" on an object of class "query"
#
#	action sequence for object action deleteQueryAttribute
#
# log start
qexpression 
	copycvars(this,"action,objtype,attribute,key,value");
	logger.debug("deleteQueryAttribute: query: "+this.key+", attribute: "+this.attribute)

#
# determine if the attribute is 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	deleteinccrw

#
# 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, check the attribute there
#
if (this.mfres.getRowCount()>0)
goto checkinmfile

#
# 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 present in CCRW, delete it there
#
deleteinccrw:
sql				delete from CCRW where RWTYP='DQUERYPARAM' and RWPARENT=::key:: and RWNAME=::attribute::
named_params	key,attribute

#
# delete in CCRW complete
#
goto	done

#
# check if attribute contained in DQUERYMFILE
#
checkinmfile:
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 delete in MFILE
#
if		(this.mfileHasAttribute)
goto	deletefrommfile

#
#	attribute isn't in MFILE, nothing to delete
#
goto	done
	

#
# 	delete attribute from dquerymfile, temporarily implemented as overwriting with "delete" value
#	TODO: implement better deletion of attribute definition from DQUERYMFILE
#
deletefrommfile:
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");				// ^@<name> instructs MFILE compiler to DELETE query attribute <name>
	fs.closeSync(this.fd);
	
#
#	deleteQueryAttribute done, chain next query to re-display the query object
#
done:
qexpression this.query.chain_query = {dataname: "queryinfo", queryname: this.key};
