The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

FWS::V2::Database - Framework Sites version 2 data management

VERSION

Version 0.005

SYNOPSIS

        use FWS::V2;

        #
        # Create FWS with MySQL connectivity
        #
        my $fws = FWS::V2->new(       DBName          => "theDBName",
                                      DBUser          => "myUser",
                                      DBPassword      => "myPass");

        #
        # create FWS with SQLite connectivity
        #
        my $fws2 = FWS::V2->new(      DBType          => "SQLite",
                                      DBName          => "/home/user/your.db");

DESCRIPTION

Framework Sites version 2 common methods that connect, read, write, reorder or alter the database itself.

METHODS

addExtraHash

In FWS database tables there is a field named extra_value. This field holds a hash that is to be appended to the return hash of the record it belongs to.

        #
        # If we have an extra_value field and a real hash lets combine them together
        #
        %dataHash = $fws->addExtraHash($extra_value,%dataHash);

Note: If anything but stored extra_value strings are passed, the method will throw an error

adminUserArray

Return an array of the admin users. The hash array will contain name, userId, and guid.

        #
        # get a reference to the hash array
        #
        my $dataArrayRef = $fws->adminUserArray(ref=>1);

adminUserHash

Return an array of the admin users. The hash array will contain name, userId, and guid.

        #
        # get a reference to the hash
        #
        my $dataHashRef = $fws->adminUserHash(guid=>'someGUIDOfAnAdminUser',ref=>1);

alterTable

It is not recommended you would use the alterTable method outside of its intended core database creation and maintenance routines but is here for completeness. Some of the internal table definitions alter data based on its context and will be unpredictable. For work with table structures not directly tied to the FWS 2 core schema, use FWS::Lite in a non web rendered script.

        #
        # retrieve a reference to an array of data we asked for
        #
        # Note: It is not recommended to change the data structure of
        # FWS default tables
        #
        print $fws->alterTable( table   =>"table_name",         # case sensitive table name
                                field   =>"field_name",         # case sensitive field name
                                type    =>"char(255)",          # Any standard cross platform type
                                key     =>"",                   # MUL, PRIMARY KEY, FULL TEXT
                                default =>"");                  # '0000-00-00', 1, 'this default value'...

connectDBH

Do the initial database connection via MySQL or SQLite. This method will return back the DBH it creates, but it is only here for completeness and would normally never be used. For FWS database routines this is not required as it will be implied when executing those methods.

        $fws->connectDBH();

If you want to pass DBType, DBName, DBHost, DBUser, and DBPassword as a hash, the global FWS DBH will not be passed, and the DBH it creates will be returned from the method.

dataArray

Retrieve a hash array based on any combination of keywords, type, guid, or tags

        my @dataArray = $fws->dataArray(guid=>$someParentGUID);
        for my $i (0 .. $#dataArray) {
                $valueHash{'html'} .= $dataArray[$i]{'name'}."<br/>";
        }

Any combination of the following parameters will restrict the results. At least one is required.

  • guid: Retrieve any element whose parent element is the guid

  • keywords: A space delimited list of keywords to search for

  • tags: A comma delimited list of element tags to search for

  • type: Match any element which this exact type

  • containerId: Pull the data from the data container

  • childGUID: Retrieve any element whose child element is the guid (This option can not be used with keywords attribute)

  • showAll: Show active and inactive records. By default only active records will show

Note: guid and containerId cannot be used at the same time, as they both specify the parent your pulling the array from

dataHash

Retrieve a hash or hash reference for a data matching the passed guid. This can only be used after setSiteValues() because it required $fws->{'siteGUID'} to be defined.

        #
        # get the hash itself
        #
        my %dataHash    = $fws->dataHash(guid=>'someguidsomeguidsomeguid');
       
        #
        # get a reference to the hash
        # 
        my $dataHashRef = $fws->dataHash(guid=>'someguidsomeguidsomeguid',ref=>1);

deleteData

