App-PhotoDB

 view release on metacpan or  search on metacpan

lib/App/PhotoDB/funcs.pm  view on Meta::CPAN

		&writeconfig($path);
		return $path;
	} else {
		exit;
	}
}

=head2 db

Connect to the database, run migrations and return database handle

=head4 Usage

    my $db = &db;

=head4 Arguments

None

=head4 Returns

Variable representing the database handle

=cut

sub db {
	my $href = shift;
	my $args = $href->{args};

	my $skipmigrations = $$args{skipmigrations} // 0;

	my $connect;
	if (defined($$args{host}) && defined($$args{schema}) && defined($$args{user}) && defined($$args{password})) {
		# use args
		$$connect{'database'}{'host'} = $$args{host};
		$$connect{'database'}{'schema'} = $$args{schema};
		$$connect{'database'}{'user'} = $$args{user};
		$$connect{'database'}{'pass'} = $$args{password};

	} elsif (defined($$args{host}) || defined($$args{schema}) || defined($$args{user}) || defined($$args{password})) {
		# warn user they they must pass in ALL or NO args
		print "If configuring the database by command line arguments, you must provide all of host, schema, user, password\n";
		exit;
	} else {
		$connect = ReadINI(&ini);
	}

	# host, schema, user, pass
	if (!defined($$connect{'database'}{'host'}) || !defined($$connect{'database'}{'schema'}) || !defined($$connect{'database'}{'user'}) || !defined($$connect{'database'}{'pass'})) {
		print "Config file did not contain correct values";
		exit;
	}

	my $dbh = DBI->connect("DBI:mysql:database=$$connect{'database'}{'schema'};host=$$connect{'database'}{'host'}",
		$$connect{'database'}{'user'},
		$$connect{'database'}{'pass'},
		{
			# Required for updates to work properly
			mysql_client_found_rows => 0,
			# Required to print symbols
			mysql_enable_utf8mb4 => 1,
		}
	) or die "Couldn't connect to database: " . DBI->errstr;

	&runmigrations($dbh) unless $skipmigrations;

	return $dbh;
}

=head2 runmigrations

Run database migrations

=head4 Usage

    &runmigrations($db);

=head4 Arguments

=item * C<$db> DB handle

=head4 Returns

Nothing

=cut

sub runmigrations {
	my $dbh = shift;
	use DB::SQL::Migrations;
	my $migrator = DB::SQL::Migrations->new(dbh=>$dbh, migrations_directory=>'migrations');

	print "Checking database schema... \n";

	# Creates migrations table if it doesn't exist
	$migrator->create_migrations_table();

	# Run migrations
	$migrator->apply();

	return;
}

# Update an existing record in any table

=head2 updaterecord

Update an existing record in any table

=head4 Usage

    my $rows = &updaterecord({db=>$db, data=>\%data, table=>'FILM', where=>{film_id=>$film_id}});

=head4 Arguments

=item * C<$db> DB handle

=item * C<$data> Hash of new values to update

=item * C<$table> Name of table to update



( run in 1.274 second using v1.01-cache-2.11-cpan-6aa56a78535 )