File: pspg.sql

package info (click to toggle)
pspg 5.8.14-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,360 kB
  • sloc: ansic: 23,354; sh: 101; makefile: 93; sql: 54
file content (75 lines) | stat: -rw-r--r-- 2,346 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
script
var CommandRegistry = Java.type("oracle.dbtools.raptor.newscriptrunner.CommandRegistry");
var CommandListener =  Java.type("oracle.dbtools.raptor.newscriptrunner.CommandListener")

var Runtime = Java.type("java.lang.Runtime");
var Scanner  = Java.type("java.util.Scanner");
var System = Java.type("java.lang.System");

var FileOutputStream = Java.type("java.io.FileOutputStream");
var ByteArrayOutputStream = Java.type("java.io.ByteArrayOutputStream");
var BufferedOutputStream = Java.type("java.io.BufferedOutputStream");

var Files = Java.type("java.nio.file.Files");
var Path = Java.type("java.nio.file.Path");
var File = Java.type("java.io.File");

var cmd = {};

cmd.handle = function (conn,ctx,cmd) {
  if (cmd.getSql().startsWith("pspg ")) {
    var tty = System.getenv("TTY");
    if (tty == null) {
      print("\nIn order to use pspg to page results, make sure you pass in your tty as an environment variable.");
      print("For example, invoke sqlcl like this:\n");
      print("$ TTY=$(tty) sqlcl ...\n");

      return true;
    }

    var sql = cmd.getSql().substring(5);
    var tempPath = Files.createTempFile("sqlcl-result", ".data");
    try {
      var bout = new ByteArrayOutputStream();
      sqlcl.setOut(new BufferedOutputStream(bout));

      // Set this to a big value so that we do not get repeating headers
      ctx.putProperty("script.runner.setpagesize", 1000000);
      sqlcl.setConn(conn);
      sqlcl.setStmt(sql);
      sqlcl.run();

      var fileOutputStream = new FileOutputStream(tempPath.toFile());
      bout.writeTo(fileOutputStream);
      fileOutputStream.close();

      var pager = Runtime.getRuntime().exec(
        [ "sh", "-c", "pspg '" + tempPath.toString() + "' < " + tty + " > " + tty ]
      );
      pager.waitFor();
    } finally {
      Files.delete(tempPath);
    }

    // return TRUE to indicate the command was handled
    return true;
  } 

  // return FALSE to indicate the command was not handled
  // and other commandListeners will be asked to handle it
  return false;
}

cmd.begin = function (conn,ctx,cmd) {}
cmd.end = function (conn,ctx,cmd) {}

var pspgCommand = Java.extend(CommandListener, {
  handleEvent: cmd.handle,
  beginEvent: cmd.begin, 
  endEvent: cmd.end    
});

// Registering the new Command
CommandRegistry.addForAllStmtsListener(pspgCommand.class);
/