Delete something from the data table. %dataHash must contain guid and either containerId or parent. By passing noOrphanDelete with a value of 1, any data ophaned from the act of this delete will also be deleted.

        my %dataHash;
        $dataHash{'noOrphanDelete'}     = '0';
        $dataHash{'guid'}               = 'someguid123123123';
        $dataHash{'parent'}             = 'someparentguid';
        my %dataHash $fws->deleteData(%dataHash);

deleteQueue

Delete from the message and process queue

        my %queueHash;
        $queueHash{'guid'}               = 'someQueueGUID';
        my %queueHash $fws->deleteData(%queueHash);

elementHash

Return the hash for an element from cache, plugin for element database

exportCSV

Return a hash array in a csv format.

        my $csv = $fws->exportCSV(dataArray=>[@someArray]);

flushSearchCache

Delete all cached data and rebuild it from scratch. Will return the number of records it optimized. If no siteGUID was passed then the one from the current site being rendered is used

        print $fws->flushSearchCache($fws->{'siteGUID'});

fwsGUID

Retrieve the GUID for the fws site. If it does not yet exist, make a new one.

        print $fws->fwsGUID();

gatewayPassword

Retrieve the payment gateway password

        my $gatewayPass =  $fws->gatewayPassword();

getSiteGUID

Get the site GUID for a site by passing the SID of that site. If the SID does not exist it will return an empty string.

        print $fws->getSiteGUID('somesite');

getPageGUID

Get the GUID for a site by passing a guid of an item on a page. If the guid is referenced in more than one place, the page it will be passed could be random.

        my $pageGUID =  $fws->getPageGUID($valueHash{'elementId'},10);

Note: This procedure is very database extensive and should be used lightly. The default depth to look before giving up is 5, the example above shows searching for 10 depth before giving up.

newDBCheck

Do a new database check and then create the base records for a new install of FWS if the database doesn't have an admin record. The return is the HTML that would render for a browser to let them know what just happened.

queueArray

Return a hash array of the current items in the processing queue.

queueHash

Return a hash or reference to the a queue hash.

queueHistoryArray

Return a hash array of the history items from the processing queue.

Parmeters to constrain data:

  • limit

    Maximum number of records to return.

  • email

    Only items that were sent to or from an email account specified.

  • synced

    Only items that match the sync flaged that is passed. [0|1]

  • userGUID

    Only items created from this user.

  • directoryGUID

    Only items referencing this directory record.

queueHistoryHash

Return a hash or reference to the a queue history hash. History hashes will be referenced by passing a guid key or if present a queueGUID key from the derived queue record it was created from.

runSQL

Return an reference to an array that contains the results of the SQL ran. In addition if you pass noUpdate=>1 the method will not run updateDatabase on errors. This is important if you doing something that could create a recursion problem.

        #
        # retrieve a reference to an array of data we asked for
        #
        my $dataArray = $fws->runSQL(SQL=>"select id,type from id_and_type_table");     # Any SQL statement or query

        #
        # loop though the array
        #
        while (@$dataArray) {

                #
                # collect the data each row at a time
                #
                my $id          = shift(@$dataArray);
                my $type        = shift(@$dataArray);

                #
                # display or do something with the data
                #
                print "ID: ".$id." - ".$type."\n";
        }

saveData

Update or create a new data record. If guid is not provided then a new record will be created. If you pass "newGUID" as a parameter for a new record, the new guid will not be auto generated, newGUID will be used.

        %dataHash = $fws->saveData(%dataHash);

Required hash keys if the data is new:

  • parent: This is the reference to where the data belongs

  • name: This is the reference id for the record

  • type: A valid element type

Not required hash keys:

  • $active: 0 or 1. Default is 0 if not specified

  • newGUID: If this is a new record, use this guid (Note: There is no internal checking to make sure this is unique)

  • lang: Two letter language definition. (Not needed for most multi-lingual sites, only if the code has a requirement that it is splitting language based on other criteria in the control)

  • ... Any other extended data fields you want to save with the data element

Example of adding a data record

        my %paramHash;
        $paramHash{'parent'}            = $fws->formValue('guid');
        $paramHash{'active'}            = 1;
        $paramHash{'name'}              = $fws->formValue('name');
        $paramHash{'title'}             = $fws->formValue('title');
        $paramHash{'type'}              = 'site_myElement';
        $paramHash{'color'}             = 'red';

        %paramHash = $fws->saveData(%paramHash);

