est. spine=1.78"

Wrox Programmer to ProgrammerTM Wrox Programmer to ProgrammerTM Developing Web Applications Galbraith with Apache, MySQL ®, , and

Adding a cache layer to the popular LAMP stack is becoming What you will learn from this book the common solution to significantly reduce the load on back- ● How to install, configure, and work with MySQL particularly with Apache, MySQL Apache, with Developing Web Applications end databases, and also allows for better web application basic concepts involving data, joins, and indexes as well as Perl and memcached, performance. This new caching component is represented by advanced usage of triggers, stored procedures, user-defined another “m” in LAMMP, which stands for memcached—a high- functions, storage engine usage, and more! performance, distributed memory object caching system that ● provides caching for web applications. The author walks you A Perl refresher on basic concepts as well as how to work through the process of using Perl to develop web applications with data from MySQL using various Perl data types both in terms of the front-end display logic as well as the ● A chapter on object-oriented Perl back-end data retrieval from MySQL and memcached. You ● How to the use Sphinx storage engine for full-text searching also see how to configure the Apache web server to run these as well as to distribute tasks mod_perl applications. ● How to install and configure Apache 2.2 to work with You’ll discover that MySQL and memcached are where the mod_perl 2.0 data is stored, and Apache is the server that hosts this ● How to use mod_perl handlers to develop web applications, functionality. You’ll also examine each system while you learn including working with Ajax how to install, set up, and administer it. ● A sample search engine application that puts together the The book shows you how to put each of these systems various technologies discussed in the book together so you can start building successful applications. Helpful examples put in practice the information covered Who this book is for throughout the book and a problem-solving chapter offers This book is for developers who want to write applications using real-world problems and the process of how you might go MySQL, memcached, Apache, and Perl, and are interested in about finding a solution to them. improving the development process and efficiency. Developing

Wrox Professional guides are planned and written by working programmers to meet the real-world needs of programmers, developers, and IT professionals. Focused and relevant, they address the issues technology professionals face every day. They provide examples, practical solutions, and expert education in new technologies, all designed to help programmers do a better job. Web Applications ® , with Apache, MySQL®, memcached, and Perl www.wrox.com

Recommended Database Management ISBN: 978-0-470-41464-4 Computer Book Categories Web Applications Patrick Galbraith

$49.99 USA $59.99 CANADA Updates, source code, and Wrox technical support at www.wrox.com Galbraith cag.tex V2 - 06/02/2009 11:44am Page ii Galbraith cag.tex V2 - 06/02/2009 4:43pm Page i

Developing Web Applications with Perl, memcached, MySQL® and Apache

Foreword ...... xxv Introduction ...... xxvii Chapter 1: LAMMP, Now with an Extra M ...... 1 Chapter 2: MySQL...... 15 Chapter 3: Advanced MySQL ...... 85 Chapter 4: Perl Primer...... 163 Chapter 5: Object-Oriented Perl...... 211 Chapter 6: MySQL and Perl ...... 245 Chapter 7: Simple Database Application ...... 285 Chapter 8: memcached ...... 313 Chapter 9: libmemcached ...... 359 Chapter 10: Memcached Functions for MySQL ...... 383 Chapter 11: Apache ...... 417 Chapter 12: Contact List Application ...... 503 Chapter 13: mod_perl ...... 565 Chapter 14: Using mod_perl Handlers ...... 601 Chapter 15: More mod_perl ...... 633 Chapter 16: Perl and Ajax ...... 707 Chapter 17: Search Engine Application ...... 739 Appendix A: Installing MySQL ...... 793 Appendix B: Configuring MySQL ...... 811 Index...... 831 Galbraith cag.tex V2 - 06/02/2009 11:44am Page ii Galbraith ffirs.tex V3 - 06/03/2009 4:22pm Page iii

Developing Web Applications with Perl, memcached, MySQL® and Apache

Patrick Galbraith

Wiley Publishing, Inc. Galbraith ffirs.tex V3 - 06/03/2009 4:22pm Page iv

® Developing Web Applications with Perl, memcached, MySQL and Apache

Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com

Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada

ISBN: 978-0-470-41464-4

Manufactured in the United States of America 10987654321

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Library of Congress Control Number: 2009927343 Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. MySQL is a registered trademark of MySQL AB. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Galbraith ffirs.tex V3 - 06/03/2009 4:22pm Page v

To my wonderful wife, Ruth, whom I have known for 27 years and who has stood by me while writing this book, even when I couldn’t give her the time she deserved. Also, to my dear friend Krishna, who gave me inspiration every day. Galbraith fcre.tex V3 - 06/02/2009 11:44am Page vi

Credits Acquisitions Editor Vice President and Executive Group Jenny Watson Publisher Richard Swadley Project Editor Maureen Spears Vice President and Executive Publisher Barry Pruett Technical Editor John Bokma Associate Publisher Jim Minatel Production Editor Rebecca Coleman Project Coordinator, Cover Lynsey Stanford Copy Editor Sara E. Wilson Proofreader Corina Copp, Word One Editorial Manager Mary Beth Wakefield Indexer Robert Swanson Production Manager Tim Tate Galbraith fauth.tex V3 - 06/02/2009 11:46am Page vii

About the Author Patrick Galbraith lives up in the sticks of southwestern New Hampshire near Mt. Monadnock with his wife, Ruth. Since 1993, he has been using and developing open source software. He has worked on various open source projects, including MySQL, Federated storage engine, Memcached Functions for MySQL, Drizzle, and Slashcode, and is the maintainer of DBD::. He has worked at a number of companies throughout his career, including MySQL AB, Classmates.com, OSDN/Slashdot. He currently works for Lycos. He is also part owner of a wireless broadband company, Radius North, which provides Internet service to underserved rural areas of New Hampshire. His web site, which comes by way of a 5.8GHz Alvarion access unit up in a pine tree, is http://patg.net.

About the Technical Editor John Bokma is a self-employed Perl programmer and consultant from the Netherlands. He has been working professionally in software development since 1994, moving his primary focus more and more toward the Perl programming language. John and his wife, Esmeralda, currently live in the state of Veracruz, Mexico, with their daughter Alice. John’s other two children, Jim and Laurinda, live with their mother in New Zealand. For more information or to contact John, visit his web site at http://johnbokma.com/. Galbraith fauth.tex V3 - 06/02/2009 11:46am Page viii Galbraith fack.tex V3 - 06/02/2009 11:46am Page ix

Acknowledgments

One weekend in 1993, I had the chance to go on a getaway to San Diego. Instead, I opted to stay home and download, onto 26 floppies, Slackware , which I promptly installed onto my Packard Bell 386. I could never get the built-in video card to work with X, so I ended up buying a separate video card and had to edit my XConfig file to get it to work. How much more interesting this was to do than editing a config.sys and an autoexec.bat! From then on, I was hooked. I worked at Siemens Ultrasound Group in Issaquah, Washington, at the time. An engineer there named Debra, when asked what was a good thing to learn, said something I’ll never forget: ‘‘Learn Perl.’’ Debra — you were right!

I always wanted to be a ++ graphics programmer. That didn’t happen because of this thing called the World Wide Web. I remember Ray Jones and Randy Bentson of Celestial Software showing me a program called Mosaic, which allowed you to view text over the Internet. Images would be launched using XV. Everywhere I worked, I had to write programs that ran on the Web, which required me to write CGI in Perl. So much for my goal of being a C++ programmer — but I consider this a great trade for a great career. (I did eventually get to write C++ for MySQL!)

I would first like to thank my editor, Maureen Spears, who is not only a great editor, but also a friend. She gave me much-needed encouragement throughout the writing of this book.

A special thanks goes to John Bokma for his meticulous attention to detail and great knowledge of Perl — particularly with regard to Perl programming style and convention that I didn’t realize had changed over the last several years. I was somewhat set in my ways!

Thank you to Jenny Watson, who gave me the opportunity to write this book in the first place!

Thanks to Monty Widenius for creating MySQL and for being a mentor as well as a good friend, and thanks, Monty, for looking over Chapters 1, 2, and 3! Thanks also to for being another great mentor and friend, as well as being a software-producing machine with a scrolling page full of open source software projects that he’s created, including Drizzle and libmemcached. Thanks to Sheeri Kritzer for her encouragement and for listening to me — she finished her book not too long before I finished mine, so she understood completely what I was going through.

I’d like to thank my friend, Wes Moran, head of design for Sourceforge, for providing the nice, clean, simple HTML design I used for many of the examples in this book.

