htsql-sqlascii-patch / src / htsql / ctl / shell.py

   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
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
#
# Copyright (c) 2006-2012, Prometheus Research, LLC
#


"""
:mod:`htsql.ctl.shell`
======================

This module implements the `shell` routine.
"""


from __future__ import with_statement
from .error import ScriptError
from .routine import Argument, Routine
from .option import PasswordOption, ExtensionsOption, ConfigOption
from .request import Request, ConfigYAMLLoader
from ..core.validator import DBVal
from ..core.util import DB, listof, trim_doc
from ..core.model import (HomeNode, InvalidNode, InvalidArc, TableArc, 
                          ColumnArc, ChainArc, AmbiguousArc)
from ..core.classify import classify, normalize
import traceback
import StringIO
import mimetypes
import sys
import os, os.path
import re
import subprocess
import getpass
try:
    import readline
except ImportError:
    readline = None
import yaml


class Cmd(object):
    """
    Describes a shell command.

    This is the base abtract class for all shell commands.  To create
    a concrete command, subclass :class:`Cmd`, declare the command
    name and other parameters, and override :meth:`execute`.

    The following class attributes could be overridden.

    `name` (a string)
        The name of the command.  Name equal to an empty string (``''``)
        means this command is executed when no explicit command name
        is provided.  The name must be unique across all commands.

    `aliases` (a list of strings)
        The list of alternative command names.

    `signature` (a string or ``None``)
        Declaration of the command name and the arguments.

    `hint` (a string or ``None``)
        A short one-line description of the command.

    `help` (a string or ``None``)
        A long description of the command.  Keep the line width
        at 72 characters.

    Instances of :class:`Cmd` have the following attributes.

    `routine` (:class:`ShellRoutine`)
        The routine that executed the command.

    `ctl` (:class:`htsql.ctl.script.Script`)
        The script that started the shell routine.

    `state` (:class:`ShellState`)
        The shell state.

    `argument` (a string)
        The argument of the command.
    """

    name = None
    aliases = []
    signature = None
    hint = None
    help = None

    @classmethod
    def get_signature(cls):
        """
        Returns an (informal) signature of the command.
        """
        if cls.signature is not None:
            return cls.signature
        return cls.name

    @classmethod
    def get_hint(cls):
        """
        Returns a short one-line description of the command.
        """
        return cls.hint

    @classmethod
    def get_help(cls):
        """
        Returns a long description of the command.
        """
        return trim_doc(cls.help)

    @classmethod
    def complete(cls, routine, argument):
        return None

    def __init__(self, routine, argument):
        assert isinstance(routine, ShellRoutine)
        assert isinstance(argument, str)
        self.routine = routine
        self.ctl = routine.ctl
        self.state = routine.state
        self.argument = argument

    def execute(self):
        """
        Executes the command.

        The normal return value is ``None``; any other value causes
        the shell to exit.
        """
        # Override in a subclass.
        self.ctl.out("** not implemented")


class HelpCmd(Cmd):
    """
    Implements the `help` command.
    """

    name = 'help'
    aliases = ['?']
    signature = """help [command]"""
    hint = """describe the shell or a shell command"""
    help = """
    Type `help` to learn how to use the shell and to get a list of available
    commands.

    Type `help <command>` to learn how to use the specified command.
    """

    @classmethod
    def complete(cls, routine, argument):
        if argument:
            return None
        return sorted(routine.command_by_name)

    def execute(self):
        # If called without arguments, describe the shell.
        # If called with an argument, assume it is the name of the command
        # to describe.
        if not self.argument:
            self.describe_routine()
        else:
            if self.argument not in self.routine.command_by_name:
                self.ctl.out("** unknown command %r" % self.argument)
                return
            command_class = self.routine.command_by_name[self.argument]
            self.describe_command(command_class)

    def describe_routine(self):
        # Display:
        # {usage}
        #
        # Available commands:
        #   {command} : {hint}
        #   ...
        #
        usage = self.routine.get_usage()
        if usage is not None:
            self.ctl.out(usage)
        if self.routine.commands:
            self.ctl.out()
            self.ctl.out("Available commands:")
            for command_class in self.routine.commands:
                signature = command_class.get_signature()
                hint = command_class.get_hint()
                self.ctl.out("  ", end="")
                if hint is not None:
                    self.ctl.out("%-24s : %s" % (signature, hint))
                else:
                    self.ctl.out(signature)
        self.ctl.out()

    def describe_command(self, command_class):
        # Display:
        # {NAME} - {hint}
        #
        # Usage: {signature}
        #
        # {help}
        #
        name = command_class.name
        hint = command_class.get_hint()
        if hint is not None:
            self.ctl.out(name.upper(), "-", hint)
        else:
            self.ctl.out(name.upper())
        signature = command_class.get_signature()
        self.ctl.out("Usage:", signature)
        help = command_class.get_help()
        if help is not None:
            self.ctl.out()
            self.ctl.out(help)
        self.ctl.out()


