App-Access2CSV

 view release on metacpan or  search on metacpan

lib/App/Access2CSV/Exporter.pm  view on Meta::CPAN


	# mdb-count prints just the number (perhaps with spaces around it).
	# Anything else - nothing, "-5", an error text - is not a count, and
	# must not quietly become 0: it is reported (as a warning, by
	# _try_count_rows)
	my ($rows) = ($stdout // '') =~ /\A\s*(\d+)\s*\z/;
	defined($rows) or $self->_croak_i18n('count_unreadable', { params => [$self->_printable(substr($stdout // '', 0, $COUNT_SHOWN))] });
	return $rows;
}

# _try_count_rows
# Purpose:        Count a table's rows, where a failure is only a warning.
#                 Row counts are optional extras: they must never make an
#                 exported table count as failed, nor end a dry run.
# Entry Criteria: $self->{programs}{'mdb-count'} is set.
# Exit Status:    Returns the count, or undef if it could not be had.
# Side Effects:   Runs mdb-count; on failure warns and logs "Cannot count
#                 the rows of T: E".  An interruption is not a failure to
#                 count: it is passed on, to stop the run.
sub _try_count_rows :Private {
	my ($self, $database, $table) = @_;

	local $@;
	my $rows = eval { $self->_count_rows($database, $table) };
	return $rows if defined $rows;

	die $@ if $self->{interrupted};
	my $error = $@;
	chomp $error;
	$self->_warn('count_failed', { params => [$table, $error] });
	return;
}

# _run_program
# Purpose:        Run an mdbtools program and check that it succeeded.
#                 Shared by every call to mdbtools, so that failures are
#                 reported consistently.
# Entry Criteria: $name is a key of $self->{programs}; $args is an arrayref;
#                 $stdout is a scalar ref or a filehandle for run3().
# Exit Status:    Returns $self; croaks if the program exits non-zero or
#                 dies from a signal.
# Side Effects:   Runs a child process; writes to $stdout; sets $?.
sub _run_program :Private {
	my ($self, $name, $args, $stdout) = @_;

	# run3 sets $?, and reads captured output back from a temporary file,
	# which changes the handle $. refers to; keep the caller's values
	local ($?, $.);

	# Start the program in a clean environment (as perlsec asks, and as
	# taint mode requires): PATH keeps only absolute directory, and variables
	# that can change how a program is started are removed
	# (File::Spec->path and path_sep, not ":": Windows separates PATH with
	# ";" and its paths contain ":", as in C:\\)
	local $ENV{PATH} = join($Config{path_sep}, map { _untaint($_) } grep { length && File::Spec->file_name_is_absolute($_) } File::Spec->path());
	local @ENV{@UNSAFE_ENV};
	delete @ENV{@UNSAFE_ENV};

	# A list (not a string) is passed, so no shell ever sees the file or
	# table name and quoting cannot be abused
	my $stderr = '';
	run3([$self->{programs}{$name}, @{$args}], \undef, $stdout, \$stderr);

	# Distinguish "never started" (-1) and a signal from an ordinary
	# non-zero exit status; $! only means something in the first case
	my ($status, $reason) = ($?, "$!");
	chomp $stderr;
	if($status == -1) {
		$self->_croak_i18n('program_not_run', { params => [$name, $reason] });
	}
	if($status & 127) {
		# While system() waits, Perl ignores INT and QUIT in this process,
		# so Ctrl-C shows up only as the child dying of SIGINT.  Treat
		# that as the user stopping the whole run, not as a bad table.
		my $signal = (split ' ', $Config{sig_name})[$status & 127] // '';
		if($signal eq 'INT' || $signal eq 'QUIT') {
			$self->{interrupted} = $signal;
			$self->_croak_i18n('interrupted', { params => [$signal] });
		}
		$self->_croak_i18n('program_signalled', { params => [$name, $status & 127] });
	}
	if($status) {
		$self->_croak_i18n('program_failed', { params => [$name, $status >> 8, $stderr] });
	}
	return $self;
}

# _csv_filename
# Purpose:        Turn a table name into a safe, unique CSV file name.
# Entry Criteria: $table is a table name (possibly empty).
# Exit Status:    Returns a file name (no directory) ending in ".csv".
# Side Effects:   Records the name in $self->{used_names}.
#
# Names are compared case-insensitively, because Windows and macOS file
# systems are, so "Orders" and "ORDERS" do not overwrite each other.
# The loop (rather than a single suffix) guarantees uniqueness even when
# another table is literally called "Orders_2".
sub _csv_filename :Protected {
	my ($self, $table) = @_;

	my $name = $table // '';

	# macOS only accepts file names that are valid UTF-8 (anything else
	# fails with "Illegal byte sequence").  mdbtools gives UTF-8, so other
	# bytes come from a damaged database: each one becomes "_", on every
	# system, so a table gets the same file name everywhere
	if(!utf8::is_utf8($name)) {
		$name = $UTF8_CODEC->encode($UTF8_CODEC->decode($name, sub { '_' }));
	}

	# Replace characters that are illegal somewhere, then strip leading
	# and trailing whitespace; Windows also silently drops trailing dots
	$name =~ s/$UNSAFE_CHARS_RE/_/g;
	$name =~ s/$BIDI_CONTROLS_RE/_/g;

	# C1 controls (U+0080-U+009F; U+009B acts like ESC [ on terminals).
	# In a byte string they must be matched as their UTF-8 form, because a
	# bare [\x80-\x9F] would also hit the continuation bytes of ordinary
	# characters such as the Euro sign (E2 82 AC)
	if(utf8::is_utf8($name)) {
		$name =~ s/[\x{80}-\x{9F}]/_/g;
	} else {
		$name =~ s/\xC2[\x80-\x9F]/_/g;
	}
	$name =~ s/\A\s+//;

	# Shorten over-long names (a hostile or corrupt database can give any
	# length), before trailing spaces and dots are removed, as shortening
	# may leave some at the end
	$name = $self->_shorten_name($name);
	$name =~ s/[\s.]+\z//;

	# Avoid hidden files, Windows device names and empty names
	$name =~ s/\A\./_/;
	$name = "_$name" if $name =~ $RESERVED_NAME_RE;
	$name = $UNNAMED unless length $name;

	# Find the smallest free suffix (_2, _3, ...).  Start from where this
	# name's last search ended rather than from 2: every suffix below that
	# point was taken then and is still taken (names are never released
	# during a run), so the answer is the same, but N tables with the same
	# name cost O(N) in total instead of O(N squared).
	my $used = $self->{used_names};



( run in 0.878 second using v1.01-cache-2.11-cpan-60884a8df76 )