0% found this document useful (0 votes)
21 views57 pages

Procedural Programming With Postgresql PL/PGSQL: Design Complex Database-Centric Applications With PL/PGSQL 1St Edition Baji Shaik

Uploaded by

qillahmyrnes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views57 pages

Procedural Programming With Postgresql PL/PGSQL: Design Complex Database-Centric Applications With PL/PGSQL 1St Edition Baji Shaik

Uploaded by

qillahmyrnes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Download the full version of the ebook at

https://ebookmass.com

Procedural Programming with PostgreSQL


PL/pgSQL: Design Complex Database-Centric
Applications with PL/pgSQL 1st Edition Baji
Shaik
https://ebookmass.com/product/procedural-
programming-with-postgresql-pl-pgsql-design-
complex-database-centric-applications-with-pl-
pgsql-1st-edition-baji-shaik/

Explore and download more ebook at https://ebookmass.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Procedural Programming with PostgreSQL PL/pgSQL: Design


Complex Database-Centric Applications with PL/pgSQL 1 /
converted Edition Baji Shaik
https://ebookmass.com/product/procedural-programming-with-postgresql-
pl-pgsql-design-complex-database-centric-applications-with-pl-
pgsql-1-converted-edition-baji-shaik/
testbankdeal.com

Modern Oracle Database Programming: Level Up Your Skill


Set to Oracle’s Latest and Most Powerful Features in SQL,
PL/SQL, and JSON 1st Edition Alex Nuijten
https://ebookmass.com/product/modern-oracle-database-programming-
level-up-your-skill-set-to-oracles-latest-and-most-powerful-features-
in-sql-pl-sql-and-json-1st-edition-alex-nuijten-2/
testbankdeal.com

Modern Oracle Database Programming: Level Up Your Skill


Set to Oracle’s Latest and Most Powerful Features in SQL,
PL/SQL, and JSON 1st Edition Alex Nuijten
https://ebookmass.com/product/modern-oracle-database-programming-
level-up-your-skill-set-to-oracles-latest-and-most-powerful-features-
in-sql-pl-sql-and-json-1st-edition-alex-nuijten/
testbankdeal.com

Oracle PL/SQL by Example, 6th Edition Benjamin Rosenzweig

https://ebookmass.com/product/oracle-pl-sql-by-example-6th-edition-
benjamin-rosenzweig/

testbankdeal.com
Oracle Database Programming with Visual Basic.NET:
Concepts, Designs and Implementations Ying Bai

https://ebookmass.com/product/oracle-database-programming-with-visual-
basic-net-concepts-designs-and-implementations-ying-bai/

testbankdeal.com

Programming for Game Design: A Hands-On Guide with Godot


1st Edition Wang

https://ebookmass.com/product/programming-for-game-design-a-hands-on-
guide-with-godot-1st-edition-wang/

testbankdeal.com

Starting Out With Programming Logic and Design, 6e 6th


Edition Tony Gaddis

https://ebookmass.com/product/starting-out-with-programming-logic-and-
design-6e-6th-edition-tony-gaddis/

testbankdeal.com

Programming for Game Design: A Hands-On Guide with Godot


1st Edition Wallace Wang

https://ebookmass.com/product/programming-for-game-design-a-hands-on-
guide-with-godot-1st-edition-wallace-wang/

testbankdeal.com

Programming for Game Design: A Hands-On Guide with Godot


1st Edition Wallace Wang

https://ebookmass.com/product/programming-for-game-design-a-hands-on-
guide-with-godot-1st-edition-wallace-wang-2/

testbankdeal.com
Q L
S
E
AG
NGU
Y LA
ER
D QU
RE
TU
RUC
ST

B
TA

Procedural Programming DA

with PostgreSQL DA
TAB
A SE

DA
T

PL/pgSQL
Design Complex Database-Centric
Applications with PL/pgSQL

Baji Shaik
Dinesh Kumar Chemuduru
Procedural Programming
with PostgreSQL
PL/pgSQL
Design Complex Database-Centric
Applications with PL/pgSQL

Baji Shaik
Dinesh Kumar Chemuduru
Procedural Programming with PostgreSQL PL/pgSQL: Design Complex
Database-­Centric Applications with PL/pgSQL
Baji Shaik Dinesh Kumar Chemuduru
Texas, TX, USA Andhra Pradesh, India

ISBN-13 (pbk): 978-1-4842-9839-8 ISBN-13 (electronic): 978-1-4842-9840-4


https://doi.org/10.1007/978-1-4842-9840-4