class ExitCmd(Cmd):
    """
    Implements the `exit` command.
    """

    name = 'exit'
    aliases = ['quit', 'q']
    hint = """quit the shell"""
    help = """
    Type `exit` or Ctrl-D to quit the shell.
    """

    def execute(self):
        # Returning any non-`None` value exits the shell.
        return True


class UserCmd(Cmd):
    """
    Implements the `user` command.
    """

    name = 'user'
    signature = """user [remote_user]"""
    hint = """set the remote user for HTTP requests"""
    help = """
    To set the remote user for HTTP requests, type `user <name>`.

    To unset the remote user for HTTP requests, type `user`.
    """

    def execute(self):
        # If set, `state.remote_user` is passed to the WSGI application
        # as `environ['REMOTE_USER']`.
        if self.argument:
            self.state.remote_user = self.argument
            self.ctl.out("** remote user is set to %r" % self.argument)
        else:
            self.state.remote_user = None
            self.ctl.out("** remote user is unset")


class HeadersCmd(Cmd):
    """
    Implements the `headers` command.
    """

    name = 'headers'
    signature = """headers on|off"""
    hint = """display HTTP status line and headers"""
    help = """
    Type `headers on` to enable output of HTTP status line and headers along
    with any HTTP response body.

    Type `headers off` to disable output of HTTP status line and headers.
    Only HTTP response body will be displayed.
    """

    @classmethod
    def complete(cls, routine, argument):
        if argument:
            return None
        return ['on', 'off']

    def execute(self):
        # `state.with_headers` indicates whether or not to display
        # the status line and headers of the WSGI response.
        if not self.argument:
            self.ctl.out("** expected 'on' or 'off'")
            return
        if self.argument not in ['on', 'off']:
            self.ctl.out("** expected 'on' or 'off'; got %r" % self.argument)
            return
        if self.argument == 'on':
            self.state.with_headers = True
            self.ctl.out("** headers are turned on")
        if self.argument == 'off':
            self.state.with_headers = False
            self.ctl.out("** headers are turned off")


class PagerCmd(Cmd):
    """
    Implements the `pager` command.
    """

    name = 'pager'
    signature = """pager on|off"""
    hint = """pipe long output to a pager"""
    help = """
    Type `pager on` or `pager off` to enable or disable the pager
    respectively.

    If the pager is enabled, and the number of lines in the HTTP response
    exceeds the height of the terminal, the response is displayed via the
    pager.

    The pager is a command which allows you to scroll and search in the
    output.  The pager application is determined by the environment variable
    $PAGER.  When $PAGER is not set, one of the common pagers such as
    `/usr/bin/more` is used if available.  The pager could only be enabled
    when the shell is running in a terminal.
    """

    @classmethod
    def complete(cls, routine, argument):
        if argument:
            return None
        return ['on', 'off']

    def execute(self):
        if not self.argument:
            self.ctl.out("** expected 'on' or 'off'")
            return
        if self.argument not in ['on', 'off']:
            self.ctl.out("** expected 'on' or 'off'; got %r" % self.argument)
            return
        if self.argument == 'on':
            # `stdin` and `stdout` must come from a terminal.
            if not self.ctl.is_interactive:
                self.ctl.out("** pager cannot be enabled"
                             " in the non-interactive mode")
                return
            # The pager application must be present.
            if self.routine.pager is None:
                self.ctl.out("** no pager is found")
                return
            self.state.with_pager = True
            self.ctl.out("** pager %r is enabled" % self.routine.pager)
        if self.argument == 'off':
            self.state.with_pager = False
            self.ctl.out("** pager is disabled")


