Auth::ColumnInformation: fetch nur in reset, nicht in init
[kivitendo-erp.git] / t / 000setup_database.t
1 #!/usr/bin/perl
2
3 use strict;
4
5 use lib 't';
6
7 use Data::Dumper;
8 use Test::More;
9
10 use SL::Auth;
11 use SL::DBConnect;
12 use SL::Form;
13 use SL::InstanceConfiguration;
14 use SL::LXDebug;
15 use SL::Layout::None;
16 use SL::LxOfficeConf;
17
18 our ($db_cfg, $dbh);
19
20 sub dbg {
21   # diag(@_);
22 }
23
24 sub dbh_do {
25   my ($dbh, $query, %params) = @_;
26
27   if (ref($query)) {
28     return if $query->execute(@{ $params{bind} || [] });
29     BAIL_OUT($dbh->errstr);
30   }
31
32   return if $dbh->do($query, undef, @{ $params{bind} || [] });
33
34   BAIL_OUT($params{message} . ": " . $dbh->errstr) if $params{message};
35   BAIL_OUT("Query failed: " . $dbh->errstr . " ; query: $query");
36 }
37
38 sub verify_configuration {
39   SL::LxOfficeConf->read;
40
41   my %config = %{ $::lx_office_conf{'testing/database'} || {} };
42   my @unset  = sort grep { !$config{$_} } qw(host port db user template);
43
44   BAIL_OUT("Missing entries in configuration in section [testing/database]: " . join(' ', @unset)) if @unset;
45 }
46
47 sub setup {
48   package main;
49
50   $SIG{__DIE__}    = sub { Carp::confess( @_ ) } if $::lx_office_conf{debug}->{backtrace_on_die};
51   $::lxdebug       = LXDebug->new(target => LXDebug::STDERR_TARGET);
52   $::lxdebug->disable_sub_tracing;
53   $::locale        = Locale->new($::lx_office_conf{system}->{language});
54   $::form          = Form->new;
55   $::auth          = SL::Auth->new(unit_tests_database => 1);
56   $::locale        = Locale->new('de');
57   $::instance_conf = SL::InstanceConfiguration->new;
58   $db_cfg          = $::lx_office_conf{'testing/database'};
59 }
60
61 sub drop_and_create_database {
62   my @dbi_options = (
63     'dbi:Pg:dbname=' . $db_cfg->{template} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
64     $db_cfg->{user},
65     $db_cfg->{password},
66     SL::DBConnect->get_options,
67   );
68
69   my $dbh_template = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("No database connection to the template database: " . $DBI::errstr);
70   my $auth_dbh     = $::auth->dbconnect(1);
71
72   if ($auth_dbh) {
73     dbg("Database exists; dropping");
74     $auth_dbh->disconnect;
75
76     dbh_do($dbh_template, "DROP DATABASE \"" . $db_cfg->{db} . "\"", message => "Database could not be dropped");
77   }
78
79   dbg("Creating database");
80
81   dbh_do($dbh_template, "CREATE DATABASE \"" . $db_cfg->{db} . "\" TEMPLATE \"" . $db_cfg->{template} . "\" ENCODING 'UNICODE'", message => "Database could not be created");
82   $dbh_template->disconnect;
83 }
84
85 sub report_success {
86   $dbh->disconnect;
87   ok(1, "Database has been setup sucessfully.");
88   done_testing();
89 }
90
91 sub apply_dbupgrade {
92   my ($dbupdater, $control_or_file) = @_;
93
94   my $file    = ref($control_or_file) ? ("sql/Pg-upgrade2" . ($dbupdater->{auth} ? "-auth" : "") . "/$control_or_file->{file}") : $control_or_file;
95   my $control = ref($control_or_file) ? $control_or_file                                                                        : undef;
96
97   dbg("Applying $file");
98
99   my $error = $dbupdater->process_file($dbh, $file, $control);
100
101   BAIL_OUT("Error applying $file: $error") if $error;
102 }
103
104 sub create_initial_schema {
105   dbg("Creating initial schema");
106
107   my @dbi_options = (
108     'dbi:Pg:dbname=' . $db_cfg->{db} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
109     $db_cfg->{user},
110     $db_cfg->{password},
111     SL::DBConnect->get_options(PrintError => 0, PrintWarn => 0),
112   );
113
114   $dbh           = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("Database connection failed: " . $DBI::errstr);
115   $::auth->{dbh} = $dbh;
116   my $dbupdater  = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, silent => 1);
117   my $coa        = 'Germany-DATEV-SKR03EU';
118
119   apply_dbupgrade($dbupdater, "sql/lx-office.sql");
120   apply_dbupgrade($dbupdater, "sql/${coa}-chart.sql");
121
122   dbh_do($dbh, qq|UPDATE defaults SET coa = '${coa}', accounting_method = 'cash', profit_determination = 'income', inventory_system = 'periodic', curr = 'EUR'|);
123   dbh_do($dbh, qq|CREATE TABLE schema_info (tag TEXT, login TEXT, itime TIMESTAMP DEFAULT now(), PRIMARY KEY (tag))|);
124 }
125
126 sub create_initial_auth_schema {
127   dbg("Creating initial auth schema");
128
129   my $dbupdater = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => 1);
130   apply_dbupgrade($dbupdater, 'sql/auth_db.sql');
131 }
132
133 sub apply_upgrades {
134   my %params            = @_;
135   my $dbupdater         = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => $params{auth});
136   my @unapplied_scripts = $dbupdater->unapplied_upgrade_scripts($dbh);
137
138   apply_dbupgrade($dbupdater, $_) for @unapplied_scripts;
139 }
140
141 sub create_client_user_and_employee {
142   dbg("Creating client, user, group and employee");
143
144   dbh_do($dbh, qq|DELETE FROM auth.clients|);
145   dbh_do($dbh, qq|INSERT INTO auth.clients (id, name, dbhost, dbport, dbname, dbuser, dbpasswd, is_default) VALUES (1, 'Unit-Tests', ?, ?, ?, ?, ?, TRUE)|,
146          bind => [ @{ $db_cfg }{ qw(host port db user password) } ]);
147   dbh_do($dbh, qq|INSERT INTO auth."user"         (id,        login)    VALUES (1, 'unittests')|);
148   dbh_do($dbh, qq|INSERT INTO auth."group"        (id,        name)     VALUES (1, 'Vollzugriff')|);
149   dbh_do($dbh, qq|INSERT INTO auth.clients_users  (client_id, user_id)  VALUES (1, 1)|);
150   dbh_do($dbh, qq|INSERT INTO auth.clients_groups (client_id, group_id) VALUES (1, 1)|);
151   dbh_do($dbh, qq|INSERT INTO auth.user_group     (user_id,   group_id) VALUES (1, 1)|);
152
153   my %config                 = (
154     default_printer_id       => '',
155     template_format          => '',
156     default_media            => '',
157     email                    => 'unit@tester',
158     tel                      => '',
159     dateformat               => 'dd.mm.yy',
160     show_form_details        => '',
161     name                     => 'Unit Tester',
162     signature                => '',
163     hide_cvar_search_options => '',
164     numberformat             => '1.000,00',
165     vclimit                  => 0,
166     favorites                => '',
167     copies                   => '',
168     menustyle                => 'v3',
169     fax                      => '',
170     stylesheet               => 'lx-office-erp.css',
171     mandatory_departments    => 0,
172     countrycode              => 'de',
173   );
174
175   my $sth = $dbh->prepare(qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (1, ?, ?)|) || BAIL_OUT($dbh->errstr);
176   dbh_do($dbh, $sth, bind => [ $_, $config{$_} ]) for sort keys %config;
177   $sth->finish;
178
179   $sth = $dbh->prepare(qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (1, ?, TRUE)|) || BAIL_OUT($dbh->errstr);
180   dbh_do($dbh, $sth, bind => [ $_ ]) for sort $::auth->all_rights;
181   $sth->finish;
182
183   dbh_do($dbh, qq|INSERT INTO employee (id, login, name) VALUES (1, 'unittests', 'Unit Tester')|);
184
185   $::auth->set_client(1) || BAIL_OUT("\$::auth->set_client(1) failed");
186   %::myconfig = $::auth->read_user(login => 'unittests');
187 }
188
189 verify_configuration();
190 setup();
191 drop_and_create_database();
192 create_initial_schema();
193 create_initial_auth_schema();
194 apply_upgrades(auth => 1);
195 create_client_user_and_employee();
196 apply_upgrades();
197 report_success();
198
199 1;