0

I'm trying to execute a query in Caché and output the results to a file on a Unix server, but I'm having trouble finding the right commands.

I tried the following:

%SYS>s rs=##Class(%ResultSet).%New()
%SYS>s rs.ClassName="%SYS.Namespace"
%SYS>s rs.QueryName="List"
%SYS>s sc=rs.Prepare(rs.QueryName)
%SYS>s sc=rs.Execute()
%SYS>s fs=##Class(%IO.FileStream).%New()
%SYS>d fs.Open("/myDir/outputDir/test_filestream.txt")
%SYS>while rs.Next(){d fs.Write(rs.Nsp)}
%SYS>d fs.Close()
%SYS>s sc=rs.Close()

I didn't get any errors when I ran the above, but I also didn't get any output. I would like to have the file created if it doesn't already exist or overwrite it if it does. Is that possible with Caché commands or is server scripting the only way to accomplish this?

I'm having to do this all from the command line on the server so if easier functionality exists using a Caché utility like Caché Studio or Terminal, I don't have that luxury.

Thanks.

user2063351
  • 503
  • 2
  • 13
  • 31

2 Answers2

1

You can try this code

#; you can use simple call
s rs=##Class(%ResultSet).%New("%SYS.Namespace:List")
#; for query it does not need
#;s sc=rs.Prepare(rs.QueryName)
s sc=rs.Execute()
#; better to use %FileCharacterStream or %FileBinaryStream
s fs=##Class(%FileCharacterStream).%New()
s fs.Filename="/home/daimor/test_filestream.txt"
while rs.Next(){ d fs.WriteLine(rs.Nsp) }
#; important things, saving stream. Close don't  need now
d fs.SaveStream()
#; and we can see, what we saved
d fs.OutputToDevice()

And you can use NBStudio for editing existing routines or clasess in Linux, but you can't create new routines yet.

DAiMor
  • 3,185
  • 16
  • 24
0

I figured it out using the following:

%SYS>s rs=##Class(%ResultSet).%New()
%SYS>s rs.ClassName="%SYS.Namespace"
%SYS>s rs.QueryName="List"
%SYS>s sc=rs.Prepare(rs.QueryName)
%SYS>s sc=rs.Execute()
%SYS>s outFile="/myDir/outputDir/test_filestream.txt"
%SYS>OPEN outFile:"WNS" ; open in Write, New (overwrite if it exists in Windows/Unix, Stream mode)
%SYS>while rs.Next(){USE outFile WRITE rs.Nsp, !}
%SYS>CLOSE outFile

Apparently, you can also use the $ZF utility, but I'm not 100% clear on the syntax.

user2063351
  • 503
  • 2
  • 13
  • 31
  • I prefer @DAiMor's approach as it avoids using the file device directly and uses a stream abstraction to achieve what it needs. You can use the direct OPEN/USE/WRITE/CLOSE operations on the device, but you then need to add your own error handling. I believe your original example was missing the flags for the mode to open the file in -- I suspect you wanted "WNS" for your call to %IO.FileStream::Open(). – DdP Nov 21 '13 at 20:53