/*
 	arguments: <directory>
 	
 	e.g.: script load_blobs.js "/Users/daust/Desktop/Screenshots"
*/

/* load javascript helper file from github */
load('https://raw.githubusercontent.com/oracle/Oracle_DB_Tools/master/sqlcl/lib/helpers.js');
 
/* Clean out the table just to prove it's not a baked demo */
sqlcl.setStmt("truncate table k");
sqlcl.run();
 
/* output to screen */
ctx.write('Load from directory: ' + args[1] + "\n\n");
 
/* Search for filenames using the operating system */
var stmt='find ' + args[1] + ' -maxdepth 1 -type f ';
ctx.write(stmt);
var files= helpers.exec(stmt).stdout.split('\n');
 
/* bind map for reuse */
var binds = helpers.getBindMap();
 
/* loop over files */
for(f in files ) {
  ctx.write("Loading : " + files[f] + "\n");
  /* load the blob */
  blob = helpers.getBlobFromFile(files[f]);
 
  /* assign the binds */
  binds.put("path",files[f]);
  binds.put("b",blob);
 
 /* Just do it */
  var ret = util.execute("insert into k(path,blob_content,when) values(:path , :b, sysdate)",binds);
}
 
/* print the results to see if it worked */
sqlcl.setStmt("select path,dbms_lob.getlength(blob_content) from k order by when desc;");
sqlcl.run();

sqlcl.setStmt("commit;");
sqlcl.run();
