Add-db

From Organic Design wiki
Revision as of 11:52, 25 August 2007 by Nad (talk | contribs) (take a bit of the manual labour out of replicating a template many times)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
  1. !/usr/bin/perl
  2. - Licenced under LGPL (http://www.gnu.org/copyleft/lesser.html)Our Perl scripts.
  1. - Author: http://www.organicdesign.co.nz/nad
  2. - Started: 2007-08-25

$user = 'dbuser'; $pwd = 'dbpasswd'; $tmp = '/tmp/replicate-db';

  1. Display usage info and die if too few or no parameters supplied

die " Replicate a mediawiki SQL database dump to many databases and prefixes. - The database dump being used as a template should only contain one wiki. - It should not include create or drop database statements. - The destination databases must already exist - The destination tables will be replaced if they exist

Usage: replicate-db TEMPLATE DB1.PREFIX1 [DB2.]PREFIX2 [DB3.]PREFIX3... Where, TEMPLATE is the name of the SQL dump file to use as the template.

DB*.PREFIX* are the databases to replicate the template into and the table prefixes to use (prefixes are mandatory). The DB part is optional for all but the first and means to continue using the previous database. " unless $#ARGV > 0 and $ARGV[1] =~ /^\w+\.\w+$/;

  1. Read in the template file

$file = shift @ARGV; if (open FH,'<',$file) { sysread FH,$template,-s $file; close FH; } else { die " Could not read template file '$file' " }

  1. Find the prefix (if any) being used in the template and prepare for use in replacement regexp

die " The template file supplied is not a valid wiki dump " unless $template =~ /^CREATE TABLE `(\w*)recentchanges`/m; $prefix = qr($1);

  1. Main replication loop

for (@$ARGV) {

# Determine the database and prefix to replicate template into if (/^(\w+)\.(\w+)$/) { ($db,$pre) = ($1,$2) } else { $pre = $_ } $pre .= '_' unless $pre =~ /_$/;

# Make a duplicate of the template modified to the current prefix $data = $template; $data =~ s/$prefix/$pre/g;

# Write the duplicate into a tmp file if (open FH,'>',$tmp) { print FH $data; close FH } else { print "Could not write data for wiki $db.$pre to '$tmp'\n" }

# Pipe the file into MySQL and remove the tmp file qx(mysql -u $user -p $pwd < $tmp); if ($!) { print "Error creating wiki $db.$pre: $!\n" } else { print "Wiki $db.$pre created.\n" } unlink $tmp; }