class ScanState(object):

    def __init__(self):
        self.indicator = '/'
        self.identifiers = []
        self.stack = []

    def push(self, indicator, identifiers=None):
        self.stack.append((self.indicator, self.identifiers))
        self.indicator = indicator
        if identifiers is not None:
            self.identifiers = identifiers

    def drop(self, indicators):
        if self.indicator in indicators:
            self.indicator, self.identifiers = self.stack.pop()
            return True
        return False

    def drop_all(self, indicators=None):
        if self.indicator in indicators:
            while self.indicator in indicators:
                self.indicator, self.identifiers = self.stack.pop()
            return True
        return False

    def clone(self):
        copy = ScanState()
        copy.indicator = self.indicator
        copy.identifiers = self.identifiers
        copy.stack = self.stack[:]
        return copy


class NodeChain(object):

    def __init__(self, app):
        self.app = app
        self.nodes = []
        self.labels_by_node = {}
        self.names_by_node = {}

    def push(self, node):
        self.nodes.append(node)
        if node not in self.labels_by_node:
            with self.app:
                labels = classify(node)
            labels = [label for label in labels
                            if not isinstance(label.arc, InvalidArc)]
            names = dict((label.name, label) for label in labels)
            self.labels_by_node[node] = labels
            self.names_by_node[node] = names

    def drop(self):
        self.nodes.pop()

    def labels(self):
        if not self.nodes:
            return []
        return self.labels_by_node[self.nodes[-1]]

    def label(self, name):
        if not self.nodes:
            return None
        return self.names_by_node[self.nodes[-1]].get(name)

    def __nonzero__(self):
        return bool(self.nodes)

    def clone(self):
        copy = NodeChain(self.app)
        copy.nodes = self.nodes[:]
        copy.labels_by_node = self.labels_by_node
        copy.names_by_node = self.names_by_node
        return copy


