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