This file is indexed.

/usr/bin/qadmin is in skytools3 3.2.6-4.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
#!/usr/bin/python

"""Commands that require only database connection:

    connect dbname=.. host=.. service=.. queue=..;
    connect [ queue=.. ] [ node=.. ];
    install pgq | londiste;

    show queue [ <qname | *> ];
    create queue <qname>;
    alter queue <qname | *> set param = , ...;
    drop queue <qname>;

    show consumer [ <cname | *> [on <qname>] ];
    register consumer <consumer> [on <qname> | at <tick_id> | copy <consumer> ]* ;
    unregister consumer <consumer | *> [from <qname>];
    register subconsumer <subconsumer> for <consumer> [on <qname>];
    unregister subconsumer <subconsumer | *> for <consumer> [from <qname>] [close [batch]];

    show node [ <node | *> [on <qname>] ];
    show table <tbl>;
    show sequence <seq>;

Following commands expect default queue:

    show batch <batch_id>;
    show batch <consumer>;

Londiste commands:

    londiste add table <tbl> [ , ... ]
        with skip_truncate, tgflags='UIDBAQL',
             expect_sync, no_triggers,
             -- pass trigger args:
             backup, skip, when='EXPR', ev_XX='EXPR';
    londiste add sequence <seq>;
    londiste remove table <tbl> [ , ... ];
    londiste remove sequence <seq> [ , ... ];
    londiste tables;
    londiste seqs;
    londiste missing;

Other commands:

    exit;  - quit program
    ^D     - quit program
    ^C     - clear current buffer
"""

# unimplemented:
"""
create <root | branch | leaf> node <node> location <loc> [on <qname>];
drop node <node> [on <qname>];
alter node <node> [location=<loc>]
show_queue_stats <q>;

change provider
drop node
status
rename node

node create

create root_node <name>;
create branch_node <name>;
create leaf_node <name>;

alter node <name> provider <new>;

alter node <name> takeover <oldnow> with all;
alter node <name> rename <new>;

takeover <oldnode>;

drop node <name>;

show node [ <node | *> [on <qname>] ];
show cascade;

"""

cmdline_usage = '''\
Usage: qadmin [switches]

Initial connection options:
    -h host
    -p port
    -U user
    -d dbname
    -Q queuename

Command options:
    -c cmd_string
    -f execfile

General options:
    --help
    --version
'''

import sys, os, readline, getopt, re, psycopg2, traceback

import pkgloader
pkgloader.require('skytools', '3.0')
import skytools

__version__ = skytools.__version__

script = None

IGNORE_HOSTS = {
    'ip6-allhosts': 1,
    'ip6-allnodes': 1,
    'ip6-allrouters': 1,
    #'ip6-localhost': 1,
    'ip6-localnet': 1,
    'ip6-loopback': 1,
    'ip6-mcastprefix': 1,
}

_ident_rx =''' ( " ( "" | [^"]+ )* " ) | ( [a-z_][a-z0-9_]* ) | [.] | (?P<err> .)  '''
_ident_rc = re.compile(_ident_rx, re.X | re.I)

def unquote_any(typ, s):
    global _ident_rc
    if typ == 'ident':
        res = []
        pos = 0
        while 1:
            m = _ident_rc.match(s, pos)
            if not m:
                break
            if m.group('err'):
                raise Exception('invalid syntax for ident')
            s1 = m.group()
            if s1[0] == '"':
                s1 = s1[1:-1].replace('""', '"')
            res.append(s1)
            pos = m.end()
        s = ''.join(res)
    elif typ == 'str' or typ == 'dolq':
        s = skytools.unquote_literal(s, True)
    return s

def normalize_any(typ, s):
    if typ == 'ident' and s.find('"') < 0:
        s = s.lower()
    return s

def display_result(curs, desc, fields = []):
    """Display multirow query as a table."""

    rows = curs.fetchall()

    if not fields:
        fields = [f[0] for f in curs.description]

    widths = [10] * len(fields)
    for i, f in enumerate(fields):
        rlen = len(f)
        if rlen > widths[i]:
            widths[i] = rlen
    for row in rows:
        for i, k in enumerate(fields):
            rlen = row[k] and len(str(row[k])) or 0
            if rlen > widths[i]:
                widths[i] = rlen
    widths = [w + 2 for w in widths]

    fmt = '%%-%ds' * (len(widths) - 1) + '%%s'
    fmt = fmt % tuple(widths[:-1])
    if desc:
        print(desc)
    print(fmt % tuple(fields))
    print(fmt % tuple([ '-' * (w - 2) for w in widths ]))

    for row in rows:
        print(fmt % tuple([row[k] for k in fields]))
    print('')

##
## Base token classes
##

class Token:
    """Base class for tokens.

    The optional 'param' kwarg will set corresponding key in
    'params' dict to final token value.
    """
    # string to append to completions
    c_append = ' '

    # token type to accept
    tk_type = ("ident", "dolq", "str", "num", "sym")
    # skipped: numarg, pyold, pynew

    def __init__(self, next = None, name = None, append = 0):
        self.next = next
        self.name = name
        self._append = append

    # top-level api

    def get_next(self, typ, word, params):
        """Return next token if 'word' matches this token."""
        if not self.is_acceptable(typ, word):
            return None
        self.set_param(typ, word, params)
        return self.next

    def get_completions(self, params):
        """Return list of all completions possible at this point."""
        wlist = self.get_wlist()
        comp_list = [w + self.c_append for w in wlist]
        return comp_list

    # internal api

    def get_wlist(self):
        """Return list of potential words at this point."""
        return []

    def set_param(self, typ, word, params):
        # now set special param
        if not self.name:
            return
        uw = unquote_any(typ, word)
        if self._append:
            lst = params.setdefault(self.name, [])
            lst.append(uw)
        else:
            params[self.name] = uw

    def is_acceptable(self, tok, word):
        if tok not in self.tk_type:
            return False
        return True

