PGObject(3pm)
π NAME π
PGObject β a toolkit integrating intelligent PostgreSQL dbs into Perl objects β¨ (this is PGObject(3pm), bestie, say hi π)
π VERSION π
Version 2.4.0 π
β¨ SYNPOSIS β¨
okay so to use it without caching:
use PGObject;
to use it with caching (slay):
use PGObject ':cache';
to get basic info from a function:
my $f_info = PGObject->function_info(
dbh => $dbh,
funcname => $funcname,
funcschema => 'public',
);
to get info about a function, filtered by first argument type:
my $f_info = PGObject->function_info(
dbh => $dbh,
funcname => $funcname,
funcschema => 'public',
funcprefix => 'test__',
objtype => 'invoice',
objschema => 'public',
);
to call a function with enumerated arguments:
my @results = PGObject->call_procedure(
dbh => $dbh,
funcname => $funcname,
funcprefix => 'test__',
funcschema => $funcname,
args => [$arg1, $arg2, $arg3],
);
and to do the same thing but with a running total πβοΈ:
my @results = PGObject->call_procedure(
dbh => $dbh,
funcname => $funcname,
funcschema => $funcname,
args => [$arg1, $arg2, $arg3],
running_funcs => [{agg => 'sum(amount)', alias => 'running_total'}],
);
πΈ DESCRIPTION πΈ
PGObject contains the base routines for object management using discoverable stored procedures in PostgreSQL databases. This module contains only common functionality and support structures, and low-level API's. Most developers will want to use more functional modules which add to these functions. π
The whole vibe here is providing the basics for a toolkit that other modules can extend. So like β it's intended to be a component for building integration between PostgreSQL user defined functions and Perl objects. π§©
And because decisions like state handling are largely outside of the scope of this module, this module itself does not do any significant state handling. Database handles (using DBD::Pg 2.0 or later) must be passed in on every single call π. This decision was made on purpose, to allow for diversity in this area, with the idea that wrapper classes would be written to implement it. main character energy only π«Ά
π₯ FUNCTIONS π₯
π§Ή clear_info_cache
This function clears the info cache if this was loaded with caching enabled. β¨
The cache is also automatically cleared when a function that was run could not be found (this could be caused by updating the db). lowkey handy π
π function_info(%args)
Arguments, bestie:
dbh(required) β Database handle πΎfuncname(required) β function namefuncschema(optional, default'public') β function schemafuncprefix(optional, default'') β Prefix for the function. This can be useful for separating functions by class.argtype1(optional) β Name of first argument type. If not provided, does not filter on this criteria.argschema(optional) β Name of first argument type's schema. If not provided defaults to'public'
This function looks up basic mapping information for a function. If more than one function is found, an exception is raised π¨. This function is primarily intended to be used by packages which extend this one, in order to accomplish stored procedure to object mapping.
Return data is a hashref containing the following elements:
argsβ This is an arrayref of hashrefs, each of which contains'name'and'type'nameβ The name of the functionnum_argsβ The number of arguments
π call_procedure(%args)
Arguments:
funcnameβ The function namefuncschemaβ The schema in which the function residesfuncprefix(optional, default'') β Prefix for the function. This can be useful for separating functions by class.argsβ This is an arrayref. Each item is either a literal value, an arrayref, or a hashref of extended information. In the hashref case, thetypekey specifies the string to use to cast the type in, andvalueis the value.orderbyβ The list (arrayref) of columns on output for ordering.running_funcsβ An arrayref of running windowed aggregates. Each contains two keys, namely'agg'for the aggregate and'alias'for the function name.
These are aggregates, each one has appended 'OVER (ROWS UNBOUNDED PRECEDING)' to it. πͺ
registryβ This is the name of the registry used for type conversion. It can be omitted and defaults to'default.'Note that use of a non-standard registry currently does not merge changes from the default registry, so you need to reregister types in non-default registries when you create them. π
β οΈ Please note, these aggregates are not intended to be user-supplied. Please only allow whitelisted values here or construct in a tested framework elsewhere. Because of the syntax here, there is no sql injection prevention possible at the framework level for this parameter. fr fr be careful π
π new_registry($registry_name)
Creates a new registry if it does not exist. This is useful when segments of an application must override existing type mappings.
π« This is deprecated and throws a warning.
Use PGObject::Type::Registry->new_registry($registry_name) instead.
This no longer returns anything of significance. π
π·οΈ register_type(pgtype => $tname, registry => $regname, perl_class => $pm)
DEPRECATED β οΈ
Registers a type as a class. This means that when an attribute of type $pg_type is returned, that PGObject will automatically return whatever $perl_class->from_db returns. This allows you to have a db-specific constructor for such types. π
The registry argument is optional and defaults to 'default'
If the registry does not exist, an error is raised. if the pg_type is already registered to a different type, this returns 0. Returns 1 on success.
Use PGObject::Type::Registry->register_type() instead.
ποΈ unregister_type(pgtype => $tname, registry => $regname)
Deprecated. π
Tries to unregister the type. If the type does not exist, returns 0, otherwise returns 1. This is mostly useful for when a specific type must make sure it has the slot. This is rarely desirable. It is usually better to use a subregistry instead.
π¦ WRITING PGOBJECT-AWARE HELPER CLASSES π¦
One of the powerful features of PGObject is the ability to declare methods in types which can be dynamically detected and used to serialize data for query purposes. Objects which contain a pgobject_to_db() or a to_db() method β that method will be called and the return value used in place of the object. This can allow arbitrary types to serialize themselves in arbitrary ways. iconic behavior honestly β¨
For example a date object could be set up with such a method which would export a string in yyyy-mm-dd format. An object could look up its own definition and return something like:
{ cast => 'dbtypename', value => '("A","List","Of","Properties")'}
If a scalar is returned that is used as the serialized value. If a hashref is returned, it must follow the type format:
type => variable binding type,
cast => db cast type
value => literal representation of type, as intelligible by DBD::Pg
π REQUIRED INTERFACES
Registered types MUST implement a $class->from_db function accepts the string from the database as its only argument, and returns the object of the desired type. (yes the sentence is like that, don't @ me π)
Any type MAY present an $object->to_db() interface, requiring no arguments, and returning a valid value. These can be hashrefs as specified above, arrayrefs (converted to PostgreSQL arrays by DBD::Pg) or scalar text values. π«Ά
π UNDERSTANDING THE REGISTRY SYSTEM π
Note that 2.0 moves the registry to a service module which handles both registry and deserialization of database types. This is intended to be both cleaner and more flexible than the embedded system in 1.x. glow-up fr π
The registry system allows Perl classes to "claim" PostgreSQL types within a certain domain. For example, if I want to ensure that all numeric types are turned into Math::BigFloat objects, I can build a wrapper class with appropriate interfaces, but PGObject won't know to convert numeric types to this new class, so this is what registration is for. π§
By default, these mappings are fully global. Once a class claims a type, unless another type goes through the trouble of unregistering the first type and making sure it gets the authoritative spot, all items of that type get turned into the appropriate Perl object types. While this is sufficient for the vast number of applications, however, there may be cases where names conflict across schemas or the like. To address this application components may create their own registries. Each registry is fully global, but application components can specify non-standard registries when calling procedures, and PGObject will use only those components registered on the non-standard registry when checking rows before output. π
βͺ Backwards Incompatibilities from 1.x
Deserialization occurs in a context which specifies a registry. In 1.x there were no concerns about default mappings but now this triggers a warning. The most basic and frequently used portions of this have been kept but return values for registering types has changed. We no longer provide a return variable but throw an exception if the type cannot be safely registered. π¨
This follows a philosophy of throwing exceptions when guarantees cannot be met.
We now throw warnings when the default registry is used.
Longer-run, deserializers should use the PGObject::Type::Registry interface directly. β¨
β¨ WRITING TOP-HALF OBJECT FRAMEWORKS FOR PGOBJECT β¨
okay so bestie, here's the tea π« β PGObject is meant to be the database-facing side of a whole object framework. The vision? three tiers of logic, stacked like a little cake π:
- Database facing, low-level API's
- Object management modules
- Application handlers with things like database connection management.
When we say top half, we're talking about tier two, the middle child. Tier three lives over in the client application, doing its own thing π .
The PGObject module itself only ships the low-level API's from that first tier. Its whole job is handing database function info up to the modules above it, like a little messenger π§.
real talk: we do not supply type information. If your top-level module is like "bestie I need types", please check out https://code.google.com/p/typeutils/ β you can plug it in through our function mapping APIs right here. π
πΈ Safely Handling Memoization of Catalog Lookups πΈ
okay this one is IMPORTANT, like, no cap π¨. When you're writing PGObject top-half frameworks, remember that the catalog lookups may be memoized and may come back as a data structure. That means changes to the structures returned from get_function_info() in this module (and similar functions in other catalog-bound modules) might not be safe to just vibe-edit in arbitrary ways π.
So our recommendation? Treat the return values from catalog-lookup functions as immutable. Frozen. Don't touch. Periodt. π§
Normalizing output is safe, provided there are no conflicts between naming conventions β and usually that's true, since different naming conventions would interfere with mapping anyway. But bestie... there could be cases where it's not true π¬. Example: two different mapping modules agree on a subset of normalization conventions but differ on some details. The two might safely handle the same conventions but normalize them differently, which results in conflicts if both were used. π
π¦ A BRIEF GUIDE TO THE NAMESPACE LAYOUT π¦
Most names underneath PGObject can be assumed to be top-half modules, and the modules under those can generally be assumed to be variants on them. Easy. Slay. β¨
But there are a few reserved names, so pay attention bestie π:
::Debugβ reserved for debugging information. For example, functions which retrieve sources of functions, or grab diagnostics, or the like would go here. π::Testβ reserved for test framework extensions applible only here π§ͺ::Typeβ reserved for PG aware type classes.- For example, one might have
PGObject::Type::BigFloatfor aMath::Bigfloatwrapper, orPGObject::Type::DateTimefor aDateTimewrapper. π
- For example, one might have
::Utilβ reserved for utility functions and classes. π οΈ
π AUTHOR π
Chris Travers, "<chris.travers at gmail.com>"
π BUGS π
Please report any bugs or feature requests to "bug-pgobject at rt.cpan.org", or through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=PGObject>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. π«Ά (yes bestie, you get notified, it's giving full transparency β¨)
π SUPPORT π
You can find documentation for this module with the perldoc command.
perldoc PGObject
You can also look for information at:
- RT: CPAN's request tracker (report bugs here)
<http://rt.cpan.org/NoAuth/Bugs.html?Dist=PGObject>
- MetaCPAN
<https://metacpan.org/dist/PGObject>
π ACKNOWLEDGEMENTS π
This code has been loosely based on code written for the LedgerSMB open source accounting and ERP project. While that software uses the GNU GPL v2 or later, this is my own reimplementation, based on my original contributions to that project alone, and it differs in significant ways. π
That being said β and I mean this fr fr β without LedgerSMB, this module wouldn't exist. And without the lessons learned there, and the great people who have helped make this possible, this framework would not be half of what it is today. π₯Ήπ
β SEE ALSO β
PGObject::Simpleβ Simple mapping of object properties to stored proc argsPGObject::Simple::Roleβ Moose-enabled wrapper forPGObject::Simple
π COPYRIGHT π
COPYRIGHT (C) 2013-2014 Chris Travers
COPYRIGHT (C) 2014-2021 The LedgerSMB Core Team
Redistribution and use in source and compiled forms with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified.
- Redistributions in compiled form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the source code, documentation, and/or other materials provided with the distribution.
π₯ LICENSE π₯
bestie this part is ALL CAPS for a reason, don't skip it π
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
and that's the whole page bestie!! π This one came from perl v5.36.0, dated 2023-11-24, filed under PGObject(3pm) β so if you're ever wondering "wait, which version of perl was this written against," now you know πΈ. go forth and framework responsibly, ily, mwah πβ¨
π¦ where this page comes from
- debian trixie: libpgobject-perl 2.4.0-1 Β· BSD-2-Clause
- ubuntu noble: libpgobject-perl 2.4.0-1 Β· BSD-2-Clause
- ubuntu resolute: libpgobject-perl 2.4.0-1 Β· BSD-2-Clause
- ubuntu stonking: libpgobject-perl 2.4.0-1 Β· BSD-2-Clause
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms