]> git.donarmstrong.com Git - debbugs.git/blob - lib/Debbugs/DB/ResultSet/Correspondent.pm
Debbugs::DB::Util is now a component of Debbugs::DB
[debbugs.git] / lib / Debbugs / DB / ResultSet / Correspondent.pm
1 # This module is part of debbugs, and is released
2 # under the terms of the GPL version 2, or any later version. See the
3 # file README and COPYING for more information.
4 # Copyright 2017 by Don Armstrong <don@donarmstrong.com>.
5 use utf8;
6 package Debbugs::DB::ResultSet::Correspondent;
7
8 =head1 NAME
9
10 Debbugs::DB::ResultSet::Correspondent - Correspondent table actions
11
12 =head1 SYNOPSIS
13
14
15
16 =head1 DESCRIPTION
17
18
19
20 =cut
21
22 use strict;
23 use warnings;
24
25 use base 'DBIx::Class::ResultSet';
26
27 use Debbugs::DB::Util qw(select_one);
28
29 use Debbugs::Common qw(getparsedaddrs);
30 use Scalar::Util qw(blessed);
31
32 sub get_correspondent_id {
33     my ($self,$addr) = @_;
34     my $full_name;
35     if (blessed($addr)) {
36         $full_name = $addr->phrase();
37         $addr = $addr->address();
38     } elsif ($addr =~ /</) {
39         $addr = getparsedaddrs($addr);
40         $full_name = $addr->phrase();
41         $addr = $addr->address();
42     }
43     if (defined $full_name) {
44         $full_name =~ s/^\"|\"$//g;
45         $full_name =~ s/^\s+|\s+$//g;
46     }
47     my $rs =
48         $self->
49         search({addr => $addr},
50               {result_class => 'DBIx::Class::ResultClass::HashRefInflator',
51               }
52               )->first();
53     if (defined $rs) {
54         return $rs->{id};
55     }
56     my $ci =
57         $self->result_source->schema->
58         select_one(<<'SQL',$addr,$addr);
59 WITH ins AS (
60 INSERT INTO correspondent (addr) VALUES (?)
61  ON CONFLICT (addr) DO NOTHING RETURNING id
62 )
63 SELECT id FROM ins
64 UNION ALL
65 SELECT id FROM correspondent WHERE addr = ?
66 LIMIT 1;
67 SQL
68     if (defined $full_name) {
69         $self->result_source->schema->
70             select_one(<<'SQL',$ci,$full_name);
71 WITH ins AS (
72 INSERT INTO correspondent_full_name (correspondent,full_name)
73    VALUES (?,?) ON CONFLICT (correspondent,full_name) DO NOTHING RETURNING 1
74 ) SELECT 1 FROM ins
75 UNION ALL
76 SELECT 1;
77 SQL
78     }
79     return $ci;
80 }
81
82
83
84 1;
85
86 __END__