File: xml2sql.pl

package info (click to toggle)
libdbix-xml-rdb-perl 0.05-13
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 92 kB
  • sloc: perl: 319; makefile: 6
file content (240 lines) | stat: -rwxr-xr-x 5,394 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/perl -w

package XMLDBI;
use DBI qw/:sql_types/;
use XML::Parser;

use vars qw(@ISA @EXPORT $table $dbh $sth @col_vals);

@ISA= ("XML::Parser");

sub IsNumber {
	my ($value) = @_;

	return ($value =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/); # Regexp taken from the perlfaq4
}

sub new {
	my($proto) = shift @_;
	my($class) = ref($proto) || $proto;
	my($self) = $class->SUPER::new(@_);

	my $driver = shift;
	my $datasource = shift;
	my $userid = shift;
	my $passwd = shift;
	$table = shift; # Not sure if we want to limit to individual tables yet
	my $dbname = shift;

	bless($self, $class);
	$self->setHandlers('Start' => $self->can('Start'),
						'Init' => $self->can('Init'),
						'End'  => $self->can('End'),
						'Char' => $self->can('Char'),
						'Proc' => $self->can('Proc'),
						'Final' =>$self->can('Final'),
						);

	# Setup the DB Connection

	$dbh = DBI->connect("dbi:$driver:$datasource", $userid, $passwd) or die "Can't connect to datasource";
	if ($dbname) {
		$dbh->do("use $dbname") || die $dbh->errstr;
	}

	return($self);
}

sub execute {
	my ($self, $sql) = @_;
	$dbh->do($sql);
}

sub Init {
	my $expat = shift;

	# OK, here we setup the insert statement.
	# We use the prepare method because it offers us _very_ fast inserts.

	$sth = $dbh->prepare("select * from $table where 1=2") || die $dbh->errstr;
	$sth->execute() || die $dbh->errstr; # Get column names
	my $names = $sth->{NAME};

	my $sql = "insert into $table ( " . (join ", ", @$names) . " ) values ( ";
	my $colnum = 1;
	eval {
		$sql .= (join ", ",
					(map {
							$expat->{ __PACKAGE__ . "columns"}->{uc($_)} = $colnum++;
							'?';
						} @{$names})
				);
		};
	if ($@) {
		die $@;
	}

	$sql .= " )";
#	print $sql, "\n\n";
	$sth = $dbh->prepare($sql) || die;

#	my $count = 1;
#	foreach my $f (keys(%{$expat->{ __PACKAGE__ . "columns"}})) {
#		$sth->bind_param( $count++ , undef );
#	}

	# Possibly add begin transaction code here.
}

sub Start {
	my ($expat, $element, %attrs) = @_;
	# Structure goes: DSN->Table->Column
	if ($expat->within_element("ROW")) {
		# OK, got a column, reset the data within that column
		undef $expat->{ __PACKAGE__ . "currentData"};
	}
}

sub End {
	my ($expat, $element) = @_;
	if ($element eq "ROW") {

		# Found the end of a row
		print "Inserting a row...\n";
                shift @col_vals;

                #kip: handy for debugging.
                #DBI->trace(5);
		#print "colvals are @col_vals\n";

		$sth->execute(@col_vals) || die;
	        @col_vals = ();

                # kip:
		# the following is no longer needed but I'll leave it just in case I'm wrong.
		# Re-bind to undef (makes sure things are NULL)
		#my $count = 1;
		#foreach my $f (keys(%{$expat->{ __PACKAGE__ . "columns"}})) {
		#	$sth->bind_param( $count++ , undef );
		#}
	}
	elsif ($expat->within_element("ROW")) {
		$element = uc($element);
		return unless $expat->{ __PACKAGE__ . "columns"}->{$element};
                $col_vals[$expat->{ __PACKAGE__ . "columns"}->{$element}] = 
                  $expat->{ __PACKAGE__. "currentData"};
	}
}

sub Char {
	my ($expat, $string) = @_;
	# The only Char is the data. (AFAIK) Otherwise this will break (sorry!)
	my @context = $expat->context;
	my $column = pop @context;
	my $curtable = pop @context;

	if (($curtable) && ($curtable eq "ROW")) {
		$expat->{ __PACKAGE__ . "currentData"} .= $string;
	}
}

sub Proc {
    my $expat = shift;
    my $target = shift;
    my $text = shift;
}

sub Final {
    my $expat = shift;

	# Possibly put commit code here.
}

1;
#########################################################################################

package main;
use strict;
use Getopt::Long;
use vars qw($datasource $userid $password $table $inputfile $help
			$dbname $verbose $truncate $driver);

sub usage;
sub quote;
sub IsNumber;

# Options to variables mapping
my %optctl = (
	'sn' => \$datasource,
	'uid' => \$userid,
	'pwd' => \$password,
	'table' => \$table,
	'input' => \$inputfile,
	'help' => \$help,
	'db' => \$dbname,
	'verbose' => \$verbose,
	'x' => \$truncate,
	'driver' => \$driver,
	);

# Option types
my @options = (
			"sn=s",
			"uid=s",
			"pwd=s",
			"table=s",
			"input=s",
			"db=s",
			"driver=s",
			"help",
			"verbose",
			"x"
			);

GetOptions(\%optctl, @options) || die "Get Options Failed";

usage if $help;

unless ($datasource and $userid and $table and $inputfile) {
	usage;
}

$driver = $driver || "ODBC"; # ODBC is the default driver. Change this if you want.

my $xmldb = XMLDBI->new($driver, $datasource, $userid, $password, $table, $dbname);

if ($truncate) {
	$xmldb->execute("DELETE FROM $table");
}

open(FILE, $inputfile) or die $!;
my $file = join "", <FILE>;

$xmldb->parsestring($file);

# End

####################################################################
### subs ###

sub usage {
	print <<EOF;
Usage:
    xls2sql.pl {Options}

    where options are:

        Option   ParamName     ParamDesc
        -sn      servername    Data source name
		[-driver dbi_driver]   Driver that DBI uses. Defaults to ODBC
        -uid     username      Username
        -pwd     password      Password
        -table   tablename     Table to extract
        -input   inputfile     File to get input from (excel file)
        [-x]                   Delete from table first
        [-db     dbname]       Sybase database name
        [-v or --verbose]      Verbose output
EOF
	exit;
}