Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

shortcut to wrap a single SQL execution/error output w/o leaving your…

… $EDITOR
  • Loading branch information...
commit 982b4c40451d473ad9f3c08131aa2236ff8ef11a 1 parent 97ed4db
Jonathan Zacsh authored December 08, 2012

Showing 1 changed file with 59 additions and 0 deletions. Show diff stats Hide diff stats

  1. 59  share/sql_vim
59  share/sql_vim
... ...
@@ -0,0 +1,59 @@
  1
+#!/usr/bin/env bash
  2
+
  3
+# Run an SQL query from inside SQL file; allows for SQL comments anywhere.
  4
+
  5
+# Originally based on stripping comments, then empty lines, then passing to
  6
+# mysql, from ~/.vimrc:
  7
+#   map <LocalLeader>S :!sed 's/^\(.*\)--.*$/\1/' % \| sed -e '/^[[:space:]]*$/'d \| mysql <CR>
  8
+
  9
+if [[ "$BASH_VERSINFO" -lt 4 ]];then
  10
+  printf 'Bash V4 features heavily used, Bash 4 required.\n' >&2
  11
+  exit 1
  12
+fi
  13
+(( $# != 1 )) && exit 1
  14
+type printcols > /dev/null 2>&1 || {
  15
+  printf 'Error: `printcols` script not found.\n' >&2
  16
+  exit 2
  17
+}
  18
+
  19
+SQLVIM_BINARY="${SQLVIM_BINARY:-mysql}"
  20
+QUERY_FILE="$1"
  21
+LESS_INDENT=8 # `less -N` indents for massive number of lines
  22
+STRIPPED_FILE="$(mktemp)"
  23
+strip_comments() { sed 's/^\(.*\)--.*$/\1/' "$1"; }
  24
+strip_empties() { sed -e '/^[[:space:]]*$/'d; }
  25
+column_markers() { printcols "$1"; }
  26
+
  27
+strip_comments "$QUERY_FILE" | strip_empties > "$STRIPPED_FILE"
  28
+
  29
+# save this for error reporting, below
  30
+longest_line=$(( 10#$(wc -L < "$STRIPPED_FILE") ));
  31
+
  32
+# Some padding between QUERY_FILE file and SQL error
  33
+printf '\n\n' >> "$STRIPPED_FILE"
  34
+
  35
+
  36
+"$SQLVIM_BINARY" < "$STRIPPED_FILE" 2>> "$STRIPPED_FILE"
  37
+if (( $? ));then
  38
+  cols="$(column_markers "$longest_line")"
  39
+
  40
+
  41
+  # View the utilized-SQL source, with line numbers
  42
+  # including the SQL error at the bottom
  43
+  if [[ $PAGER = less ]];then
  44
+    less -f <(
  45
+      printf "%${LESS_INDENT}s%s\n" ' ' "$cols"
  46
+      cat -n "$STRIPPED_FILE"
  47
+      printf "%${LESS_INDENT}s%s\n" ' ' "$cols"
  48
+    )
  49
+  else
  50
+    # TODO this LESS_INDENT logic doesn't work without `less` :P
  51
+    ${PAGER} <(
  52
+      printf "%${LESS_INDENT}s%s\n" ' ' "$cols"
  53
+      cat -n "$STRIPPED_FILE"
  54
+      printf "%${LESS_INDENT}s%s\n" ' ' "$cols"
  55
+    )
  56
+  fi
  57
+fi
  58
+
  59
+rm -v "$STRIPPED_FILE"

0 notes on commit 982b4c4

Please sign in to comment.
Something went wrong with that request. Please try again.