Example of adding the same data record to a "data container"

        my %paramHash;
        $paramHash{'containerId'}       = 'thisReference';
        $paramHash{'active'}            = 1;
        $paramHash{'name'}              = $fws->formValue('name');
        $paramHash{'type'}              = 'site_thisType';
        $paramHash{'title'}             = $fws->formValue('title');
        $paramHash{'color'}             = 'red';

        %paramHash = $fws->saveData(%paramHash);

Note: If the containerId does not match or exist, then one will be created in the root of your site, and the data will be added to the new one.

Example of updating a data record:

        $guid = 'someGUIDaaaaabbbbccccc';
 
        #
        # get the original hash
        #
        my %dataHash = $fws->dataHash(guid=>$guid);
 
        #
        # make some changes
        #
        $dataHash{'name'}       = "New Reference Name";
        $dataHash{'color'}      = "blue";
 
        #
        # Give the altered hash to the update procedure
        # 
        $fws->saveData(%dataHash);

saveExtra

Save data that is part of the extra hash for a FWS table.

        $self->saveExtra(       table           =>'table_name',
                                siteGUID        =>'site_guid_not_required',
                                guid            =>'some_guid',
                                field           =>'table_field','the value we are setting it to');

saveQueue

Save a hash to the process and message queue.

        %queueHash = $fws->saveQueue(%queueHash);

saveQueueHistory

Save a hash to the process and message queue history.

        %queueHash = $fws->saveQueueHistory(%queueHash);

schemaHash

Return the schema hash for an element. You can pass either the guid or the element type.

        my %schemaHash = $fws->schemaHash('someGUIDorType');

setCacheIndex

Set a sites cache index for its site. you can bas a siteGUID as a hash parameter if you wish to update the index for a site not currently being rendered.

        $fws->setCacheIndex();

sortArray

Return a sorted array reference by passing the array reference, what key to sort by, and numrical or alpha sort.

        #
        # type: alpha|number
        # key: the key you are sorting by
        # array: an array reference
        #
        my $arrayRef = $fws->sortArray(key=>'id',type=>'alpha',array=>\@someArray); 

tableFieldHash

Return a multi-dimensional hash of all the fields in a table with its properties. This usually isn't used by anything but internal table alteration methods, but it could be useful if you are making conditionals to determine the data structure before adding or changing data. The method is CPU intensive so it should only be used when performance is not a requirement.

        $tableFieldHashRef = $fws->tableFieldHash('the_table');

The return dump will have the following structure:

        $tableFieldHashRef->{field}{type}
        $tableFieldHashRef->{field}{ord}
        $tableFieldHashRef->{field}{null}
        $tableFieldHashRef->{field}{default}
        $tableFieldHashRef->{field}{extra}
        

If the field is indexed it will return a unique table field combination key equal to MUL or FULLTEXT:

        $tableFieldHashRef->{thetable_field}{key} 

updateDataCache

Update the cache version of the data record. This is called automatically when saveData is called.

        $fws->updateDataCache(%theDataHash);

userArray

Return an array or reference to an array of the users on an installation. You can pass they keywords paramater and it will look though name and email address.

updateDatabase

Alter the database to match the schema for FWS 2. The return will print the SQL statements used to adjust the tables.

        print $fws->updateDatabase()."\n";

This method is automatically called when on the web optimized version of FWS when rendering the 'System' screen.

updateModifiedDate

Update the modified date of the page a dataHash element resides on.

        $fws->updateModifiedDate(%dataHash);

Note: By updating anything that is persistant against multiple pages all pages will have thier date updated as it is considered a site wide change.

AUTHOR

Nate Lewis, <nlewis at gnetworks.com>

BUGS

Please report any bugs or feature requests to bug-fws-v2 at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=FWS-V2. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc FWS::V2::Database

You can also look for information at:

ACKNOWLEDGEMENTS

LICENSE AND COPYRIGHT

Copyright 2012 Nate Lewis.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.