#
#	action sequence for object action copyTextfrag
#
# 0: determine SQL statement and key values
qexpression
	proc: {
		copycvars(this,"action,objtype,attribute,key,value");
		this.newkeyseq = 0;
		this.keyparts = this.key.split("%%%");
		if (this.keyparts.length!=3) {
			this.errcoll.collect(null,"textfrag key does not have 3 parts",{ key: this.key });
			break proc;
		}
		this.ident = this.keyparts[0];
		this.child_index = this.keyparts[1];
		this.frag_index = this.keyparts[2];
		this.newkeyroot = this.keyparts.join("__");
		logger.debug("copyTextfrag.key="+this.key+".newkeyroot="+this.newkeyroot);
	}
	
#
# 1: first, check if the copy identity is already existing
#
check_new:
pre_qexpression
	this.newident = (this.newkeyseq>0)?(this.newkeyroot+this.newkeyseq):this.newkeyroot;
	logger.debug("copyTextfrag.newident="+this.newident);
sql				select * from CCTEXTFRAG where ident=::newident::
named_params	newident
result_varname	creadres

#
# 2: if not yet existing, create it
#
pre_qexpression
	logger.debug("copyTextfrag.check_read.rowcount="+this.creadres.getRowCount());
if (this.creadres.getRowCount()<1)
goto create_copy

#
# 3: new ident already there, create new sequence number
#
pre_qexpression
	this.newkeyseq++;
	logger.debug("copyTextfrag.newkeyseq="+this.newkeyseq);
goto check_new

#
# 4: create new record, read original and prepare new ident
#
create_copy:
pre_qexpression
	logger.debug("copyTextfrag.before_read_original");
sql				select type,ident,parent,version,child_index,frag_index,data from CCTEXTFRAG where ident=::ident:: and child_index=::child_index:: and frag_index=::frag_index::
named_params	ident,child_index,frag_index
result_varname  oreadres
post_qexpression
	proc: {
		logger.debug("copyTextfrag.original.rowcount="+this.oreadres.getRowCount());
		if (this.oreadres.getRowCount()!=1) {
			this.errcoll.collect(null,"copyTextfrag: read original for key=\""+this.key+"\" did not return exactly one row",this.oreadres);
			break proc;
		}
		this.orow = this.oreadres.getRowObject(0);
		logger.debug("copyTextfrag.orig: "+aux.objTxt(this.orow));
		for (let cnam in this.orow) {
			this[cnam] = this.orow[cnam];
			logger.debug("copyTextfrag.copy_orig.nam="+cnam+".val="+this[cnam]);
		}
	}


#
# 5: insert the new record
#
sql				insert into CCTEXTFRAG(type,ident,parent,version,child_index,frag_index,data)
				  values(::type::,::newident::,::parent::,::version::,::child_index::,::frag_index::,::data::)
named_params	type,newident,parent,version,child_index,frag_index,data
result_varname	insresult
post_qexpression
	logger.debug("copyTextfrag.insresult: "+aux.objTxt(this.insresult));

# 6: complete
goto done

#
# 7: finally, set chain query to re-display all text fragments
#
done:
qexpression this.query.chain_query = {dataname: "alltextFragInfo"};