class GetPostBaseCmd(Cmd):
    """
    Implements the common methods of `get` and `post` commands.
    """

    # The HTTP method implemented by the command.
    method = None

    pattern = r"""
    ~ | < | > | = | ! | & | \| | -> | \. | , | \? | \^ |
    / | \* | \+ | - | \( | \) | \{ | \} | := | : | \$ | @ |
    ' (?: [^'] | '')* ' | \d+ [.eE]? |
    (?! \d) \w+
    """
    letter_pattern = r"""(?! \d) \w"""
    regexp = re.compile(pattern, re.X|re.U)
    letter_regexp = re.compile(letter_pattern, re.X|re.U)

    @classmethod
    def complete(cls, routine, argument):
        if routine.state.app is None:
            return
        argument = argument.decode('utf-8', 'replace')
        tokens = cls.regexp.findall(argument)
        tokens = [''] + [token.encode('utf-8') for token in tokens] + ['']
        state = ScanState()
        for idx in range(1, len(tokens)-1):
            token = tokens[idx]
            prev_token = tokens[idx-1]
            next_token = tokens[idx+1]
            if cls.letter_regexp.match(token) is not None:
                if not (prev_token == ':' or prev_token == '$'
                        or next_token == '('):
                    state.push('_', state.identifiers+[token])
            elif token == '.':
                pass
            elif token == '->' or token == '@':
                state.push('_', [])
            elif token == '?' or token == '^':
                state_copy = state.clone()
                state.drop_all('_')
                if not state.drop('?^'):
                    state = state_copy
                state.push(token)
            elif token == '(':
                state.push(token)
            elif token == ')':
                state_copy = state.clone()
                state.drop_all('_?^')
                if not state.drop('('):
                    state = state_copy
            elif token == '{':
                state_copy = state.clone()
                state.drop_all('_')
                if not state.drop('?^'):
                    state = state_copy
                state.push(token)
            elif token == '}':
                state_copy = state.clone()
                state.drop_all('_?^')
                if not state.drop('{'):
                    state = state_copy
            elif token == ':=':
                state.drop('_')
            elif token == ':':
                state.drop_all('_?^')
            elif token == '$':
                state.push('_', [])
            else:
                state.drop_all('_')
        identifiers = state.identifiers
        chain = NodeChain(routine.state.app)
        chain.push(HomeNode())
        for identifier in identifiers:
            identifier = normalize(identifier.decode('utf-8'))
            chain_copy = chain.clone()
            while chain:
                label = chain.label(identifier)
                if label is not None:
                    break
                chain.drop()
            node = label.target if label is not None else InvalidNode()
            chain = chain_copy
            chain.push(node)
        labels = chain.labels()
        names = [label.name.encode('utf-8') for label in labels]
        return names

    def execute(self):
        # Check if the argument of the command looks like an HTSQL query.
        if not self.argument:
            self.ctl.out("** a query is expected")
            return
        if self.argument[0] != '/':
            self.ctl.out("** a query is expected; got %r" % self.argument)
            return

        # Prepare the WSGI `environ` for a GET request.
        if self.method == 'GET':
            request = Request.prepare('GET', query=self.argument,
                                      remote_user=self.state.remote_user)

        # Prepare the WSGI `environ` for a POST request.
        if self.method == 'POST':
            # Get the name of the file containing POST data of the request.
            if self.ctl.is_interactive:
                self.ctl.out("File with POST data:", end=" ")
            content_path = self.ctl.stdin.readline().strip()
            if not content_path:
                self.ctl.out("** a file name is expected")
                return
            if not os.path.exists(content_path):
                self.ctl.out("** file %r does not exist" % content_path)
                return
            content_body = open(content_path, 'rb').read()

            # Determine the content type of the POST data.
            default_content_type = mimetypes.guess_type(content_path)[0]
            if default_content_type is None:
                default_content_type = 'application/octet-stream'
            if self.ctl.is_interactive:
                self.ctl.out("Content type [%s]:" % default_content_type,
                             end=" ")
            content_type = self.ctl.stdin.readline().strip()
            if not content_type:
                content_type = default_content_type

            request = Request.prepare('POST', query=self.argument,
                                      remote_user=self.state.remote_user,
                                      content_type=content_type,
                                      content_body=content_body)

        # Execute the WSGI request.
        response = request.execute(self.state.app)

        # Check for exceptions and incomplete responses.
        if response.exc_info is not None:
            exc_type, exc_value, exc_traceback = response.exc_info
            traceback.print_exception(exc_type, exc_value, exc_traceback,
                                      file=self.ctl.stderr)
            return
        if not response.complete():
            self.ctl.out("** incomplete response")
            return

        # Check if we need to use the pager.
        length = response.body.count('\n')
        if (self.state.with_pager
                and length > self.routine.pager_line_threshold):
            # Pipe the response to the pager.
            stream = StringIO.StringIO()
            response.dump(stream, self.state.with_headers)
            output = stream.getvalue()
            process = subprocess.Popen(self.routine.pager,
                                       stdin=subprocess.PIPE)
            try:
                process.communicate(output)
            except IOError, exc:
                self.ctl.out(exc)
        else:
            # Dump the response.
            response.dump(self.ctl.stdout, self.state.with_headers)


class GetCmd(GetPostBaseCmd):
    """
    Implements the `get` command.
    """

    name = 'get'
    aliases = ['']
    signature = """[get] /query"""
    hint = """execute an HTSQL query"""
    help = """
    Type `get /query` or just `/query` to execute an HTSQL query.

    The output of the query is dumped to the console.  When the pager is
    enabled and the number of lines in the response body exceeds the height
    of the terminal, the output is displayed via the pager.  Use `pager off`
    to disable the pager.

    By default, the command does not dump the response status line and the
    headers.  To enable displaying the status line and the headers along
    with the response body, use `headers on`.
    """
    method = 'GET'


