3d5ca6c7ac30220e948963f63f712a266683f9a8
[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 XML::LibXML;
18
19 our ($db_cfg, $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          = Form->new;
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   $::auth->reset;
71   my $dbh_template = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("No database connection to the template database: " . $DBI::errstr);
72   my $auth_dbh     = $::auth->dbconnect(1);
73
74   if ($auth_dbh) {
75     dbg("Database exists; dropping");
76     $auth_dbh->disconnect;
77
78     dbh_do($dbh_template, "DROP DATABASE \"" . $db_cfg->{db} . "\"", message => "Database could not be dropped");
79
80     $::auth->reset;
81   }
82
83   dbg("Creating database");
84
85   dbh_do($dbh_template, "CREATE DATABASE \"" . $db_cfg->{db} . "\" TEMPLATE \"" . $db_cfg->{template} . "\" ENCODING 'UNICODE'", message => "Database could not be created");
86   $dbh_template->disconnect;
87 }
88
89 sub report_success {
90   $dbh->disconnect;
91   ok(1, "Database has been setup sucessfully.");
92   done_testing();
93 }
94
95 sub apply_dbupgrade {
96   my ($dbupdater, $control_or_file) = @_;
97
98   my $file    = ref($control_or_file) ? ("sql/Pg-upgrade2" . ($dbupdater->{auth} ? "-auth" : "") . "/$control_or_file->{file}") : $control_or_file;
99   my $control = ref($control_or_file) ? $control_or_file                                                                        : undef;
100
101   dbg("Applying $file");
102
103   my $error = $dbupdater->process_file($dbh, $file, $control);
104
105   BAIL_OUT("Error applying $file: $error") if $error;
106 }
107
108 sub create_initial_schema {
109   dbg("Creating initial schema");
110
111   my @dbi_options = (
112     'dbi:Pg:dbname=' . $db_cfg->{db} . ';host=' . $db_cfg->{host} . ';port=' . $db_cfg->{port},
113     $db_cfg->{user},
114     $db_cfg->{password},
115     SL::DBConnect->get_options(PrintError => 0, PrintWarn => 0),
116   );
117
118   $dbh           = SL::DBConnect->connect(@dbi_options) || BAIL_OUT("Database connection failed: " . $DBI::errstr);
119   $::auth->{dbh} = $dbh;
120   my $dbupdater  = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, silent => 1);
121   my $defaults   = SL::DefaultManager->new($::lx_office_conf{system}->{default_manager});
122   my $coa        = $defaults->chart_of_accounts( 'Germany-DATEV-SKR03EU' );
123   my $am         = $defaults->accounting_method( 'cash' );
124   my $pd         = $defaults->profit_determination( 'balance' );
125   my $is         = $defaults->inventory_system( 'periodic' );
126   my $curr       = $defaults->currency( 'EUR' );
127
128   apply_dbupgrade($dbupdater, "sql/lx-office.sql");
129   apply_dbupgrade($dbupdater, "sql/${coa}-chart.sql");
130
131   dbh_do($dbh, qq|UPDATE defaults SET coa = '${coa}', accounting_method = '${am}', profit_determination = '${pd}', inventory_system = '${is}', curr = '${curr}'|);
132   dbh_do($dbh, qq|CREATE TABLE schema_info (tag TEXT, login TEXT, itime TIMESTAMP DEFAULT now(), PRIMARY KEY (tag))|);
133 }
134
135 sub create_initial_auth_schema {
136   dbg("Creating initial auth schema");
137
138   my $dbupdater = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => 1);
139   apply_dbupgrade($dbupdater, 'sql/auth_db.sql');
140 }
141
142 sub apply_upgrades {
143   my %params            = @_;
144   my $dbupdater         = SL::DBUpgrade2->new(form => $::form, return_on_error => 1, auth => $params{auth});
145   my @unapplied_scripts = $dbupdater->unapplied_upgrade_scripts($dbh);
146
147   apply_dbupgrade($dbupdater, $_) for @unapplied_scripts;
148 }
149
150 sub create_client_user_and_employee {
151   dbg("Creating client, user, group and employee");
152
153   dbh_do($dbh, qq|DELETE FROM auth.clients|);
154   dbh_do($dbh, qq|INSERT INTO auth.clients (id, name, dbhost, dbport, dbname, dbuser, dbpasswd, is_default) VALUES (1, 'Unit-Tests', ?, ?, ?, ?, ?, TRUE)|,
155          bind => [ @{ $db_cfg }{ qw(host port db user password) } ]);
156   dbh_do($dbh, qq|INSERT INTO auth."user"         (id,        login)    VALUES (1, 'unittests')|);
157   dbh_do($dbh, qq|INSERT INTO auth."group"        (id,        name)     VALUES (1, 'Vollzugriff')|);
158   dbh_do($dbh, qq|INSERT INTO auth.clients_users  (client_id, user_id)  VALUES (1, 1)|);
159   dbh_do($dbh, qq|INSERT INTO auth.clients_groups (client_id, group_id) VALUES (1, 1)|);
160   dbh_do($dbh, qq|INSERT INTO auth.user_group     (user_id,   group_id) VALUES (1, 1)|);
161
162   my %config                 = (
163     default_printer_id       => '',
164     template_format          => '',
165     default_media            => '',
166     email                    => 'unit@tester',
167     tel                      => '',
168     dateformat               => 'dd.mm.yy',
169     show_form_details        => '',
170     name                     => 'Unit Tester',
171     signature                => '',
172     hide_cvar_search_options => '',
173     numberformat             => '1.000,00',
174     vclimit                  => 0,
175     favorites                => '',
176     copies                   => '',
177     menustyle                => 'v3',
178     fax                      => '',
179     stylesheet               => 'lx-office-erp.css',
180     mandatory_departments    => 0,
181     countrycode              => 'de',
182   );
183
184   my $sth = $dbh->prepare(qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (1, ?, ?)|) || BAIL_OUT($dbh->errstr);
185   dbh_do($dbh, $sth, bind => [ $_, $config{$_} ]) for sort keys %config;
186   $sth->finish;
187
188   $sth = $dbh->prepare(qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (1, ?, TRUE)|) || BAIL_OUT($dbh->errstr);
189   dbh_do($dbh, $sth, bind => [ $_ ]) for sort $::auth->all_rights;
190   $sth->finish;
191
192   dbh_do($dbh, qq|INSERT INTO employee (id, login, name) VALUES (1, 'unittests', 'Unit Tester')|);
193
194   $::auth->set_client(1) || BAIL_OUT("\$::auth->set_client(1) failed");
195   %::myconfig = $::auth->read_user(login => 'unittests');
196 }
197
198 verify_configuration();
199 setup();
200 drop_and_create_database();
201 create_initial_schema();
202 create_initial_auth_schema();
203 apply_upgrades(auth => 1);
204 create_client_user_and_employee();
205 apply_upgrades();
206 report_success();
207
208 1;