#
#			ITSV GmbH
#	CCDB - Command and Control Database
#
#	FILE:			dquerymfile_CRESTAB.txt
#	DESCRIPTION:	DQUERY definition for DQUERY CRESTAB
#
@querytitle					CCDB-Tabelle aus Strukturbeschreibung erstellen
@querydescription			Erstellt eine Tabelle in der CCDB aus den Angaben in der Strukturbeschreibung aus dem übergebenen Managed File
@group						DATAFILE
@attributenames				tabname:string:{{tabnameoptions}},smfileid:mfileid:{{smfileidoptions}}
@tabnameoptions				{"labeltext":"Tabellenname","typedesc":"Name der Tabelle in der CCDB, die angelegt werden soll. Diese Tabelle darf noch nicht existieren"}
@smfileidoptions			{"labeltext":"Struktur-Managed-File","typedesc":"Managed-File, das die Strukturbeschreibung enthält, nach der die Tabelle angelegt werden soll"}
@querytype					function
@function					seqtrans.seqtrans

~query.tsteps

#
# <<TSTEPNUM:0>>: check if table already exists
#
pre_qexpression
	this.tabname = this.query.tabname;
sql				select * from information_schema.columns where table_name=::tabname::
named_params	tabname
result_varname	tpcres
post_qexpression
	if (this.tpcres.getRowCount()>0) {
		this.errcoll.collect(null,"Table \""+this.tabname+"\" already exists",this.tpcres);
	}


#
# <<TSTEPNUM:1>>: read structure from structure managed file
#
aexpression
	mfile.get_mfile_data(this.query.smfileid,
							function(err,res) {
								if (err) {
									this.errcoll.collect(err,"Error reading structure description from managed file \""+this.query.smfileid+"\"",res);
									this();
									return;
								}
								this.smfres = res;
								this.ppush([this.phead("STRUCTFILEREAD"),"","",this.smfres.filedata]);
								this();
							}.bind(this),
							null,
							{ getfiledata: true });

#
# <<TSTEPNUM:2>>: create table from structure descriptor
#
qexpression
	logger.debug(this.phead("STRUCT_MFILEREAD")+".structure: "+aux.objTxt(this.smfres.filedata));
	this.struct = JSON.parse(this.smfres.filedata);
	db.createCCDBtable(this.tabname,
						{ tabledesc: this.struct, create_if_not: true },
						function(err,res) {
							if (err) {
								logger.debug("CRESTAB.create.error: "+aux.objTxt({err: err, res: res}));
								this.errcoll.collect(err,"Error in creating table \""+this.tabname+"\"",res);
								this();
								return;
							}
							this.ppush([this.phead("CREATED"),"TABNAME="+this.tabname,"",res]);
							this();
						}.bind(this),
						function(pstat) {
							this.pstat = { state: "creating table", pstat: pstat };
						}.bind(this)
						);