class Exact(Token):
    """Single fixed token."""
    def __init__(self, value, next, **kwargs):
        Token.__init__(self, next, **kwargs)
        self.value = value
    def get_wlist(self):
        return [self.value]
    def is_acceptable(self, typ, word):
        if not Token.is_acceptable(self, typ, word):
            return False
        return word == self.value

class List(Token):
    """List of Tokens, will be tried sequentially until one matches."""
    def __init__(self, *args, **kwargs):
        Token.__init__(self, **kwargs)
        self.tok_list = list(args)

    def add(self, *args):
        for a in args:
            self.tok_list.append(a)

    def get_next(self, typ, word, params):
        for w in self.tok_list:
            n = w.get_next(typ, word, params)
            if n:
                self.set_param(typ, word, params)
                return n
        return None

    def get_completions(self, params):
        comp_list = []
        for w in self.tok_list:
            comp_list += w.get_completions(params)
        return comp_list

##
## Dynamic token classes
##

class ConnstrPassword(Token):
    tk_type = ("str", "num", "ident")

class StrValue(Token):
    tk_type = ("str",)

class NumValue(Token):
    tk_type = ("num",)

class Word(Exact):
    """Single fixed keyword."""
    tk_type = ("ident",)

class Name(Token):
    """Dynamically generated list of idents."""
    tk_type = ("ident")

class Symbol(Exact):
    """Single fixed symbol."""
    tk_type = ("sym",)
    c_append = ''

class XSymbol(Symbol):
    """Symbol that is not shown in completion."""
    def get_wlist(self):
        return []

class SubConsumerName(Token):
    tk_type = ("str", "num", "ident")

# data-dependant completions

class Queue(Name):
    def get_wlist(self):
        return script.get_queue_list()

class Consumer(Name):
    def get_wlist(self):
        return script.get_consumer_list()

class DBNode(Name):
    def get_wlist(self):
        return script.get_node_list()

class Database(Name):
    def get_wlist(self):
        return script.get_database_list()

class Host(Name):
    def get_wlist(self):
        return script.get_host_list()

class User(Name):
    def get_wlist(self):
        return script.get_user_list()

class NewTable(Name):
    def get_wlist(self):
        return script.get_new_table_list()

class KnownTable(Name):
    def get_wlist(self):
        return script.get_known_table_list()

class PlainTable(Name):
    def get_wlist(self):
        return script.get_plain_table_list()

class PlainSequence(Name):
    def get_wlist(self):
        return script.get_plain_seq_list()

class NewSeq(Name):
    def get_wlist(self):
        return script.get_new_seq_list()

class KnownSeq(Name):
    def get_wlist(self):
        return script.get_known_seq_list()

class BatchId(NumValue):
    def get_wlist(self):
        return script.get_batch_list()

class TickId(NumValue):
    def get_wlist(self):
        return []

class Port(NumValue):
    def get_wlist(self):
        return ['5432', '6432']

# easier completion - add follow-up symbols

class WordEQ(Word):
    """Word that is followed by '='."""
    c_append = '='
    def __init__(self, word, next, **kwargs):
        next = Symbol('=', next)
        Word.__init__(self, word, next, **kwargs)

class WordEQQ(Word):
    """Word that is followed by '=' and string."""
    c_append = "='"
    def __init__(self, word, next, **kwargs):
        next = Symbol('=', next)
        Word.__init__(self, word, next, **kwargs)

##
##  Now describe the syntax.
##

top_level = List(name = 'cmd')

w_done = Symbol(';', top_level)
w_xdone = XSymbol(';', top_level)

w_sql = List(w_done)
w_sql.add(Token(w_sql))

w_connect = List()
w_connect.add(
        WordEQ('dbname', Database(w_connect, name = 'dbname')),
        WordEQ('host', Host(w_connect, name = 'host')),
        WordEQ('port', Port(w_connect, name = 'port')),
        WordEQ('user', User(w_connect, name = 'user')),
        WordEQ('password', ConnstrPassword(w_connect, name = 'password')),
        WordEQ('queue', Queue(w_connect, name = 'queue')),
        WordEQ('node', DBNode(w_connect, name = 'node')),
        w_done)

w_show_batch = List(
    BatchId(w_done, name = 'batch_id'),
    Consumer(w_done, name = 'consumer'))

w_show_queue = List(
    Symbol('*', w_done, name = 'queue'),
    Queue(w_done, name = 'queue'),
    w_done)

w_show_on_queue = List(
    Symbol('*', w_done, name = 'queue'),
    Queue(w_done, name = 'queue'),
    )

w_on_queue = List(Word('on', w_show_on_queue), w_done)

w_show_consumer = List(
    Symbol('*', w_on_queue, name = 'consumer'),
    Consumer(w_on_queue, name = 'consumer'),
    w_done)

w_show_node = List(
    Symbol('*', w_on_queue, name = 'node'),
    DBNode(w_on_queue, name = 'node'),
    w_done)

w_show_table = PlainTable(w_done, name = 'table')

w_show_seq = PlainSequence(w_done, name = 'seq')

w_show = List(
    Word('batch', w_show_batch),
    Word('help', w_done),
    Word('queue', w_show_queue),
    Word('consumer', w_show_consumer),
    Word('node', w_show_node),
    Word('table', w_show_table),
    Word('sequence', w_show_seq),
    Word('version', w_done),
    name = "cmd2")

w_install = List(
    Word('pgq', w_done),
    Word('londiste', w_done),
    name = 'module')

# alter queue
w_qargs2 = List()

w_qargs = List(
    WordEQQ('idle_period', StrValue(w_qargs2, name = 'ticker_idle_period')),
    WordEQ('max_count', NumValue(w_qargs2, name = 'ticker_max_count')),
    WordEQQ('max_lag', StrValue(w_qargs2, name = 'ticker_max_lag')),
    WordEQ('paused', NumValue(w_qargs2, name = 'ticker_paused')))

w_qargs2.add(w_done)
w_qargs2.add(Symbol(',', w_qargs))

w_set_q = Word('set', w_qargs)

w_alter_q = List(
        Symbol('*', w_set_q, name = 'queue'),
        Queue(w_set_q, name = 'queue'))

# alter
w_alter = List(
        Word('queue', w_alter_q),
        w_sql,
        name = 'cmd2')

# create
w_create = List(
        Word('queue', Queue(w_done, name = 'queue')),
        w_sql,
        name = 'cmd2')

# drop
w_drop = List(
        Word('queue', Queue(w_done, name = 'queue')),
        w_sql,
        name = 'cmd2')

# register
w_reg_target = List()
w_reg_target.add(
        Word('on', Queue(w_reg_target, name = 'queue')),
        Word('copy', Consumer(w_reg_target, name = 'copy_reg')),
        Word('at', TickId(w_reg_target, name = 'at_tick')),
        w_done)

w_cons_on_queue = Word('consumer',
        Consumer(w_reg_target, name = 'consumer'),
        name = 'cmd2')

w_sub_reg_target = List()
w_sub_reg_target.add(
        Word('on', Queue(w_sub_reg_target, name = 'queue')),
        Word('for', Consumer(w_sub_reg_target, name = 'consumer')),
        w_done)

w_subcons_on_queue = Word('subconsumer',
        SubConsumerName(w_sub_reg_target, name = 'subconsumer'),
        name = 'cmd2')

w_register = List(w_cons_on_queue,
                  w_subcons_on_queue)

# unregister

w_from_queue = List(w_done, Word('from', Queue(w_done, name = 'queue')))
w_cons_from_queue = Word('consumer',
        List( Symbol('*', w_from_queue, name = 'consumer'),
              Consumer(w_from_queue, name = 'consumer')
            ),
        name = 'cmd2')

w_done_close = List(w_done,
            Word('close', List(w_done, Word('batch', w_done)), name = 'close'))
w_from_queue_close = List(w_done_close,
                          Word('from', Queue(w_done_close, name = 'queue')))
w_con_from_queue = Consumer(w_from_queue_close, name = 'consumer')
w_subcons_from_queue = Word('subconsumer',
    List( Symbol('*', Word('for', w_con_from_queue), name = 'subconsumer'),
          SubConsumerName(Word('for', w_con_from_queue), name = 'subconsumer')
        ),
    name = 'cmd2')

w_unregister = List(w_cons_from_queue,
                    w_subcons_from_queue)

# londiste add table
w_table_with2 = List()
w_table_with = List(
    Word('skip_truncate', w_table_with2, name = 'skip_truncate'),
    Word('expect_sync', w_table_with2, name = 'expect_sync'),
    Word('backup', w_table_with2, name = 'backup'),
    Word('skip', w_table_with2, name = 'skip'),
    Word('no_triggers', w_table_with2, name = 'no_triggers'),
    WordEQQ('ev_ignore', StrValue(w_table_with2, name = 'ignore')),
    WordEQQ('ev_type', StrValue(w_table_with2, name = 'ev_type')),
    WordEQQ('ev_data', StrValue(w_table_with2, name = 'ev_data')),
    WordEQQ('ev_extra1', StrValue(w_table_with2, name = 'ev_extra1')),
    WordEQQ('ev_extra2', StrValue(w_table_with2, name = 'ev_extra2')),
    WordEQQ('ev_extra3', StrValue(w_table_with2, name = 'ev_extra3')),
    WordEQQ('ev_extra4', StrValue(w_table_with2, name = 'ev_extra4')),
    WordEQQ('pkey', StrValue(w_table_with2, name = 'pkey')),
    WordEQQ('when', StrValue(w_table_with2, name = 'when')),
    WordEQQ('tgflags', StrValue(w_table_with2, name = 'tgflags'))
    )

w_table_with2.add(w_done)
w_table_with2.add(Symbol(',', w_table_with))

w_londiste_add_table = List()
w_londiste_add_table2 = List(
    Symbol(',', w_londiste_add_table),
    Word('with', w_table_with),
    w_done)
w_londiste_add_table.add(
    NewTable(w_londiste_add_table2,
             name = 'tables', append = 1))

# londiste add seq
w_londiste_add_seq = List()
w_londiste_add_seq2 = List(
    Symbol(',', w_londiste_add_seq),
    w_done)
w_londiste_add_seq.add(
    NewSeq(w_londiste_add_seq2, name = 'seqs', append = 1))

# londiste remove table
w_londiste_remove_table = List()
w_londiste_remove_table2 = List(
    Symbol(',', w_londiste_remove_table),
    w_done)
w_londiste_remove_table.add(
    KnownTable(w_londiste_remove_table2, name = 'tables', append = 1))

# londiste remove sequence
w_londiste_remove_seq = List()
w_londiste_remove_seq2 = List(
    Symbol(',', w_londiste_remove_seq),
    w_done)
w_londiste_remove_seq.add(
    KnownSeq(w_londiste_remove_seq2, name = 'seqs', append = 1))

w_londiste_add = List(
        Word('table', w_londiste_add_table),
        Word('sequence', w_londiste_add_seq),
        name = 'cmd3')

