Share E-Book

PostgreSQL for Data Architects (Jayadevan Maymala) (z-library.sk, 1lib.sk, z-lib.sk)

Author

Rating 3.5 AI initial rating

Log in to rate

Data
Language English

Discover how to design, develop, and maintain your database application effectively with PostgreSQL About This Book Understand how to utilize the most frequently used PostgreSQL ecosystem-related tools and technologies A hands-on guide focused primarily on providing a practical approach to learning about architecture and design considerations for database architects The book covers PostgreSQL from a data architect's perspective – covering topics from installation from source to designing tables using SQL Power Architect, as well as deciding replication and failover strategies. Who This Book Is For This book is for developers and data architects who have some exposure to databases. It is assumed that you understand the basic concepts of tables and common database objects, including privileges and security. What You Will Learn Compile PostgreSQL from source and understand the PostgreSQL architecture Configure parameters and change default settings for a PostgreSQL server Leverage the logging mechanism to identify errors and suboptimal queries Use replication to scale horizontally Set up backup and recovery processes Tweak parameters to optimize queries and processes Troubleshoot connection errors Use indexes and rewrite queries to improve performance Install and use PostgreSQL extensions Learn how to leverage the command-line client (psql) In Detail PostgreSQL is an incredibly flexible and dependable open source relational database. Harnessing its power will make your applications more reliable and extensible without increasing costs. Using PostgreSQL's advanced features will save you work and increase performance, once you've discovered how to set it up. PostgreSQL for Data Architects will teach you everything you need to learn in order to get a scalable and optimized PostgreSQL server up and running. The book starts with basic concepts like installing PostgreSQL from source and covers theoretical aspects such as concurrency and transaction management. After this

