Docsity

Sistema gestor de base de datos Postgres y SQL, Monografías, Ensayos de Sistemas de Gestión de Bases de Datos

Vista previa parcial del texto

¡Descarga Sistema gestor de base de datos Postgres y SQL y más Monografías, Ensayos en PDF de Sistemas de Gestión de Bases de Datos solo en Docsity!

PostgreSQL Database Handbook i

PostgreSQL Database Handbook

  • 1 Introduction and installation Contents
    • 1.1 What’s PostgreSQL?
    • 1.2 Installing PostgreSQL
    • 1.3 Populating the database with data
    • 1.4 Configuring phppgadmin in Linux
    • 1.5 PostgreSQL Windows client
  • 2 Commands and datatypes
    • 2.1 PostgreSQL commands
      • 2.1.1 Getting help
      • 2.1.2 Displaying databases and tables
    • 2.2 PostgreSQL data types
    • 2.3 Enumerated types
    • 2.4 Summary
  • 3 VACUUM Command Example
    • 3.1 Updating and removing rows
    • 3.2 Introducing VACUUM
    • 3.3 Summary
  • 4 PostgreSQL indexes example
    • 4.1 Introducing indexes
    • 4.2 Examples
    • 4.3 Unique indexes
    • 4.4 Multicolumn indexes
    • 4.5 Summary
  • 5 Database Creation and Data Population
    • 5.1 Creating a new database
    • 5.2 Populating the database
    • 5.3 More queries
    • 5.4 Summary
  • 6 Common Table Expressions PostgreSQL Database Handbook iii
    • 6.1 Definition of Common Table Expressions (CTE)
    • 6.2 Non-recursive Common Table Expressions
    • 6.3 Summary
  • 7 Hot-Standby Database Replication Tutorial
    • 7.1 Step 0 - Change hostnames and IP addresses as needed
    • 7.2 Step 1 - Configuring the master
    • 7.3 Step 2 - Configuring the slave
    • 7.4 Step 3 - Performing the replication
    • 7.5 Step 4 - Testing the replication
    • 7.6 Troubleshooting
  • 8 Backup, Restore and Migration
    • 8.1 Backup, restore, and migration strategies
    • 8.2 Installing Barman
      • 8.2.1 Step 1 - Create a dedicated PostgreSQL user in oldserver
      • 8.2.2 Step 2 - Create the .pgpass file in newserver
      • 8.2.3 Step 3 - Set up key-based authentication
      • 8.2.4 Step 4 - Configure Barman
      • 8.2.5 Step 5 - Configure PostgreSQL
      • 8.2.6 Step 6 - Test the Barman configuration
      • 8.2.7 Step 7 - Perform the backup
      • 8.2.8 Step 8 - Restore the backup on newserver
    • 8.3 Automating backups
  • 9 Connect to PostgreSQL using PHP
    • 9.1 Installing the software
    • 9.2 Connecting to the database server
    • 9.3 Writing the application
    • 9.4 Creating a mobile-friendly web page
    • 9.5 Summary

PostgreSQL Database Handbook iv

Copyright (c) Exelixis Media P.C., 2016

All rights reserved. Without limiting the rights under copyright reserved above, no part of this publication may be reproduced, stored or introduced into a retrieval system, or transmitted, in any form or by any means (electronic, mechanical, photocopying, recording or otherwise), without the prior written permission of the copyright owner.

PostgreSQL Database Handbook vi

About the Author

Gabriel Canepa is a Linux Foundation Certified System Administrator (LFCS-1500-0576-0100) and web developer from Villa Mercedes, San Luis, Argentina.

He works for a worldwide leading consumer product company and takes great pleasure in using FOSS tools to increase produc- tivity in all areas of his daily work.

When he’s not typing commands or writing code or articles, he enjoys telling bedtime stories with his wife to his two little daughters and playing with them, the great pleasure of his life.

PostgreSQL Database Handbook 1 / 50

Chapter 1

Introduction and installation

With all the Relational Database Management Systems (RDBMs) out there, it may be somewhat difficult to identify the best solution for your needs and to take an informed decision as to which one to choose. Thus, in this series we will provide an introduction to PostgreSQL and share some of the reasons why you may want to consider this solution when exploring the available technologies for a database implementation.

1.1 What’s PostgreSQL?