w_londiste_remove = List(
        Word('table', w_londiste_remove_table),
        Word('sequence', w_londiste_remove_seq),
        name = 'cmd3')

# londiste
w_londiste = List(
    Word('add', w_londiste_add),
    Word('remove', w_londiste_remove),
    Word('missing', w_done),
    Word('tables', w_done),
    Word('seqs', w_done),
    name = "cmd2")

top_level.add(
    Word('alter', w_alter),
    Word('connect', w_connect),
    Word('create', w_create),
    Word('drop', w_drop),
    Word('install', w_install),
    Word('register', w_register),
    Word('unregister', w_unregister),
    Word('show', w_show),
    Word('exit', w_done),
    Word('londiste', w_londiste),

    Word('select', w_sql),
    w_sql)

##
## Main class for keeping the state.
##

class AdminConsole:
    cur_queue = None
    cur_database = None

    server_version = None
    pgq_version = None

    cmd_file = None
    cmd_str = None

    comp_cache = {
        'comp_pfx': None,
        'comp_list': None,
        'queue_list': None,
        'database_list': None,
        'consumer_list': None,
        'host_list': None,
        'user_list': None,
    }
    db = None
    initial_connstr = None

    rc_hosts = re.compile('\s+')

    def get_queue_list(self):
        q = "select queue_name from pgq.queue order by 1"
        return self._ccache('queue_list', q, 'pgq')

    def get_database_list(self):
        q = "select datname from pg_catalog.pg_database order by 1"
        return self._ccache('database_list', q)

    def get_user_list(self):
        q = "select usename from pg_catalog.pg_user order by 1"
        return self._ccache('user_list', q)

    def get_consumer_list(self):
        q = "select co_name from pgq.consumer order by 1"
        return self._ccache('consumer_list', q, 'pgq')

    def get_node_list(self):
        q = "select distinct node_name from pgq_node.node_location order by 1"
        return self._ccache('node_list', q, 'pgq_node')

    def _new_obj_sql(self, queue, objname, objkind):
        args = {'queue': skytools.quote_literal(queue),
                'obj': objname,
                'ifield': objname + '_name',
                'itable': 'londiste.' + objname + '_info',
                'kind': skytools.quote_literal(objkind),
            }
        q = """select quote_ident(n.nspname) || '.' || quote_ident(r.relname)
            from pg_catalog.pg_class r
            join pg_catalog.pg_namespace n on (n.oid = r.relnamespace)
            left join %(itable)s i
                 on (i.queue_name = %(queue)s and
                     i.%(ifield)s = (n.nspname || '.' || r.relname))
            where r.relkind = %(kind)s
              and n.nspname not in ('pg_catalog', 'information_schema', 'pgq', 'londiste', 'pgq_node', 'pgq_ext')
              and n.nspname !~ 'pg_.*'
              and i.%(ifield)s is null
            union all
            select londiste.quote_fqname(%(ifield)s) from %(itable)s
             where queue_name = %(queue)s and not local
            order by 1 """ % args
        return q

    def get_new_table_list(self):
        if not self.cur_queue:
            return []
        q = self._new_obj_sql(self.cur_queue, 'table', 'r')
        return self._ccache('new_table_list', q, 'londiste')

    def get_new_seq_list(self):
        if not self.cur_queue:
            return []
        q = self._new_obj_sql(self.cur_queue, 'seq', 'S')
        return self._ccache('new_seq_list', q, 'londiste')

    def get_known_table_list(self):
        if not self.cur_queue:
            return []
        qname = skytools.quote_literal(self.cur_queue)
        q = "select londiste.quote_fqname(table_name)"\
            " from londiste.table_info"\
            " where queue_name = %s order by 1" % qname
        return self._ccache('known_table_list', q, 'londiste')

    def get_known_seq_list(self):
        if not self.cur_queue:
            return []
        qname = skytools.quote_literal(self.cur_queue)
        q = "select londiste.quote_fqname(seq_name)"\
            " from londiste.seq_info"\
            " where queue_name = %s order by 1" % qname
        return self._ccache('known_seq_list', q, 'londiste')

    def get_plain_table_list(self):
        q = "select quote_ident(n.nspname) || '.' || quote_ident(r.relname)"\
            " from pg_class r join pg_namespace n on (n.oid = r.relnamespace)"\
            " where r.relkind = 'r' "\
            "   and n.nspname not in ('pg_catalog', 'information_schema', 'pgq', 'londiste', 'pgq_node', 'pgq_ext') "\
            "   and n.nspname !~ 'pg_.*' "\
            " order by 1"
        return self._ccache('plain_table_list', q)

    def get_plain_seq_list(self):
        q = "select quote_ident(n.nspname) || '.' || quote_ident(r.relname)"\
            " from pg_class r join pg_namespace n on (n.oid = r.relnamespace)"\
            " where r.relkind = 'S' "\
            "   and n.nspname not in ('pg_catalog', 'information_schema', 'pgq', 'londiste', 'pgq_node', 'pgq_ext') "\
            " order by 1"
        return self._ccache('plain_seq_list', q)

    def get_batch_list(self):
        if not self.cur_queue:
            return []
        qname = skytools.quote_literal(self.cur_queue)
        q = "select current_batch::text from pgq.get_consumer_info(%s)"\
            " where current_batch is not null order by 1" % qname
        return self._ccache('batch_list', q, 'pgq')

    def _ccache(self, cname, q, req_schema = None):
        if not self.db:
            return []

        # check if schema exists
        if req_schema:
            k = "schema_exists_%s" % req_schema
            ok = self.comp_cache.get(k)
            if ok is None:
                curs = self.db.cursor()
                ok = skytools.exists_schema(curs, req_schema)
                self.comp_cache[k] = ok
            if not ok:
                return []

        # actual completion
        clist = self.comp_cache.get(cname)
        if clist is None:
            curs = self.db.cursor()
            curs.execute(q)
            clist = [r[0] for r in curs.fetchall()]
            self.comp_cache[cname] = clist
        return clist

    def get_host_list(self):
        clist = self.comp_cache.get('host_list')
        if clist is None:
            try:
                f = open('/etc/hosts', 'r')
                clist = []
                while 1:
                    ln = f.readline()
                    if not ln:
                        break
                    ln = ln.strip()
                    if ln == '' or ln[0] == '#':
                        continue
                    lst = self.rc_hosts.split(ln)
                    for h in lst[1:]:
                        if h not in IGNORE_HOSTS:
                            clist.append(h)
                clist.sort()
                self.comp_cache['host_list'] = clist
            except IOError:
                clist = []
        return clist

    def parse_cmdline(self, argv):
        switches = "c:h:p:d:U:f:Q:"
        lswitches = ['help', 'version']
        try:
            opts, args = getopt.getopt(argv, switches, lswitches)
        except getopt.GetoptError, ex:
            print str(ex)
            print "Use --help to see command line options"
            sys.exit(1)

        cstr_map = {
            'dbname': None,
            'host': None,
            'port': None,
            'user': None,
            'password': None,
        }
        cmd_file = cmd_str = None
        for o, a in opts:
            if o == "--help":
                print cmdline_usage
                sys.exit(0)
            elif o == "--version":
                print "qadmin version %s" % __version__
                sys.exit(0)
            elif o == "-h":
                cstr_map['host'] = a
            elif o == "-p":
                cstr_map['port'] = a
            elif o == "-d":
                cstr_map['dbname'] = a
            elif o == "-U":
                cstr_map['user'] = a
            elif o == "-Q":
                self.cur_queue = a
            elif o == "-c":
                self.cmd_str = a
            elif o == "-f":
                self.cmd_file = a

        cstr_list = []
        for k, v in cstr_map.items():
            if v is not None:
                cstr_list.append("%s=%s" % (k, v))
        if len(args) == 1:
            a = args[0]
            if a.find('=') >= 0:
                cstr_list.append(a)
            else:
                cstr_list.append("dbname=%s" % a)
        elif len(args) > 1:
            print "too many arguments, use --help to see syntax"
            sys.exit(1)

        self.initial_connstr = " ".join(cstr_list)

    def db_connect(self, connstr, quiet=False):
        db = skytools.connect_database(connstr)
        db.set_isolation_level(0) # autocommit

        q = "select current_database(), current_setting('server_version')"
        curs = db.cursor()
        curs.execute(q)
        res = curs.fetchone()
        self.cur_database = res[0]
        self.server_version = res[1]
        q = "select pgq.version()"
        try:
            curs.execute(q)
            res = curs.fetchone()
            self.pgq_version = res[0]
        except psycopg2.ProgrammingError:
            self.pgq_version = "<none>"
        if not quiet:
            print "qadmin (%s, server %s, pgq %s)" % (__version__, self.server_version, self.pgq_version)
            #print "Connected to %r" % connstr
        return db

    def run(self, argv):
        self.parse_cmdline(argv)

        if self.cmd_file is not None and self.cmd_str is not None:
            print "cannot handle -c and -f together"
            sys.exit(1)

        # append ; to cmd_str if needed
        if self.cmd_str and not self.cmd_str.rstrip().endswith(';'):
            self.cmd_str += ';'

        cmd_str = self.cmd_str
        if self.cmd_file:
            cmd_str = open(self.cmd_file, "r").read()

        try:
            self.db = self.db_connect(self.initial_connstr, quiet=True)
        except psycopg2.Error, d:
            print str(d).strip()
            sys.exit(1)

        if cmd_str:
            self.exec_string(cmd_str)
        else:
            self.main_loop()

    def main_loop(self):
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.rl_completer_safe)
        #print 'delims: ', repr(readline.get_completer_delims())
        # remove " from delims
        #readline.set_completer_delims(" \t\n`~!@#$%^&*()-=+[{]}\\|;:',<>/?")

        hist_file = os.path.expanduser("~/.qadmin_history")
        try:
            readline.read_history_file(hist_file)
        except IOError:
            pass

        print "Welcome to qadmin %s (server %s), the PgQ interactive terminal." % (__version__, self.server_version)
        print "Use 'show help;' to see available commands."
        while 1:
            try:
                ln = self.line_input()
                self.exec_string(ln)
            except KeyboardInterrupt:
                print
            except EOFError:
                print
                break
            except psycopg2.Error, d:
                print 'ERROR:', str(d).strip()
            except Exception:
                traceback.print_exc()
            self.reset_comp_cache()

        try:
            readline.write_history_file(hist_file)
        except IOError:
            pass

    def rl_completer(self, curword, state):
        curline = readline.get_line_buffer()
        start = readline.get_begidx()
        end = readline.get_endidx()

        pfx = curline[:start]
        sglist = self.find_suggestions(pfx, curword)
        if state < len(sglist):
            return sglist[state]
        return None

    def rl_completer_safe(self, curword, state):
        try:
            return self.rl_completer(curword, state)
        except BaseException, det:
            print 'got some error', str(det)

    def line_input(self):
        qname = "(noqueue)"
        if self.cur_queue:
            qname = self.cur_queue
        p = "%s@%s> " % (qname, self.cur_database)
        return raw_input(p)

    def sql_words(self, sql):
        return skytools.sql_tokenizer(sql,
                standard_quoting = True,
                fqident = True,
                show_location = True,
                ignore_whitespace = True)

    def reset_comp_cache(self):
        self.comp_cache = {}

    def find_suggestions(self, pfx, curword, params = {}):

        # refresh word cache
        c_pfx = self.comp_cache.get('comp_pfx')
        c_list = self.comp_cache.get('comp_list', [])
        c_pos = self.comp_cache.get('comp_pos')
        if c_pfx != pfx:
            c_list, c_pos = self.find_suggestions_real(pfx, params)
            orig_pos = c_pos
            while c_pos < len(pfx) and pfx[c_pos].isspace():
                c_pos += 1
            #print repr(pfx), orig_pos, c_pos
            self.comp_cache['comp_pfx'] = pfx
            self.comp_cache['comp_list'] = c_list
            self.comp_cache['comp_pos'] = c_pos

        skip = len(pfx) - c_pos
        if skip:
            curword = pfx[c_pos : ] + curword

        # generate suggestions
        wlen = len(curword)
        res = []
        for cword in c_list:
            if curword == cword[:wlen]:
                res.append(cword)

        # resync with readline offset
        if skip:
            res = [s[skip:] for s in res]
        #print '\nfind_suggestions', repr(pfx), repr(curword), repr(res), repr(c_list)
        return res

    def find_suggestions_real(self, pfx, params):
        # find level
        node = top_level
        pos = 0
        xpos = 0
        xnode = node
        for typ, w, pos in self.sql_words(pfx):
            w = normalize_any(typ, w)
            node = node.get_next(typ, w, params)
            if not node:
                break
            xnode = node
            xpos = pos

        # find possible matches
        if xnode:
            return (xnode.get_completions(params), xpos)
        else:
            return ([], xpos)

    def exec_string(self, ln, eof = False):
        node = top_level
        params = {}
        self.tokens = []
        for typ, w, pos in self.sql_words(ln):
            self.tokens.append((typ, w))
            w = normalize_any(typ, w)
            if typ == 'error':
                print 'syntax error 1:', repr(ln)
                return
            onode = node
            node = node.get_next(typ, w, params)
            if not node:
                print "syntax error 2:", repr(ln), repr(typ), repr(w), repr(params)
                return
            if node == top_level:
                self.exec_params(params)
                params = {}
                self.tokens = []
        if eof:
            if params:
                self.exec_params(params)
        elif node != top_level:
            print "multi-line commands not supported:", repr(ln)

    def exec_params(self, params):
        #print 'RUN', params
        cmd = params.get('cmd')
        cmd2 = params.get('cmd2')
        cmd3 = params.get('cmd3')
        if not cmd:
            print 'parse error: no command found'
            return
        if cmd2:
            cmd = "%s_%s" % (cmd, cmd2)
        if cmd3:
            cmd = "%s_%s" % (cmd, cmd3)
        #print 'RUN', repr(params)
        fn = getattr(self, 'cmd_' + cmd, self.execute_sql)
        fn(params)

    def cmd_connect(self, params):
        qname = params.get('queue', self.cur_queue)

        if 'node' in params and not qname:
            print 'node= needs a queue also'
            return

        # load raw connection params
        cdata = []
        for k in ('dbname', 'host', 'port', 'user', 'password'):
            if k in params:
                arg = "%s=%s" % (k, params[k])
                cdata.append(arg)

        # raw connect
        if cdata:
            if 'node' in params:
                print 'node= cannot be used together with raw params'
                return
            cstr = " ".join(cdata)
            self.db = self.db_connect(cstr)

        # connect to queue
        if qname:
            curs = self.db.cursor()
            q = "select queue_name from pgq.get_queue_info(%s)"
            curs.execute(q, [qname])
            res = curs.fetchall()
            if len(res) == 0:
                print 'queue not found'
                return

            if 'node' in params:
                q = "select node_location from pgq_node.get_queue_locations(%s)"\
                    " where node_name = %s"
                curs.execute(q, [qname, params['node']])
                res = curs.fetchall()
                if len(res) == 0:
                    print "node not found"
                    return
                cstr = res[0]['node_location']
                self.db = self.db_connect(cstr)

        # set default queue
        if 'queue' in params:
            self.cur_queue = qname

        print "CONNECT"

    def cmd_show_version (self, params):
        print "qadmin version %s" % __version__
        print "server version %s" % self.server_version
        print "pgq version %s" % self.pgq_version

    def cmd_install(self, params):
        pgq_objs = [
            skytools.DBLanguage("plpgsql"),
            #skytools.DBFunction("txid_current_snapshot", 0, sql_file="txid.sql"),
            skytools.DBSchema("pgq", sql_file="pgq.sql"),
            skytools.DBSchema("pgq_ext", sql_file="pgq_ext.sql"),
            skytools.DBSchema("pgq_node", sql_file="pgq_node.sql"),
            skytools.DBSchema("pgq_coop", sql_file="pgq_coop.sql"),
        ]
        londiste_objs = pgq_objs + [
            skytools.DBSchema("londiste", sql_file="londiste.sql"),
        ]
        mod_map = {
            'londiste': londiste_objs,
            'pgq': pgq_objs,
        }
        mod_name = params['module']
        objs = mod_map[mod_name]
        if not self.db:
            print "no db?"
            return
        curs = self.db.cursor()
        skytools.db_install(curs, objs, None)
        print "INSTALL"

    def cmd_show_queue(self, params):
        queue = params.get('queue')
        if queue is None:
            # "show queue" without args, show all if not connected to
            # specific queue
            queue = self.cur_queue
            if not queue:
                queue = '*'
        curs = self.db.cursor()
        fields = [
            "queue_name",
            "queue_cur_table || '/' || queue_ntables as tables",
            "queue_ticker_max_count as max_count",
            "queue_ticker_max_lag as max_lag",
            "queue_ticker_idle_period as idle_period",
            "queue_ticker_paused as paused",
            "ticker_lag",
            "ev_per_sec",
            "ev_new",
        ]
        pfx = "select " + ",".join(fields)

        if queue == '*':
            q = pfx + " from pgq.get_queue_info()"
            curs.execute(q)
        else:
            q = pfx + " from pgq.get_queue_info(%s)"
            curs.execute(q, [queue])

        display_result(curs, 'Queue "%s":' % queue)

    def cmd_show_consumer(self, params):
        """Show consumer status"""
        consumer = params.get('consumer', '*')
        queue = params.get('queue', '*')

        q_queue = (queue != '*' and queue or None)
        q_consumer = (consumer != '*' and consumer or None)

        curs = self.db.cursor()
        q = "select * from pgq.get_consumer_info(%s, %s)"
        curs.execute(q, [q_queue, q_consumer])

        display_result(curs, 'Consumer "%s" on queue "%s":' % (consumer, queue))

    def cmd_show_node(self, params):
        """Show node information."""

        # TODO: This should additionally show node roles, lags and hierarchy.
        # Similar to londiste "status".

        node = params.get('node', '*')
        queue = params.get('queue', '*')

        q_queue = (queue != '*' and queue or None)
        q_node = (node != '*' and node or None)

        curs = self.db.cursor()
        q = """select queue_name, node_name, node_location, dead
               from pgq_node.node_location
               where node_name = coalesce(%s, node_name)
                     and queue_name = coalesce(%s, queue_name)
               order by 1,2"""
        curs.execute(q, [q_node, q_queue])

        display_result(curs, 'Node "%s" on queue "%s":' % (node, queue))

    def cmd_show_batch(self, params):
        batch_id = params.get('batch_id')
        consumer = params.get('consumer')
        queue = self.cur_queue
        if not queue:
            print 'No default queue'
            return
        curs = self.db.cursor()
        if consumer:
            q = "select current_batch from pgq.get_consumer_info(%s, %s)"
            curs.execute(q, [queue, consumer])
            res = curs.fetchall()
            if len(res) != 1:
                print 'no such consumer'
                return
            batch_id = res[0]['current_batch']
            if batch_id is None:
                print 'consumer has no open batch'
                return

        q = "select * from pgq.get_batch_events(%s)"
        curs.execute(q, [batch_id])

        display_result(curs, 'Batch events:')

    def cmd_register_consumer(self, params):
        queue = params.get("queue", self.cur_queue)
        if not queue:
            print 'No queue specified'
            return
        at_tick = params.get('at_tick')
        copy_reg = params.get('copy_reg')
        consumer = params['consumer']
        curs = self.db.cursor()

        # copy other registration
        if copy_reg:
            q = "select coalesce(next_tick, last_tick) as pos from pgq.get_consumer_info(%s, %s)"
            curs.execute(q, [queue, copy_reg])
            reg = curs.fetchone()
            if not reg:
                print "Consumer %s not registered on queue %d" % (copy_reg, queue)
                return
            at_tick = reg['pos']

        # avoid double reg if specific pos is not requested
        if not at_tick:
            q = "select * from pgq.get_consumer_info(%s, %s)"
            curs.execute(q, [queue, consumer])
            if curs.fetchone():
                print 'Consumer already registered'
                return

        if at_tick:
            q = "select * from pgq.register_consumer_at(%s, %s, %s)"
            curs.execute(q, [queue, consumer, int(at_tick)])
        else:
            q = "select * from pgq.register_consumer(%s, %s)"
            curs.execute(q, [queue, consumer])
        print "REGISTER"

    def cmd_register_subconsumer(self, params):
        queue = params.get("queue", self.cur_queue)
        if not queue:
            print 'No queue specified'
            return
        subconsumer = params['subconsumer']
        consumer = params.get("consumer")
        if not consumer:
            print 'No consumer specified'
            return
        curs = self.db.cursor()

        _subcon_name = '%s.%s' % (consumer, subconsumer)

        q = "select * from pgq.get_consumer_info(%s, %s)"
        curs.execute(q, [queue, _subcon_name])
        if curs.fetchone():
            print 'Subconsumer already registered'
            return

        q = "select * from pgq_coop.register_subconsumer(%s, %s, %s)"
        curs.execute(q, [queue, consumer, subconsumer])
        print "REGISTER"

    def cmd_unregister_consumer(self, params):
        queue = params.get("queue", self.cur_queue)
        if not queue:
            print 'No queue specified'
            return
        consumer = params['consumer']
        curs = self.db.cursor()
        if consumer == '*':
            q = 'select consumer_name from pgq.get_consumer_info(%s)'
            curs.execute(q, [queue])
            consumers = [row['consumer_name'] for row in curs.fetchall()]
        else:
            consumers = [consumer]
        q = "select * from pgq.unregister_consumer(%s, %s)"
        for consumer in consumers:
            curs.execute(q, [queue, consumer])
        print "UNREGISTER"

    def cmd_unregister_subconsumer(self, params):
        queue = params.get("queue", self.cur_queue)
        if not queue:
            print 'No queue specified'
            return
        subconsumer = params["subconsumer"]
        consumer = params['consumer']
        batch_handling = int(params.get('close') is not None)
        curs = self.db.cursor()
        if subconsumer == '*':
            q = 'select consumer_name from pgq.get_consumer_info(%s)'
            curs.execute(q, [queue])
            subconsumers = [row['consumer_name'].split('.')[1]
                           for row in curs.fetchall()
                           if row['consumer_name'].startswith('%s.' % consumer)]
        else:
            subconsumers = [subconsumer]
        q = "select * from pgq_coop.unregister_subconsumer(%s, %s, %s, %s)"
        for subconsumer in subconsumers:
            curs.execute(q, [queue, consumer, subconsumer, batch_handling])
        print "UNREGISTER"

    def cmd_create_queue(self, params):
        curs = self.db.cursor()
        q = "select * from pgq.get_queue_info(%(queue)s)"
        curs.execute(q, params)
        if curs.fetchone():
            print "Queue already exists"
            return
        q = "select * from pgq.create_queue(%(queue)s)"
        curs.execute(q, params)
        print "CREATE"

    def cmd_drop_queue(self, params):
        curs = self.db.cursor()
        q = "select * from pgq.drop_queue(%(queue)s)"
        curs.execute(q, params)
        print "DROP"

    def cmd_alter_queue(self, params):
        """Alter queue parameters, accepts * for all queues"""
        queue = params.get('queue')
        curs = self.db.cursor()
        if queue == '*':
            # operate on list of queues
            q = "select queue_name from pgq.get_queue_info()"
            curs.execute(q)
            qlist = [ r[0] for r in curs.fetchall() ]
        else:
            # just single queue specified
            qlist = [ queue ]

        for qname in qlist:
            params['queue'] = qname

            # loop through the parameters, passing any unrecognized
            # key down pgq.set_queue_config
            for k in params:
                if k in ('queue', 'cmd', 'cmd2'):
                    continue

                q = "select * from pgq.set_queue_config" \
                    "(%%(queue)s, '%s', %%(%s)s)" % (k, k)

                curs.execute(q, params)
        print "ALTER"

    def cmd_show_help(self, params):
        print __doc__

    def cmd_exit(self, params):
        sys.exit(0)

    ##
    ## Londiste
    ##

    def cmd_londiste_missing(self, params):
        """Show missing objects."""

        queue = self.cur_queue

        curs = self.db.cursor()
        q = """select * from londiste.local_show_missing(%s)"""
        curs.execute(q, [queue])

        display_result(curs, 'Missing objects on queue "%s":' % (queue))

    def cmd_londiste_tables(self, params):
        """Show local tables."""

        queue = self.cur_queue

        curs = self.db.cursor()
        q = """select * from londiste.get_table_list(%s) where local"""
        curs.execute(q, [queue])

        display_result(curs, 'Local tables on queue "%s":' % (queue))

    def cmd_londiste_seqs(self, params):
        """Show local seqs."""

        queue = self.cur_queue

        curs = self.db.cursor()
        q = """select * from londiste.get_seq_list(%s) where local"""
        curs.execute(q, [queue])

        display_result(curs, 'Sequences on queue "%s":' % (queue))

    def cmd_londiste_add_table(self, params):
        """Add table."""

        args = []
        for a in ('skip_truncate', 'expect_sync', 'backup', 'no_triggers', 'skip'):
            if a in params:
                args.append(a)
        for a in ('tgflags', 'ignore', 'pkey', 'when',
                  'ev_type', 'ev_data',
                  'ev_extra1', 'ev_extra2', 'ev_extra3', 'ev_extra4'):
            if a in params:
                args.append("%s=%s" % (a, params[a]))

        curs = self.db.cursor()
        q = """select * from londiste.local_add_table(%s, %s, %s)"""
        for tbl in params['tables']:
            curs.execute(q, [self.cur_queue, tbl, args])
            res = curs.fetchone()
            print res[0], res[1]
        print 'ADD_TABLE'

    def cmd_londiste_remove_table(self, params):
        """Remove table."""

        curs = self.db.cursor()
        q = """select * from londiste.local_remove_table(%s, %s)"""
        for tbl in params['tables']:
            curs.execute(q, [self.cur_queue, tbl])
            res = curs.fetchone()
            print res[0], res[1]
        print 'REMOVE_TABLE'

    def cmd_londiste_add_seq(self, params):
        """Add seq."""

        curs = self.db.cursor()
        q = """select * from londiste.local_add_seq(%s, %s)"""
        for seq in params['seqs']:
            curs.execute(q, [self.cur_queue, seq])
            res = curs.fetchone()
            print res[0], res[1]
        print 'ADD_SEQ'

    def cmd_londiste_remove_seq(self, params):
        """Remove seq."""

        curs = self.db.cursor()
        q = """select * from londiste.local_remove_seq(%s, %s)"""
        for seq in params['seqs']:
            curs.execute(q, [self.cur_queue, seq])
            res = curs.fetchone()
            print res[0], res[1]
        print 'REMOVE_SEQ:', res[0], res[1]

    ## generic info

    def cmd_show_table(self, params):
        print '-' * 64
        tbl = params['table']
        curs = self.db.cursor()
        s = skytools.TableStruct(curs, tbl)
        s.create(fakecurs(), skytools.T_ALL)
        print '-' * 64

    def cmd_show_sequence(self, params):
        print '-' * 64
        seq = params['seq']
        curs = self.db.cursor()
        s = skytools.SeqStruct(curs, seq)
        s.create(fakecurs(), skytools.T_ALL)
        print '-' * 64

    ## sql pass-through

    def execute_sql(self, params):
        tks = [tk[1] for tk in self.tokens]
        sql = ' '.join(tks)

        curs = self.db.cursor()
        curs.execute(sql)

        if curs.description:
            display_result(curs, None)
        print curs.statusmessage

class fakecurs:
    def execute(self, sql):
        print sql

def main():
    global script
    script = AdminConsole()
    script.run(sys.argv[1:])

if __name__ == '__main__':
    main()