Search code examples
perlperl-moduleperl-data-structures

Is there a Perl module for accessing complex structure data with SQL language?


I often save a lot of data into a hash var, or get data according to the conditions. It is not convenient, so i want a module with which accessing data with SQL as a NoSQL. I found DBD::RAM, but is there a smaller module?

For example: a hash data like a MySQL table:

{
   "table": "company",
   "rows" : [
       {
         "name": "baidu",
         "location": "China"
       },
       {
         "name": "taobao",
         "location": "China"
       }
    ]
}

In general, inserting a record like this:

my %new_row = (name=>xxx, location=>yyy);
push (@{$hash->{rows}}, \%new_row);

If I do that, there will be a lot of hash variable, so I want to do it more like this:

$handle->insert('insert into company values("xxx", "yyy")');

my ($name, $location) = $handle->select_unqiue_record(<<"_EOC_";
    select name, location from company where name="baidu"
_EOC_);

Solution

  • I recommend https://metacpan.org/module/DBIx::DataModel.

    Once you setup a Schema describing your target table - and you can do this automatically by reverse engineering - you can insert your hash directly like this:

    my $table = $schema->table($table_name);
    my $id = $table->insert($hash_ref);
    

    In fact you can pass DBIx::DataModel an array of hash_refs (as per your question) and it will insert each of these for you. See the documentation at: https://metacpan.org/module/DBIx::DataModel#Insert