Skip to content

Tcl_script_saveToFile

Paweł Salawa edited this page Jan 15, 2018 · 6 revisions

Definition

Language: Tcl
Plugin for language: ScriptingTcl
How to use: Create custom SQL function. Suggested name: saveToFile
Function arguments directory, fileName, contents
Function usage: SELECT saveToFile('/tmp/files', columnForFileName, columnWithContentsForFile) AS res FROM tableName;
SELECT saveToFile('C:/temp', column1 || '_' column2, 'Contents: ' || column3) AS res FROM tableName;
SELECT saveToFile('/tmp/files_' || dirSuffixColumn, 'file.txt', columnWithContentsForFile) AS res FROM tableName;
Description: This function is useful if you want to create a file for each row of data returned from a query. You can specify file name basing on columns, so for each row the file name will be different. You can also specify what contents go into the file. First argument defines where are the files created. If the directory doesn't exist, it's created (when possible). Function will return ok for each row saved successfully and error: ... with details when there was some problem with the specific row.

Code

if {[catch {
  lassign $argv dir fileName contents
  file mkdir $dir
  set fd [open "$dir/$fileName" a+]
  puts $fd $contents
  close $fd
} res]} {
  return "error: $res"
} else {
  return "ok"
}
You can’t perform that action at this time.