Format PDF
Size 5.5 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
PostgreSQL for Data Architects Discover how to design, develop, and maintain your database application effectively with PostgreSQL Jayadevan Maymala BIRMINGHAM - MUMBAI
Page 3
PostgreSQL for Data Architects Copyright © 2015 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 author, 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. First published: March 2015 Production reference: 1240315 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78328-860-1 www.packtpub.com Cover image by Kai Stachowiak (kalhh@web.de)
Page 4
Credits Author Jayadevan Maymala Reviewers Pascal Charest Bahman Movaqar Ângelo Marcos Rigo Hans-Jürgen Schönig Stéphane Wirtel Commissioning Editor Anthony Albuquerque Acquisition Editor Sonali Vernekar Content Development Editors Rahul Nair Sharvari Tawde Technical Editor Shashank Desai Copy Editor Relin Hedly Project Coordinator Judie Jose Proofreaders Maria Gould Clyde Jenkins Chris Smith Jonathan Todd Indexer Hemangini Bari Graphics Sheetal Aute Abhinash Sahu Production Coordinator Aparna Bhagat Cover Work Aparna Bhagat
Page 5
About the Author Jayadevan Maymala is a database developer, designer, and architect. He started working with the Oracle database in 1999. Over the years, he has worked with DB2, Sybase, and SQL Server. Of late, he has been working with open source technologies. His database of choice is PostgreSQL. In his career, he has worked in different domains spanning supply chain management, finance, and travel. He has spent an equal amount of time working with databases supporting critical transaction processing systems as well as data warehouses supporting analytical systems. When he is not working on open source technologies, he spends time reading and updating himself on economic and political issues. I would like to thank my wife, Uma, for putting up with my marathon writing sessions over weekends. I am also deeply indebted to the PostgreSQL community, which has individuals who are always promptly replying to my basic and not-so-basic queries. It's an amazing team that has been working tirelessly to build such a great database and then give it away for free with such liberal licensing terms. Thank you.
Page 6
About the Reviewers Pascal Charest is a cutting-edge technology professional working with a very wide array of open source technologies. He is currently leading system administrators in strategic planning of networked infrastructures and is often consulted for system architecture design. He can be reached via his LinkedIn profile at http://www.linkedin.com/in/pascalcharest. I'd like to thank Anthony and Zachary for keeping me awake, day and night. Bahman Movaqar has been developing, deploying, and delivering software for the past 14 years, ranging from embedded operating systems to ERP implementations. He's an open source believer and a passionate amateur chess player. He blogs at http://bahmanm.com/. I'd like to thank my lovely wife, Nahid, who has taught me how to be strong.
Page 7
Ângelo Marcos Rigo has a strong background in web development since 1998, focusing on content management systems. For the past 7 years, he has been managing, customizing, and developing extensions for Moodle LMS. He can be reached at his website http://www.u4w.com.br/novosite/index.php for CMS or Moodle LMS consulting. He has reviewed Moodle Security, Packt Publishing. I would like to thank my wife, Janaina de Souza, and my daughter, Lorena Rigo, for their support when I was away reviewing this book. Hans-Jürgen Schönig has been involved in professional PostgreSQL training, consulting, and support for more than 15 years now. He and his company Cybertec Schönig & Schönig GmbH (http://www.cybertec.at/) are serving clients around the globe and have worked on some of the world's largest PostgreSQL deployments. Stéphane Wirtel is an enthusiast software craftsman who is interested in high availability, replication, and distributed systems. Since 2000, he has been using PostgreSQL with the Python programming language. Stephane gives talks on Python and PostgreSQL in several conferences in Europe. The last one was called Python & PostgreSQL, a Wonderful Wedding. He is also a former core developer of the Odoo project, having worked on it for 6 years. Stéphane is also a member of the Python Software Foundation and the EuroPython Society. He promotes the Python programming language via the PythonFOSDEM event at Brussels. You can reach him at http://wirtel.be/ or via Twitter @matrixise. He works for Mgx.IO, a company that specializes in Python and Erlang developments. You can reach this company at http://mgx.io/ or via Twitter @mgxio. He has also reviewed the books Getting Started with PhantomJS and PhantomJS Cookbook, both by Packt Publishing. I would like to thank my wife, Anne, my daughter, Margaux, my family and friends for their support, and the PostgreSQL and Python communities for the awesome tools.
Page 8
www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.PacktPub.com. 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 service@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. TM 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 Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Page 9
(This page has no text content)
Page 10
[ i ] Table of Contents Preface vii Chapter 1: Installing PostgreSQL 1 Installation options 1 Downloading and extracting the source 2 Inspecting the contents 3 Dependencies to compile the source 4 Configuring and creating the makefile 5 Building and creating the executables 8 Installing and moving the files to where they belong 9 Inspecting the changes 10 Initializing a cluster 11 A quick walk through the directories 14 Processes created 17 Important files created 17 Working with extensions 18 Summary 19 Chapter 2: Server Architecture 21 Starting with the daemon process 21 Understanding the shared buffer 23 Inspecting the buffer cache 25 Checkpoint 29 WAL and the WAL writer process 32 Recovery 34 Incremental backup and point-in-time recovery 34 Replication 34 The background writer 36 The autovacuum launcher process 37
Page 11
Table of Contents [ ii ] The logging process 41 The stats collector process 46 The WAL sender and WAL receiver 49 Sorting in memory with work_mem 49 Maintenance with maintenance_work_mem 51 Understanding effective_cache_size 53 Summary 54 Chapter 3: PostgreSQL – Object Hierarchy and Roles 55 The PostgreSQL cluster 55 Understanding tablespaces 56 Managing temporary objects with temporary tablespaces 59 Views 61 Databases, schemas, and search_path 61 Schemas – use cases 67 Roles and privileges 67 Summary 72 Chapter 4: Working with Transactions 73 Understanding transactions 73 ACID properties of transactions 76 A for atomicity 76 C for consistency 76 I for isolation 76 D for durability 85 PostgreSQL and MVCC 86 Summary 90 Chapter 5: Data Modeling with SQL Power Architect 91 Tools for databases and their uses 91 Database design tools 93 SQL Power Architect – downloading and installing 93 Creating tables 95 Generating SQL 97 Reverse engineering and making changes 100 Exporting the data model 101 Profiling 102 Summary 103 Chapter 6: Client Tools 105 GUI tools and command-line tools 105 pgAdmin – downloading and installation 105 Adding a server 106
Page 12
Table of Contents [ iii ] The pgAdmin main window 108 The Query tool 111 psql – working from the command line 114 psql – connection options 114 The power of \d 115 More meta-commands 117 Setting up the environment 120 History of commands 121 Summary 122 Chapter 7: SQL Tuning 123 Understanding basic facts about databases 123 Fact 1 – databases are more frequently read from than written to 123 Fact 2 – data is always read in blocks or pages, not as individual records or columns 124 Approaches to reducing the number of blocks read/written 125 Query execution components 125 Planner 126 Access methods 126 Join strategies 127 Finding the execution plan 128 Optimization guidelines and catches 130 Indexing foreign keys 130 Using SELECT * 132 Using ORDER BY 133 Using DISTINCT 134 Using UNION ALL instead of UNION 134 Using functions in the FILTER clause 134 Reducing the number of SQL statements 137 Reducing function executions 138 Not using indexes 140 Partial indexes 142 Optimizing functions 143 Summary 145 Chapter 8: Server Tuning 147 Server-wide memory settings 147 shared_buffers 147 effective_cache_size 148 Managing writes, connections, and maintenance 149
Page 13
Table of Contents [ iv ] Seek/scan cost and statistics parameters 151 CPU costs 155 Materialized views 157 Partitioned tables 160 Summary 165 Chapter 9: Tools to Move Data in and out of PostgreSQL 167 Setting up the production database – considerations 167 COPY 168 Fast loading with pg_bulkload 171 pg_dump 173 Filtering options 175 pg_dumpall 176 pg_restore 176 Summary 178 Chapter 10: Scaling, Replication, and Backup and Recovery 179 Scalability 179 Vertical scaling 181 Horizontal scaling 182 Master-slave(s) with read/write separation 182 Streaming replication 184 Connection pooling, load balancing, and failover with pgpool-II 189 Sharding 199 Multi-master full replication 201 Point-in-time recovery 202 Summary 206 Chapter 11: PostgreSQL – Troubleshooting 207 Connection issues 207 Authentication and permission issues 208 Parameter changes not effective 210 Query not responding 212 Summary 216 Chapter 12: PostgreSQL – Extras 217 Interesting data types 217 RANGE 218 Using network address types 220 hstore for key-value pairs 222 json/jsonb 224 XML 227 Inserting and verifying XML data 228 Generating XML files for table definitions and data 228
Page 14
Table of Contents [ v ] Geometry and geography 229 Foreign Data Wrappers 229 FDW for files 230 PostgreSQL FDW 231 Data wrappers – other aspects 232 pgbadger 233 Features over time 236 Interesting features in 9.4 236 Keeping the buffer ready 236 Better recoverability 238 Easy-to-change parameters 238 Logical decoding and consumption of changes 239 Summary 240 Index 241
Page 15
(This page has no text content)
Page 16
[ vii ] Preface PostgreSQL is an incredibly flexible and dependable open source relational database. Harnessing its power will make your applications more reliable and extensible without increasing costs. Using PostgreSQL's advanced features will save you work and increase performance, once you've discovered how to set it up. PostgreSQL for Data Architects will teach you everything you need to learn in order to get a scalable and optimized PostgreSQL server up and running. The book starts with basic concepts (such as installing PostgreSQL from source) and covers theoretical aspects (such as concurrency and transaction management). After this, you'll learn how to set up replication, use load balancing to scale horizontally, and troubleshoot errors. As you continue through this book, you will see the significant impact of configuration parameters on performance, scalability, and transaction management. Finally, you will get acquainted with useful tools available in the PostgreSQL ecosystem used to analyze PostgreSQL logs, set up load balancing, and recovery. What this book covers Chapter 1, Installing PostgreSQL, provides an overview of the process to install PostgreSQL from source. The chapter covers the prerequisites to compile from source, and the process to initialize a cluster in Unix/Linux environment. It also covers the directory structure. Chapter 2, Server Architecture, covers the important processes started when we start a PostgreSQL cluster and how they work along with the memory structures to provide the functionality expected from a database management system.
Page 17
Preface [ viii ] Chapter 3, PostgreSQL – Object Hierarchy and Roles, explains various object types and objects provided by PostgreSQL. Important concepts such as databases, clusters, tablespaces, and schemas are covered in this chapter. Chapter 4, Working with Transactions, covers ACID properties of transactions, isolation levels, and how PostgreSQL provides them. Multiversion concurrency control is another topic dealt with in this chapter. Chapter 5, Data Modeling with SQL Power Architect, talks about how we can model tables and relationships with SQL Power Architect. Some of the aspects that should be considered when we choose a design tool are also covered in this chapter. Chapter 6, Client Tools, covers two clients tools (pgAdmin: a UI tool and psql: a command-line tool). Browsing database objects, generating queries, and generating the execution plan for queries using pgAdmin are covered. Setting up the environment variables for connecting from psql, viewing history of SQL commands executed, and meta-commands are also covered in this chapter. Chapter 7, SQL Tuning, explains query optimization techniques. To set the context, some patterns about database use and theory on how the PostgreSQL optimizer works are covered. Chapter 8, Server Tuning, covers PostgreSQL server settings that have significant impact on query performance. These include memory settings, cost settings, and so on. Two object types: partitions and materialized views are also covered in this chapter. Chapter 9, Tools to Move Data in and out of PostgreSQL, covers common tools/utilities, such as pg_dump, pg_bulkload, and copy used to move data in and out of PostgreSQL. Chapter 10, Scaling, Replication, and Backup and Recovery, covers methods that are usually used for achievability. A step-by-step method to achieve horizontal scalability using PostgreSQL's streaming replication and pgpool-II is also presented. Point-in-time recovery for PostgreSQL is also covered in this chapter. Chapter 11, PostgreSQL – Troubleshooting, explains a few of the most common problems developers run into when they start off with PostgreSQL and how to troubleshoot them. Connection issues, privilege issues, and parameter setting issues are also covered. Chapter 12, PostgreSQL – Extras, covers quite a few topics. Some interesting data types that every data architect should be aware of, a couple of really useful extensions, and a tool to analyze PostgreSQL log files are covered. It also covers a few interesting features available in PostgreSQL 9.4.
Page 18
Preface [ ix ] What you need for this book A computer with access to the Internet is mandatory. It will definitely help if the computer is running on a Unix/Linux operating system. Who this book is for You are expected to have some exposure to databases. Basic familiarity with database objects such as tables and views is expected. You will find this book really useful if you have no or a little exposure to PostgreSQL. If you have been working with PostgreSQL for a few years, you should still find a few useful commands that you were not aware of or a couple of optimization approaches you have not tried. You will also gain more insight into how the database works. Conventions In this book, you will find a number of text styles that distinguish among 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: "We will use the following wget command to download the source." A block of code/SQL at psql prompt as well as the output from the server at psql is set as follows: CREATE TABLE emp(id serial, first_name varchar(50)); Commands executed at shell/command prompt, the output, and parameters and settings are formatted as follows: [root@MyCentOS ~]# ps f -U postgres PID TTY STAT TIME COMMAND 1918 tty1 S 0:00 /usr/local/pgsql/bin/postgres New terms and important words are shown in bold.
Page 19
Preface [ x ] Warnings or important notes appear in a box like this. Tips and tricks appear like this. 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. Downloading the example code You can download the example code files from your account at http://www. packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Page 20
Preface [ xi ] 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. To view the previously submitted errata, go to https://www.packtpub.com/books/ content/support and enter the name of the book in the search field. The required information will appear under the Errata section. 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. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. 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.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List