class PostCmd(GetPostBaseCmd):
    """
    Implements the `post` command.
    """

    name = 'post'
    signature = """post /query"""
    hint = """execute an HTSQL query with POST data"""
    help = """
    Type `post /query` to execute an HTSQL query with POST data.

    You will be asked to provide a file containing the POST data and to
    indicate the content type of the data.

    The output of the query is dumped to the console.  When the pager is
    enabled and the number of lines in the response body exceeds the height
    of the terminal, the output is displayed via the pager.  Use `pager off`
    to disable the pager.

    By default, the command does not dump the response status line and the
    headers.  To enable displaying the status line and the headers along
    with the response body, use `headers on`.
    """
    method = 'POST'


class RunCmd(Cmd):
    """
    Implements the `run` command.
    """

    name = 'run'
    signature = """run filename.htsql"""
    hint = """run an HTSQL query from a file"""
    help = """
    Type `run filename.htsql` to load and execute an HTSQL query from a file.

    The command reads an HTSQL query from the given file and executes it as
    a GET request.

    The output of the query is dumped to the console.  When the pager is
    enabled and the number of lines in the response body exceeds the height
    of the terminal, the output is displayed via the pager.  Use `pager off`
    to disable the pager.

    By default, the command does not dump the response status line and the
    headers.  To enable displaying the status line and the headers along
    with the response body, use `headers on`.
    """

    # FIXME: duplicates `GetPostBaseCmd.execute()`.
    def execute(self):
        # Check if the argument is suppied and is a valid filename.
        if not self.argument:
            self.ctl.out("** a file name is expected")
            return
        if not os.path.isfile(self.argument):
            self.ctl.out("** file %r does not exist" % self.argument)
            return

        # Read the file, check if it looks like valid HTSQL.
        stream = open(self.argument)
        query = stream.read().strip()
        stream.close()
        if not query or query[0] != '/':
            self.ctl.out("** file %r does not contain a valid HTSQL query"
                         % self.argument)

        # Prepare and execute a WSGI request.
        request = Request.prepare('GET', query=query,
                                  remote_user=self.state.remote_user)
        response = request.execute(self.state.app)

        # Check for exceptions and incomplete responses.
        if response.exc_info is not None:
            exc_type, exc_value, exc_traceback = response.exc_info
            traceback.print_exception(exc_type, exc_value, exc_traceback,
                                      file=self.ctl.stderr)
            return
        if not response.complete():
            self.ctl.out("** incomplete response")
            return

        # Check if we need to use the pager.
        length = response.body.count('\n')
        if (self.state.with_pager
                and length > self.routine.pager_line_threshold):
            # Pipe the response to the pager.
            stream = StringIO.StringIO()
            response.dump(stream, self.state.with_headers)
            output = stream.getvalue()
            process = subprocess.Popen(self.routine.pager,
                                       stdin=subprocess.PIPE)
            try:
                process.communicate(output)
            except IOError, exc:
                self.ctl.out(exc)
        else:
            # Dump the response.
            response.dump(self.ctl.stdout, self.state.with_headers)


class ShellState(object):
    """
    Holds mutable shell parameters.

    `app`
        The current HTSQL application.

    `with_headers` (Boolean)
        Indicates whether to display the status line and the headers of
        an HTTP response.

    `remote_user` (a string or ``None``)
        The WSGI remote user.

    `with_pager` (Boolean)
        Indicates whether the pager is enabled.
    """

    def __init__(self, app=None, with_headers=False,
                 remote_user=None, with_pager=True,
                 completer=None, completer_delims=None,
                 completions=()):
        self.app = app
        self.with_headers = with_headers
        self.remote_user = remote_user
        self.with_pager = with_pager
        self.completer = completer
        self.completer_delims = completer_delims
        self.completions = completions

