#!/usr/bin/env python

# export_table.py allows to dump a PostgreSQL database
# Copyright (C) 2008 Florent Flament (florent.flament@telecom-paristech.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Class managing transaction with the database
from pyPgSQL import PgSQL

class export_table:
	""" Class providing database IOs """
	# Some constants
	__host = "dpa.enst.fr"
	__user = "guest"
	__pass = "guest"
	__db   = "production_traces"

	# Private variables
	__conn  = None
	__curs  = None

	def __init__(self, table):
		""" No arguments needed """
		self.__conn  = PgSQL.connect(
			user     = self.__user,
			password = self.__pass,
			host     = self.__host,
			database = self.__db
		)
		self.__curs  = self.__conn.cursor()
		self.__curs.execute("SELECT filename, filecontent FROM \""+table+"\";" )
		# Notice: self.__curs.rowcount is equal to -1 here

	def __del__(self):
		""" Automatically called method """
		self.__conn.close()

	def get_trace(self):
		""" Does not take any argument and returns the next couple (filename, filecontent) """
		return self.__curs.fetchone()

def main():
	tdb= export_table( "secmatv1_2006_04_0809" )
	# Nota bene: the 2008/2009 version of the contest focuses on this table.
	#            However, three acquisition camaigns (i.e. database tables) are
	#            provided from http://www.dpacontest.org/:
	#            [1/3] "secmatv1_2006_04_0809", aka "SecMatV1[ASIC]", 81089 traces
	#            [2/3] "secmatv3_20070924_des", aka "SecMatV3[ASIC]", 81569 traces
	#            [3/3] "secmatv3_20071219_des", aka "SecMatV3[FPGA]", 67753 traces
	while True: # do ... while does not exist in python
		res= tdb.get_trace()
		if res == None: break      # There is no more data in the database
		filename, filecontent= res # Continue saving this entry
		fd= open( filename, "wb" ) # Opening in binary mode.
		                           # /!\ Text mode (default) corrupts binary data: \n => \r\n under Windows
		for byte in filecontent: fd.write( byte )
		fd.close()

if __name__ == "__main__": main()
