'Inner main function. If anything fails in here, file handles and
database connections will be safely closed.'

def _failsafe_main(self):

    if self.connection:
        transaction = self.connection.begin()
    for f in self.input_files:
        try:
            table_name = self.table_names.pop(0)
        except IndexError:
            if (f == sys.stdin):
                table_name = 'stdin'
            else:
                table_name = os.path.splitext(os.path.basename(f.name))[0]
        table = None
        try:
            table = agate.Table.from_csv(f, skip_lines=self.args.skip_lines, sniff_limit=self.args.sniff_limit, column_types=self.get_column_types(), **self.reader_kwargs)
        except StopIteration:
            continue
        if table:
            if self.connection:
                table.to_sql(self.connection, table_name, overwrite=self.args.overwrite, create=(not self.args.no_create), create_if_not_exists=self.args.create_if_not_exists, insert=(self.args.insert and (len(table.rows) > 0)), prefixes=self.args.prefix, db_schema=self.args.db_schema, constraints=(not self.args.no_constraints))
            else:
                statement = table.to_sql_create_statement(table_name, dialect=self.args.dialect, db_schema=self.args.db_schema, constraints=(not self.args.no_constraints))
                self.output_file.write(('%s\n' % statement))
    if self.connection:
        if self.args.query:
            if os.path.exists(self.args.query):
                with open(self.args.query, 'r') as f:
                    query = f.read()
            else:
                query = self.args.query
            queries = query.split(';')
            rows = None
            for q in queries:
                if q.strip():
                    rows = self.connection.execute(q)
            output = agate.csv.writer(self.output_file, **self.writer_kwargs)
            output.writerow(rows._metadata.keys)
            for row in rows:
                output.writerow(row)
        transaction.commit()