class VersionCmd(Cmd):
    """
    Implements the `version` command.
    """

    name = 'version'
    signature = """version"""
    hint = """prints version and license information"""
    help = """
    Type `version` to list the current software version and
    license information.
    """

    def execute(self):
        self.ctl.out(self.ctl.get_legal())
        self.ctl.out()

class DescribeCmd(Cmd):
    """
    Implements the `describe` command.
    """

    name = 'describe'
    signature = """describe [table]"""
    hint = """list tables, or slots for a given table"""
    help = """
    Type `describe` to list all tables or `describe <table>` to list
    all columns and links for a given table.
    """

    @classmethod
    def complete(cls, routine, argument):
        if argument:
            return None
        with routine.state.app:
             return [label.name for label in classify(HomeNode())]

    def execute(self):
        with self.state.app:
             root_labels = classify(HomeNode())

        if not self.argument:
            #
            # Enumerate introspected tables if one isn't provided
            #
            if not(root_labels):
                 self.ctl.out("No tables introspected or configured.")
                 return
            self.ctl.out("Tables introspected for this database are:")
            for label in root_labels:
                if not isinstance(label.arc, TableArc):
                     continue
                if label.name == label.arc.target.table.name:
                    self.ctl.out("\t%s" % label.name)
                else:
                    self.ctl.out("\t%s (%s)" % (label.name,
                                                label.arc.target.table.name))
            self.ctl.out()
            return
        #
        # Dump table attributes if a specific table is requested.
        #
        slots = None
        with self.state.app:
            for label in root_labels:
                if label.name == self.argument:
                    slots = classify(label.arc.target)
        if slots is None:
            self.ctl.out("Unable to find table: %s" % self.argument)
            self.ctl.out()
            return

        max_width = 0
        for slot in slots:
            if isinstance(slot.arc, AmbiguousArc):
                continue
            if len(slot.name) > max_width:
                max_width = len(slot.name)
        if not max_width:
            self.ctl.out("Table `%s` has no slots." % self.argument)
            self.ctl.out()
            return

        self.ctl.out("Slots for `%s` are:" % self.argument)
        for slot in slots:
            name = slot.name.ljust(max_width)
            post = str(slot.arc.target)
            if isinstance(slot.arc, ChainArc):
                if slot.arc.is_contracting:
                    post = "SINGULAR(%s)" % post
                else:
                    post = "PLURAL(%s)" % post
            if isinstance(slot.arc, AmbiguousArc):
                continue
            self.ctl.out("\t %s %s" % (name, post))
        self.ctl.out()


