Alister West

home is where your code is ...

GLinks

Various glinks helpers.

Create GLinks Categories

# create-categories.pl
use FindBin qw/$Bin/;
use lib "$Bin/../admin";
use Links;
use GT::SQL;
Links::init("$Bin/../admin");
Links::init_admin();

my @categories = ( 'Foo/Bar/Baz', 'Foo/Bar/Awesomeness/Yeah', 'Pie' );
Links::Category::Custom::create_category( $_ ) for @categories;



package Links::Category::Custom;
sub create_category {
# -------------------------------------------------
    my $category = shift;

    $category =~ s{^/}{};
    my @parts = split '/', $category;

    my ($father_id,$root_id,$depth,$full_name) = (0,0,0,'');

    foreach my $cat_name (@parts) {

        $full_name = $full_name ? "$full_name/$cat_name" : $cat_name;
        my $category = $DB->table('Category')->select('ID', { Full_Name => $full_name });

        my $cat_id;
        if ($category->rows) {
            $cat_id = $category->fetchrow_arrayref->[0];
            print "exists: $cat_id -- $full_name\n";
        }
        else {
            $cat_id = $DB->table('Category')->add({
                Name => $cat_name, FatherID => $father_id, CatRoot => $root_id, CatDepth => $depth, Full_Name => $full_name
            });
            print "added: $cat_id -- $full_name\n";
        }
        $root_id ||= $cat_id;
        $father_id = $cat_id;
        $depth++;
        die $GT::SQL::error unless $cat_id;
    }
}

GLinks Create or Update Pattern

package GT::SQL;
use Carp qw/croak/;

sub create_or_update {

    my ( $table_name, $fields, $hash ) = @_;
    my $table = $DB->table($table_name);

    # Check inputs.
    croak 'Error: arg_1 must be an ARRAYREF' unless ref $fields eq 'ARRAY';
    croak 'Error: arg_2 must be an HASHREF'  unless ref $hash   eq 'HASH';
    foreach (@$fields) {
        croak "Error: key $_ isnot in " . Dumper($hash) . "\n"
          unless defined $hash->{$_};
    }

    # Primary Key
    my %pk = map { $_, $hash->{$_} } @$fields;

    # Create
    #
    if ( 0 == $tbl->count( \%pk ) ) {
        my $id = $tbl->add($hash) or croak 'Error: No record added';
    }

    # Update
    #
    elsif ( 1 == $tbl->count( \%pk ) ) {

        # Common 'create' fields we don't want to override.
        delete $hash->{created};
        delete $hash->{Add_Date};
        $tbl->update( $hash, \%pk ) or croak 'Error: Couldn\'t update record';
    }

    else {
        die "Error: Multiple values found with Primary Key lookup";
    }

    # Return the record as a hash
    my $rec = $tbl->select( \%pk )->fetchrow_hashref;
    return $rec;
}
By Alister West