#!/usr/local/bin/perl
# create_table.cgi
# Create a new table

require './mysql-lib.pl';
&ReadParse();
&can_edit_db($in{'db'}) || &error($text{'dbase_ecannot'});
$access{'edonly'} && &error($text{'dbase_ecannot'});
&error_setup($text{'table_err'});
$in{'name'} =~ /^\S+$/ || &error($text{'table_ename'});
if ($in{'copy'}) {
	local ($db, $table) = split(/\./, $in{'copy'});
	foreach $f (&table_structure($db, $table)) {
		local $copy = &quotestr($f->{'field'})." $f->{'type'}";
		$copy .= " not null" if (!$f->{'null'});
		if ($f->{'key'} eq 'PRI') {
			$copy .= " primary key";
			}
		$copy .= " default '$f->{'default'}'"
			if ($f->{'default'} && $f->{'default'} ne 'NULL');
		$copy .= " $f->{'extra'}" if ($f->{'extra'});
		push(@fields, $copy);
		}
	}
for($i=0; defined($in{"field_$i"}); $i++) {
	next if (!$in{"field_$i"});
	$in{"field_$i"} =~ /^\S+$/ ||
		&error(&text('table_efield', $in{"field_$i"}));
	$in{"type_$i"} || &error(&text('table_etype', $in{"field_$i"}));
	if ($in{"size_$i"}) {
		push(@fields, sprintf "%s %s(%s)",
		     &quotestr($in{"field_$i"}), $in{"type_$i"},$in{"size_$i"});
		}
	else {
		push(@fields, sprintf "%s %s",
			&quotestr($in{"field_$i"}), $in{"type_$i"});
		}
	if ($in{"key_$i"}) {
		$fields[@fields-1] .= " not null";
		push(@pri, $in{"field_$i"});
		}
	if ($in{"auto_$i"}) {
		$in{"key_$i"} || &error($text{'table_eautokey'});
		push(@auto, $fields[@fields-1]);
		}
	}
@auto < 2 || &error($text{'table_eauto'});
@fields || &error($text{'table_enone'});
$sql = "create table ".&quotestr($in{'name'})." (".join(",", @fields).")";
$sql .= " type = $in{'type'}" if ($in{'type'});
&execute_sql_logged($in{'db'}, $sql);
if (@pri) {
	# Setup primary fields too
	&execute_sql_logged($in{'db'},
		    "alter table ".&quotestr($in{'name'})." add primary key (".
		    join(",", map { &quotestr($_) } @pri).")");
	}
if (@auto) {
	# Make field auto-increment
	&execute_sql_logged($in{'db'},
		    "alter table ".&quotestr($in{'name'}).
		    " modify $auto[0] auto_increment");
	}
&webmin_log("create", "table", $in{'name'}, \%in);
&redirect("edit_dbase.cgi?db=$in{'db'}");


