Instant download PostgreSQL Development Essentials 1st Edition Kaur pdf all chapter
Instant download PostgreSQL Development Essentials 1st Edition Kaur pdf all chapter
com
https://ebookname.com/product/postgresql-development-
essentials-1st-edition-kaur/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/game-development-essentials-an-
introduction-3rd-edition-jeannie-novak/
ebookname.com
https://ebookname.com/product/postgresql-high-availability-
cookbook-2nd-edition-shaun-m-thomas/
ebookname.com
https://ebookname.com/product/marmalade-sdk-mobile-game-development-
essentials-1st-new-edition-edition-sean-scaplehorn/
ebookname.com
https://ebookname.com/product/las-romanticas-susan-kirkpatrick/
ebookname.com
https://ebookname.com/product/english-irish-and-subversives-among-the-
dismal-scientists-1st-edition-noel-w-thompson/
ebookname.com
https://ebookname.com/product/between-morality-and-the-law-corruption-
anthropology-and-comparative-society-1st-edition-italo-pardo/
ebookname.com
https://ebookname.com/product/breaking-the-fourth-wall-direct-address-
in-the-cinema-1st-edition-tom-brown/
ebookname.com
https://ebookname.com/product/breadlines-knee-deep-in-wheat-food-
assistance-in-the-great-depression-nestle/
ebookname.com
The Oxford Handbook of the Word Oxford Handbooks John R.
Taylor
https://ebookname.com/product/the-oxford-handbook-of-the-word-oxford-
handbooks-john-r-taylor/
ebookname.com
PostgreSQL Development
Essentials
Manpreet Kaur
Baji Shaik
BIRMINGHAM - MUMBAI
PostgreSQL Development Essentials
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the authors, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be caused
directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-78398-900-3
www.packtpub.com
Credits
Baji Shaik
Danny Sauer
Additionally, she is very creative and enjoys oil painting. She also has a youtube channel,
Oh so homemade, where she posts easy ways to make recycled crafts.
He comes from a small village named Vutukutu in Andhra Pradesh and currently lives in
Hyderabad. He likes to watch movies, read books, and write technical blogs. He loves to
spend time with family. He has tech-reviewed Troubleshooting PostgreSQL by Packt
Publishing. He is a certified PostgreSQL professional.
Thanks to my loving parents. Thanks to Packt Publishing for giving me this opportunity.
Special thanks to Izzat Contractor for choosing me, and Anish Sukumaran, Nitin Dasan,
and Sunith Shetty for working with me. Thanks to Dinesh Kumar for helping me write.
About the Reviewers
Daniel Durante started spending time with computers at the age of 12. He has built
applications for various sectors, such as the medical industry, universities, the
manufacturing industry, and the open source community. He mainly uses Golang, C, Node,
or PHP for developing web applications, frameworks, tools, embedded systems, and so
on. Some of his personal work can be found on GitHub and his personal website.
He has also worked on the PostgreSQL Developer's Guide, published by Packt Publishing.
I would like to thank my parents, brother, and friends, who’ve all put up with my insanity,
day in and day out. I would not be here today if it weren’t for their patience, guidance, and
love.
Danny Sauer has been a Linux sysadmin, software developer, security engineer, open
source advocate, and general computer geek at various companies for around 20 years. He
has administered, used, and programmed PostgreSQL for over half of that time. When he's
not building solutions in the digital world, he and his wife enjoy restoring their antique
home and teaching old cars new tricks.
www.PacktPub.com
eBooks, discount offers, and more
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at customercare@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Table of Contents
Preface 1
Chapter 1: Advanced SQL 5
Creating views 5
Deleting and replacing views 7
Materialized views 8
Why materialized views? 8
Read-only, updatable, and writeable materialized views 8
Read-only materialized views 9
Updatable materialized views 9
Writeable materialized views 10
Creating cursors 10
Using cursors 11
Closing a cursor 12
Using the GROUP BY clause 12
Using the HAVING clause 14
Parameters or arguments 14
Using the UPDATE operation clauses 15
Using the LIMIT clause 15
Using subqueries 16
Subqueries that return multiple rows 18
Correlated subqueries 18
Existence subqueries 19
Parameters or arguments 19
Using the Union join 20
Using the Self join 21
Using the Outer join 22
Left outer join 23
Right outer join 24
Full outer join 24
Summary 26
Chapter 2: Data Manipulation 27
Conversion between datatypes 27
Introduction to arrays 28
Array constructors 28
String_to_array() 31
Array_dims( ) 32
ARRAY_AGG() 32
ARRAY_UPPER() 34
Array_length() 34
Array slicing and splicing 34
UNNESTing arrays to rows 35
Introduction to JSON 37
Inserting JSON data in PostgreSQL 37
Querying JSON 38
Equality operation 38
Containment 38
Key/element existence 39
Outputting JSON 40
Using XML in PostgreSQL 41
Inserting XML data in PostgreSQL 41
Querying XML data 42
Composite datatype 42
Creating composite types in PostgreSQL 42
Altering composite types in PostgreSQL 44
Dropping composite types in PostgreSQL 45
Summary 45
Chapter 3: Triggers 46
Introduction to triggers 46
Adding triggers to PostgreSQL 47
Modifying triggers in PostgreSQL 52
Removing a trigger function 53
Creating a trigger function 54
Testing the trigger function 55
Viewing existing triggers 56
Summary 57
Chapter 4: Understanding Database Design Concepts 58
Basic design rules 58
The ability to solve the problem 58
The ability to hold the required data 59
The ability to support relationships 59
The ability to impose data integrity 59
The ability to impose data efficiency 59
The ability to accommodate future changes 59
Normalization 60
Anomalies in DBMS 60
[ ii ]
First normal form 62
Second normal form 62
Third normal form 63
Common patterns 64
Many-to-many relationships 64
Hierarchy 65
Recursive relationships 66
Summary 67
Chapter 5: Transactions and Locking 68
Defining transactions 68
ACID rules 69
Effect of concurrency on transactions 70
Transactions and savepoints 70
Transaction isolation 71
Implementing isolation levels 72
Dirty reads 72
Non-repeatable reads 73
Phantom reads 74
ANSI isolation levels 74
Transaction isolation levels 75
Changing the isolation level 75
Using explicit and implicit transactions 76
Avoiding deadlocks 76
Explicit locking 77
Locking rows 77
Locking tables 78
Summary 79
Chapter 6: Indexes and Constraints 81
Introduction to indexes and constraints 81
Primary key indexes 82
Unique indexes 83
B-tree indexes 84
Standard indexes 85
Full text indexes 86
Partial indexes 86
Multicolumn indexes 88
Hash indexes 89
GIN and GiST indexes 89
Clustering on an index 90
Foreign key constraints 91
[ iii ]
Unique constraints 92
Check constraints 94
NOT NULL constraints 95
Exclusion constraints 96
Summary 96
Chapter 7: Table Partitioning 97
Table partitioning 97
Partition implementation 102
Partitioning types 107
List partition 107
Managing partitions 109
Adding a new partition 109
Purging an old partition 110
Alternate partitioning methods 111
Method 1 111
Method 2 112
Constraint exclusion 114
Horizontal partitioning 116
PL/Proxy 117
Foreign inheritance 118
Summary 121
Chapter 8: Query Tuning and Optimization 122
Query tuning 122
Hot versus cold cache 123
Cleaning the cache 124
pg_buffercache 127
pg_prewarm 129
Optimizer settings for cached data 130
Multiple ways to implement a query 132
Bad query performance with stale statistics 134
Optimizer hints 136
Explain Plan 141
Generating and reading the Explain Plan 141
Simple example 142
More complex example 142
Query operators 143
Seq Scan 143
Index Scan 143
Sort 144
Unique 144
[ iv ]
LIMIT 144
Aggregate 144
Append 144
Result 144
Nested Loop 145
Merge Join 145
Hash and Hash Join 145
Group 145
Subquery Scan and Subplan 145
Tid Scan 145
Materialize 146
Setop 146
Summary 146
Chapter 9: PostgreSQL Extensions and Large Object Support 147
Creating an extension 147
Compiling extensions 149
Database links in PostgreSQL 150
Using binary large objects 153
Creating a large object 154
Importing a large object 154
Exporting a large object 155
Writing data to a large object 155
Server-side functions 155
Summary 156
Chapter 10: Using PHP in PostgreSQL 157
Postgres with PHP 157
PHP-to-PostgreSQL connections 158
Dealing with DDLs 161
DML operations 162
pg_query_params 163
pg_insert 164
Data retrieval 165
pg_fetch_all 165
pg_fetch_assoc 166
pg_fetch_result 167
Helper functions to deal with data fetching 168
pg_free_results 168
pg_num_rows 168
[v]
pg_num_fields 168
pg_field_name 168
pg_meta_data 168
pg_convert 169
UPDATE 171
DELETE 172
COPY 172
Summary 174
Chapter 11: Using Java in PostgreSQL 175
Making database connections to PostgreSQL using Java 175
Using Java to create a PostgreSQL table 178
Using Java to insert records into a PostgreSQL table 179
Using Java to update records into a PostgreSQL table 180
Using Java to delete records into a PostgreSQL table 181
Catching exceptions 182
Using prepared statements 184
Loading data using COPY 184
Connection properties 186
Summary 187
Index 188
[ vi ]
Preface
The purpose of this book is to teach you the fundamental practices and techniques of
database developers for programming database applications with PostgreSQL. It is targeted
to database developers using PostgreSQL who have basic experience developing database
applications with the system, but want a deeper understanding of how to implement
programmatic functions with PostgreSQL.
Chapter 2, Data Manipulation, provides you the ability to perform data type conversions
and perform JSON and XML operations in PostgreSQL.
Chapter 3, Triggers, explains how to perform trigger operations and use trigger functions in
PostgreSQL.
Chapter 5, Transactions and Locking, covers the effect of transactions and locking on the
database.The reader will also be able to understand isolation levels and understand multi-
version concurrency control behavior.
Chapter 6, Indexes And Constraints, provides knowledge about the different indexes and
constraints available in PostgreSQL. This knowledge will help the reader while coding and
the reader will be in a better position to choose among the different indexes and constraints
depending upon the requirement during the coding phase.
Chapter 8, Query Tuning and Optimization, provides knowledge about different mechanisms
and approaches available to tune a query. The reader will be able to utilize this knowledge
in order to write a optimal/efficient query or code.
Chapter 9, PostgreSQL Extensions and Large Object Support, will familiarize the reader with
the concept of extensions in PostgreSQL and also with the usage of large objects' datatypes
in PostgreSQL.
Chapter 10, Using PHP in PostgreSQL, covers the basics of performing database operations
in PostgreSQL using the PHP language, which helps reader to start with PHP code.
Chapter 11, Using Java in PostgreSQL, this chapter provides knowledge about database
connectivity using Java and creating/modifying objects using Java code. It also talks about
JDBC drivers.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds
of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Database
views are created using the CREATE VIEW statement. "
[2]
Preface
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or disliked. Reader feedback is important for us as it helps us
develop titles that you will really get the most out of. To send us general feedback, simply
e-mail feedback@packtpub.com, and mention the book's title in the subject of your
message. If there is a topic that you have expertise in and you are interested in either
writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
[3]
Preface
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-
we would be grateful if you could report this to us. By doing so, you can save other readers
from frustration and help us improve subsequent versions of this book. If you find any
errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting
your book, clicking on the Errata Submission Form link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata will
be uploaded to our website or added to any list of existing errata under the Errata section of
that title.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come
across any illegal copies of our works in any form on the Internet, please provide us with
the location address or website name immediately so that we can pursue a remedy.
We appreciate your help in protecting our authors and our ability to bring you valuable
content.
Questions
If you have a problem with any aspect of this book, you can contact us
at questions@packtpub.com, and we will do our best to address the problem.
[4]
Advanced SQL
1
This book is all about an open source software product, a relational database called
PostgreSQL. PostgreSQL is an advanced SQL database server, available on a wide range of
platforms. The purpose of this book is to teach database developers the fundamental
practices and techniques to program database applications with PostgreSQL.
Creating views
Understanding materialized views
Creating cursors
Using the GROUP BY clause
Using the HAVING clause
Understanding complex topics such as subqueries and joins
Creating views
A view is a virtual table based on the result set of an SQL statement. Just like a real table, a
view consist of rows and columns. The fields in a view are from one or more real tables in
the database. Generally speaking, a table has a set of definitions that physically stores data.
A view also has a set of definitions built on top of table(s) or other view(s) that does not
physically store data. The purpose of creating views is to make sure that the user does not
have access to all the data and is being restricted through a view. Also, it's better to create a
view if we have a query based on multiple tables so that we can use it straightaway rather
than writing a whole PSQL again and again.
Database views are created using the CREATE VIEW statement. Views can be created from a
single table or multiple tables, or another view.
Advanced SQL
You can then query this view as though it were a table. (In PostgreSQL, at the time of
writing, views are read-only by default.) You can SELECT data from a view just as you
would from a table and join it to other tables; you can also use WHERE clauses. Each time
you execute a SELECT query using the view, the data is rebuilt, so it is always up-to-date. It
is not a frozen copy stored at the time the view was created.
Let's create a view on supplier and order tables. But, before that, let's see what the structure
of the suppliers and orders table is:
CREATE TABLE suppliers
(supplier_id number primary key,
Supplier_name varchar(30),
Phone_number number);
CREATE TABLE orders
(order_number number primary key,
Supplier_id number references suppliers(supplier_id),
Quanity number,
Is_active varchar(10),
Price number);
CREATE VIEW active_supplier_orders AS
SELECT suppliers.supplier_id, suppliers.supplier_name orders.quantity,
orders.price
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_name = 'XYZ COMPANY'
[6]
Advanced SQL
And orders.active='TRUE';
The preceding example will create a virtual table based on the result set of the SELECT
statement. You can now query the PostgreSQL VIEW as follows:
SELECT * FROM active_supplier_orders;
If you want to replace an existing view with one that has the same name and returns the
same set of columns, you can use a CREATE OR REPLACE command.
CREATE OR REPLACE VIEW: This command helps modify the existing view.
SELECT: This command selects the columns that you want as part of the view.
FROM: This command gives the table name from where we can fetch the columns.
This may include one or more table names, since you have to create a view at the
top of multiple tables.
WHERE: This command provides the condition to restrict the data for a view. Also,
if you include multiple tables in the FROM clause, you can provide the joining
condition under the WHERE clause.
Let's modify a view, supplier_orders, by adding some more columns in the view. The
view was originally based on supplier and order tables having supplier_id,
supplier_name, quantity, and price. Let's also add order_number in the view.
[7]
Advanced SQL
Materialized views
A materialized view is a table that actually contains rows but behaves like a view. This has
been added in the PostgreSQL 9.3 version. A materialized view cannot subsequently be
directly updated, and the query used to create the materialized view is stored in exactly the
same way as the view's query is stored. As it holds the actual data, it occupies space as per
the filters that we applied while creating the materialized view.
You may notice that certain queries are very slow. You may have exhausted all the
techniques in the standard bag of techniques to speed up those queries. In the end, you will
realize that getting queries to run as fast as you want simply isn't possible without
completely restructuring the data.
Now, if you have an environment where you run the same type of SELECT query multiple
times against the same set of tables, then you can create a materialized view for SELECT so
that, on every run, this view does not go to the actual tables to fetch the data, which will
obviously reduce the load on them as you might be running a Data Manipulation
Language (DML) against your actual tables at the same time. So, basically, you take a view
and turn it into a real table that holds real data rather than a gateway to a SELECT query.
[8]
Advanced SQL
In a replication environment, a materialized table holds the table data and resides in a
different database. A table that has a materialized view on it is called a master table. The
master table resides on a master site and the materialized view resides on a materialized-
view site.
The CREATE MATERIALIZED VIEW command helps us create a materialized view. The
command acts in way similar to the CREATE VIEW command, which was explained in the
previous section.
This view is a read-only materialized view and will not reflect the changes to the master
site.
When we say “refreshing the materialized view,” we mean synchronizing the data in the
materialized view with data in its master table.
[9]
Advanced SQL
An updatable materialized view enables you to decrease the load on master sites because
users can make changes to data on the materialized view site.
Whenever changes are made in the suppliers_matview clause, it will reflect the changes
to the master sites during refresh.
Creating cursors
A cursor in PostgreSQL is a read-only pointer to a fully executed SELECT statement's result
set. Cursors are typically used within applications that maintain a persistent connection to
the PostgreSQL backend. By executing a cursor and maintaining a reference to its returned
result set, an application can more efficiently manage which rows to retrieve from a result
set at different times without re-executing the query with different LIMIT and OFFSET
clauses.
The four SQL commands involved with PostgreSQL cursors are DECLARE, FETCH, MOVE, and
CLOSE.
[ 10 ]
Advanced SQL
The DECLARE command both defines and opens a cursor, in effect defining the cursor in
memory, and then populates the cursor with information about the result set returned from
the executed query. A cursor may be declared only within an existing transaction block, so
you must execute a BEGIN command prior to declaring a cursor.
DECLARE cursorname is the name of the cursor to create. The optional BINARY keyword
causes the output to be retrieved in binary format instead of standard ASCII; this can be
more efficient, though it is only relevant to custom applications as clients such as psql are
not built to handle anything but text output. The INSENSITIVE and SCROLL keywords exist
to comply with the SQL standard, though they each define PostgreSQL's default behavior
and are never necessary. The INSENSITIVE SQL keyword exists to ensure that all data
retrieved from the cursor remains unchanged from other cursors or connections. As
PostgreSQL requires the cursors to be defined within transaction blocks, this behavior is
already implied. The SCROLL SQL keyword exists to specify that multiple rows at a time
can be selected from the cursor. This is the default in PostgreSQL, even if it is unspecified.
The CURSOR FOR query is the complete query and its result set will be accessible by the
cursor when executed.
The [FOR { READ ONLY | UPDATE [ OF column [, ...] ] } ] cursors may only be
defined as READ ONLY, and the FOR clause is, therefore, superfluous.
Let's begin a transaction block with the BEGIN keyword, and open a cursor named
order_cur with SELECT * FROM orders as its executed select statement:
BEGIN;
DECLARE order_cur CURSOR
FOR SELECT * FROM orders;
Once the cursor is successfully declared, it means that the rows retrieved by the query are
now accessible from the order_cur cursor.
Using cursors
In order to retrieve rows from the open cursor, we need to use the FETCH command. The
MOVE command moves the current location of the cursor within the result set and the CLOSE
command closes the cursor, freeing up any associated memory.
[ 11 ]
Advanced SQL
cursor is the name of the cursor from where we can retrieve row data. A cursor always
points to a current position in the executed statement's result set and rows can be retrieved
either ahead of the current location or behind it. The FORWARD and BACKWARD keywords
may be used to specify the direction, though the default is forward. The NEXT keyword (the
default) returns the next single row from the current cursor position. The PRIOR keyword
causes the single row preceding the current cursor position to be returned.
Let's consider an example that fetches the first four rows stored in the result set, pointed to
by the order_cur cursor. As a direction is not specified, FORWARD is implied. It then uses a
FETCH statement with the NEXT keyword to select the fifth row, and then another FETCH
statement with the PRIOR keyword to again select the fourth retrieved row.
FETCH 4 FROM order_cur;
Closing a cursor
You can use the CLOSE command to explicitly close an open cursor. A cursor can also be
implicitly closed if the transaction block that it resides within is committed with the COMMIT
command, or rolled back with the ROLLBACK command.
Here is the syntax for the CLOSE command, where Cursorname is the name of the cursor
intended to be closed:
CLOSE
Cursorname;
[ 12 ]
Random documents with unrelated
content Scribd suggests to you:
great banks of ugly rock-and-castle clouds in front, a sight that made us
think another baby tornado was a-brewin'.
"I was drawin' away at my pipe, and not saying a deal, when all of a
sudden the bo's'n seized me by the arm.
"He was all of a shake now, and his eyes was eyes of terror, as he
pointed aloft with outstretched arm.
"We both stood mute with fear. It burned brightly for a minute, then
flickered and went out. Only to reappear, however, in a few seconds, this
time more blue than white. Then, flickering once more, it fled, and we saw
it not again.
"Neither spoke for long seconds. We looked into each others' faces
inquiringly-like.
"'That,' said the bo's'n, 'is St. Helmo's (St. Elmo's) fire, and this bloomin'
ship is doomed.'
"I said nothing. I merely walked below, and passin' thro' the saloon
entered the skipper's cabin and touched him gentle-like on the shoulder.
Two candles was burnin' in jimbles, and a book he had been reading lay on
the white coverlet. Sound asleep as a baby he were, but sailor-like he
opened his eyes the moment I touched him.
"'Nothin' much, sir. Only St. Helmo's fire been a burnin' on the mizen
truck.'
"'And,' I adds, 'we may as well get the fires up, for we're precious near
the Sea of Sargasso. If we gets swallowed up there with mebbe a broken
screw it may be a two years' job, if ever we sees blue water again in this
world.'
"'Well, well, lad. If the winds doesn't blow get steam up. Meanwhile, go
and whistle for the wind. I'm tired!'
"I left the cabin slowly, only just stopping to have a tot o' rum, for there
was a kind o' hincubus a-weighing me down. But little did I know of the
horror to come."
CHAPTER XIX.
"At twelve o'clock," continued Goodwin, "I went below to call old
Deadlight, our first mate.
"When he came up, I stopped a few minutes to talk to him and tell him
what we'd seen, and the captain's orders in case of getting too near the
Sargasso Sea.
"I was just slueing round to go below, when I couldn't help thinking I felt
smoke, like.
"At first the mate wouldn't have it. It was my imagination, he said. I'd
been thinking too much about St. Elmo's fire, and all that rot. I'd better go
and turn in, I should be better in the morning. He were just agoin' on like
this and laughin' low to hisself, when up the fore-hatch comes the bo's'n.
"'Beggin' your pardon, sir,' he said, 'but I think the cargo is a-fire on the
port side.'
"Deadlight and I hurried below now. Yes, sure enough, there was smoke
coming up from the hold through the crevices of the hatchway.
"The cap'n was called, and was on deck afore you could have said
'binnacle'.
"He and the mate were very cool. So was all hands; and, cap'n, I always
think it is a blessing when the ship and precious lives are in danger not to
have any ladies on board, or longshore passenger swells. They beat creation
with the fuss they make.
"I was precious sorry now that I hadn't got steam up instead of waitin'
for the wind, for then we could have turned it into the hold and soon put out
the fire.
"We cut a hole in the fore-hatch of the hold, and poured tons of water
down. But even there where we stood our soles burned with heat, and we
walked cautiously lest we should fall through the under-charred deck and be
devoured by the fire below.
"I guess, cap'n, that the water we poured in just sunk through a portion o'
the cargo, like, and lay at the bottom.
"It was an anxious time,—you bet your last rupee on that, sir!—but all
hands worked like grim death in cholera times, and we hadn't time to funk.
"Hours and hours, taking turn and turn about. Provisions and rum were
got to the upper deck, and water too, for it was evident that the skipper
feared the worst. At the same time the boats were hoisted to the davits and
hung over the sea, all ready to let go. And they were provisioned, every one
of the three o' them, for ten days.
"To our dismay we found that the fire was now working farther aft, so
we determined to clear the after-hold of cargo.
"A working-party was at once organized, but, cap'n, when the hatch was
opened, such a stream of sparks and such stiflin' clouds of smoke rolled up,
that glad was we when we got that hatch back in position.
"Fires was now well lit, though, and steam was turned into the hold.
"Our object was to keep the fire confined to the hold, until we should
succeed, if possible, in reaching some of the islands of the Azores, there to
beach her and escape in our boats.
"It was not to be, although the boys worked like African slaves.
"We scuppered the decks now in the cabin, and down through the hole
made thus, cap'n, we put the nozzle of the hose.
"And so we worked away all that fearful night and long into next
forenoon. We didn't think much o' rest, gentlemen, nor food either. We just
choked down a bit o' junk now and then, or a morsel o' biscuit, and kept it
down with a peg o' rum. But, bless you, sir, our eyes was burnin', our faces
hangin' in bags of blisters, and our mouths so dry by this time that there was
no good trying to sing, for we were hardly fit to talk.
"Soon, now, the deck all along became so hot that the men had to leave
in relays to put their shoes on.
"Ah, what a sight! The clouds of smoke risin' as high as the foretop, and
the tongues of red flame following and licking them up!
"About the same time the fire spread up out of the scuppered hole, and
the saloon was all in a blaze 'fore ye could have said 'marling-spike'. It was
all over now.
"But, next minute, and just as we was preparin' to lower the boats, a
white squall came thunderin' over the sea, took the Ossian aback, and for
five minutes at least we stood holding on to the riggin' or stays, while she
went ploughin' astern. We 'xpected, cap'n, to see her go under, stern
foremost, every minute. Mebbe I was a bit white, cap'n. I don't know, but
my pals was."
"Yes, sir, and gettin' worse as the time went on, for so long as the squall
lasted the smoke and fire and sparks flew over us. But it stopped at last, and
the breeze came round the other way.
"Then we worked like devils, cap'n, to get her afore it, and when we did
it weren't quite so bad.
"We had a compass in each boat, but not a rag of a sail, just the oars; and
so wild was the sea that, what with keepin' her head on to the big coombing
waves that else would have sunk us, precious little progress was made, I can
assure you.
"We saw that burning ship an hour after we'd left her. Then she suddenly
disappeared, and at the same moment the roar of an explosion, louder 'n
thunder, rolled over the sea, and for the time being the waves hadn't a
chance o' bein' heard.
"About the beginning of the middle watch the wind began to go down,
and the sea too. 'I think, boys,' I said to my pals, 'we can have a bite and a
sup, now.' But, mercy on us, sir! when I bent down to scramble for the
provisions—none was there! The tack must have slipped overboard as we
lowered the boat stern first.
"There was a bottle o' rum, that was all. I poured out just a little, in the
shell of an old silver watch my poor mother had given me, and the men was
thankful.
"But they was mostly exhausted, and I was feared they'd sleep. So,
getting hold of some lanyard, I made 'em make the oars fast to the
rowlocks, with freedom to move and no more.
"In an hour's time the storm had passed away, and the night was clear. I
put just two to the oars, leaving two men to sleep and to relieve their pals
when they began to nod. Good thing I'd tied the oars, cap'n, for by an' by
one poor beggar fell off the thwart and I kicked up a sleeping chap to take
his place.
"Well, now that the sea was quiet, steerin' was of no account like. I just
told 'em to go on and keep their weather eye on a certain star I pointed out.
"Then I curled up and slept like a stone. It was daybreak when I awoke.
There was a glittering blood-red path across the waters where the crimson
sun was shinin'. The sea was lumpy now, but the day promised fine."
"Not one, sir, to be seen near or far, and we've never seen or overhauled
them since. This was a terrible trial for us, as we had no food. No, nor
water. On'y the rum, that could only excite us and make us by and by more
wretched and unhappy.
"I put it to the vote, cap'n. Should we drink the rum or leave it till it was
more wanted? Right bravely came the answer, ringing from for'ard:
"'We won't touch or taste it, till we ain't able to sit up.'
"All that day we rowed as well as we could, watchin' sea, watchin' sky,
for a sight of a boat of our own, for sight of a sail. But the sun went down
like a great blood orange, and weary and faint now, we hardly cared to row.
"There was neither moon nor stars that night, and so I just lashed the
helm so as to keep her driftin' a kind of in her course.
"We stepped a little mast for'ard, and hung up our lantern. We blessed
God that we had this, anyhow.
"Then we tumbled down to sleep, and long and sound that sleep must
have been, for it was the short gray gloamin' o' mornin' when we pulled
ourselves together again.
"And what think you was the first thing my hot eyes caught sight of?
"Our hearts sunk down, down after this. No one cared to speak much
above his breath, and I noticed more'n once that day, cap'n, the tears quietly
streamin' over the cheeks of a young sailor. Our fate, we feared, would be
worse by far than that of our other brave shipmates.
"I told out a watch-shell of rum all round at eight bells, and we were a
little heartened after this.
"But now, cap'n, the wind began to rise and moan over the sea once
more, and though it was right for us, if it increased we couldn't keep her
long afloat. Well, what does we do, sir, but tie two jackets together to make
a sail, and bent them on two oars.
"The poor fellows were half-dead now, and couldn't have rowed two
hours longer. After a rest and a kind of dreamy doze, we found the wind
still higher, and the seas breakin' on board of us all the time.
"Nothing for it now but bail her out. We had two pannikins and our sou'-
westers, and wi' these we just managed to keep her afloat till the second
dog-watch.
"Another little tot o' rum at eight, and when the sea and most o' the wind
went down we bailed her out once more, and then just tumbled down in the
bottom, wet, shivery, wretched.
"When day dawned, and there was still no sail nor land in sight, we kind
o' gave up in despair. The young sailor,—Tom Ball were his name,—sort of
went dotty, cap'n, and tried to eat the flesh oft the ball of his thumb. I gave
him four watch-shells of rum, and he sunk like a wet swab down between
the thwarts. Bill Jones took off his own coat and covered him up.
"We suffered more from thirst than hunger, though, and Tom had drunk
salt water, which sent him nearly mad, you see. So none o' the others
touched it.
"I dozed again several times that day, and always my dreams, cap'n, was
the self-same. I was wanderin' among beautiful woods, near my own old
home in Berkshire, birds was singin' in the trees, there was wild flowers all
along the banks of a stream, and again and again I stooped to drink, then all
became dark and dreadful and I awoke with a shriek.
"You don't mind me quotin' pottery, cap'n, do you? For I really is main
fond of it.
"How that night wore along I cannot tell you, cap'n. No one rowed, no
one steered.
"Next day our sufferings were fearful. Oh, cap'n, may you never know
what it is to be afloat in a foodless boat on the bosom of a deserted ocean.
"'Mate, we must cast lots who shall die, or shall we chance it and kill the
young un?"
"I knew this man would soon be a raving maniac, so I gave him four
more shells of the rum; then he slept.
"Another sunset.
"I prayed then, cap'n, as I'd never prayed before, that God in his mercy
would let us pass from life before we woke.
"Then once more I dozed, once more I dreamt, and again the green
summer woods all a-wavin' in the sunshine, the bird-song and the purlin'
brook.
"But I had not slept long ere I was aroused. It was the young Tom Ball
shriekin' in a strange high-pitched voice—for his throat was as dry as emery
paper.
"I rubbed my eyes for a time, then saw your lights through a kind of
haze.
"'The lantern—quick!' I cried.
"It was handed me, and with my hand all a-shakin' I brought out my
match-box.
"O God, cap'n, there was but one lucifer there! On this our lives
depended, and I felt that, if I did not succeed in lightin' that lamp, I myself
should go mad and throw myself into the sea, to be devoured by the shark
that, all throughout this weary time, had followed in our wake. I stood the
hurricane-lantern under the stern-sheets; then I put one hand holdin' the
empty box inside, lest a breath of air should blow out our only hope.
"Then I struck the match. A flare at first, then only a tiny blaze of blue. I
turned it round, and its light grew brighter and whiter.
"The lantern was lit, and Bill Jones seized it from me, just as I fell down
in the bottom of the boat in a dead faint.
"Young Tom Ball crept aft to me, while Bill kept waving the lantern on
high.
"I was all doubled up, with my chin on my breast, and but for that young
fellow Tom I should have died. But he laid me flat out, and rubbed my chest
with rum, and when I sighed—a sad, sobbing kind of sigh it were, so he
says—he got me to swallow a mouthful, and just as we got alongside your
ship, cap'n, I was able to sit up.
"And I knew we was saved, though I didn't know then that the two hands
lying asleep, like, in the bottom of the boat, was dead."
CHAPTER XX.
GUN-ROOM FUN.
If the reader—who I sincerely hope is going to be a sailor, for there is no
life like that on the ocean wave—will take a glance at a map of the world
and ferret out Venezuela, he will note that by sailing south-west by west in
almost a bee-line for about 4700 miles, he would strike this land of beauty,
and land of flowers and forests.
After leaving Azores, if his ship called there, he would find himself in a
long and lonesome sea indeed, and after some weeks the Caribbean Islands
would heave in sight, and our young sailor would know then he was far, far
away from home.
Our own land—God bless it, and wouldn't you and I fight for it just?—is
but like the cloud of fog that hangs over a city, compared to the loveliness
of many of these fairy isles. The blue sky is fringed with the tall palm-trees
that shoot from the soil, the islands themselves as you approach them
appear to hang on the horizon, and so azure is the ocean, so cerulean the
sky, you scarce can tell in fine weather where they meet and kiss.
Well, all around Bermuda the rocks and sea-gardens are almost quite as
lovely. Had the Osprey been going straight to Venezuela it would have been
out of her course to stop here, but she had despatches to leave.
Two of the Ossian's shipwrecked crew were left there, but the mate
begged to be allowed to remain and the captain had no objections. Goodwin
was a naval reserve man, and even a lieutenant in that service.
"Ah, boys," he would say, "there was much romance attached to the
glorious days of Nelson, when hostile fleets lay in rows, mebbe two deep,
one to support t'other like. When it was ship to ship, and hammer and tongs
till one blazed, blew up, and sank, or when the skipper of a Britisher
shouted through his trumpet to the master at the wheel: 'Lay us aboard that
frog-eating Frenchman!' When the master steered so close to the foe that
guns met muzzle to muzzle, and high o'er the din o' battle rang out the
order: 'Away, boarders! Give the beggars Rule Britannia, lads!' The days
when our brave blue-jackets used to swarm over the sides of the enemy's
ship, or creep in through the ports, pistol in hand, cutlass in mouth perhaps,
and lay the Frenchees dead at their guns.
"Yes, boys, these were the dashin' days of old, and somehow I sighs w'en
I think they're gone.
"But the future sea-fights, young gents, are goin' to be fought with cool
heads on sturdy shoulders. Excitement or rashness will mean annihilation;
manoeuvring will be prominent, ay, and pre-eminent."
Here Goodwin would pause perhaps, look funnily down at his models
and smile.
"You may think it a droll remark o' me to make, lads, but I do believe
that, given two hostile battleships, encountering each other, then that
skipper who is a good whist player, and has a long head that can see a bit
into futurity as it were, or guesses before-hand what t'other chap will do
when he, the whist man, plays his next card, will win the game o' war.
"This will kind o' knock some o' the romance out o' naval warfare. But
not so much as we may think. Moral courage, mind you, boys, is of a far
higher sort of quality than physical. And altho' the poet asks—
one might answer him thus: He may die more truly courageously, more
bravely too, if calm, if he meets his fate on a sinking iron-clad man-o'-war."
***********
This midshipman's mess was always a merry one. Guns may change
their form in the service, and ships as well, but our bold blue-jackets, and
our daft, fun-loving and gallant middies, will never change as long as
Britain's flag is unfurled,
Gun-room officers are fond of chaff, and unsparing in the use of it, no
matter how it gives offence or how it is taken. But they always like best
when the banter is returned. There is the banterer and the banteree, and woe
betide the latter if he gets angry!
The Ugly Duckling is, you will readily believe when I tell you, a sketch
from the life, and now that my memory brings him once more up before my
mind's eye, I believe I am right in asserting that poor Mr. Duckling's face
was more droll than ugly. Somewhat difficult to describe too. Forehead
receded somewhat; nose nowhere, or hardly anywhere; eyes half-shut and
full of fun; plenty of cheek, moral and physical; a longish, protruding upper
lip; and an immense square jaw. His ears stuck out too, like lug-sails.
"Mind, Mr. Ugly Duckling," Bobbie told him one day at mess, "you
must never get lost on the coast of Benin."
"Why, Scottie?"
"Why? How can you ask? Forgotten all your history? The king of Benin,
you know, always nails his captives by the ears to a tree, and your ears you
know, mon ami, are wonderfully suggestive!"
That day when the Duckling sat beside Admiral Jacko there was a good
deal of amusement. The Admiral, I may tell you, was a very large and by no
means handsome species of ape, and though he could not use a knife and
fork, he ate most contentedly from the plate that M'Carthy the steward
always placed before him, and he even used a table-napkin. On this
particular day he more than once put his head cheek-by-jowl with the
Duckling's, and the merriment increased.
"Oh, look, mess-mates, look, now that their heads are together!" This
from Bobbie. "Why, I declare that Jacko takes the cake!"
"For ugliness?"
But Admiral Jacko had another very dear friend, namely, the ship's cat, a
beautiful, half-bred brindled Persian.
After every meal Jacko used to collect tit-bits and stuff them into his
jowl till his cheek stuck out, then he went at once in search of pussy and fed
him. The action was almost human. Indeed it might have been called more
so, for the "lower animals", as we are all too fond of calling them, often
exhibit more kindness to each other than mankind does to any of them.
There was something quite out of the common about Jacko in many
ways. He really had less mischief in his mental composition than monkeys
generally. Hurricane Bob and Oscar used to be washed regularly once a
week. The gun-room steward, superintended by Creggan himself, used to
perform this operation. After the rubbing and rinsing with warm water and
soap, they were always deluged with pailfuls of clear, soft water, and after
they were dried down with half a dozen towels—the dogs' own property—
they were combed and brushed.
Then ensued a wild scamper round and round the Osprey's decks, that
made everyone laugh who saw it.
Admiral Jacko used to squat on top of the capstan while the doggies
were being washed, and from the long, doleful face he wore, it was evident
he pitied them. But as soon as the scamper up and down the decks after
belaying-pins that the men threw to them was over, both dogs went and lay
down on the quarter-deck in the sunshine. And now Jacko considered that
his duties had commenced. He would leap solemnly down from the top of
the capstan, Creggan would hand him the comb, then off he went to his
friends the dogs. No peasant woman in Normandy could have combed her
boy's hair more carefully than did Jacko go over Hurricane Bob's coat first,
and then honest Oscar's, with finger-nails and brush. Well, if he did catch an
errant flea it was executed on the spot; but the earnestness with which Jacko
did the work, and the exceeding gravity of his face while at it, would have
drawn laughter from a California mule.
***********
I myself have never yet seen a more active middy on board a British
man-o'-war than the Ugly Duckling was. No part of the ship's rigging was
inaccessible to him. He would climb to the main-truck and wave his cap to
those below.
There was no laughing now among those below, all were mute with fears
for the poor boy's fate. This daring middy balanced himself first on one foot
and then on the other, and then—will it be believed?—he took from his
jacket pocket a tiny ebony fife, at playing which he was a great adept, and
commenced to pipe The Girl I left behind me.
Something had suddenly unnerved him, and well he knew that to fall
deckwards would be death. He was seen, therefore, to suddenly crouch, and
putting his hands in swimming fashion above his head, to spring into the air.
He came down like a flash, and sunk far into the water, many yards on the
port side of the ship.
The Ugly Duckling was too good a swimmer, however, to need such
assistance, only he kept close to it, as he did not wish it to be lost.
Now the great danger was the sharks, cruel tigers of the seas, that in
these hot latitudes swarm.
But the boat picked the middy up just at the very moment that two
monster sharks sprang at the life-buoy and hauled it down.
The Ugly Duckling had stuck to his fife all the time, and now much to
the amusement of the life-boat's crew commenced once more to play The
Girl I left behind me, and continued to play till the boat got alongside. Then
up ran the still dripping Duckling, and on gaining the quarter-deck first
saluted it and then saluted Captain Leeward.
"Come to report myself, sir," he said, "for leaving the ship without
leave."
"And I ought to punish you, sir," said the captain, trying in vain to
suppress a smile; "but I will forgive you if you promise not to stand on the
truck again."
"I promise, sir, readily; for, sir, it wouldn't be half good enough to be
swallowed by a shark, fife and all."
And down below dived this queer middy to change his dripping
garments.
CHAPTER XXI.
It would take a good many chapters to tell my readers all the tricks that
this favourite of the gun-room mess played.
The surgeon, Dr. Grant, and he were excellent friends, and were often
together; and sometimes if one of his mess-mates was a bit off colour, the
Ugly Duckling would prescribe or pretend to prescribe for him, and his
prescriptions were at times droll, to say the least.
One day, for instance, the white-faced young clerk was ailing. He
frequently was.
"No use you going to Dr. Grant," said the Duckling; "he'll only give you
black-strap and make you worse. Here, out with your note-book and I'll