class ShellRoutine(Routine):
    """
    Implements the `shell` routine.
    """

    name = 'shell'
    aliases = ['sh']
    arguments = [
            Argument('db', DBVal(), default=None,
                     hint="""the connection URI"""),
    ]
    options = [
            PasswordOption,
            ExtensionsOption,
            ConfigOption,
    ]
    hint = """start an HTSQL shell"""
    help = """
    The routine starts an interactive HTSQL shell over the specified database.

    The DB argument specifies database connection parameters; must have the
    form:
    
        engine://username:password@host:port/database

    Here,
    
      - ENGINE is the type of the database server; supported values are
        `sqlite`, `pgsql`, `mysql`, `mssql` and `oracle`.
      - The parameters USERNAME:PASSWORD are used for authentication.
      - The parameters HOST:PORT indicate the address of the database
        server.
      - DATABASE is the name of the database; for SQLite, the path to the
        database file.

    All parameters except ENGINE and DATABASE are optional.

    When the shell is started, you will see the shell prompt with the
    database name followed by `$`.  Type an HTSQL query and press ENTER to
    execute it.  Type a command with any arguments and press ENTER to
    execute the command.  In particular, use `help` to get a list of shell
    commands, `help <command>` to describe a command.

    Type `exit` or Ctrl-D to exit the shell.
    """

    # List of supported shell commands.
    commands = [
            HelpCmd,
            ExitCmd,
            UserCmd,
            DescribeCmd,
            HeadersCmd,
            PagerCmd,
            GetCmd,
            PostCmd,
            RunCmd,
            VersionCmd,
    ]

    # A notice displayed when the shell is started.
    intro = """
    Type 'help' for more information, 'exit' to quit the shell.
    """

    # The description of the shell displayed by the `help` command.
    usage = """
    To execute an HTSQL query, type

        /query

    To execute a shell command, type

        command [arguments...]
    """

    # Path to the file keeping the `readline` history.
    history_path = '~/.htsql_shell_history'

    # Potential pagers, used when $PAGER is not set.
    default_pager_paths = ['/usr/bin/pager', '/usr/bin/more']

    # The default value of the pager line threshold, used
    # when $LINES is not set
    default_pager_line_threshold = 25

    # The pattern to check for commands.
    command_name_pattern = re.compile(r'^[a-zA-Z.?]')

    @classmethod
    def get_intro(cls):
        """
        Returns a notice to display when the shell is started.
        """
        return trim_doc(cls.intro)

    @classmethod
    def get_usage(cls):
        """
        Returns the shell description used by the `help` command.
        """
        return trim_doc(cls.usage)

    @classmethod
    def get_help(cls, **substitutes):
        """
        Returns a long description of the routine.
        """
        # The description of the shell routine has the form:
        # {help}
        #
        # Shell commands: (run ... for more help)
        #   {command.signature} : {command.hint}
        #   ...
        help = super(ShellRoutine, cls).get_help(**substitutes)
        if cls.commands:
            lines = []
            lines.append("Shell commands:"
                         " (run '%(executable)s help shell <command>'"
                         " for more help)" % substitutes)
            for command_class in cls.commands:
                signature = command_class.get_signature()
                hint = command_class.get_hint()
                if hint is not None:
                    line = "  %-24s : %s" % (signature, hint)
                else:
                    line = "  %s" % signature
                lines.append(line)
            if help is not None:
                help = "%s\n\n%s" % (help, "\n".join(lines))
            else:
                help = "\n".join(lines)
        return help

    @classmethod
    def get_feature(cls, name):
        """
        Returns the shell command by name.
        """
        for command_class in cls.commands:
            if name == command_class.name or name in command_class.aliases:
                return command_class
        raise ScriptError("unknown shell command %r" % name)

    def __init__(self, ctl, attributes):
        super(ShellRoutine, self).__init__(ctl, attributes)
        # A mapping of command_class.name -> command_class
        self.command_by_name = {}
        # Path to the pager.
        self.pager = None
        # The pager will be activated when the number of lines in the response
        # exceeds this value.
        self.pager_line_threshold = self.default_pager_line_threshold
        # Populate `command_by_name`.
        self.init_commands()
        # Set `pager` and `pager_line_threshold`.
        self.init_pager()
        # The mutable shell state.
        self.state = ShellState(with_pager=(self.ctl.is_interactive and
                                            self.pager is not None))

    def init_commands(self):
        # Populate `command_by_name`; also, sanity check on the commands.
        for command_class in self.commands:
            assert issubclass(command_class, Cmd)
            assert isinstance(command_class.name, str)
            assert isinstance(command_class.aliases, listof(str))
            for name in [command_class.name]+command_class.aliases:
                assert name not in self.command_by_name, \
                       "duplicate command name: %r" % name
                self.command_by_name[name] = command_class

    def init_pager(self):
        # Initialize the attributes `pager` and `pager_line_threshold`.

        # Use the environment variable $PAGER; if not set, check for
        # some common pagers.
        if 'PAGER' in os.environ:
            self.pager = os.environ['PAGER']
        else:
            for path in self.default_pager_paths:
                if os.path.exists(path):
                    self.pager = path
                    break

        # $LINES indicates the number of lines in the terminal.
        if 'LINES' in os.environ:
            try:
                self.pager_line_threshold = int(os.environ['LINES'])
            except ValueError:
                pass

    def run(self):
        # The database URI.
        db = self.db

        # Ask for the database password if necessary.
        if self.password and db is not None:
            db = DB(engine=db.engine,
                    username=db.username,
                    password=getpass.getpass(),
                    host=db.host,
                    port=db.port,
                    database=db.database,
                    options=db.options)

        # Load addon configuration.
        extensions = self.extensions
        if self.config is not None:
            stream = open(self.config, 'rb')
            loader = ConfigYAMLLoader(stream)
            try:
                config_extension = loader.load()
            except yaml.YAMLError, exc:
                raise ScriptError("failed to load application configuration:"
                                  " %s" % exc)
            extensions = extensions + [config_extension]

        # Create the HTSQL application.
        from htsql import HTSQL
        try:
            self.state.app = HTSQL(db, *extensions)
        except ImportError, exc:
            raise ScriptError("failed to construct application: %s" % exc)

        # Display the welcome notice; load the history.
        self.setup()
        try:
            # Read and execute commands until instructed to exit.
            while self.loop() is None:
                pass
        finally:
            # Save the history.
            self.shutdown()

    def setup(self):
        # Load the `readline` history; initialize completion.
        if self.ctl.is_interactive and readline is not None:
            path = os.path.abspath(os.path.expanduser(self.history_path))
            if os.path.exists(path):
                readline.read_history_file(path)
            self.state.completer = readline.get_completer()
            self.state.completer_delims = readline.get_completer_delims()
            readline.set_completer(self.completer)
            readline.set_completer_delims(
                    " \t\n`~!@#$%^&*()-=+[{]}\\|;:\'\",<.>/?")
            readline.parse_and_bind("tab: complete")

        # Display the welcome notice.
        if self.ctl.is_interactive:
            intro = self.get_intro()
            if intro:
                self.ctl.out(intro)

    def shutdown(self):
        # Save the `readline` history; restore the original state of completion.
        if self.ctl.is_interactive and readline is not None:
            path = os.path.abspath(os.path.expanduser(self.history_path))
            readline.write_history_file(path)
            readline.set_completer(self.state.completer)
            readline.set_completer_delims(self.state.completer_delims)

    def loop(self):
        # Display the prompt and read the command from the console.
        # On EOF, exit the loop.
        if self.ctl.is_interactive:
            prompt = "$ "
            app = self.state.app
            if app is not None and app.htsql.db is not None:
                prompt = "%s$ " % app.htsql.db.database.strip(".sqlite")
            try:
                line = raw_input(prompt)
            except EOFError:
                self.ctl.out()
                return True
        else:
            line = self.ctl.stdin.readline()
            if not line:
                return True

        # Skip empty lines.
        line = line.strip()
        if not line:
            return

        # Determine the command name and the command argument.
        name = line.split()[0]
        if self.command_name_pattern.match(name):
            argument = line[len(name):].strip()
        else:
            name = ''
            argument = line

        # Complain if the command is not found.
        if name not in self.command_by_name:
            self.ctl.out("** unknown command %r" % name)
            return

        # Instantiate and execute the command.
        command_class = self.command_by_name[name]
        command = command_class(self, argument)
        return command.execute()

    def completer(self, text, index):
        try:
            if index == 0:
                line = readline.get_line_buffer()
                begidx = readline.get_begidx()
                endidx = readline.get_endidx()
                delta = len(line)
                line = line.lstrip()
                delta -= len(line)
                begidx -= delta
                endidx -= delta
                prefix = line[:begidx]
                if not prefix:
                    completions = sorted(self.command_by_name)
                else:
                    name = prefix.split()[0]
                    if self.command_name_pattern.match(name):
                        prefix = prefix[len(name):].strip()
                    else:
                        name = ''
                    if name in self.command_by_name:
                        command_class = self.command_by_name[name]
                        completions = command_class.complete(self, prefix)
                        if completions is None:
                            completions = []
                    else:
                        completions = []
                completions = [word for word in completions
                                    if word and word.startswith(text)]
                self.state.completions = tuple(completions)
            if index < len(self.state.completions):
                return self.state.completions[index]
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_traceback,
                                      file=self.ctl.stderr)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.