| 1 | package DBIx::QuickORM::Manual::Types; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | our $VERSION = '0.000033'; | ||
| 6 | |||
| 7 | =pod | ||
| 8 | |||
| 9 | =encoding UTF-8 | ||
| 10 | |||
| 11 | =head1 NAME | ||
| 12 | |||
| 13 | DBIx::QuickORM::Manual::Types - Write a type: inflate, deflate, keys, caching, and registering it, by example. | ||
| 14 | |||
| 15 | =head1 DESCRIPTION | ||
| 16 | |||
| 17 | A type is a class that consumes L<DBIx::QuickORM::Role::Type> and implements | ||
| 18 | C<inflate> (a stored value to the Perl value your code wants) and C<deflate> | ||
| 19 | (back). The role supplies defaults for how rows cache inflated values. The | ||
| 20 | other methods below are optional. | ||
| 21 | |||
| 22 | Two example types. B<Money> inflates an integer column of cents into an | ||
| 23 | object, and can be a primary key. B<Tags> inflates text into an arrayref, | ||
| 24 | and cannot. | ||
| 25 | |||
| 26 | =head1 SCHEMA | ||
| 27 | |||
| 28 | The examples use PostgreSQL and this schema: | ||
| 29 | |||
| 30 | =for highlighter language=sql | ||
| 31 | |||
| 32 | CREATE TABLE users ( | ||
| 33 | id SERIAL PRIMARY KEY, | ||
| 34 | name TEXT NOT NULL, | ||
| 35 | email TEXT UNIQUE, | ||
| 36 | prefs JSON, | ||
| 37 | referred_by INTEGER REFERENCES users (id), | ||
| 38 | created TIMESTAMP NOT NULL DEFAULT now() | ||
| 39 | ); | ||
| 40 | |||
| 41 | CREATE TABLE posts ( | ||
| 42 | id SERIAL PRIMARY KEY, | ||
| 43 | user_id INTEGER NOT NULL REFERENCES users (id), | ||
| 44 | title TEXT NOT NULL, | ||
| 45 | views INTEGER NOT NULL DEFAULT 0 | ||
| 46 | ); | ||
| 47 | |||
| 48 | CREATE DOMAIN cents AS INTEGER; | ||
| 49 | |||
| 50 | CREATE TABLE products ( | ||
| 51 | id SERIAL PRIMARY KEY, | ||
| 52 | name TEXT NOT NULL, | ||
| 53 | price cents NOT NULL, | ||
| 54 | shipping_cents INTEGER NOT NULL DEFAULT 0, | ||
| 55 | tags TEXT | ||
| 56 | ); | ||
| 57 | |||
| 58 | CREATE TABLE price_points (price cents PRIMARY KEY, label TEXT); | ||
| 59 | CREATE TABLE labels (tags TEXT PRIMARY KEY); | ||
| 60 | |||
| 61 | =head1 MONEY: A VALUE OBJECT | ||
| 62 | |||
| 63 | The inflated value is a read-only object. C<plus> returns a new object | ||
| 64 | rather than changing one: | ||
| 65 | |||
| 66 | =for highlighter language=perl | ||
| 67 | |||
| 68 | package My::Money; | ||
| 69 | use Hash::Util qw/lock_hashref/; | ||
| 70 | use overload | ||
| 71 | '""' => sub { $_[0]->amount }, | ||
| 72 | '<=>' => sub { | ||
| 73 | my ($x, $y, $swap) = @_; | ||
| 74 | my $r = $x->cents <=> (ref($y) ? $y->cents : $y); | ||
| 75 | $swap ? -$r : $r; | ||
| 76 | }, | ||
| 77 | fallback => 1; | ||
| 78 | |||
| 79 | sub new { my ($class, $cents) = @_; lock_hashref(bless {cents => $cents}, $class) } | ||
| 80 | sub cents { $_[0]->{cents} } | ||
| 81 | sub amount { sprintf '%.2f', $_[0]->cents / 100 } # '12.50', and -1 cent is '-0.01' | ||
| 82 | sub plus { my ($self, $other) = @_; My::Money->new($self->cents + $other->cents) } | ||
| 83 | |||
| 84 | The type claims every column of the C<cents> domain, and numeric columns | ||
| 85 | named C<*_cents>: | ||
| 86 | |||
| 87 | package My::Type::Money; | ||
| 88 | use Role::Tiny::With qw/with/; | ||
| 89 | with 'DBIx::QuickORM::Role::Type'; | ||
| 90 | |||
| 91 | sub base_types { 'cents' } | ||
| 92 | |||
| 93 | sub matches { | ||
| 94 | my ($class, $name, $field, $dialect) = @_; | ||
| 95 | $name =~ m/_cents$/ && $field->{affinity} eq 'numeric'; | ||
| 96 | } | ||
| 97 | |||
| 98 | C<deflate> takes an object, an amount (C<'12.5'>, C<'-0.01'>), or cents | ||
| 99 | already: | ||
| 100 | |||
| 101 | sub inflate { my ($class, $raw, $field, $conn) = @_; My::Money->new($raw) } | ||
| 102 | |||
| 103 | sub deflate { | ||
| 104 | my ($class, $value, $field, $conn) = @_; | ||
| 105 | ref($value) ? $value->cents : $value =~ m/\./ ? sprintf('%.0f', $value * 100) : $value; | ||
| 106 | } | ||
| 107 | |||
| 108 | C<inflate> and C<deflate> get the field's record from the map (a hashref: | ||
| 109 | C<name>, C<affinity>, C<db_type>, and more, listed in | ||
| 110 | L<DBIx::QuickORM::Role::Type>) and the connection (C<< $conn->dialect >>, | ||
| 111 | C<< $conn->time_zone >>, see | ||
| 112 | L<DBIx::QuickORM::Manual::Dialects/"TIME ZONES">). Neither sees NULL. | ||
| 113 | |||
| 114 | C<is_inflated> (L<DBIx::QuickORM::Manual::Values/DEFLATION>) distinguishes an | ||
| 115 | amount to deflate (C<'12.50'>) from cents already (C<1250>). The object is | ||
| 116 | read-only, so every read may share one cached object. C<canonical_key_value> | ||
| 117 | makes C<1250>, C<'12.50'>, C<'01250'>, and a C<My::Money> one key | ||
| 118 | (L<DBIx::QuickORM::Manual::Keys/"TYPED KEYS">): | ||
| 119 | |||
| 120 | sub is_inflated { my ($class, $value) = @_; $value =~ m/\./ ? 1 : 0 } | ||
| 121 | |||
| 122 | sub inflated_is_immutable_for_cache { 1 } | ||
| 123 | |||
| 124 | sub canonical_key_value { | ||
| 125 | my ($class, $value, $field, $conn) = @_; | ||
| 126 | 0 + $class->deflate($value, $field, $conn); | ||
| 127 | } | ||
| 128 | |||
| 129 | C<append_autotype> asks the type after the built-in types. C<+> marks a full | ||
| 130 | class name: | ||
| 131 | |||
| 132 | my $orm = DBIx::QuickORM->new( | ||
| 133 | credentials => { | ||
| 134 | dsn => $dsn, | ||
| 135 | user => $user, | ||
| 136 | pass => $pass, | ||
| 137 | }, | ||
| 138 | append_autotype => ['+My::Type::Money'], | ||
| 139 | ); | ||
| 140 | |||
| 141 | my $book = $orm->insert(products => { | ||
| 142 | name => 'Book', | ||
| 143 | price => '12.50', # is_inflated is true: deflated to 1250 | ||
| 144 | shipping_cents => 300, # is_inflated is false: 300 goes as given | ||
| 145 | }); | ||
| 146 | |||
| 147 | Reads return a C<My::Money>, the same object every time: | ||
| 148 | |||
| 149 | my $price = $book->field('price'); | ||
| 150 | my $text = "$price"; # '12.50' | ||
| 151 | my $cents = $book->raw_field('price'); # 1250, as stored | ||
| 152 | my $total = $price->plus($book->field('shipping_cents')); # 15.50 | ||
| 153 | my $more = $price > $book->field('shipping_cents'); # true: the overloaded <=> | ||
| 154 | |||
| 155 | $book->update({price => My::Money->new(1399)}); # a reference is always deflated | ||
| 156 | |||
| 157 | A C<where> sends values as given, so a C<My::Money> there would go as its | ||
| 158 | text (C<'20.00'>). Compare in cents, or mark a value to deflate with | ||
| 159 | C<inflated> (L<DBIx::QuickORM::Manual::Values/INFLATED>): | ||
| 160 | |||
| 161 | use DBIx::QuickORM::Value qw/inflated/; | ||
| 162 | |||
| 163 | my @cheap = $orm->handle('products')->where({price => {'<' => 2000}})->all; | ||
| 164 | my @again = $orm->handle('products') | ||
| 165 | ->where({price => {'<' => inflated(My::Money->new(2000))}}) | ||
| 166 | ->all; | ||
| 167 | |||
| 168 | =head1 TAGS: A LIST | ||
| 169 | |||
| 170 | package My::Type::Tags; | ||
| 171 | use Role::Tiny::With qw/with/; | ||
| 172 | with 'DBIx::QuickORM::Role::Type'; | ||
| 173 | |||
| 174 | sub matches { | ||
| 175 | my ($class, $name, $field, $dialect) = @_; | ||
| 176 | $name =~ m/(?:^|_)tags$/ && $field->{affinity} eq 'string'; | ||
| 177 | } | ||
| 178 | |||
| 179 | sub inflate { my ($class, $raw, $field, $conn) = @_; [split /,/, $raw] } | ||
| 180 | |||
| 181 | # a plain string is stored text already | ||
| 182 | sub deflate { | ||
| 183 | my ($class, $value, $field, $conn) = @_; | ||
| 184 | ref($value) ? join(',', @$value) : $value; | ||
| 185 | } | ||
| 186 | |||
| 187 | # a shallow copy is enough for strings, and cheaper than the default deep copy | ||
| 188 | sub clone_inflated { my ($class, $value) = @_; [@$value] } | ||
| 189 | |||
| 190 | The inflated value is an arrayref of non-empty, comma-free strings: | ||
| 191 | C<['a,b']> is stored as C<a,b> and reads back as two tags. | ||
| 192 | |||
| 193 | Tags leaves the rest to the role. C<is_inflated> returns undef (the type | ||
| 194 | cannot tell, so a plain string goes as given). C<inflated_is_immutable_for_cache> | ||
| 195 | is false (an arrayref can be changed, so every read gets a copy). There is no | ||
| 196 | C<canonical_key_value> (see L</TYPES ON PRIMARY KEYS>). | ||
| 197 | |||
| 198 | my $tagged = DBIx::QuickORM->new( | ||
| 199 | credentials => { | ||
| 200 | dsn => $dsn, | ||
| 201 | user => $user, | ||
| 202 | pass => $pass, | ||
| 203 | }, | ||
| 204 | types => {products => {tags => '+My::Type::Tags'}}, # this one field | ||
| 205 | ); | ||
| 206 | |||
| 207 | my $pen = $tagged->insert(products => { | ||
| 208 | name => 'Pen', | ||
| 209 | price => 199, | ||
| 210 | tags => ['office', 'blue'], | ||
| 211 | }); | ||
| 212 | |||
| 213 | my $tags = $pen->field('tags'); # ['office', 'blue']: a copy | ||
| 214 | push @$tags, 'sale'; # changes the copy only | ||
| 215 | my $again = $pen->field('tags'); # ['office', 'blue']: the row is as it was | ||
| 216 | $pen->update({tags => $tags}); # write the change back | ||
| 217 | my $joined = $pen->raw_field('tags'); # 'office,blue,sale' | ||
| 218 | |||
| 219 | =head1 TYPES ON PRIMARY KEYS | ||
| 220 | |||
| 221 | my $point = $orm->insert(price_points => { | ||
| 222 | price => My::Money->new(999), | ||
| 223 | label => 'budget', | ||
| 224 | }); | ||
| 225 | |||
| 226 | my $held = $orm->find(price_points => '9.99'); # the held row, with no query | ||
| 227 | |||
| 228 | # same hashref: canonical_key_value made '9.99' and the object one key | ||
| 229 | my $one = $held->row_data == $point->row_data; | ||
| 230 | |||
| 231 | my $hit = $orm->refresh_row( | ||
| 232 | price_points => {price => 999}, | ||
| 233 | # the cache only, no query: the same row, or undef when it is not held | ||
| 234 | db => 0, | ||
| 235 | ); | ||
| 236 | |||
| 237 | The ORM files each held row (L<DBIx::QuickORM::Manual::Caching>) under its | ||
| 238 | type's C<canonical_key_value>, so every form of one key finds the same row. A | ||
| 239 | type without it cannot sit on a primary key: | ||
| 240 | |||
| 241 | my $ok = eval { | ||
| 242 | DBIx::QuickORM->new( | ||
| 243 | credentials => { | ||
| 244 | dsn => $dsn, | ||
| 245 | user => $user, | ||
| 246 | pass => $pass, | ||
| 247 | }, | ||
| 248 | # croaks: labels.tags is a primary key, and Tags has no canonical_key_value() | ||
| 249 | append_autotype => ['+My::Type::Tags'], | ||
| 250 | ); | ||
| 251 | 1; | ||
| 252 | }; | ||
| 253 | # "... has no canonical_key_value(); pass types => {'labels' => {'tags' => undef}} | ||
| 254 | # to key it by its plain value" | ||
| 255 | my $error = $@; | ||
| 256 | |||
| 257 | my $plain = DBIx::QuickORM->new( | ||
| 258 | credentials => { | ||
| 259 | dsn => $dsn, | ||
| 260 | user => $user, | ||
| 261 | pass => $pass, | ||
| 262 | }, | ||
| 263 | append_autotype => ['+My::Type::Tags'], | ||
| 264 | types => {labels => {tags => undef}}, # key it by its plain text instead | ||
| 265 | ); | ||
| 266 | |||
| 267 | A type can also make a key value for an insert that leaves it out | ||
| 268 | (C<generate_key_value>). See L<DBIx::QuickORM::Manual::Keys/"GENERATED KEYS">. | ||
| 269 | |||
| 270 | =head1 REGISTERING TYPES | ||
| 271 | |||
| 272 | my $shop = DBIx::QuickORM->new( | ||
| 273 | credentials => { | ||
| 274 | dsn => $dsn, | ||
| 275 | user => $user, | ||
| 276 | pass => $pass, | ||
| 277 | }, | ||
| 278 | # asked after UUID, JSON, and DateTime. The first to claim a field wins | ||
| 279 | append_autotype => ['+My::Type::Money', '+My::Type::Tags'], | ||
| 280 | types => { | ||
| 281 | products => {shipping_cents => undef}, # no type, whatever a claim said | ||
| 282 | labels => {tags => undef}, | ||
| 283 | price_points => {label => '+My::Type::Tags'}, # this field, claim or not | ||
| 284 | }, | ||
| 285 | # an option for every field of a type: here, store lower case | ||
| 286 | type_options => {'+My::Type::Tags' => {format => sub { lc $_[0] }}}, | ||
| 287 | ); | ||
| 288 | |||
| 289 | my $only = DBIx::QuickORM->new( | ||
| 290 | credentials => { | ||
| 291 | dsn => $dsn, | ||
| 292 | user => $user, | ||
| 293 | pass => $pass, | ||
| 294 | }, | ||
| 295 | # in place of the built-in list: JSON and DateTime fields are plain now | ||
| 296 | autotype => ['+My::Type::Money'], | ||
| 297 | ); | ||
| 298 | |||
| 299 | A type named for C<autotype> or C<append_autotype> needs C<base_types> or | ||
| 300 | C<matches>. One named only in C<types> needs neither. A bare name (C<JSON>) | ||
| 301 | is a class under C<DBIx::QuickORM::Type::>. C<+> marks a full class name. | ||
| 302 | Types are loaded for you. Array columns (C<TEXT[]>) are never claimed, but | ||
| 303 | C<types> can still type one. | ||
| 304 | |||
| 305 | The hashref form of C<types> gives one field options: | ||
| 306 | C<< {class => '+My::Type::Tags', format => sub { lc $_[0] }} >>. Without | ||
| 307 | C<class> the field keeps its type. | ||
| 308 | C<format> runs on text the type deflated for a non-binary field. A value sent | ||
| 309 | as given (a plain C<'BLUE'> on a Tags field) skips it. C<generate> is for | ||
| 310 | keys (L<DBIx::QuickORM::Manual::Keys>). C<type_options> gives the same options | ||
| 311 | to every field of a type. An ORM defined as a package takes the same names | ||
| 312 | through C<type>, C<autotype>, and C<append_autotype> (L<DBIx::QuickORM::DSL>, | ||
| 313 | L<DBIx::QuickORM::Manual::Classes>). | ||
| 314 | |||
| 315 | =head1 THE METHODS | ||
| 316 | |||
| 317 | =over 4 | ||
| 318 | |||
| 319 | =item C<inflate>, C<deflate> | ||
| 320 | |||
| 321 | Required. | ||
| 322 | |||
| 323 | =item C<is_inflated> | ||
| 324 | |||
| 325 | Whether a plain value is already inflated (an amount with a decimal point) | ||
| 326 | and must be deflated. The default, undef, means the type cannot tell, so a | ||
| 327 | plain value goes as given. A reference is always deflated. | ||
| 328 | |||
| 329 | =item C<base_types>, C<matches> | ||
| 330 | |||
| 331 | To be chosen by C<autotype>. C<base_types> lists the column types claimed. | ||
| 332 | C<matches> gets the field's name, its record, and the dialect. | ||
| 333 | |||
| 334 | =item C<inflated_is_immutable_for_cache>, C<inflate_on_each_read>, C<clone_inflated> | ||
| 335 | |||
| 336 | True when nothing can change an inflated value: rows share the cached one. | ||
| 337 | Otherwise, with C<inflate_on_each_read> true, rows inflate the stored value | ||
| 338 | again for every read (JSON does: decoding beats copying). Otherwise rows hand | ||
| 339 | out C<clone_inflated> copies. The default deep-copies with L<Storable>. | ||
| 340 | |||
| 341 | =item C<inflate_is_identity> | ||
| 342 | |||
| 343 | True when C<inflate> returns the stored value unchanged for this field (UUID | ||
| 344 | on a text column): rows then hand out the raw value without inflating or | ||
| 345 | caching. Default false. | ||
| 346 | |||
| 347 | =item C<canonical_key_value> | ||
| 348 | |||
| 349 | Needed on a primary key field: one string for every form of a key value. | ||
| 350 | |||
| 351 | =item C<generate_key_value> | ||
| 352 | |||
| 353 | Optional: a new value for a key an insert leaves out. | ||
| 354 | |||
| 355 | =back | ||
| 356 | |||
| 357 | L<DBIx::QuickORM::Role::Type> has every signature. | ||
| 358 | |||
| 359 | =cut | ||
| 360 | |||
| 361 | 1; | ||
| 362 | |||
| 363 | __END__ |