Hello monks!
I want to be able to read content from the __DATA__ block in a file from within a BEGIN { } block or a packages 'import' function. Is this something that is possible?
I do a lot of testing against databases, and recently I wrote a module that allows my to easily install and remove database tables from within my test code. Take this for example:
use Test::More 'no_plan';
use Gi::Testing::TestDB;
my $testdb = Gi::Testing::TestDB->new(
[qw/DBI:mysql:database:address:3306 tester password/],
*main::DATA
);
$testdb->install;
# perform tests
$dbh = $testdb->dbh;
END {
$testdb->uninstall;
}
__DATA__
CREATE TABLE TestObject (
identifier INT(10) NOT NULL PRIMARY KEY,
name VARCHAR(50),
attribute VARCHAR(50)
);
That does what I want and all, but not as elegantly as I would like. I just want to stick
use Gi::Testing::TestDB
DataSource => [qw/DBI:mysql:database:address:3306 tester password/
+],
Schema => *main::DATA;
at the top of my file and be done with it. Later in the tests, when I want to access my dbh, I just say
my $dbh = Gi::Testing::TestDB->dbh;
So I made Gi::Testing::TestDB a singleton. I have provided my own import method, so that when the user calls
use Gi::Testing::TestDB with parameters - the singleton is constructed and the schema is executed against the database connection. When the singleton is destroyed, it will delete all the tables it created.
The problem I am running into with this approach is that the content in *main::DATA is not an open file-handle from within the import method or if you call it from within a BEGIN block.
Here is the error message:
tell() on unopened filehandle DATA at C:/camelbox/site/lib/Gi/Installe
+r/Database
/Schema.pm line 125.
readline() on unopened filehandle DATA at C:/camelbox/site/lib/Gi/Inst
+aller/Data
base/Schema.pm line 126.
seek() on unopened filehandle DATA at C:/camelbox/site/lib/Gi/Installe
+r/Database
/Schema.pm line 127.
could not read any data from file handle - the file is empty or you ar
+e at the e
nd of the file at C:/camelbox/site/lib/Gi/Installer/Database.pm line
+20
Does anybody have any suggestions on how to get around this? I really want the schema information in the __DATA__ section of the test script, so all the test information is contained within one file - as opposed to a test script file and schema information file.
One option I have thought about is requiring that
Gi::Testing::TestDBI->install be called from within the script - and not parsing the file handle until install was called - which would happen at execution time when the <DATA> file handle is valid. But I really want to keep it to just the singular 'use' statement.
Thanks for the help!