Copyright © 2023 by Baji Shaik and Dinesh Kumar Chemuduru


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Divya Modi
Development Editor: James Markham
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit
www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub (https://github.com/Apress). For more detailed information, please visit
https://www.apress.com/gp/services/source-code.
Paper in this product is recyclable
I extend this dedication to Afrah Razzak, my exceptional wife.
Her enduring support and remarkable patience during the extended
writing sessions have been invaluable to me.
—Baji Shaik

I lovingly extend this dedication to my dear friend, Baji Shaik.


Your unwavering support and encouragement have been my guiding
light, especially in the most challenging moments. Your belief in me has
been a constant source of inspiration, and I am grateful for your
presence in my journey. This book is as much a tribute to our
friendship as it is a testament to the power of steadfast camaraderie.
Thank you for always being there.
—Dinesh Kumar Chemuduru
Table of Contents
About the Authors�������������������������������������������������������������������������������������������������� xiii

About the Technical Reviewer���������������������������������������������������������������������������������xv

Acknowledgments�������������������������������������������������������������������������������������������������xvii
Introduction������������������������������������������������������������������������������������������������������������xix

Chapter 1: Introduction to PL/pgSQL������������������������������������������������������������������������ 1


A Closer Look at PL/pgSQL����������������������������������������������������������������������������������������������������������� 1
PL/pgSQL Installation�������������������������������������������������������������������������������������������������������������������� 2
PL/pgSQL Execution Flow������������������������������������������������������������������������������������������������������������� 4
PL/pgSQL Blocks��������������������������������������������������������������������������������������������������������������������������� 6
Anonymous or Unnamed Blocks���������������������������������������������������������������������������������������������� 6
Named Blocks����������������������������������������������������������������������������������������������������������������������������� 10
Summary������������������������������������������������������������������������������������������������������������������������������������ 12
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 12

Chapter 2: PL/pgSQL Variables������������������������������������������������������������������������������� 13


What Are Variables in PL/pgSQL?������������������������������������������������������������������������������������������������ 13
Declaring Variables��������������������������������������������������������������������������������������������������������������������� 13
Variable Scope���������������������������������������������������������������������������������������������������������������������������� 15
Constant Variables���������������������������������������������������������������������������������������������������������������������� 17
Variable Alias������������������������������������������������������������������������������������������������������������������������������ 18
Scalar Variables��������������������������������������������������������������������������������������������������������������������� 19
Array Variables���������������������������������������������������������������������������������������������������������������������� 21
Record Variables�������������������������������������������������������������������������������������������������������������������� 22
Cursor Variables�������������������������������������������������������������������������������������������������������������������� 23

v
Table of Contents

Summary������������������������������������������������������������������������������������������������������������������������������������ 25
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 25

Chapter 3: PL/pgSQL Data Types���������������������������������������������������������������������������� 27


Data Types����������������������������������������������������������������������������������������������������������������������������������� 27
Declaring Variables with Data Types������������������������������������������������������������������������������������������� 28
Supported Types������������������������������������������������������������������������������������������������������������������������� 30
Base Type������������������������������������������������������������������������������������������������������������������������������������ 32
Composite Type��������������������������������������������������������������������������������������������������������������������������� 33
Domain Type�������������������������������������������������������������������������������������������������������������������������������� 35
Pseudo-Type������������������������������������������������������������������������������������������������������������������������������� 37
Range Type���������������������������������������������������������������������������������������������������������������������������������� 38
Multirange Types������������������������������������������������������������������������������������������������������������������������� 40
Summary������������������������������������������������������������������������������������������������������������������������������������ 41
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 41

Chapter 4: Dealing with Strings, Numbers, and Arrays������������������������������������������ 43


Strings����������������������������������������������������������������������������������������������������������������������������������������� 43
Function Format�������������������������������������������������������������������������������������������������������������������� 45
Dealing with Null String��������������������������������������������������������������������������������������������������������� 47
Numbers������������������������������������������������������������������������������������������������������������������������������������� 50
Arrays������������������������������������������������������������������������������������������������������������������������������������������ 53
Example Use Cases��������������������������������������������������������������������������������������������������������������������� 54
Strings����������������������������������������������������������������������������������������������������������������������������������������� 54
Numbers�������������������������������������������������������������������������������������������������������������������������������� 55
Arrays������������������������������������������������������������������������������������������������������������������������������������ 57
Summary������������������������������������������������������������������������������������������������������������������������������������ 58
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 59

Chapter 5: Control Statements������������������������������������������������������������������������������� 61


IF/ELSE Statement���������������������������������������������������������������������������������������������������������������������� 62
Cascading IF Statements������������������������������������������������������������������������������������������������������� 65
CASE Statement�������������������������������������������������������������������������������������������������������������������������� 66
vi
Table of Contents

Iterative Statement��������������������������������������������������������������������������������������������������������������������� 68
LOOP Statement�������������������������������������������������������������������������������������������������������������������� 69
WHILE Statement������������������������������������������������������������������������������������������������������������������������ 72
FOR Statement���������������������������������������������������������������������������������������������������������������������������� 74
Example Use Cases��������������������������������������������������������������������������������������������������������������������� 78
Example 1������������������������������������������������������������������������������������������������������������������������������ 78
Example 2������������������������������������������������������������������������������������������������������������������������������ 81
Best Practices of Using Control Statements in PL/pgSQL����������������������������������������������������� 84
Summary������������������������������������������������������������������������������������������������������������������������������������ 85
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 85

Chapter 6: Handling Arrays������������������������������������������������������������������������������������ 87


Array Index���������������������������������������������������������������������������������������������������������������������������������� 88
Array Length������������������������������������������������������������������������������������������������������������������������������� 89
Iterate Array�������������������������������������������������������������������������������������������������������������������������������� 91
Find Duplicate Elements in Array������������������������������������������������������������������������������������������������ 92
Append Elements to Array����������������������������������������������������������������������������������������������������������� 93
Array Merge�������������������������������������������������������������������������������������������������������������������������������� 94
Multidimensional Arrays������������������������������������������������������������������������������������������������������������� 94
Summary������������������������������������������������������������������������������������������������������������������������������������ 96
What’s Next��������������������������������������������������������������������������������������������������������������������������������� 96

Chapter 7: Handling JSON�������������������������������������������������������������������������������������� 97


What Is JSON?���������������������������������������������������������������������������������������������������������������������������� 97
Use Cases��������������������������������������������������������������������������������������������������������������������������������� 100
Advantages and Disadvantages������������������������������������������������������������������������������������������������ 104
Build PL/pgSQL Functions for JSON������������������������������������������������������������������������������������������ 105
Indexing JSON Data������������������������������������������������������������������������������������������������������������������ 109
Other Useful JSON Functions���������������������������������������������������������������������������������������������������� 111
Summary���������������������������������������������������������������������������������������������������������������������������������� 111
What’s Next������������������������������������������������������������������������������������������������������������������������������� 112

vii
Table of Contents

Chapter 8: Cursors������������������������������������������������������������������������������������������������ 113


What Are Cursors?�������������������������������������������������������������������������������������������������������������������� 113
CURSOR Attributes��������������������������������������������������������������������������������������������������������������� 115
ISOPEN Attribute������������������������������������������������������������������������������������������������������������������ 115
FOUND Attribute������������������������������������������������������������������������������������������������������������������� 117
NOTFOUND Attribute������������������������������������������������������������������������������������������������������������ 119
ROWCOUNT Attribute����������������������������������������������������������������������������������������������������������� 120
Monitor Cursors������������������������������������������������������������������������������������������������������������������� 122
SCROLL Cursor�������������������������������������������������������������������������������������������������������������������� 123
NO SCROLL Cursor��������������������������������������������������������������������������������������������������������������� 125
WITH HOLD Cursors������������������������������������������������������������������������������������������������������������� 127
Refcursors��������������������������������������������������������������������������������������������������������������������������� 128
Summary���������������������������������������������������������������������������������������������������������������������������������� 130
What’s Next������������������������������������������������������������������������������������������������������������������������������� 130

Chapter 9: Custom Operators������������������������������������������������������������������������������� 131


Built-In Operators���������������������������������������������������������������������������������������������������������������������� 131
Creating a Custom Operator������������������������������������������������������������������������������������������������������ 135
Simple Example������������������������������������������������������������������������������������������������������������������� 136
SCENARIO 1: Case-Insensitive Comparison������������������������������������������������������������������������� 140
SCENARIO 2: Custom Data Type Math��������������������������������������������������������������������������������� 142
SCENARIO 3: Date Differentiate Operator���������������������������������������������������������������������������� 144
SCENARIO 4: Custom Operator for Data Classification�������������������������������������������������������� 146
Advantages������������������������������������������������������������������������������������������������������������������������������� 148
Disadvantages�������������������������������������������������������������������������������������������������������������������������� 149
Summary���������������������������������������������������������������������������������������������������������������������������������� 149
What’s Next������������������������������������������������������������������������������������������������������������������������������� 149

Chapter 10: Custom Casting��������������������������������������������������������������������������������� 151


Built-In Casts���������������������������������������������������������������������������������������������������������������������������� 151
Custom Casts���������������������������������������������������������������������������������������������������������������������������� 160

viii
Table of Contents

Creating a Custom Cast������������������������������������������������������������������������������������������������������� 160


Simple Example������������������������������������������������������������������������������������������������������������������� 161
SCENARIO 1: Converting Custom Data Types����������������������������������������������������������������������� 163
SCENARIO 2: Custom Data Type to JSONB��������������������������������������������������������������������������� 165
Summary���������������������������������������������������������������������������������������������������������������������������������� 168
What’s Next������������������������������������������������������������������������������������������������������������������������������� 168

Chapter 11: Dynamic SQL������������������������������������������������������������������������������������� 169


What Is Dynamic SQL?�������������������������������������������������������������������������������������������������������������� 169
Syntax of Dynamic SQL in PL/pgSQL����������������������������������������������������������������������������������� 169
Simple Example������������������������������������������������������������������������������������������������������������������� 170
Use Cases of Dynamic SQL�������������������������������������������������������������������������������������������������� 171
Best Practices and Considerations for Dynamic SQL���������������������������������������������������������������� 178
1. Preventing SQL Injection������������������������������������������������������������������������������������������������� 179
2. Sanitizing and Validating Inputs�������������������������������������������������������������������������������������� 179
3. Security Concerns����������������������������������������������������������������������������������������������������������� 180
4. Performance Optimization����������������������������������������������������������������������������������������������� 180
Summary���������������������������������������������������������������������������������������������������������������������������������� 181
What’s Next������������������������������������������������������������������������������������������������������������������������������� 181

Chapter 12: Building Functions and Procedures�������������������������������������������������� 183


Functions���������������������������������������������������������������������������������������������������������������������������������� 183
Defining Functions��������������������������������������������������������������������������������������������������������������� 184
Calling Functions����������������������������������������������������������������������������������������������������������������� 184
Categories��������������������������������������������������������������������������������������������������������������������������������� 185
Immutable Functions���������������������������������������������������������������������������������������������������������������� 186
STABLE Functions��������������������������������������������������������������������������������������������������������������������� 188
VOLATILE Functions������������������������������������������������������������������������������������������������������������������� 191
Procedures�������������������������������������������������������������������������������������������������������������������������������� 194
Temporary Functions/Procedures��������������������������������������������������������������������������������������������� 195
VARIADIC Functions/Procedures����������������������������������������������������������������������������������������������� 196
Best Practices���������������������������������������������������������������������������������������������������������������������� 198

ix
Visit https://ebookmass.com
now to explore a rich
collection of eBooks and enjoy
exciting offers!
Table of Contents

Summary���������������������������������������������������������������������������������������������������������������������������������� 199
What’s Next������������������������������������������������������������������������������������������������������������������������������� 199

Chapter 13: Return Values and Parameters���������������������������������������������������������� 201


Return Values���������������������������������������������������������������������������������������������������������������������������� 201
Simple Example������������������������������������������������������������������������������������������������������������������� 202
Different Ways to Return Values������������������������������������������������������������������������������������������������ 203
RETURNS����������������������������������������������������������������������������������������������������������������������������� 203
RETURNS SETOF������������������������������������������������������������������������������������������������������������������ 204
RETURNS TABLE������������������������������������������������������������������������������������������������������������������ 204
OUT�������������������������������������������������������������������������������������������������������������������������������������� 205
Simple Difference Matrix����������������������������������������������������������������������������������������������������� 206
Different Examples for Each RETURN Type�������������������������������������������������������������������������� 206
Using SELECT Statements��������������������������������������������������������������������������������������������������� 207
Using RETURNS TABLE�������������������������������������������������������������������������������������������������������� 208
Using RETURN NEXT������������������������������������������������������������������������������������������������������������ 209
Using RETURNS SETOF TABLE��������������������������������������������������������������������������������������������� 210
Using RETURNS SETOF Data Type���������������������������������������������������������������������������������������� 210
Using RETURNS RECORD����������������������������������������������������������������������������������������������������� 211
Using RETURNS SETOF RECORD������������������������������������������������������������������������������������������ 212
Using OUT Parameters��������������������������������������������������������������������������������������������������������� 214
Using INOUT Parameter������������������������������������������������������������������������������������������������������� 216
Summary���������������������������������������������������������������������������������������������������������������������������������� 216
What’s Next������������������������������������������������������������������������������������������������������������������������������� 217

Chapter 14: Handling Exceptions�������������������������������������������������������������������������� 219


Exceptions��������������������������������������������������������������������������������������������������������������������������������� 219
GET DIAGNOSTICS���������������������������������������������������������������������������������������������������������������� 219
FOUND��������������������������������������������������������������������������������������������������������������������������������� 223
Exceptions in PL/pgSQL������������������������������������������������������������������������������������������������������������ 225
Different Ways to Handle Exceptions in PL/pgSQL�������������������������������������������������������������� 226
Using the BEGIN and END Statements��������������������������������������������������������������������������������� 226

x
Table of Contents

Using the RAISE Statement������������������������������������������������������������������������������������������������� 231


Custom Exceptions�������������������������������������������������������������������������������������������������������������� 232
Rethrow Exceptions������������������������������������������������������������������������������������������������������������� 233
ASSERT�������������������������������������������������������������������������������������������������������������������������������� 234
Get Call Stack���������������������������������������������������������������������������������������������������������������������� 235
Using the GET STACKED DIAGNOSTICS Statement�������������������������������������������������������������� 237
Advantages of Using Exceptions����������������������������������������������������������������������������������������� 238
Disadvantages of Using Exceptions������������������������������������������������������������������������������������� 239
Summary���������������������������������������������������������������������������������������������������������������������������������� 239
What’s Next������������������������������������������������������������������������������������������������������������������������������� 240

Chapter 15: Triggers��������������������������������������������������������������������������������������������� 241


What Are Triggers?�������������������������������������������������������������������������������������������������������������������� 241
Syntax���������������������������������������������������������������������������������������������������������������������������������� 242
Simple Example������������������������������������������������������������������������������������������������������������������� 243
Types of Triggers in PostgreSQL������������������������������������������������������������������������������������������������ 245
Row-Level Triggers�������������������������������������������������������������������������������������������������������������� 246
INSTEAD OF Triggers������������������������������������������������������������������������������������������������������������ 253
Statement-Level Triggers���������������������������������������������������������������������������������������������������� 254
Event Triggers���������������������������������������������������������������������������������������������������������������������� 258
Advantages of Triggers�������������������������������������������������������������������������������������������������������� 260
Disadvantages of Triggers��������������������������������������������������������������������������������������������������� 261
DROP Triggers��������������������������������������������������������������������������������������������������������������������������� 261
Summary���������������������������������������������������������������������������������������������������������������������������������� 262
What’s Next������������������������������������������������������������������������������������������������������������������������������� 262

Chapter 16: Transaction Management������������������������������������������������������������������ 263


Nested Transactions������������������������������������������������������������������������������������������������������������������ 263
Exception Handling������������������������������������������������������������������������������������������������������������������� 266
Summary���������������������������������������������������������������������������������������������������������������������������������� 270
What’s Next������������������������������������������������������������������������������������������������������������������������������� 270

xi
Table of Contents

Chapter 17: Aggregates���������������������������������������������������������������������������������������� 271


Custom Aggregate��������������������������������������������������������������������������������������������������������������������� 271
Simple Example������������������������������������������������������������������������������������������������������������������� 272
State Transition Function����������������������������������������������������������������������������������������������������� 273
Final Function���������������������������������������������������������������������������������������������������������������������� 275
Creating Custom Aggregate������������������������������������������������������������������������������������������������� 276
Create Type�������������������������������������������������������������������������������������������������������������������������� 277
Create State Transition Function����������������������������������������������������������������������������������������� 277
Create Aggregate����������������������������������������������������������������������������������������������������������������� 278
Final Function���������������������������������������������������������������������������������������������������������������������� 279
Summary���������������������������������������������������������������������������������������������������������������������������������� 281
What’s Next������������������������������������������������������������������������������������������������������������������������������� 281

Chapter 18: Listen and Notify������������������������������������������������������������������������������� 283


Simple Example������������������������������������������������������������������������������������������������������������������������ 283
Build Polling in psql������������������������������������������������������������������������������������������������������������������ 285
TCN Extension��������������������������������������������������������������������������������������������������������������������������� 290
Summary���������������������������������������������������������������������������������������������������������������������������������� 292
What’s Next������������������������������������������������������������������������������������������������������������������������������� 292

Chapter 19: PL/pgSQL Essential Extensions��������������������������������������������������������� 293


plprofiler Extension������������������������������������������������������������������������������������������������������������������� 293
Installation��������������������������������������������������������������������������������������������������������������������������� 295
Usage����������������������������������������������������������������������������������������������������������������������������������� 296
plpgsql_check Extension���������������������������������������������������������������������������������������������������������� 305
Installation��������������������������������������������������������������������������������������������������������������������������� 305
Usage����������������������������������������������������������������������������������������������������������������������������������� 306
Summary���������������������������������������������������������������������������������������������������������������������������������� 309

Index��������������������������������������������������������������������������������������������������������������������� 311

xii
About the Authors
Baji Shaik, currently serving as a Senior Database
Consultant at AWS Professional Services, embarked on
his journey into the world of databases in 2011. Since
then, his expertise has encompassed an array of database
technologies, including Oracle, PostgreSQL, EDB Postgres,
Amazon RDS, Amazon Aurora, Amazon Redshift, and
Greenplum. Baji’s extensive background spans both depth
and breadth, showcasing his mastery in SQL/NoSQL
database technologies.
Baji stands out as a Database Migration Expert, having
successfully developed numerous database solutions that
tackle complex business challenges, particularly in migrating databases from on-
premises environments to Amazon RDS and Aurora PostgreSQL/MySQL. His prowess
also extends to performance optimization, having fine-tuned RDS/Aurora PostgreSQL/
MySQL databases to achieve remarkable performance benchmarks.
With a passion for knowledge sharing, Baji has authored several notable books on
PostgreSQL, such as PostgreSQL Configuration, Beginning PostgreSQL on the Cloud, and
PostgreSQL Development Essentials. His commitment to education and information
dissemination is further evident through his contributions to conferences, workshops,
and a multitude of insightful blogs within the AWS blog community.

Dinesh Kumar Chemuduru, an accomplished Principal


Architect (OSS), brings a wealth of experience to the realm
of technology and open source solutions. With a notable
background at AWS as a proficient database consultant,
Dinesh excelled in orchestrating numerous successful
database migrations. His expertise extends to the open
source arena, where he has both crafted and augmented
solutions around PostgreSQL, showcasing his commitment
to collaborative innovation.

xiii
About the Authors

A coding enthusiast at heart, Dinesh finds joy in crafting applications using Flutter,
Golang, and C++, platforms where his creativity knows no bounds. His proficiency
extends to the deployment phase, as he deftly navigates Kubernetes to bring his coding
creations to life. In the literary domain, Dinesh stands as a coauthor of the esteemed
PostgreSQL High Performance Cookbook, a testament to his mastery of the subject
matter. Beyond his own works, he actively engages in the appraisal of fellow authors’
PostgreSQL books, cementing his status as a valued participant in the exchange of
knowledge.
Dinesh’s impact reverberates through his open source contributions, which include
the inception and enrichment of projects such as PTOR – an ingenious RPO/RTO/SLA
calculator tailored for PostgreSQL. Another tool, “hammerpost,” sets a benchmark for
synthetic parameter evaluation in PostgreSQL, seamlessly integrated with HammerDB.

xiv
About the Technical Reviewer
Deepak Ramnandan Mahto works as a PostgreSQL
Database Engineer at Google Cloud. He has been working
with PostgreSQL since 2018, and he also worked as a
database migration consultant at AWS. He is also a keen
blogger and loves to publish articles on migration, best
practices, and on cloud with PostgreSQL. He loves to
code and build database-related utilities using PL/pgSQL
and SQL.

xv
Acknowledgments
I would like to express my gratitude to several individuals who have played a crucial
role in making this book a reality. A heartfelt thank-you to Apress Media for providing
me with this valuable opportunity. I am especially grateful to my coauthor and mentor,
Dinesh Kumar Chemuduru, for his exceptional collaboration. I want to express my
gratitude to Divya Modi and Nirmal Selvaraj for being understanding of our hectic
schedules and providing us with continuous support throughout the entire process.
Special thanks to Deepak Mahto for his thorough review of the book. Lastly, I am
profoundly thankful to my parents, Lalu Saheb Shaik and Nasar Bee, whose unwavering
support has shaped me into the person I am today.

—Baji Shaik

I would like to extend my heartfelt gratitude to a remarkable group of individuals who


have been instrumental in making this endeavor a reality. My heartfelt thank-you
to Apress Media for providing me with this valuable opportunity. A special note of
appreciation to my esteemed coauthor, Baji Shaik. Sincere thanks to Deepak Mahto,
whose meticulous review and insightful feedback significantly enhanced the quality and
depth of this manuscript. To Divya Modi and Nirmal Selvaraj, our project coordinators,
your organizational skills and dedication ensured that every aspect of this project fell
seamlessly into place. To my parents Vanamma, Sreenivasulu and my dearest children,
Yashvi and Isha, and to the future luminaries, Hema Siri K and Rahul Sonu K – your
unwavering love and understanding throughout the demanding phases of this project
have served as my steadfast anchor. Your continuous support is my driving force.
Finally, a heartfelt thank-you to my exceptional team at Tessell. Your commitment
to excellence and innovation is awe-inspiring. Together, we are shaping the future of
DBaaS, and I am privileged to work alongside such talented individuals.

—Dinesh Kumar Chemuduru

xvii
Introduction
The PostgreSQL engine comes with its own dedicated procedural language, similar
to procedural languages found in other commercial database engines. This language,
known as PL/pgSQL, offers a range of powerful features that developers have long
desired. For instance, PL/pgSQL includes certain object-oriented programming
capabilities like the ability to define custom operators and types, as well as custom
aggregates.
In contrast to other programming languages supported by PostgreSQL, PL/pgSQL is
intricately linked with the PostgreSQL database engine interface. This tight integration
ensures optimal performance and a seamless fit for constructing business logic on
the database side. In this book, we not only introduce the fundamentals of PL/pgSQL,
but we also dive deep into specific use cases that we’ve implemented for particular
scenarios. Our aim is to comprehensively cover the various features, functionalities, and
application scenarios of PL/pgSQL, offering assistance in crafting effective server-side
objects with ease.
Through the content of this book, you will gain an understanding of PL/pgSQL’s
design and dive deep into its transaction model, including how commit and rollback
operations function. You’ll discover strategies for optimizing PL/pgSQL functions and
procedures and explore the mechanics of inline or anonymous server-side code, along
with its limitations. Furthermore, you’ll acquire insights into debugging and profiling
PL/pgSQL code and learn techniques for conducting statistical analyses on the PL/
pgSQL code you create.

xix
CHAPTER 1

Introduction to PL/pgSQL
In this chapter, we will start with an introduction of PL/pgSQL, on what is PL/pgSQL
and what are the key features of it. We will talk about some common use cases where
PL/pgSQL is used. PL/pgSQL comes by default when you install the PostgreSQL server.
However, we will provide the steps to install PL/pgSQL. We will explain how PL/pgSQL
works with a simple flow diagram. We will show some basic examples of PL/pgSQL code
blocks which are called anonymous and named code blocks.

A Closer Look at PL/pgSQL


PostgreSQL uses SQL (Structured Query Language) as a default query language.
SQL is a common domain-specific language for relational databases. PostgreSQL uses
some extensions and features to implement the standards of SQL. In addition to SQL,
PostgreSQL supports many procedural languages like PL/pgSQL, PL/Java, PLV8,
PL/Python, PL/Perl, etc. Using these languages, you can create functions, stored
procedures, and triggers which will improve the performance by reducing the multiple
iterations to the databases.
PL/pgSQL is the most commonly used procedural language in PostgreSQL. It is
an extension of SQL. It is similar to Oracle's PL/SQL and supports features like control
structures, exception handling, variables, loops, and conditional statements. These
features help us to develop complex database applications in an efficient way.
When working on designing a complex business logic inside the database, you would
need to develop multiple SQLs which are sometimes interdependent. Results of one SQL
will be used by other SQLs. In this case, running multiple SQLs increases the data flow
between the database and the client application and will cause performance bottlenecks
due to high data transfer through the network. To overcome this, you can use stored
procedures or functions.

1
© Baji Shaik and Dinesh Kumar Chemuduru 2023
B. Shaik and D. K. Chemuduru, Procedural Programming with PostgreSQL PL/pgSQL,
https://doi.org/10.1007/978-1-4842-9840-4_1
Visit https://ebookmass.com
now to explore a rich
collection of eBooks and enjoy
exciting offers!
Chapter 1 Introduction to PL/pgSQL

PL/pgSQL supports stored procedures, functions, and triggers. A stored procedure


is a set of precompiled SQL statements which can be executed repeatedly. Stored
procedures can help to reduce network traffic and improve performance by reducing the
amount of data that needs to be sent between the database and the client application.
The common use cases to use stored procedures or functions using PL/pgSQL are
1. Improve data processing speed by using precompiled code
through stored procedures which will be faster than raw SQL
queries.
2. Write more complex code using features like control structures,
exception handling, variables, loops, conditional statements, etc.

3. Using stored procedures or functions, you can create a reusable


code to call from the applications to save time and effort.

4. PL/pgSQL is portable across different operating systems and


platforms. This makes it easier to migrate code between different
environments.
5. Prevent unauthorized access and data breaches by controlling the
user authentication on stored procedures or functions.

6. Use triggers to implement constraints of business processes that


cannot be expressed as foreign keys or check constraints.

PL/pgSQL Installation
PL/pgSQL is already included in PostgreSQL, so if you have PostgreSQL installed, you
should have PL/pgSQL as well. However, you may need to enable it if it is not already
enabled. Here are the steps to enable PL/pgSQL in PostgreSQL:
1. Install PostgreSQL psql client to connect to the database, or you
can use the pgAdmin client tool.

For Ubuntu, the following are the simple steps to install the client:

# Create the file repository configuration:

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt


$(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

2
Chapter 1 Introduction to PL/pgSQL

# Import the repository signing key:

wget --quiet -O - https://www.postgresql.org/media/keys/


ACCC4CF8.asc | sudo apt-key add -

# Update the package lists:

sudo apt-get update

# Install the latest version of PostgreSQL. If you want a specific


version, use 'postgresql-12' or similar instead of 'postgresql':

sudo apt-get -y install postgresql-client-15

For Linux (RHEL), you can follow the steps here:


www.postgresql.org/download/linux/redhat/

2. Connect to the database and check if PL/pgSQL is already


installed:
postgres=# \dx
List of installed extensions
Name | Version | Schema | Description
-----+---------+--------+-------------
(0 rows)
postgres=# select * from pg_extension where extname='plpgsql';
oid | extname | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition
----+---------+----------+--------------+----------------+------------+-----------+--------------
(0 rows)

3. Execute the following command to enable PL/pgSQL:

postgres=# CREATE EXTENSION plpgsql;


CREATE EXTENSION

3
Random documents with unrelated
content Scribd suggests to you:
At first starting there was a slight confusion, owing to the
eagerness of all parties to occupy the foremost ranks; but our troop
of regular cavalry, forming a line on each side of our party, kept the
crowd from pressing too closely upon us, whilst the company of
infantry, marching ahead, kept the road clear.
Our path led across a succession of corn-fields and kárez streams,
and passing between the villages of Dih Khojah and Hodera, took us
round by the Bardurrani gate to the north side of the city. We
proceeded along this, past the Hazrat-jí shrine and the city cemetery,
and then turning down the other side, turned off from the Topkhana
gate, and crossing the pátáo canals, entered the road leading from
the Herat gate westward to the garden of Rahmdil Khán. When I
was here in 1857-58, with Lumsden’s mission to the court of the
heir-apparent, the late Sardár Ghulám Hydar Khán, this road was
adorned by an avenue of tall poplar-trees. I now missed them, and
inquiring the cause of their disappearance, was told that they had
been, one by one, cut down, and used as fuel by the townspeople
during the troublous times following on the death of Dost
Muhammad.
As we proceeded we found the latter half of the road, this erst
avenue, was lined by a large body of troops, and behind them, in a
field to the left, was drawn up a half battery of artillery. The troops
comprised nearly the whole of the Kandahar garrison, and were
paraded in the following order:—First, a regiment of regular cavalry,
of which a troop was on duty with our party, next three regiments of
regular infantry (two of Kabulis and one of Kandaharis), and lastly, a
small body of Kandahar militia. The men were not as fine a body as
I had expected to see, judging from the company that had escorted
us from Peshín. These men belonged to one of the Kabul regiments,
and had evidently been picked for the duty, for the purpose of
making an impression. Their colonel, Táj Muhammad, Ghilzai, had
come down with the Saggid to meet us at the Calát border, and was
evidently proud of his men, and somewhat enthusiastically used to
try and persuade us that all the Kabul army were just as fine, if not
superior fellows.
We now saw the rest of the regiment to which they belonged, for
there was no possibility of mistaking its identity, their uniform of its
kind being unique. Their uniform was a tight jacket and trousers, cut
on the old English pattern, but of a striped material called ticken, the
same as is used for making mattress-cases at home. The head-dress
was the native quilted conical cap or topi, with a boss of scarlet wool
stuck on to its point. The other Kabuli regiment wore red jackets,
and the Kandahari one a uniform of dingy yellow colour. The militia
were the most sensibly dressed of all, and, encased in their great
sheepskin coats, looked the only comfortable people on the parade.
As we came up to the troops, a startling object pranced his horse
to the front of the line, and gave the word for a general salute, but
the words were not yet out of his mouth, when our horses stood
stock-still, and, pricking their ears, commenced snorting with fear.
Our own persuasive measures, aided by the banging of the guns
close beside us, presently overcame their objections, and they shied
and shuffled past the object of their terror—whom we now
discovered to be no other than our road-companion, Colonel Táj
Muhammad—in no very dignified manner. The Colonel had left us,
on approaching the city, to superintend the arrangements for the
parade, and he now completely took us by surprise by the wonderful
change in his dress. A Russian-pattern forage-cap, with a broad gold
band and straight peak, adorned his head, but the body was covered
by a capacious overcoat of chessboard pattern, in great squares of
brightest red, white, and blue. Having passed him, our steeds
recovered their equanimity, which was more than we had, and
enabled the General to acknowledge the honours of “dipped colours”
and “God save the Queen” with becoming grace and dignity.
At the end of the line we ran the gantlet of another apparition
similar to the first, and entered Rahmdil Khán’s garden, where his
summer palace had been prepared for our reception. Sardárs Mír
Afzal Khán and Núr Muhammad Khán conducted us to our quarters,
and after partaking of some tea and sweets that had been provided
for our refreshment, took their leave of us, and we saw no more of
them here. The first thing we did on being left alone was to stop the
pendulums of no less than five American clocks, which, whether they
figured or not, most decidedly ticked, and that too with a vigour and
rapidity that gave rise to the surmise that they were racing to make
up for lost time, having been only just wound up and set agoing for
the occasion.
CHAPTER V.
We halted four days at Kandahar to recruit our cattle, and replace
the broken-down ones by new purchases. Our entertainment all this
time was most hospitable, and was really more than we could
conveniently endure. The apartments were luxuriously furnished
with Persian carpets, Herat felts, and Kashmir embroideries. Several
coloured glass globes were suspended from the ceiling, and every
niche that was not already occupied by an American clock—and
there were some ten or twelve such—was ornamented with a glass
lamp. The clocks were all of the same pattern, and brightly gilded all
over, and, together with the globes and lamps, appeared to form
part of an investment ventured in this yet barbarous region by some
enterprising merchant with a partiality for “Yankee notions.”
We had hardly been left alone in our palatial quarters when a
succession of huge trays of all sorts of sweetmeats began to arrive.
Each was borne in by two servants, one supporting each end, and
deposited one after the other on the floor. The array was quite
alarming, for I knew they would go to our servants for disposal, and
was certain they would exceed the bounds of prudence and
moderation; a surmise in which I was not far wrong, for nearly all of
them had to undergo a physicking before we set out on our onward
journey. One of the trays in particular attracted our attention, on
account of the variety of zoological forms its surface was crowded
with. We dubbed it “Noah’s Ark,” and kept it till our departure, partly
from a suspicion that the different species of animals might not all
be good for the food of man, and partly as an amusing specimen of
the artistic skill of the confectioners of Kandahar. Much cannot be
said for their proficiency in the art of moulding. Their figures
generally left a good deal for the imagination to supplement before
their identity could be satisfactorily brought home to the mind; but
some, with even the most liberal allowance of fancy, were altogether
beyond recognition. One figure in particular afforded us much
amusement from its puzzling resemblance to several totally distinct
animals, and various were the speculations hazarded as to its real
prototype. Looked at on one side, it was pronounced to be a hare,
but this was negatived by the length of its tail. Then it was
suggested that it was meant to represent a wolf; but this was
objected to on account of the square form of the head and face.
“Perhaps it’s a tiger,” observed one of our attendants. “Perhaps it is,”
said Ghulám Ahmad, the General’s Munshí, “or any other animal you
like to call it. The material is the same, and just as good under either
name.” This was a well-directed hint to the servants, some of whom
he observed were inclined to differ in opinion as to the respective
qualities of the different mathematical figures and animal forms
which were about to be divided amongst them. “Yes,” chimed in his
assistant, “whether disc or diamond, sun or star, the sugar of all is
alike, and the pistacio paste equally thick; whether elephant, ox, or
horse, the candy is alike transparent in all, whilst the difference in
size is nothing to what it is between the real animals.”
After these encouraging signs of a peaceable division of the spoils,
we were glad to see the trays removed, for their size and number
incommoded our movements. On their removal, an excellent zújafát,
or cooked dinner, was served up Afghan fashion, and with the
profusion of Afghan hospitality. The principal dish, as a matter of
course, was the puláo—a whole sheep stuffed with a rich and
savoury store of pistacio and almond kernels, with raisins, dried
apricots, and preserved plums, &c., and concealed under a tumulus
of rice mixed with pomegranate seeds, caraways, cardamums, and
other aids to digestion, and reeking with appetising perfumes.
Around it were placed, in crowded confusion, a most substantial
array of comestibles, the variety and excellence of which were rather
puzzling to inquiring foreigners with only limited powers of digestion.
There was the yakhni, the mattanjan, and the corma, the kabáb, the
cuímá, and the cúrút, with the phirín, and falúda, and the nucl by
way of dessert, together with sherbets of sorts, sweet preserves and
sour preserves, and bread in the forms of the nán, paráta, bákir-
khání, and tuakí. Our host, the Saggid, with an inviting bismillah (“In
the name of God,” used as an invitation to commence any act),
stretched forth his hand against the puláo, and we followed suit, but
without making the smallest impression on the savoury heap before
us. With this as a secure foundation, we dipped from dish to dish to
make acquaintance with their contents. Each had particular merits of
its own, but as only an Afghan palate can distinguish them, of
course they were not appreciated by us. The Saggid, who had seen
a good deal of the English in India, and was familiar with our mode
of living, was careful to point out the dishes most resembling our
own; but alas! for the prejudice of human nature, I could trace no
points of similarity, and would have preferred a good mutton-chop
and some mealy potatoes to all the rich chef d’œuvres of the Afghan
culinary science that loaded the table. As a nation the Afghans are
gross feeders. They eat largely and consume astonishing quantities
of fatty matter. The merit of any particular dish with them depends
more upon the quantity and quality of the melted butter or fat in
which it swims than on the tenderness or flavour of the flesh, and
the more rancid the fatty matter is, the more highly is it esteemed.
This is particularly the case amongst the peasantry and the nomads,
amongst whom it is an ordinary occurrence to dispose of the tail of a
dumba sheep between three or four mouths at a single meal. The
tail of this variety of sheep is a mass of pure fat, and weighs from six
to eighteen pounds. The hardy out-door life they lead requires that
they should have a certain amount of carbonaceous pabulum in their
food; and as by their religion they are debarred from the use of
fermented liquors, the deficiency is very probably supplied by the
abundant use of fat and butter. At all events, they lay great stress on
a liberal supply of roghan, or grease, in all their food, and to its
plentiful use, I believe, is to be attributed their physical superiority,
combined, of course, with the influences of climate, which, taken
alone, are not sufficient to account for their large limbs and robust
frames.
At length our part of the performance came to a close, and the
row of attendants marching in, carried off the feast to the side-
apartments, where, in the character of hosts, they entertained our
domestics. The Saggid now took leave of us to go to his home in the
city, and we put out most of the lamps and candles, that filled the
room with a painful glare, and increased its already close
temperature.
The Afghans have no idea of domestic comfort or refinement
according to the European standard, nor have they any taste in the
arrangement of their houses. The rooms prepared for us, though full
of costly and really fine specimens of native manufacture, were yet
singularly deficient in comfort and tasteful decoration. The Saggid,
and his coadjutor here, General Safdar Ali, had accompanied the
Amir Sher Ali Khán on his visit to India in the spring of 1869, for the
conference at Amballa, and they now attempted to light up our
quarters here after the fashion they had seen in our houses in India.
Lamps and candles without stint were lighted, and set wherever
there was room to stand them, without reference to the amount of
light required, or the proper places for exhibiting it. Consequently,
the room, which was entirely unventilated, except through the
doorways opening into side-chambers, speedily became
insupportably hot and stifling, so much so, that we were obliged
before we could go to sleep to open all the doors and let a draught
of the cold frosty night air through the house.
Next morning we rode out with the Saggid and General Safdar Ali
to visit the gold-mine at the foot of the hills to the north of the city.
The mine is situated in a small creek running up north-east into an
angle formed by a spur projecting on to the Kandahar plain from the
Baba Walí range. The hills are of a very hard and compact blue
limestone, but the surface of the creek and the adjoining plain is a
coarse gravel, containing fragments of greenstone, hornblende,
quartz, and mica-schist. Coursing down the centre of the creek is a
tortuous little water-course, now dry, and with only a few wreaths of
snow lying under the shade of its rough conglomerate banks.
The mine is situated half-way up the creek, and on its southern
side, close to the ridge of blue limestone. It is a wide excavation
straight down into the soil, and in a soft easily-worked rock, quite
different from any in the vicinity. The piles of excavated rock heaped
up round the mouth of the pit presented a remarkable variety of
colours, amongst which black, blackish-green, bluish-green, reddish-
orange and fawn colour were the most prominent. I examined
several of these stones, and found them to consist of particles of
greensand, hornblende, felspar, quartz, and mica, bound together in
a gritty ferruginous clay. The formation appears to be one of
decomposed sienite, and is sufficiently compact to require blasting in
the excavation.
We descended into the great irregular pit by a steep path in its
side, and saw the miners at work. The process is very rough, and
simply this: A vein of quartz, from three or four inches to only half
an inch or less thick, is exposed in the rock, either by the use of the
pickaxe or by the aid of gunpowder. The workmen then examine the
vein with the naked eye, and if any particles of gold are detected,
they are removed, with the surrounding portion of matrix, by means
of a chisel and hammer. The gold-dust thus removed is collected by
each workman separately in small baskets, and taken to the city,
where it is treated for the separation of the precious metal, as will
be described presently.
An immense number of quartz veins traverse the rock in all
directions, and in several of them we saw the compressed flakes of
gold in situ. In two or three instances the metal was in thick lumpy
masses, nearly the size of an almond. The pit is about one hundred
and twenty feet long, by thirty or forty wide, and about eighty feet
deep in the centre. Its sides are sloping and irregular, owing to the
tracing up of veins for a short distance in different directions. There
must be an immense amount of waste in this rough process, and no
doubt the heaps of excavated rock lying about the mouth of the pit
would yield to the experienced miner a very profitable return.
The mine was discovered in 1860 in the following manner. A
shepherd boy, tending his flock at graze on the creek, picked up a bit
of quartz studded with granules of gold. He took it home to his
father, who carried it to a Hindu to see if he could get anything for it.
The Hindu, true to the instincts of his race, in whom the love of gold
is an innate quality, at once recognised the value of the discovery,
and gradually, after his own fashion, got out of the lad’s father the
exact spot on which the specimen was discovered. His next step was
to apprise the Governor, and the site was at once explored. At a few
feet below the superficial gravel, the ferruginous formation of
disintegrated quartz and sienite above described was exposed, and
in the veins on its surface gold was discovered. The site was at once
claimed as crown property, and work was forthwith commenced by
Government.
The mine has now been worked nearly twelve years, but with
several intermissions. For the first two or three years it is said to
have yielded very abundantly. It is now farmed by a contractor, at an
annual rental of five thousand rupees, or five hundred pounds. The
yearly cost of working it is set down at another five hundred pounds,
but this is palpably a gross exaggeration. The profits, it is pretended,
hardly cover rent and working charges, though the reverse is pretty
generally believed to be the fact, notwithstanding the contractor’s
solemn protestations to the contrary, and his bold appeals to God,
his prophet, and all the saints as witnesses to the truth of his
assertions. There is little doubt that the mine, worked as it is now
even, is a really profitable speculation; but in a country such as this,
where life and property are proverbially insecure, it would be most
unsafe to admit the truth, for to do so would assuredly provoke the
cupidity of the ruler, whose despotic will brooks no hindrance in the
accomplishment of his desire, be it just or unjust. Hence it is that all
classes below the nobility, and not a few even among that favoured
class, as a precautionary safeguard, assume an appearance of
poverty, and by common consent profane their most sacred
characters for the support of a falsehood which is apparent to all.
Under the difficulties of such a position it is impossible for the
stranger to arrive at an approximation to the truth. But that the mine
does pay under the disadvantageous conditions mentioned, is best
evidenced by the fact of its continued operation. We had no
opportunities during our short stay here of ascertaining the extent of
the auriferous formation, disclosed by the excavation of the mine.
But as the surface gravel of the plain north of the city is of the same
character as that on the creek in which the mine is situated, it may
be reasonable to suppose that the gold-yielding stratum extends for
some distance under the alluvium of the plain. If this be so,
Kandahar is destined to prove a valuable acquisition to its future
possessors. Under European exploration and skilled working, it
would assuredly produce an hundred-fold of what it has hitherto
done. For in the creek itself only one pit has been dug at the actual
spot on which the metal was first discovered. All the rest of the
surface is yet untouched, and under the existing government of the
country it is destined to remain so.
On leaving the mine we passed through the Baba Walí ridge to the
shrine of the same name, dedicated to the patron saint of Kandahar,
for a view of the Argandáb valley, the most populous and fertile
district of the whole province. From its source in the hills north-west
of Ghazni, to its junction with the Tarnak at Doúb, it has thirty-one
villages on the right bank, and thirty-four on the left. They are
mostly occupied by Popalzai and Alikozai Durranis. Though now seen
in the depth of winter, the valley has a remarkably prosperous and
fertile look. We returned through the Baba Walí range by a recently-
made carriage-road blasted through the rock, in the track of an old
pass a little to the west of the one we entered by. On return to our
quarters, we found the miners ready with their implements and a
small stock of quartz to show us the process by which they extracted
the gold. The process appeared very simple and efficacious. The bits
of quartz, ascertained by the eyesight to contain particles of gold,
are first coarsely pounded between stones, and then reduced to
powder in an ordinary hand-mill. The powder is next placed on a
reed winnowing tray, and shaken so as to separate the particles of
gold and finer dust from the grit. From the latter the larger bits of
gold are picked out and thrown into a crucible, and melted with the
aid of a few grains of borax flua. When melted it is poured into an
iron trough, previously greased, or rather smeared, with oil, and at
once cools into an ingot of bright gold. The fine dust left on the
winnow is thrown into an earthen jar furnished with a wide mouth.
The jar is then half filled with water and shaken about a little while.
The whole is then stirred with the hand and the turbid water poured
off. This process is repeated four or five times, till the water ceases
to become turbid. A small quantity of quicksilver is next added to the
residue of sand, some fresh water is poured on, and the whole
stirred with the hand. The water and particles of sand suspended in
it are then poured off, and the quicksilver amalgam left at the
bottom of the vessel is removed to a strong piece of cloth, and
twisted tightly till the quicksilver is expressed as much as it thus can
be. The mass of gold alloy is then put into a crucible with a few
grains of borax, and melted over a charcoal fire. The molten mass is
finally poured into the iron trough mentioned, and at once solidifies
into a small bar of bright gold. Such was the process gone through
in our presence. Even in this there was a good deal of waste, owing
to the rejection of the coarser grit. With proper crushing machinery
there is no doubt the yield would be considerably increased.
This afternoon we received a post viâ Khozdár and Calát, with
dates from Jacobabad up to the 18th January. The courier described
the route as almost closed by snow in Shál and Peshín, where, it
seems, more snow has fallen since our passage over the Khojak.
Whilst reading our papers, General Safdar Ali was announced. He
brought a nazar, or present, on the part of the Amir for General
Pollock, as the representative of the British Government. It consisted
of fifteen silk bags ranged on a tray, and each bag contained one
thousand Kandahari rupees, the value of which is about a shilling
each.
A north-west wind has prevailed nearly all day, and the air is keen
and frosty. During the night boisterous gusts of wind disturbed our
slumbers and threatened to overturn some of the tall trees in our
garden. In the forenoon we visited the ruins of Shahri Kuhna or
Husen Shahr, the “old city,” or “city of Husen.” The latter name it
derives from the last of its sovereigns, Mír Husen, Ghilzai, the second
son of the celebrated Mír Wais, and brother of Mír Mahmúd, the
invader of Persia, and the destroyer of the Saffair dynasty by the
wanton massacre in cold blood of nearly one hundred members of
the royal family.
The city was taken and destroyed by Nadír Sháh in 1738, after a
long siege, during which the Afghan defenders displayed such
conspicuous bravery that Nadír largely recruited his army from
amongst them, and advanced on his victorious career towards India.
On our way to the ruins we visited the shrine of Sultán Wais, and
examined the great porphyry bowl supposed to be the begging-pot
of Fo or Budh. It is a circular bowl four feet wide, and two feet deep
in the centre (inside measurement), and the sides are four inches
thick. When struck with the knuckle, the stone, which is a hard
compact black porphyry, gives out a clear metallic ring. The interior
still bears very distinct marks of the chisel, and on one side under
the rim bears a Persian inscription in two lines of very indistinct
letters, amongst which the words Shahryár (or Prince) Jaláluddín are
recognisable, as also the word táríbh or “date.” The exterior is
covered with Arabic letters in four lines, below which is an
ornamental border, from which grooves converge to a central point
at the bottom of the bowl. Many of the words in the inscription were
recognised as Persian, but we had not time to decipher it General
Pollock had an accurate transcript of the whole prepared by a scribe
in the city, and forwarded it, I believe, to Sir John Kaye.
The keeper of the shrine could tell us nothing about the history of
this curious relic, except that it, and a smaller one with handles on
each side, which was carried away by the British in 1840, had been
brought here by Hazrat Ali, but from where nobody knows. Possibly
it may have come from Peshín, which in documents is still written
Foshanj and Foshín.
The bowl now rests against the trunk of an old mulberry-tree in a
corner of the enclosure of the tomb of Sultán Wais. The trunk of the
tree is studded all over with hundreds of iron nails and wooden
pegs, like the trees described on the march to Hykalzai. About the
enclosure were lying a number of great balls, chiselled out of solid
blocks of limestone. The largest were about fourteen inches in
diameter, and the smaller ones five or six inches only. They were,
our attendants informed us, some of the balls used in ancient sieges
of the adjoining city in the time of the Arabs. They were propelled by
a machine called manjaníc in Arabic—a sort of ballista or catapult.
From the ruins of the old city we went on to those of Nadírabad,
now surrounded by marshes caused by the overflow of irrigation
canals, and returned to our quarters by the southern side of the
present city, or Ahmad Shahí. The fortifications have been recently
repaired and fresh plastered, and have been strengthened by the
construction of a series of redoubts, called Kása burj.
12th February.—We visited the city this afternoon with the Saggid
and General Safdar Ali. We entered at the Herat gate, and at the
Chársú turned to the left up the Shahí bazaar, and crossing the
parade-ground, where we received a salute of fifteen guns, passed
into the Arg or “citadel,” which was our prison-house for thirteen
months when I was here in 1857-58 with Lumsden’s mission. I say
prison-house, because we could never move outside it but once a
day for exercise, and then accompanied by a strong guard, as is
described in my “Journal of a Mission to Afghanistan in 1857-58.”
From the citadel we went to see the tomb of Ahmad Sháh, Durrani,
the founder of the city, and thence passing out at the Topkhana
gate, returned to our quarters in the garden of the late Sardár
Rahmdil Khán.
The main bazaars had evidently been put in order for our visit.
The streets had been swept, and the shops stocked with a very
varied assortment of merchandise and domestic wares, which were
now displayed to the best advantage. The sides of the main
thoroughfare were lined with a picturesque crowd of citizens and
foreigners, brought here by their trade callings. The demeanour of
the crowd was quiet and orderly, and their looks were expressive of
good-will; which is more than could be said of any similar crowd in
the bazaars of Peshawar, as was very justly remarked at the time by
General Pollock. As we passed along, I now and again caught a
finger pointing at me with “Haghah dai” (“That’s him”); and in the
Chársú, where we had to pick our way through a closely packed
crowd, I was greeted with more than one nod of recognition, and
the familiar “Jorhasted?” (“Are you well?”) “Khúsh ámadíd” (“You are
welcome”), &c.
The citadel, which is now occupied by Sardár Mír Afzal Khán,
Governor of Farráh, and his family, is in a very decayed and
neglected state, and the court of the public audience hall is
disgracefully filthy. The court and quarters formerly occupied by the
mission of 1857 are now tenanted by General Safdar Ali, the Amir’s
military governor of the city.
From the citadel we passed through the artillery lines, a wretched
collection of half-ruined and tumbledown hovels, choked with dung-
heaps, horse litter, and filth of every description, and turned off to
the Ahmad Shahí mausoleum. The approach to it is over an uneven
bit of ground, which is one mass of ordure, the stench from which
was perfectly dreadful. It quite sickened us, and kept us spitting till
we got out into the open country again. The tomb, like everything
else here, appears neglected and fast going to decay. The stone
platform on which it stands is broken at the edges, and the steps
leading up to it, though only three or four, are suffered to crumble
under the feet of visitors without an attempt at repair. The dome has
a very dilapidated look from the falling off here and there of the
coloured tiles that cover it, whilst those that are still left make the
disfigurement the more prominent by their bright glaze. Where
uncovered, the mortar is honeycombed by the nests of a colony of
blue pigeons, which have here found a safe asylum even from their
natural enemies of the hawk species. The interior is occupied by a
central tomb, under which repose, in the odour of sanctity—though
those surrounding it are anything but sanctified—the ashes of the
first and greatest of the Durrani kings. Near it are some smaller
tombs, the graves of various members of the king’s family. The
cupola is very tastefully decorated by a fine Arabesque gilding, in
which run all round the sides—the dome being supported on an
octagonal building—a series of quotations from the Curán. These, in
the light admitted through the fine reticulations of the lattice
windows, appeared remarkable fresh and bright, though untouched
since their first production a century ago. We doffed our hats as we
entered the sacred precincts, as our attendants took off their shoes
at the threshold, excepting only the Saggid and General Safdar Ali
and Colonel Táj Muhammad, who were much too tightly strapped in
their odd compounds of Asiatic and European military uniforms to
attempt any such disarrangement of their evidently unaccustomed
habiliments. The mujawwir, or keeper of the shrine—for amongst
this saint-loving people the tenant of so grand a tomb could hardly
escape being converted into so holy a character—was quite pleased
at this mark of respect on our part, and made himself very agreeable
by his welcome and readiness to afford information. “I know,” said
he, with a hasty and timid glance at the shodden feet of our
companions, “that this is the manner in which Europeans testify their
reverence for holy places. The officers who visited this tomb when
the British army was here observed the same custom, and always
uncovered the head on entering beneath this roof. It is quite correct.
Every nation has its own customs; you uncover the head, and we
uncover the feet. In either case, respect for the departed great is the
object, and by either observance it is manifested. It is all right.” The
old man told us he was seventy-two years old, and had not been
beyond the precincts of the tomb for the last thirty years. It was his
world. He had not been as far as the bazaars in all this time, nor had
he seen the cantonments built by the British outside the city. This
sounds incredible, but I don’t think it improbable, for I know of three
or four instances amongst the Yusufzais of the Peshawar valley, in
which old men have assured me that in their whole lives they had
never moved beyond the limits of their own villages, not even so far
as to visit the next village, hardly three miles distant. How the old
mujawwir managed to exist so long—for one can hardly say live with
propriety—in this vile stinking corner of this filthy city, is not to be
understood except on the explanation of habit becoming second
nature. Both the confinement and the atmosphere had however left
their mark upon him, and had blanched his gaunt sickly visage as
white as the beard that graced his tall lank figure.
From the mausoleum we passed through a quarter of the city
which had evidently not been prepared for our visit. The narrow
lanes were filthy in the extreme, the shops were very poorly stocked,
and altogether the place looked oppressed, as indeed it is, by the
unpaid, ill-clad, and hungry soldiery we found lounging about its
alleys. We were glad to pass out of the Topkhana gate, and once
more breathe the fresh air of the open country.
From what we saw on this occasion, and from what we heard
during our short stay here, there is no doubt that the condition of
Kandahar, as regards population and prosperity, is even worse than
it was when I was residing here fourteen years ago. The oppression
of its successive governors, the frequent military operations in this
direction, and the location of a strong body of troops in the city
during the last ten or twelve years, has almost completely ruined the
place, and has reduced the citizens to a state of poverty bordering
on despair.
The discontent of the people is universal, and many a secret
prayer is offered up for the speedy return of the British, and many a
sigh expresses the regret that they ever left the country. Our just
rule and humanity, our care of the friendless sick, our charitable
treatment of the poor, and the wealth we scattered amongst the
people, are now remembered with gratitude, and eager is the hope
of our return. This is not an exaggerated picture, and speaks well for
the philanthropic character of the short-lived British rule in this
province, when we consider that our occupation of the country was
but a military aggression. But even if they had never had a practical
experience of British rule, the desire of the Kandaharis for the return
of our authority and extension of the British government to their
province, is explained by the glowing accounts they receive from
their returning merchants of the prosperity, happiness, and liberty
that reign in India, whilst they render them more impatient of the
tyranny under which they are forced to groan.
Hundreds of families, it is said, have left the city during the last
ten years, to seek their fortune under more favourable rulers. The
city is said to contain five thousand houses, but fully a third part of it
is either deserted or in ruins, and the population does not exceed
eighteen thousand, if it even reaches that number. Indeed it is
astonishing how the city holds out so long under the anomalous
circumstances of its government and the ill-restrained license of an
unpaid soldiery.
I was told by a non-commissioned officer of the Corps of Guides,
who was now spending his furlough here amongst his relations, and
whom I formerly knew when I was with that regiment, that the
condition of the people was deplorable. Hearing of our approach, he
came out to meet us at Mund Hissár, and attended daily at our
quarters during our stay here. From him I learned that numbers of
the citizens were anxious to see the General, and represent their
grievances to him; and that hundreds, remembering the charitable
dispensary I had opened here during my former visit, were daily
endeavouring to gain admittance to our quarters for medicine and
advice regarding their several ailments and afflictions, but that both
classes were prohibited by the sentries posted round us with strict
orders to prevent the people from holding any communication with
us, lest we should hear their complaints, and what they had to say
against our hosts.
The city is now governed by three sets of rulers, each independent
of the other, but all answerable to the Amir. Thus General Safdar Ali
is the military governor. His troops are six months in arrears of pay,
and make up the deficiency by plundering the citizens. His nephew
(sister’s son), Sultán Muhammad, is the civil governor. He has to
pacify the townspeople under their troubles, and to screw from them
the city dues or taxes. Then there is Núr Ali, the son of Sardár Sher
Ali Khán, the late governor, who is himself just now at Kabul
rendering an account of his recent charge. He is a luxurious youth,
clad in rich velvets and cloth of gold, and on behalf of his father
collects the revenues outside the city. The consequence of this
triangular arrangement is that the people are effectually crushed and
bewildered. They know not who are their rulers, and in vain seek
redress from one to the other, only to find themselves fleeced by
each in turn. As my informant pathetically remarked, “There is no
pleasure in life here. The bazaar you saw to-day is not the everyday
bazaar. There is no trade in the place. How should there be any? The
people have no money. It has all been taken from them, and where
it goes to nobody knows. There is no life (or spirits) left in the
people. They are resigned to their fate, till God answers their
prayers, and sends them a new set of rulers.”
Truly their condition is such as to call for pity. I observed, in our
progress through the city, that the people had a sickly appearance
compared with the generality of Afghans, and wore a subdued timid
look, altogether at variance with the national character. They are, as
we heard from more than one source, only waiting a change of
masters. In their present temper, anybody would be welcomed by
the Kandaharis, even a fresh set of their own rulers would afford
them a temporary relief; but a foreigner, whether British, Persian, or
Russian, they would hail with delight, and their city would fall to the
invader without even much show of resistance, for the garrison
could look for no support from the people they had so hardly
oppressed.
The Government of Kandahar, besides the city and suburbs,
includes about two hundred villages. Altogether they yield an annual
revenue of about twenty-two laks of rupees to the Amir’s treasury.
Of this total, about nine laks are derived from the city dues and
taxes. Almost the whole of this sum is expended on the civil and
military establishments of the government, so that very little finds its
way to the imperial treasury. The revenue is not all collected in cash;
on the contrary, a considerable proportion is taken in kind, such as
corn, cattle, sheep, and so forth; and the collection of much of this
last is avoided, as far as government is concerned, by the issue of
bonds, or barát, on the peasantry and landholders, to the extent of
their dues of revenue. These bonds are distributed amongst the civil
and military officials in lieu of wages. They exact their full dues, and
extort as much more as their official influence and the submission of
the peasantry enable them to do. The system is one of the worst
that can be imagined, leads to untold oppression, and is utterly
destructive of the peace and prosperity of the country.
During the last two days a number of workmen have been
employed in erecting palisades along the sides of the tank in front of
our quarters, and along the cypress avenues on each side of it,
preparatory to a grand illumination and display of fireworks, fixed for
this evening, in honour of the General’s arrival here. At seven
o’clock, darkness having set in, the performance of the evening
commenced. Thousands of little lamps, which had been fixed with
dabs of mud at short intervals along the cross poles of the
palisading, were lighted, and produced a very pretty effect.
Innumerable tapering flames reflected their long trembling shadows
across the placid surface of the tank, and lighted the long rows of
avenue on either side with a glare of brilliancy, highly intensified by
the impenetrable gloom of the close-set sombre foliage above, and
the darkness of the night-enshrouded vista of the garden beyond.
We had not sufficiently feasted our eyes on this attractive scene,
when its brilliancy was thrown into the shade by the noisy eruption
of a whole series of “volcanoes,” the contents of which shot out in a
rushing jet of yellow scintillating flakes, and finished up with a loud
bang, that sometimes exploded, and always overturned the volcano.
Flights of rockets, roman candles, wheels, &c., followed, whilst
crackers thrown into the tank scud about its surface with an angry
hissing, presently plunging into its depths, and anon rising with a
suffocating gurgle jarring ungratefully on the ears, and finally
expiring in the throes of a death-struggle. There were besides some
elephants, horses, and other nondescript animals, that were fixed in
the foremost places, as master-pieces of the pyrotechnist’s art, but
the less said of them the better. They emitted jets of fire and
volumes of smoke from the wrong places at the wrong moments, so
that, when moved to combat against each other, their clumsy shells
revealed, as they rocked from side to side in their efforts to fall, the
bare limbs of the human machinery that struggled to support them
in their proper positions against the shocks of the exploding
combustibles embedded in their flanks and extremities. Altogether
the display, though a grand effort, and perhaps a feat on the part of
the pyrotechnists of Kandahar, was inferior to what one sees in
India, and in any European capital would be hissed at as a
downright failure. The purpose, however, was noways affected by
the performance, and the honour was fully appreciated as a mark of
good-will and respect for the Government it was our privilege to
represent.
The next day was devoted to the final arrangements for our
departure on the morrow. Fresh cattle had been purchased for our
camp and baggage, some new servants had been entertained, and it
was necessary now to see that all were properly equipped and
provided for their journey. During the afternoon we had a long
interview with some Hindu bankers of the city, from whom we took a
small advance in exchange for notes of hand upon the Government
treasury at Shikárpúr. They had correspondents at Herat, Kabul,
Shikárpúr, and Amritsar, but not at Mashhad, Balkh, or Bukhára.
They confirmed what we had heard from other sources regarding
the oppressed state of the city, and the systematic plundering of the
citizens that daily goes on, but said that their own community—the
Hindu traders—were not interfered with. They assured us that the
rich furniture of our apartments was mostly the confiscated property
of Sardár Muhammad Sharíf Khán, the Amir’s rebel brother, who has
just been deported to India as a state prisoner. With the timidity and
suspicion common to their class here, they spoke in low tones and
with uneasy furtive glances around; and presently, when the Saggid
came in for his usual afternoon cup of tea, they were evidently
discomposed, and quickly retired on the first symptoms of
acquiescence in their departure. The Saggid brought us some fine
nosegays of blue violets, the familiar scent of which quite perfumed
the room. He found me busily penning notes, and jocularly
remarked, “I know you people always write down everything you see
and hear, and afterwards publish it to the world. Now pray, Doctor
Sáhib, what have you been writing about me?” This was an
unexpectedly home question; but following in his own merry mood, I
evaded a direct reply by the remark that his observation was quite
correct; that as a nation we were given to writing, and that with
some of us the habit exceeded the bounds of moderation and utility,
and was then called a cacoethes scribendi. “Very likely, very likely,”
interposed the Saggid; “no doubt you people write a great deal more
than is of any earthly use, but the habit is not without its merits.
Now you will have doubtless written down all about the country you
have come through, and will know it better than its own
inhabitants,” I here observed that, with the most careful and
leisurely inquiries, we could hardly expect to attain to such
perfection. “Nay, but you do,” said the Saggid; “you go riding along
and come to a village. To the first man you meet in it you say,
‘What’s the name of this village?’ He tells you, and then you say,
‘What do you call that hill?’ and he gives you its name. Out comes
your note-book, and down go the names, and by and by all the
world knows that there is such a hill near such a village, a fact
nobody else in the country is aware of except the inhabitants of the
actual locality.”
The Saggid was as much amused by this telling argumentum ad
hominem as we were, and added, “Now, by way of illustration, I will
tell you what occurred to me many years ago, when, as a young
man, I went to Bangalore with a batch of horses for sale. An English
officer who spoke Persian asked me one day about my country, and
when I told him the name of my village, he turned it up in his map,
and said, ‘Yes, I see. There is a place near it called Ganda China.’
‘No,’ said I, ‘there is no such place near it, nor even in the country.’
‘There must be,’ maintained he. Well, considering I knew my own
country best, I thought it useless arguing the point, so remained
silent, allowing him to have his own way. When I returned home and
recounted my adventures in the Deccan, amongst others I
mentioned this circumstance, with no very flattering allusion to the
English officer’s obstinacy. ‘You are wrong, Sháh Sáhib’ (the
respectful title by which Saggids are addressed), said two or three
voices. ‘Ganda China is the briny bog at the further end of the
hollow behind our hill.’ ‘Well,’ said I, ‘I never knew that before.’ So
the English officer, you see, knew what I did not of my native place.”
In the following conversation the Saggid, to his credit be it
recorded, spoke most sensibly, and with a freedom from prejudice
for which we were not prepared. He lamented the ignorance of his
own people, and the jealousy they evinced of our learning anything
about their country: “As if,” said he, “you could not send any number
of Afghans into it, instructed to bring you whatever information you
required regarding it.” He very truly observed that we knew more of
the history and topography of his country than the most learned
native in it could ever hope to do in their present state of benighted
ignorance. As an instance, he mentioned a discussion at which he
was present at the Amir’s court shortly before he set out from Kabul
to meet us, in which not a single member present could tell the
exact locality of Chinaran, of which they knew nothing more than
that it was an important fort on the Persian frontier in the time of
Sháh Ahmad, but in what part of the frontier nobody could tell.
14th February.—At noon we set out from Rahmdil Khán’s garden,
under a salute of fifteen guns from the artillery, drawn up for the
purpose outside the gate. Our route led over fields of young corn,
burnt yellow by the recent hard frosts, and across a succession of
irrigation streams to the village of Chihldukhtarán, beyond which we
came to the Chihlzina. We alighted here, and ascended the rock for
the sake of the view, which, the weather being fine and clear, was
very distinct and extensive over the plain to the eastward and
northwestward. In the former direction, the furthest point seen was
the snow-topped peak of Súrghar, on the further side of which we
were told lies the Abistada lake. To the north-west is the great
snowy range of Sháh Macsúd, closing the prospect by a lofty ridge
running from north-east to south-west. Beyond it lies the Derawat
valley.
On descending we took leave of General Safdar Ali, who returned
to Kandahar with a troop of regular cavalry, and proceeded in
company with the Saggid and Colonel Táj Muhammad, escorted by a
company of regular infantry, and a party of two hundred and fifty
irregular horse, fine active fellows, very well mounted, and generally
well armed. At a short distance we passed between the villages of
Mír Bazár on the left and Gundigán on the right. This last is built on
a couple of artificial mounds, and is noteworthy as being the only
Shia village of Parsiwans in the whole province. Beyond these the
road skirts a ridge of rocky hills to the left, and has the village of
Murghán some way off to the right, where flows the river Argandáb.
Further on we came to an extensive roadside graveyard, in which
the tomb of the celebrated Mír Wais, Ghilzai, forms the most
prominent object, as much from the height of its cupola above the
more humble tombs around, as from the state of its decay and
neglect. Passing these and the adjoining Kohkarán village, we
camped a mile beyond on an open gravelly patch between the
Kohkarán hill and the river bank, having marched seven miles from
Kandahar.
On approaching Kohkarán, the lord of the manor, Sardár Núr
Muhammad Khán, came out to meet us, and invited us to his fort for
refreshment; but as it stood a little way out of our road, we politely
declined, and he accompanied our party into camp, where his
servants presently arrived with trays of food of sorts, and amongst
the dishes a huge bowl of the national cúrút, which is, I believe, a
close relation to the sour kraut of the Germans. Sardár Núr
Muhammad Khán is a son of the late Tymúr Culi Khán, own brother
of the late Wazír Fath Khán, Bárakzai. He is reputed as being one of
the wealthiest of the Afghan nobles, and has always adhered loyally
to the cause of the present Amir during the long period of his trials
and adversities. During the siege of Herat by the late Amir Dost
Muhammad Khán, he was imprisoned and tortured by Shahnawáz
Khán (who continued the defence after the death of his father,
Sultán Ahmad Khán), on the suspicion of being a secret partisan of
the Dost’s. He now told me that he was at the time in command of
the Herat garrison, and that God alone preserved his life. On the fall
of Herat in May 1863, Shahnawáz fled to the Persians, and became
their pensioner at Tahrán. His brother, Sikandar Khán, fled to
Turkistan, and took service with the Russians, by whom he was
treated with distinction, and sent to St. Petersburg. Another brother,
Abdullah Khán, fell into the Amir’s hands, and being a youth of some
parts, was sent to reside at Kabul under surveillance.
Sardár Núr Muhammad Khán had accompanied the Amir Sher Ali
in all his wanderings, and shared his misfortunes. He spoke in the
gloomiest words of the future prospects of his country, and seemed
glad to retire from the troubles of public life to the solitude and quiet
of his country-seat. He had been here about twenty months, and
seldom went beyond his own domain. He came out to meet us with
Sardár Mír Afzul Khán’s isticbál from Kandahar, but except on such
occasions he seldom even goes to the city.
He is a fine, blunt, and honest Afghan, with prepossessing looks
and very hospitable manners. His time is mostly spent in improving
his castle, to which he has just added an extensive range of stables
for the hundred horses his stud consists of. He is said to possess
some of the best Arab, Baloch, and Turkman horses in the country.
He was mounted on a beautiful Arab himself, and by his side rode an
attendant mounted on a great Turkman of wonderful strength and
fleetness, as he proved to us by putting the animal to its full speed
across the plain.
He told us that this winter was the severest season known to have
occurred during the past twenty years, and, as an instance of its
severity, assured us that the black partridges in his vineyards had all
been killed by the cold, numbers having been found lying dead upon
the snow.
From our camp we have a full view of the Argandáb valley, and
the crowd of villages and gardens along the course of its river.
Numerous canals are drawn off from its stream for purposes of
irrigation, and for the water supply of Kandahar. To the northward
the valley extends in a wide upland pasture tract to the foot of the
ridge of hills separating it from the adjoining Khákrez valley. The hills
have a very barren look, and are crossed by several passes
practicable to footmen only.
From Kohkarán we marched eighteen miles, and camped on the
roadside between Hanz Maddad Khán and Sang Hissár. At a short
distance from camp we crossed a deep irrigation canal, and at once
descended a steep clay bank into the bed of the Argandáb river. The
channel here is very wide and boulder-strewed, and the river flows
through its centre, and there are besides two little streams, one
under each bank. The current is strong and stirrup-deep. We found
hundreds of wild-fowl and coolan along the pools bordering the
river; and I went off with Colonel Táj Muhammad and shot a few
teal and purse-necks. The coolan were much too vigilant to allow us
to get within range. During the hot-weather rains, this river swells
into a raging torrent, and is quite impassable for three or four days
together. The farther bank of the river is low, and lined by an
irrigation canal similar to that on the other bank.
Beyond the river, the road passes through a wide extent of corn-
fields and villages, known collectively as Sanzari, and bounding them
to the southward is a ridge of hills called Takhti Sanzari, on which we
could trace indistinctly the remains of ancient ruins.
We cleared the Sanzari lands at a roadside ziárat, over the door of
which were fixed some iben and márkhor horns; and leaving the
Ashogha canal and village to the left, entered on a vast treeless
waste, that gently slopes up to the Khákrez range towards the north.
We followed a well-trodden path over the gravelly plain in a south-
west direction, and leaving the Sufed Rawán villages and cultivation
along the river bank to our left, camped a little beyond the Hanz
Maddad, and close to a ruined mound called Sang Hissár.
The hanz, or reservoir, named after its builder, Maddad Khán, of
whom nobody could tell us anything, is now, like everything else in
this country, fast going to ruin. It has long been dry, and the
projecting wings from the central dome, which were meant as a
shelter for the wayfarer, are now choked with the débris of the
crumbling walls and heaps of drift sand. At the hanz the road
branches—one track goes due west across the plain to Kishkinákhud
and Girishk, and the other south-west to Garmsel by the route of
Calá Búst.
Westward of this point the country assumes an aspect altogether
different from that we have hitherto traversed. It presents a vast
expanse of undulating desert plain, upon which abut the terminal
offsets from the great mountain ranges to the northward and
eastward. The weather being fine and the atmosphere singularly
clear, we were enabled to get a very extensive view of the general
aspect and configuration of the country.
To the west were the terminal spurs of the Khákrez range, ending
on the plain, and concealing from view the valley of that name, and
on which we looked back as we advanced on our route. To the west
and south respectively, the horizon was cut by an arid waste and
sandy desert. Close at hand to the east, between the junction of the
Argandáb with the Tarnak, is the termination of the Baba Walí range.
To its north lies the valley of the Argandáb, running up north-east as
far as the eye can reach in a continual succession of villages,
gardens, and corn-fields, a picture of prosperity strikingly in contrast
with the arid and bare aspect of the country to the south of the
range. In this latter direction the parallel ranges of Arghasán,
Barghana, and Kadani, coursing the wide plateau from north-east to
south-west, all terminate in low ridges that abut upon the Dorí river
opposite to the sand-cliffs of the great desert that separates
Kandahar and Sistan from the mountain region of Makrán.
The angle of junction of the Argandáb and Tarnak is called Doaba.
To the south of the Takhti Sanzari it is continuous with the Panjwaí
district on the banks of the Tarnak. It is very populous, and is
covered with villages and gardens, celebrated for the excellence of
their pomegranates. From Panjwaí there is a direct route across the
desert to Hazárjuft. The distance is said to be only eighty miles. The
desert skirt from this point, along the course of the Dorí right down
to the end of the Lora river on the plain of Shorawak and Núshkí, is
said to afford excellent winter pasturage for camels and sheep. This
skirt forms a tract some fifteen or twenty miles wide on the border
of the actual sandy desert, and is at this season occupied by the
camps of the nomad Achakzai, Núrzai, and Bárech Afghans. It
produces lucerne, clover, carrot, and other wild herbs in profusion
during the spring. Our next stage was twenty-two miles, to the river
bank near the hamlet called, from its adjacent spring, Chashma. It is
included in the lands of Kishkinákhud. Our route was by a well-
beaten path on the gravelly plain at about two miles from the river,
towards which it slightly inclined as we proceeded westward.
To the left of our course, along a narrow strip on the river bank,
are the collection of villages and gardens known as Bágh Marez and
Sháhmír. Amongst them, conspicuous for its neatness and strength,
is the little fort of Khúshdil Khán, son of the late Sardár Mihrdil Khán,
and elder brother of Sardár Sher Ali Khán, the recent governor of
Kandahar. He has always held aloof from politics, and spends his life
in the seclusion of his country retreat. On the farther side of the
river the land rises at once into a high coast, formed by round bluffs
that stretch away towards the desert in a tossed and billowy surface
of loose sand.
To the right of our route lay the Kishkinákhud plain. It supports a
very scattered and thin growth of pasture herbs, amongst which we
noticed some stunted bushes of the camel-thorn and sensitive
mimosa. As we advanced we came abreast of the Khákrez valley
away to the north across the plain. It has a dreary and desert look,
and appeared uninhabited. It has no perennial stream, but is drained
by a central ravine which crosses the plain as a wide and shallow
water-run, called Khákrez Shela. We crossed it dryshod a little way
short of camp.
Beyond Khákrez is the Sháh Macsúd range of hills, now covered
with snow. The hills are said to be well stocked with large trees, and
amongst them the wild or bitter almond. We were assured that the
Popalzais, who hold this country, had of late years taken to grafting
the wild trees as they grew on the hillsides with the sweet and
cultivated almond, and with complete success.
At the foot of a dark spur branching off southward from the main
range was pointed out the site of the ruins of Mywand. They are
described as very extensive; and in the time of Mahmúd of Ghazni,
the city was the seat of the government of his wazír, Mír Hassan. At
the head of the valley, to its north, are the sulphur hot springs of
Garmába, resorted to by the natives of the vicinity as a remedy for
rheumatism and diseases of the skin.
During the latter part of the march we passed a couple of roadside
hamlets occupied by Hotab Ghilzais, and watered by kárez streams.
There was very little cultivation about, and the villagers appeared a
very poor and miserable set.
The weather is fine and clear, and the air delightfully fresh and
mild. We are now fairly clear of the hills, and are entered upon the
great basin of the Kandahar drainage.
17th February.—We set out from Chashma at eight a.m., and
marched twenty-three miles to Baldakhán by a good gravelly path
following the course of the river at about a mile from its right bank.
At about the third mile we passed the hamlet of Mulla Azím,
occupied by Mandínzai Isháczais, who are astánadár of the Saraban
Afghans (that is to say, descendants of an Afghan saint of the
Saraban division of the nation), and consequently hold their lands
rent free, and enjoy other privileges and immunities accorded to
members of the priest class. Beyond this we entered on the Bandi
Tymúr, a long strip of villages and cultivation extending for twelve
miles or so along the right bank of the river, which here flows over a
wide pebbly channel interspersed with patches of dwarf tamarisk
jangal. The soil is everywhere gravelly and charged with salines,
which here and there form extensive encrustations on the surface.
Several kárez streams, brought from the undulating tract of Kháki
Chanpán to the north, cross the road at intervals, and a succession
of irrigation canals led off from the river intersect the country on
either side. The tract derives its name from an ancient band or weir
thrown across the river in the time of Tymúr. We did not see any
signs of this dam, nor could we learn that any traces of it were still
in existence.
To the north of the Bandi Tymúr tract are first the Miskárez
hamlets and cultivation, and beyond them are the Kháki Chanpán
hamlets, concealed from view in the sheltered hollows of the
undulating pasture tract of that name. Away to the north beyond it,
between the Khákrez and Sháh Macsúd ranges, is seen the Ghorát
valley, in which are the hot sulphur springs of Garmába already
mentioned. To the north of Ghorát is seen the Dosang range of hills,
that separate it from the Derawat valley, which drains by a perennial
stream to the Helmand in Zamíndáwar. This is described as a very
populous and fertile valley, continuous to the north-east with the
country of the Hazerahs. To the north-west of it, a range of hills
intervening, is the Washír valley, which drains to the river of Khásh.
To the south, on the left of our route, the sandy desert abuts upon
the river in a high bank of water-worn stones, in the sheltered
hollows between which is a close succession of nomad camps, that
extend in a continuous line for nearly fifty miles, for we marched in
sight of them to within a few miles of Calá Búst. The camps were on
shelving banks close upon the river bed, and were seldom more than
half-a-mile apart. Their unbroken black line upon the red ground of
the sandy bluffs formed a very prominent object of attraction, and
the extent of the cordon proved the numerical strength of the
nomads to far exceed the limit of what we had supposed their
numbers to be. I counted sixty-three camps in view at the same
time. The number of tents in each ranged from twenty up to eighty,
but the majority appeared to contain from forty to fifty tents. If we
allow two hundred camps along the river from Chashma to Búst, and
reckon only forty tents in each, it will give a total of eight thousand
tents or families; and if we take each family to consist of five
individuals, it will give us forty thousand as the total of the nomad
population massed in this part of the country. The calculation is by
no means exaggerated; on the contrary I believe it to be under the
mark.
Similar encampments, we are assured, extend along the desert
skirt, where it abuts on the channels of the Tarnak and Dorí rivers,
right down to Shorawak, and are reckoned to contain a total of not
less than forty thousand tents, or two hundred thousand souls.
These nomads include a number of tribes from all the hill country
between this and Kabul. They come down from the highlands with
their cattle and flocks during September and October, pass the
winter here, and return to their summer pastures during March and
April. Their sheep and camels find abundant pasture at this season
on the borders of the desert, and are scattered over its surface to a
distance of twelve or fifteen miles from the river. There are here and
there superficial pools of rain-water (called náwar) on the pasture
tracts, but generally the cattle are driven down to water at the river
every third or fourth day. A couple of centuries ago nearly the entire
Afghan nation were nomads, or, as they are here called, kizhdí
nishín, from their mode of dwelling, and sometimes sahára nishín,
from the place of habitation.
At about the sixth mile of our march we passed another roadside
hamlet of the Mandínzai Isháczais. Some of the villagers came out
and took up a position on the road in front of us, with a Curán
suspended across the path in a sheet stretched between two poles
hastily stuck into the ground. We passed under the sacred volume,
and received the blessing of its owners in return for a rupee given to
them by the Saggid. Our grooms, with uplifted arms, made a bound,
touched the book, and then their foreheads and hearts, the while
invoking the prophet’s blessing.
At about half-way on this march we passed the ruins of an old
town and the remains of a fort overlooking the river. Beyond this the
country is bare and desolate. The soil is either a coarse gravel
covered with a thin jangal of camel-thorn, or it is a spongy clay
white with excess of salines. For many miles here the road passes
through a long succession of salt-pits. Near Ballakhan we turned off
to the left, and camped on a saline tract close to the river.

You might also like