PostgreSQL, also known by its alias Postgres, is a cross-platform object-relational database management system (ORDBMs for short). Its development started in the University of California at Berkeley in the mid 80s with a project they named simply POSTGRES, which did not feature SQL as query language at first. In the mid90s, two students added SQL to the code inherited from the university, and PostgreSQL was born as an open-source project. Today, PostgreSQL has been long known (and has a strong reputation for) for being able to handle significant workloads with a large number of concurrent users. In addition, it provides bindings for many programming languages, making it an ideal solution for a client-server environment.

1.2 Installing PostgreSQL

In this article we will explain how to install a PostgreSQL server in Ubuntu Server 16.04 (IP address 192.168.0.54), how to load a sample database, and how to install a client application (which will serve as an administrative tool) for Linux and Windows.

Step 1 - Launch a terminal and install the server and the web-based administration tool:

sudo aptitude install postgresql phppgadmin

Step 2 - Verify that the database service is running and listening on port 5432:

systemctl is-active postgresql sudo netstat -npltu | grep postgres

The first command should indicate that unit postgresql is Active, and the second command should show that the service is listening on the right port, as shown in Fig. 1.1:

Figure 1.1: Verifying that PostgreSQL is running and listening on port 5432

PostgreSQL Database Handbook 3 / 50

As the tables are created and populated with data, the output should be similar to Fig. 1.3:

Figure 1.3: Restoring the database contents from the dump file

After completing the above 6 steps, we now have a fully-setup PostgreSQL database.

1.4 Configuring phppgadmin in Linux

In order to allow remote (LAN) access to the web-based administration tool, follow these steps:

Step 7 - Integrate phppgadmin with Apache

Open /etc/apache2/conf-enabled/phppgadmin.conf, and comment out the following line:

Require local

then add

Require all granted

just below (see Fig. 1.4 for details)

PostgreSQL Database Handbook 4 / 50

Figure 1.4: Configuring access permissions for phppgadmin

Step 8 - Grant SELECT permissions on World_db

Switch to the postgres Linux account and open the database prompt by typing

psql

Then connect to the World_db database:

\c World_db;

Finally, grant SELECT permissions to role gacanepa, and exit (q) the database prompt:

GRANT SELECT ON ALL TABLES IN SCHEMA public TO gacanepa; \q

See Fig. 1.5 for details:

Figure 1.5: Connecting to a database and granting SELECT permissions to a role

Step 9 - Restart Apache and PostgreSQL

We are almost there. Let’s restart Apache and PostgreSQL:

PostgreSQL Database Handbook 6 / 50

Figure 1.7: Our first query to the PostgreSQL database through phppgadmin

Click Execute at the bottom. The results should be as shown in Fig. 1.8:

Figure 1.8: The results of our first query

1.5 PostgreSQL Windows client

If you are using Microsoft Windows, in addition to phppgadmin (which you can access through a web browser), you can also install a client application named pgAdmin in order to connect to the database server. You can download it from the pgAdmin PostgreSQL tools page at https://www.pgadmin.org/download/windows.php. The installation will only take a few clicks.

Although it is better known in Windows environments, pgAdmin is also available for Mac OS X as well.

When you’re done with the installation, make sure the following lines are present in the configuration files. Otherwise, you will NOT be able to connect to the database server from a machine other than where you installed and running.

In /etc/postgresql/9.5/main/postgresql.conf:

listen_addresses = ’*’

will ensure the database server is listening on all interfaces, and because of the following line in /etc/postgresql/9.5/main/pg_hba.conf:

host all all 192.168.0.0/24 md

PostgreSQL Database Handbook 7 / 50

you can now connect to the database server from any machine in the 192.168.0.0/24 network.

Once you added the above lines, open pgAdmin from Start → All programs → pgAdmin III. Then click on File → Add server and fill the connection details (see Fig. 1.9). If you fill the password box as shown below, the credentials will be saved in plain text in your user profile. If you are using a shared computer that is probably not a good idea, so you may want to leave that field blank if that’s the case:

Figure 1.9: Configuring access to our database server through pgAdmin

Congratulations! You have successfully installed a PostgreSQL database server and are now able to access it both from a web interface and using a client application.

PostgreSQL Database Handbook 9 / 50

you need help with, use q to return to the psql prompt and then type h followed by the SQL command you have chosen. For example, let’s say we chose ALTER USER. To see the help for that command, do