Thanks to Eric Day for his excellent input and review of chapters pertaining to Gearman.

A special thanks to Joaqu´ın Ruiz of Gear 6, who provided a lot of input on Chapter 1, as well as Jeff Freund of Clickability and Edwin Desouza and Jimmy Guerrero of Sun, who put me in touch with others and were great sources of memcached information.

I would like to thank my current colleagues at Lycos, and former colleagues at Grazr and MySQL, as well as the team members of Drizzle, for their part in my professional development, which gave me the ability to write this book. Thanks also to anyone I forgot to mention! Galbraith fack.tex V3 - 06/02/2009 11:46am Page x

Acknowledgments

Finally, I would like to thank the entire Open Source community. My life would not be the same without open source software.

There’s a verse in an ancient book, the Bhagavad Gita, that aptly describes how people like Monty Widenius, Linus Torvalds, Larry Wall, Brian Aker and other leaders within the Open Source community inspire the rest of us:

‘‘Whatever action a great man performs, common men follow. And whatever standards he sets by exemplary acts, all the world pursues.’’

x Galbraith ftoc.tex V2 - 06/02/2009 4:42pm Page xi

Contents

Foreword xxv Introduction xxvii

Chapter 1: LAMMP, Now with an Extra M 1 Linux 2 Apache 3 MySQL 4 memcached 5 Gear6 6 Clickability 6 GaiaOnline 7 How memcached Can Work for You 7 Perl 8 Other Technologies 10 Sphinx 10 Gearman 11 The New Picture 11 The Future of Open-Source Web Development and Databases 12 Projects to Watch! 13 Summary 13 Chapter 2: MySQL 15 How CGI and PHP Changed the Web Dramatically 15 About MySQL 16 MySQL Programs 19 Client Programs 20 Utility Programs 25 MySQL Daemon and Startup Utilities 27 Working with Data 28 Creating a Schema and Tables 29 Inserting Data 35 Querying Data 38 Updating Data 50 Deleting Data 52 Galbraith ftoc.tex V2 - 06/02/2009 4:42pm Page xii

Contents

Replacing Data 56 INSERT ... ON DUPLICATE KEY UPDATE 57 Operators 58 Functions 59 Using Help 70 User-Defined Variables in MySQL 72 MySQL Privileges 74 MySQL Access Control Privilege System 75 MySQL Global System User 75 MySQL System Schema Grant Tables 76 Account Management 80 Summary 84 Chapter 3: Advanced MySQL 85 SQL Features 85 Stored Procedures and Functions 86 Triggers 94 Views 102 User Defined Functions 105 Storage Engines 111 Commonly Used Storage Engines 112 Storage Engine Abilities 113 Using Storage Engines 113 MyISAM 115 InnoDB 118 Archive 123 The Federated Storage Engine 125 Tina/CSV Storage Engine 130 Blackhole Storage Engine 132 Replication 133 Replication Overview 133 Replication schemes 134 Replication Command Options 137 Setting Up Replication 139 Searching Text 148 When to Use Sphinx 161 Summary 162 Chapter 4: Perl Primer 163 What Exactly Is Perl? 163 Perl Primer 165 xii Galbraith ftoc.tex V2 - 06/02/2009 4:42pm Page xiii

Contents

Perl Data Types 165 Scalars 165 Arrays 167 Hashes 167 File Handles 168 Type Globs 168 Subroutines 168 Variable Usage 168 References 169 Scalar Usage 173 Array Usage and Iteration 174 Working with Hashes 179 Writing to Files 184 STDOUT and STDERR 184 File Handles to Processes 185 Subroutines 186 Variable Scope 189 Packages 192 Perl Modules 193 Writing a Perl Module 194 @ISA array 197 Documenting Your Module 197 Making Your Module Installable 201 Testing 201 Adding a MANIFEST file 204 CPAN 205 Regex One-Liners 206 Storing Regular Expressions in Variables 207 Regex Optimizations 208 Perl 6 Tidbits 208 Summary 210

Chapter 5: Object-Oriented Perl 211 About Object Orientation 212 Object Orientation in Perl 213 Writing a Perl Class 213 Adding Methods 217 On-Demand Method Manifestation Using AUTOLOAD 221 Other Methods 231 Making Life Easier: Moose 240 Summary 244

xiii