Integrating Perl and Databases Making simple things easy
Upcoming SlideShare
Loading in...5
×
 

Integrating Perl and Databases Making simple things easy

on

  • 985 views

 

Statistics

Views

Total Views
985
Views on SlideShare
985
Embed Views
0

Actions

Likes
0
Downloads
4
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Why? Why are you here? Why are so many developers and companies using Perl? Why Perl?
  • I’m sure other speakers are giving their reasons. These are some of mine: If I had top give one reason: Fewer lines of code. Higher level language => less code => less errors (Mythical Man Month) => Consider “A picture is worth a thousand words” - rich in powerful idioms (compact but not so terse as to be unreadable later - like APL) vs “Can’t see the wood for the trees” - in other languages like C. “ No limits” - often hard to do in other languages where much more care/effort id required Exception handling - simplifies logic - less code - less errors Rapid prototyping Rapid response to change - simply less code to maintain Many free reusable modules Perl is an approriate language for a very wide range of tasks. Learning Perl often avoids the need to learn one or more other tools.
  • => most data and database related software does one or more of these. Commercial tools for these tend to lack the flexibility of Perl (in breadth and depth). You can find yourself wasting time working around the limitations of blunt commercial tools.
  • Very few lines of code. Just about every line directly related to the task. Not the best code in the world but it gets the job done. (The split could be replaced with two lines of code to do the right thing with quoted fields and embedded commas, for example.)
  • Here we use perl’s built-in formatting mechanism to define the top of page headers and the layout and formatting of the body rows. Again: very few lines of code and just about every line directly related to the task.
  • Here we read each line from the costs text file, skip lines that don't start with digits, extract the product and cost, apply the margin (or a default), apply the note (or a default), and write the output. Again: very few lines of code and just about every line directly related to the task.
  • The company grows and now stocks thousands of products. To save time the derived price for each product can be saved in a simple DBM' database (support for which is built into perl) and made available to other perl programs. Just two additional lines of code is all that's needed. (A similar pair of lines is all that's needed to read the data.)
  • Here we add just 8 lines to store the prices in the database. The code not only updates prices for products already in the database but also inserts new records for any products not in the database.
  • Here we have changed just 4 lines to fetch the costs from the database.
  • Once upon a time: Perl4: oraperl, ingperl, uniperl, fooperl Ted Lemon: “Wouldn’t it be nice if” - Sept 29th 1992 Applications portable between databases Skills portable between databases! A vision of the future - Talk, talk, talk- the dbperl-interest mailing list Buzz Moschetti, Kevin Stock, Kurt Andersen, Ted Lemon June 93: Kevin and Kurt changed jobs and left the list. 30 people on the list. I took the lead at that point. Jan 1994: Dbperl spec is progressing and Perl 5 appears on the horizon June 1994: Perl 5 alpha releases becoming stable. Almost 200 people on list. Prototype pure-perl ‘testbed’ released for experimentation. Sept 1994 (Two years and 600 messages - 2MB - later...): Renamed to DBI and DBD. First release of the DBI (with a pure-perl driver) The future is now: continuous development interface stabilizing and more fully documented
  • Similar in concept to an ODBC Driver Manager DBI provided methods, functions and tools etc help ensure conformant implementations and efficient implementations and more automatic support for new features
  • Porting All Unix variants - (not heard of any it won’t build on) Windows 95, Windows NT, VMS Builds out-of-the-box Drivers ODBC, Oracle, Informix, DB2, Ingres, Solid, … enhancements to the DBI (inc. docs) will make it easier ODBC/JDBC Standard ways of specifying (data types, meta-data, options etc) and ways of doing The DBI won’t re-invent these wheels - but may make them easier to steer! (by offering higher-level interfaces to them). First is data types and meta-data Specifying the unspecified Documenting features once they’ve stabilized such as placeholders and bind variables
  • No particular order or time-scale! Generic standards-based SQL92 Parser (in C) supplied with the DBI but not tied closely to it. Available for use by any module. SQL interfaces could appear on all sorts of modules. Outputs a parse tree as a perl recursive data structure. A DBD::Proxy to ‘forward’ method calls and arguments across a network to any normal driver on a remote machine and return results A DBD::Pipe to act as a virtual base class to simplify the development of drivers for data sources that don’t offer a programming interface/API. Data types: date/time/interval - returned as a ref with ““ overloaded. Define interface for non-blocking: $dbh->{NonBlock}, $h->done Initially Oracle and ODBC drivers. Only if database API supports it. Make any changes required to support Threading in DB (if any) Individual drivers may need to declare themselves ‘thread-safe’ If needed the DBI may block multi-threads from entering same driver. Binding output parameters, typically for stored procedures. Binding Arrays - especially Oracle
  • Native API’s will generally offer the most power, e.g., Oracle OCI. But take a lot of effort to learn and use. Knowledge is rarely portable to other APIs Generic application language interfaces: ODBC and JDBC . Still lots of effort to learn Knowledge is portable to other APIs Power is dependant on quality of ODBC driver Pre-compilers for C (where SQL is embedded in C and ‘precompiled’) Simpler than a raw C API but typically less power. Hard to debug. Command line access - Just type it in! Generate SQL from scripts etc. Not robust - hard to check for and respond to errors Script Languages TCL (oratcl, sybtcl) generally much slower. Binary data hard. Win32::ODBC - a bottom-up approach - thin layer over raw ODBC calls. DBI is higher level but DBD::ODBC doesn’t yet have the same breadth of ODBC specific functionality. Recommended for existing users and people who need that degree of control. DBI+DBD::ODBC can run over twice as fast as Win32::ODBC. Sybase - and other database specific perl extensions Can gain some performance advantage if well written but loose out on the DBI extras: portable apps & knowledge, tools, subclasses etc.
  • It delivers what it promises It works! It’s here, there and everywhere Portable and widely ported It’s fast, flexible and well proven Thousands of users It’s free, with source on the same terms as Perl itself Commercial support is available From www.perlclinic.com or www.ig.co.uk It has a large user base and a strong future
  • So What? What’s in it for you? Simply: Greater success, faster and for less effort.
  • To show that the value of Integrating Perl and Databases isn’t all hot air and hype I offer you three Success stories from commercial users. (The British Telecom CMI service is described in detail in the Perl Conference handouts.)

Integrating Perl and Databases Making simple things easy Integrating Perl and Databases Making simple things easy Presentation Transcript

  • Integrating Perl and Databases Making simple things easy and difficult things possible Tim Bunce August 1997
  • Why?
  • Why Perl?
    • Fewer lines of code
      • faster development / fewer errors / easier maintenance
    • “ A picture is worth a thousand words” vs “Can’t see the wood for the trees”
    • Freedom of expression - “There’s more than one way to do it”
    • The tool builders tool factory
  • Why Perl for Databases?
    • Ideally suited to data processing :
      • parsing , cleansing / filtering / merging and formatting
    • Applications
      • Data Migration
      • Data acquisition and reporting
      • Web Page creation
    • Building sharper tools faster
  • Your Mission... should you choose to accept it...
  • The Task
    • Read a tabular text report file of product codes and costs
    • CODE DESCRIPTION COST OTHER NOTES
    • ---- ----------- ------ -------------------
    • 1201 WIDGET 37A 500.00 LEFT HANDED ONLY
    • 1202 BRACKET X7J 790.00 REDUCED FROM 800.00
    • 1203 FLANGE 9Q7 449.00 LIMITED STOCK
    • Read a CSV file of product codes, price markup and comments
    • 1201,0.90,Special Offer for limited period only
    • 1202,1.30,
    • Output a new tabular report containing the new product prices and comments word wrapped in a narrow field
  • Reading the CSV file
    • open MARGIN, “<margin.csv” or die “open margin.csv: $!”;
    • while (<MARGIN>) {
    • chop;
    • ($prod, $margin, $notes) = split /,/;
    • $prod_margin{$prod} = $margin;
    • $prod_notes{$prod} = $notes;
    • }
  • Defining the Output Format
    • format STDOUT_TOP =
    • Code Price Notes
    • ---- ------- --------
    • .
    • format STDOUT =
    • @>>> ^###.## ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    • $prod, $cost, $note
    • ~~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    • $note
    • .
  • Writing the New Report
    • open COST, &quot;<cost.txt&quot; or die &quot;open cost.txt: $!&quot;;
    • while ($line = <COST>) {
    • next unless $line =~ m/^d/;
    • ($prod, $cost) = unpack 'A4 @20 A7', $line;
    • $cost *= $prod_margin{$prod} || 1.10;
    • $note = $prod_notes{$prod} || 'n/a';
    • write; # using format with $prod, $cost and $note
    • }
  • Mission Accomplished!
    • Code Price Notes
    • ---- ------- --------
    • 1201 450.00 Special offer for limited
    • period only
    • 1202 1027.00 n/a
    • 1203 493.90 n/a
  • Change is the only Constant Your new mission...
  • “Cache the data for other uses!”
    • dbmopen(%price_cache, &quot;price_cache&quot;, 0644) or die …;
    • while ($line = <COST>) {
    • . . .
    • write; # using format with $prod, $cost and $note
    • $price_cache{$prod} = &quot;$cost $note&quot;;
    • }
  • “Update the Prices in a Database!”
    • use DBI;
    • $db = DBI->connect('dbi:ODBC:PRICE', 'user', 'password',
    • { RaiseError => 1 });
    • $upd = $db->prepare('UPDATE prices SET price=? WHERE prod=?');
    • $ins = $db->prepare('INSERT INTO prices(prod,price) VALUES (?,?)');
    • while ($line = <COST>) {
    • . . .
    • $rows = $upd->execute($price, $prod);
    • $ins->execute($prod,$price) if $rows == 0;
    • }
    • $db->commit;
  • “ Now get Cost Data from a Database!”
    • Original Code
    • open COST, &quot;<cost.txt&quot; or die &quot;open cost.txt: $!&quot;;
    • while ($line = <COST>) {
    • next unless $line =~ m/^d/;
    • ($prod, $cost) = unpack 'A4 @20 A7', $line;
    • . . .
    • New Code
    • $costs = $cost_db->prepare('SELECT prod,cost FROM costs');
    • $costs->execute;
    • while ( ($prod, $cost) = $costs->fetchrow_array ) {
    • . . .
  • What Is the Perl DBI?
    • The standard Database Interface for Perl
    • “A perl module and specification that defines a consistent database interface independent of the actual database being used”
  • Why the Perl DBI?
    • Once upon a time…
      • One language, many database interfaces
    • A vision of the future... “DBperl”
      • Talk, talk, talk - the dbperl-interest mailing list
    • Perl 5 - A new way
      • Modules and Objects. The DBI is born.
    • The future is now…
      • ODBC, Oracle, Informix, Ingres, mSQL, mysql, DB2, Solid, Sybase , Postgress , Quickbase , Empress , Fulcrum, ...
  • Making simple things easy and difficult things possible
    • Goals
      • Be simple to use for simple applications
      • Have sufficient flexibility to accommodate unusual functionality and non-SQL databases
      • Conform to applicable standards (ODBC etc.)
      • Enable the creation of database-independent Perl scripts without being limited to the lowest functionality
      • Be free.
    • A ‘higher-level’ interface than ODBC/JDBC
  • Getting Technical... for the techies...
  • Under the Hood
    • DBI defines and implements an interface
    • Driver modules do much of the real work
    • DBI provides default methods, functions, tools etc for drivers
    • Not limited to the lowest common denominator - mechanism provided for driver specific extensions
    • Designed and built for speed
    • Valuable detailed call tracing/debugging built-in
  • A Picture is Worth... DBI Module Perl Application DBD:: Other DBD::Informix DBD::Oracle Oracle Server Informix Server Other Server
  • State of the Nation
    • DBI builds and runs on many systems
      • Unix, Windows 95, Windows NT, VMS etc
    • Many drivers exist
      • more in development
    • Merging the ODBC/JDBC ‘inheritance’
      • data types, meta-data etc
    • Specifying the unspecified
      • Documenting the undocumented
  • What Next?
    • SQL for Non-SQL data sources
    • Networking for Non-Networked data sources
    • Template driver for command line interfaces
    • Data types, especially date/time/interval
    • Non-blocking (method calls return at once)
    • Multi-threading
    • Binding In/Out Variables
    • Binding Arrays
  • Comparing DBI and Alternatives (Attempting the Impossible!) “ Power” “ Effort” Command Line Native API ODBC/ JDBC and drivers DBI and Drivers Precompilers Win32::ODBC TCL (oratcl, sybtcl) Please note: This chart is correct only for some values of correct ! Sybase::DBlib
  • So why use the Perl DBI?
    • Because...
      • It delivers what it promises
      • It’s here, there and everywhere
      • It’s fast, flexible and well proven
      • It’s free, with source
      • Commercial support is available
      • It has a large user base and a strong future
  • So What?
  • Success Stories in Industry
    • Large Scale Data Migration
        • by Michael Peppler
    • Database Interfaced Web Pages
        • by Frank San Filippo
    • The British Telecom Call Management Information Service
        • by Tim Bunce
  • Too Good to Be True?
    • Just three examples of many
    • Thousands of Perl DBI developers around the world
    • Millions of users of DBI powered web sites
    • Oracle and Apache web servers with built-in Perl and DBI
    • Commercial support available from The Perl Clinic
  • And finally...
    • “ We have replaced all Netscape JavaScript code with Perl DBI/DBD to Informix” - Del Simmons, Cox Interactive Media.
    • “ I have found performance and stability to be exceptional” - Stuart Huges, PECC.
    • “ Perl and DBI saved our butt. The tool we came closest to purchasing was SQR but it just doesn’t have the flexibility and power of Perl/DBI.” - Jared Still, RxNet.
    • “ I have been able to recommend the Perl/DBI route to a number of our clients and all of them have been pleased with the results” - Paul Rubenis, Ulysses Telemedia Networks
  • The end. Till next year...