\h ALTER USER

as shown in Fig. 2.2:

Figure 2.2: Getting help about SQL commands

On the other hand, if you get stuck with a database management task, do? and you will see the available psql commands grouped by categories, as seen in Fig. 2.3 (some of them are highlighted in yellow - the output is truncated for the sake of space):

Figure 2.3: Getting help with psql commands

As before, type q to exit the help and return to the psql prompt.

2.1.2 Displaying databases and tables

If you find yourself examining a database server you haven’t previously worked with, or if you are not familiar with the structure of a given database, you may want to start off by listing the databases and their respective tables.

PostgreSQL Database Handbook 10 / 50

To list the databases, simply do l

To view the tables in the World_db database (which is the one we imported in our previous tutorial), connect to it and type dt

Keep in mind that you can switch from a given database to another (Alberdi in the following example) with c Alberdi

The above commands are shown in Fig. 2.4 below:

Figure 2.4: Listing databases and tables

With the psql commands above we have learned to how to list databases and switch between one and another, how to list tables, and how to get help if we get stuck along the way.

2.2 PostgreSQL data types

As a preparation to creating our own databases and tables from scratch (which we will cover in an upcoming tutorial), we need to know how what are the allowed built-in, general-purpose data types for table fields. The PostgreSQL 9.5 documentation lists the following data types and more:

a) Numeric types (with corresponding storage sizes and ranges) are listed in Fig. 2.5:

PostgreSQL Database Handbook 12 / 50

Figure 2.8: Binary data type

Knowing the allowed ranges for each data type is essential to choosing the right type for fields. It is also critical as far as disk usage is concerned, as a 2-byte integer (smallint) will occupy less space than a 4-byte one (integer). As a rule of thumb, only use a "larger" data type if and only if a smaller type is not likely to scale well with the expected use and growth of the database in terms of record numbers.

Also, the length of character fields must be taken into account while planning -for example- a web application that will gather data through forms or other types of input. While in certain cases users should not be allowed to enter text of indefinite length, you should plan ahead so that they can still enter all that is necessary. Although form validation and sanitization are out of the scope of this tutorial, you definitely will want to make sure that your application does not present security holes and is not abuse-prone.

The use of data types, among other things, contributes to data consistency in a table by ensuring that a given field will only accept the type of data it is configured to store.

2.3 Enumerated types

Besides the general purpose data types, PostgreSQL allows us to create our own data types in the form of static, ordered set of values (for example, the months of the year, or the days of the week), similarly to the enum type supported in several programming languages. We will see the benefit of enumerated types when we create our first database and start inserting data into it.

2.4 Summary

Now that you have learned how to use basic psql commands and have reviewed the most used data types, we are better prepared to dive deeper into PostgreSQL database administration. Stay tuned for the next tutorial!

PostgreSQL Database Handbook 13 / 50

Chapter 3

VACUUM Command Example

In the previous tutorials of this series (“PostgreSQL: Introduction and installation” and “PostgreSQL commands and datatypes”) we explained how to load a sample database (World_db) into our PostgreSQL server and how to get help with both SQL and psql commands.

In real-world scenarios, you will need to perform CRUD (Create, Read, Update, and Delete) operations on database tables all the time. In this post we will learn how to do U (updates) and D (deletes), and show how to clean up the database by removing the left overs resulting from these operations. As we will see in a moment, PostgreSQL provides an effective garbage collector for this.

Without going into the nitty-gritty of what happens under the hood, we can mention briefly that the previous versions of updated records or deleted table entries are not actually removed from the database. Think about the need to rollback a given transaction and this will make sense. They are just “not visible” anymore by regular means, and they keep contributing to the amount of used hard disk space until a clean-up is performed using the VACUUM psql command. Let’s take a look at it in greater detail later.

3.1 Updating and removing rows

Using the World_db database, let’s update by 7% the population of all cities in the city table. Before we do that, let’s take a look at the impact this operation would have on the current data by using a basic SELECT statement.

Before a mass update or removal, using SELECT to print the records that will be impacted by that operation is a wise thing to do. Among other things, this can help you prevent undesired results (and the associated later regret), especially if you forget to add a WHERE clause to the operation.

We will print the city name, its current population, and the population after our proposed update. To round the population increase to the nearest integer, we will use the ROUND function as shown in Fig. 3.1: